text
stringlengths
54
60.6k
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "caf/config.hpp" // exclude this suite; seems to be too much to swallow for MSVC #ifndef CAF_WINDOWS #define CAF_SUITE typed_spawn #include "caf/test/unit_test.hpp" #include "caf/string_algorithms.hpp" #include "caf/all.hpp" using namespace std; using namespace caf; using passed_atom = caf::atom_constant<caf::atom("passed")>; namespace { // check invariants of type system using dummy1 = typed_actor<reacts_to<int, int>, replies_to<double>::with<double>>; using dummy2 = dummy1::extend<reacts_to<ok_atom>>; static_assert(std::is_convertible<dummy2, dummy1>::value, "handle not assignable to narrower definition"); static_assert(! std::is_convertible<dummy1, dummy2>::value, "handle is assignable to broader definition"); /****************************************************************************** * simple request/response test * ******************************************************************************/ struct my_request { int a; int b; }; using server_type = typed_actor<replies_to<my_request>::with<bool>>; bool operator==(const my_request& lhs, const my_request& rhs) { return lhs.a == rhs.a && lhs.b == rhs.b; } server_type::behavior_type typed_server1() { return { [](const my_request& req) { return req.a == req.b; } }; } server_type::behavior_type typed_server2(server_type::pointer) { return typed_server1(); } class typed_server3 : public server_type::base { public: typed_server3(const string& line, actor buddy) { send(buddy, line); } behavior_type make_behavior() override { return typed_server2(this); } }; void client(event_based_actor* self, actor parent, server_type serv) { self->sync_send(serv, my_request{0, 0}).then( [=](bool val1) { CAF_CHECK_EQUAL(val1, true); self->sync_send(serv, my_request{10, 20}).then( [=](bool val2) { CAF_CHECK_EQUAL(val2, false); self->send(parent, passed_atom::value); } ); } ); } void test_typed_spawn(server_type ts) { scoped_actor self; self->send(ts, my_request{1, 2}); self->receive( [](bool value) { CAF_CHECK_EQUAL(value, false); } ); self->send(ts, my_request{42, 42}); self->receive( [](bool value) { CAF_CHECK_EQUAL(value, true); } ); self->sync_send(ts, my_request{10, 20}).await( [](bool value) { CAF_CHECK_EQUAL(value, false); } ); self->sync_send(ts, my_request{0, 0}).await( [](bool value) { CAF_CHECK_EQUAL(value, true); } ); self->spawn<monitored>(client, self, ts); self->receive( [](passed_atom) { CAF_MESSAGE("received `passed_atom`"); } ); self->receive( [](const down_msg& dmsg) { CAF_CHECK_EQUAL(dmsg.reason, exit_reason::normal); } ); self->send_exit(ts, exit_reason::user_shutdown); } /****************************************************************************** * test skipping of messages intentionally + using become() * ******************************************************************************/ struct get_state_msg {}; using event_testee_type = typed_actor<replies_to<get_state_msg>::with<string>, replies_to<string>::with<void>, replies_to<float>::with<void>, replies_to<int>::with<int>>; class event_testee : public event_testee_type::base { public: behavior_type wait4string() { return {on<get_state_msg>() >> [] { return "wait4string"; }, on<string>() >> [=] { become(wait4int()); }, (on<float>() || on<int>()) >> skip_message}; } behavior_type wait4int() { return { on<get_state_msg>() >> [] { return "wait4int"; }, on<int>() >> [=]()->int {become(wait4float()); return 42; }, (on<float>() || on<string>()) >> skip_message }; } behavior_type wait4float() { return { on<get_state_msg>() >> [] { return "wait4float"; }, on<float>() >> [=] { become(wait4string()); }, (on<string>() || on<int>()) >> skip_message}; } behavior_type make_behavior() override { return wait4int(); } }; /****************************************************************************** * simple 'forwarding' chain * ******************************************************************************/ using string_actor = typed_actor<replies_to<string>::with<string>>; void simple_relay(string_actor::pointer self, string_actor master, bool leaf) { string_actor next = leaf ? spawn_typed(simple_relay, master, false) : master; self->link_to(next); self->become( [=](const string& str) { return self->sync_send(next, str).then( [](const string & answer)->string { return answer; } ); }); } string_actor::behavior_type simple_string_reverter() { return { [](const string& str) { return string{str.rbegin(), str.rend()}; } }; } /****************************************************************************** * sending typed actor handles * ******************************************************************************/ using int_actor = typed_actor<replies_to<int>::with<int>>; int_actor::behavior_type int_fun() { return { [](int i) { return i * i; } }; } behavior foo(event_based_actor* self) { return { [=](int i, int_actor server) { return self->sync_send(server, i).then([=](int result) -> int { self->quit(exit_reason::normal); return result; }); } }; } int_actor::behavior_type int_fun2(int_actor::pointer self) { self->trap_exit(true); return { [=](int i) { self->monitor(self->current_sender()); return i * i; }, [=](const down_msg& dm) { CAF_CHECK_EQUAL(dm.reason, exit_reason::normal); self->quit(); }, [=](const exit_msg&) { CAF_TEST_ERROR("Unexpected message: " << to_string(self->current_message())); } }; } behavior foo2(event_based_actor* self) { return { [=](int i, int_actor server) { return self->sync_send(server, i).then([=](int result) -> int { self->quit(exit_reason::normal); return result; }); } }; } struct fixture { fixture() { announce<get_state_msg>("get_state_msg"); announce<int_actor>("int_actor"); announce<my_request>("my_request", &my_request::a, &my_request::b); } ~fixture() { await_all_actors_done(); shutdown(); } }; } // namespace <anonymous> CAF_TEST_FIXTURE_SCOPE(typed_spawn_tests, fixture) /****************************************************************************** * put it all together * ******************************************************************************/ CAF_TEST(typed_spawns) { // run test series with typed_server(1|2) test_typed_spawn(spawn_typed(typed_server1)); await_all_actors_done(); CAF_MESSAGE("finished test series with `typed_server1`"); test_typed_spawn(spawn_typed(typed_server2)); await_all_actors_done(); CAF_MESSAGE("finished test series with `typed_server2`"); { scoped_actor self; test_typed_spawn(spawn_typed<typed_server3>("hi there", self)); self->receive(on("hi there") >> [] { CAF_MESSAGE("received \"hi there\""); }); } } CAF_TEST(test_event_testee) { // run test series with event_testee scoped_actor self; auto et = self->spawn_typed<event_testee>(); string result; self->send(et, 1); self->send(et, 2); self->send(et, 3); self->send(et, .1f); self->send(et, "hello event testee!"); self->send(et, .2f); self->send(et, .3f); self->send(et, "hello again event testee!"); self->send(et, "goodbye event testee!"); typed_actor<replies_to<get_state_msg>::with<string>> sub_et = et; // $:: is the anonymous namespace set<string> iface{"caf::replies_to<get_state_msg>::with<@str>", "caf::replies_to<@str>::with<void>", "caf::replies_to<float>::with<void>", "caf::replies_to<@i32>::with<@i32>"}; CAF_CHECK_EQUAL(join(sub_et->message_types(), ","), join(iface, ",")); self->send(sub_et, get_state_msg{}); // we expect three 42s int i = 0; self->receive_for(i, 3)([](int value) { CAF_CHECK_EQUAL(value, 42); }); self->receive( [&](const string& str) { result = str; }, after(chrono::minutes(1)) >> [&] { CAF_TEST_ERROR("event_testee does not reply"); throw runtime_error("event_testee does not reply"); } ); self->send_exit(et, exit_reason::user_shutdown); self->await_all_other_actors_done(); CAF_CHECK_EQUAL(result, "wait4int"); } CAF_TEST(test_simple_string_reverter) { // run test series with string reverter scoped_actor self; // actor-under-test auto aut = self->spawn_typed<monitored>(simple_relay, spawn_typed(simple_string_reverter), true); set<string> iface{"caf::replies_to<@str>::with<@str>"}; CAF_CHECK(aut->message_types() == iface); self->sync_send(aut, "Hello World!").await([](const string& answer) { CAF_CHECK_EQUAL(answer, "!dlroW olleH"); }); anon_send_exit(aut, exit_reason::user_shutdown); } CAF_TEST(test_sending_typed_actors) { scoped_actor self; auto aut = spawn_typed(int_fun); self->send(spawn(foo), 10, aut); self->receive( [](int i) { CAF_CHECK_EQUAL(i, 100); } ); self->send_exit(aut, exit_reason::user_shutdown); } CAF_TEST(test_sending_typed_actors_and_down_msg) { scoped_actor self; auto aut = spawn_typed(int_fun2); self->send(spawn(foo2), 10, aut); self->receive([](int i) { CAF_CHECK_EQUAL(i, 100); }); } CAF_TEST_FIXTURE_SCOPE_END() #endif // CAF_WINDOWS <commit_msg>Add unit test for latest patch from ufownl<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2015 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "caf/config.hpp" // exclude this suite; seems to be too much to swallow for MSVC #ifndef CAF_WINDOWS #define CAF_SUITE typed_spawn #include "caf/test/unit_test.hpp" #include "caf/string_algorithms.hpp" #include "caf/all.hpp" using namespace std; using namespace caf; using passed_atom = caf::atom_constant<caf::atom("passed")>; namespace { // check invariants of type system using dummy1 = typed_actor<reacts_to<int, int>, replies_to<double>::with<double>>; using dummy2 = dummy1::extend<reacts_to<ok_atom>>; static_assert(std::is_convertible<dummy2, dummy1>::value, "handle not assignable to narrower definition"); static_assert(! std::is_convertible<dummy1, dummy2>::value, "handle is assignable to broader definition"); /****************************************************************************** * simple request/response test * ******************************************************************************/ struct my_request { int a; int b; }; using server_type = typed_actor<replies_to<my_request>::with<bool>>; bool operator==(const my_request& lhs, const my_request& rhs) { return lhs.a == rhs.a && lhs.b == rhs.b; } server_type::behavior_type typed_server1() { return { [](const my_request& req) { return req.a == req.b; } }; } server_type::behavior_type typed_server2(server_type::pointer) { return typed_server1(); } class typed_server3 : public server_type::base { public: typed_server3(const string& line, actor buddy) { send(buddy, line); } behavior_type make_behavior() override { return typed_server2(this); } }; void client(event_based_actor* self, actor parent, server_type serv) { self->sync_send(serv, my_request{0, 0}).then( [=](bool val1) { CAF_CHECK_EQUAL(val1, true); self->sync_send(serv, my_request{10, 20}).then( [=](bool val2) { CAF_CHECK_EQUAL(val2, false); self->send(parent, passed_atom::value); } ); } ); } void test_typed_spawn(server_type ts) { scoped_actor self; self->send(ts, my_request{1, 2}); self->receive( [](bool value) { CAF_CHECK_EQUAL(value, false); } ); self->send(ts, my_request{42, 42}); self->receive( [](bool value) { CAF_CHECK_EQUAL(value, true); } ); self->sync_send(ts, my_request{10, 20}).await( [](bool value) { CAF_CHECK_EQUAL(value, false); } ); self->sync_send(ts, my_request{0, 0}).await( [](bool value) { CAF_CHECK_EQUAL(value, true); } ); self->spawn<monitored>(client, self, ts); self->receive( [](passed_atom) { CAF_MESSAGE("received `passed_atom`"); } ); self->receive( [](const down_msg& dmsg) { CAF_CHECK_EQUAL(dmsg.reason, exit_reason::normal); } ); self->send_exit(ts, exit_reason::user_shutdown); } /****************************************************************************** * test skipping of messages intentionally + using become() * ******************************************************************************/ struct get_state_msg {}; using event_testee_type = typed_actor<replies_to<get_state_msg>::with<string>, replies_to<string>::with<void>, replies_to<float>::with<void>, replies_to<int>::with<int>>; class event_testee : public event_testee_type::base { public: behavior_type wait4string() { return {on<get_state_msg>() >> [] { return "wait4string"; }, on<string>() >> [=] { become(wait4int()); }, (on<float>() || on<int>()) >> skip_message}; } behavior_type wait4int() { return { on<get_state_msg>() >> [] { return "wait4int"; }, on<int>() >> [=]()->int {become(wait4float()); return 42; }, (on<float>() || on<string>()) >> skip_message }; } behavior_type wait4float() { return { on<get_state_msg>() >> [] { return "wait4float"; }, on<float>() >> [=] { become(wait4string()); }, (on<string>() || on<int>()) >> skip_message}; } behavior_type make_behavior() override { return wait4int(); } }; /****************************************************************************** * simple 'forwarding' chain * ******************************************************************************/ using string_actor = typed_actor<replies_to<string>::with<string>>; void simple_relay(string_actor::pointer self, string_actor master, bool leaf) { string_actor next = leaf ? spawn_typed(simple_relay, master, false) : master; self->link_to(next); self->become( [=](const string& str) { return self->sync_send(next, str).then( [](const string & answer)->string { return answer; } ); }); } string_actor::behavior_type simple_string_reverter() { return { [](const string& str) { return string{str.rbegin(), str.rend()}; } }; } /****************************************************************************** * sending typed actor handles * ******************************************************************************/ using int_actor = typed_actor<replies_to<int>::with<int>>; int_actor::behavior_type int_fun() { return { [](int i) { return i * i; } }; } behavior foo(event_based_actor* self) { return { [=](int i, int_actor server) { return self->sync_send(server, i).then([=](int result) -> int { self->quit(exit_reason::normal); return result; }); } }; } int_actor::behavior_type int_fun2(int_actor::pointer self) { self->trap_exit(true); return { [=](int i) { self->monitor(self->current_sender()); return i * i; }, [=](const down_msg& dm) { CAF_CHECK_EQUAL(dm.reason, exit_reason::normal); self->quit(); }, [=](const exit_msg&) { CAF_TEST_ERROR("Unexpected message: " << to_string(self->current_message())); } }; } behavior foo2(event_based_actor* self) { return { [=](int i, int_actor server) { return self->sync_send(server, i).then([=](int result) -> int { self->quit(exit_reason::normal); return result; }); } }; } struct fixture { fixture() { announce<get_state_msg>("get_state_msg"); announce<int_actor>("int_actor"); announce<my_request>("my_request", &my_request::a, &my_request::b); } ~fixture() { await_all_actors_done(); shutdown(); } }; } // namespace <anonymous> CAF_TEST_FIXTURE_SCOPE(typed_spawn_tests, fixture) /****************************************************************************** * put it all together * ******************************************************************************/ CAF_TEST(typed_spawns) { // run test series with typed_server(1|2) test_typed_spawn(spawn_typed(typed_server1)); await_all_actors_done(); CAF_MESSAGE("finished test series with `typed_server1`"); test_typed_spawn(spawn_typed(typed_server2)); await_all_actors_done(); CAF_MESSAGE("finished test series with `typed_server2`"); { scoped_actor self; test_typed_spawn(spawn_typed<typed_server3>("hi there", self)); self->receive(on("hi there") >> [] { CAF_MESSAGE("received \"hi there\""); }); } } CAF_TEST(test_event_testee) { // run test series with event_testee scoped_actor self; auto et = self->spawn_typed<event_testee>(); string result; self->send(et, 1); self->send(et, 2); self->send(et, 3); self->send(et, .1f); self->send(et, "hello event testee!"); self->send(et, .2f); self->send(et, .3f); self->send(et, "hello again event testee!"); self->send(et, "goodbye event testee!"); typed_actor<replies_to<get_state_msg>::with<string>> sub_et = et; // $:: is the anonymous namespace set<string> iface{"caf::replies_to<get_state_msg>::with<@str>", "caf::replies_to<@str>::with<void>", "caf::replies_to<float>::with<void>", "caf::replies_to<@i32>::with<@i32>"}; CAF_CHECK_EQUAL(join(sub_et->message_types(), ","), join(iface, ",")); self->send(sub_et, get_state_msg{}); // we expect three 42s int i = 0; self->receive_for(i, 3)([](int value) { CAF_CHECK_EQUAL(value, 42); }); self->receive( [&](const string& str) { result = str; }, after(chrono::minutes(1)) >> [&] { CAF_TEST_ERROR("event_testee does not reply"); throw runtime_error("event_testee does not reply"); } ); self->send_exit(et, exit_reason::user_shutdown); self->await_all_other_actors_done(); CAF_CHECK_EQUAL(result, "wait4int"); } CAF_TEST(test_simple_string_reverter) { // run test series with string reverter scoped_actor self; // actor-under-test auto aut = self->spawn_typed<monitored>(simple_relay, spawn_typed(simple_string_reverter), true); set<string> iface{"caf::replies_to<@str>::with<@str>"}; CAF_CHECK(aut->message_types() == iface); self->sync_send(aut, "Hello World!").await([](const string& answer) { CAF_CHECK_EQUAL(answer, "!dlroW olleH"); }); anon_send_exit(aut, exit_reason::user_shutdown); } CAF_TEST(test_sending_typed_actors) { scoped_actor self; auto aut = spawn_typed(int_fun); self->send(spawn(foo), 10, aut); self->receive( [](int i) { CAF_CHECK_EQUAL(i, 100); } ); self->send_exit(aut, exit_reason::user_shutdown); } CAF_TEST(test_sending_typed_actors_and_down_msg) { scoped_actor self; auto aut = spawn_typed(int_fun2); self->send(spawn(foo2), 10, aut); self->receive([](int i) { CAF_CHECK_EQUAL(i, 100); }); } CAF_TEST(check_signature) { using foo_type = typed_actor<replies_to<put_atom>:: with_either<ok_atom>::or_else<error_atom>>; using foo_result_type = either<ok_atom>::or_else<error_atom>; using bar_type = typed_actor<reacts_to<ok_atom>, reacts_to<error_atom>>; auto foo_action = [](foo_type::pointer self) -> foo_type::behavior_type { return { [=] (put_atom) -> foo_result_type { self->quit(); return {ok_atom::value}; } }; }; auto bar_action = [=](bar_type::pointer self) -> bar_type::behavior_type { auto foo = self->spawn_typed<linked>(foo_action); self->send(foo, put_atom::value); return { [=](ok_atom) { self->quit(); }, [=](error_atom) { self->quit(exit_reason::user_defined); } }; }; scoped_actor self; self->spawn_typed<monitored>(bar_action); self->receive( [](const down_msg& dm) { CAF_CHECK_EQUAL(dm.reason, exit_reason::normal); } ); } CAF_TEST_FIXTURE_SCOPE_END() #endif // CAF_WINDOWS <|endoftext|>
<commit_before>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, 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. * *******************************************************************************/ #ifndef GUARD_MIOPEN_CONTEXT_HPP_ #define GUARD_MIOPEN_CONTEXT_HPP_ #include <miopen/config.h> #include <miopen/kernel_info.hpp> #include <miopen/common.hpp> #include <miopen/invoker_cache.hpp> #include <miopen/kernel.hpp> #include <miopen/miopen.h> #include <miopen/names.hpp> #include <miopen/object.hpp> #include <miopen/allocator.hpp> #include <miopen/simple_hash.hpp> #include <miopen/solver_id.hpp> #include <miopen/stringutils.hpp> #include <miopen/target_properties.hpp> #include <boost/range/adaptor/transformed.hpp> #include <cstdio> #include <cstring> #include <ios> #include <sstream> #include <memory> #include <vector> #include <unordered_map> #if MIOPEN_USE_ROCBLAS #include <miopen/manage_ptr.hpp> #if MIOPEN_ROCBLAS_VERSION_FLAT < 2045000 #include <rocblas.h> #else #include <rocblas/rocblas.h> #endif #endif namespace miopen { struct HandleImpl; #if MIOPEN_USE_MIOPENGEMM struct GemmGeometry; using GemmKey = std::pair<std::string, std::string>; #endif #if MIOPEN_USE_ROCBLAS using rocblas_handle_ptr = MIOPEN_MANAGE_PTR(rocblas_handle, rocblas_destroy_handle); #endif struct Handle : miopenHandle { friend struct TargetProperties; Handle(); Handle(miopenAcceleratorQueue_t stream); Handle(Handle&&) noexcept; ~Handle(); miopenAcceleratorQueue_t GetStream() const; void SetStream(miopenAcceleratorQueue_t streamID) const; void SetAllocator(miopenAllocatorFunction allocator, miopenDeallocatorFunction deallocator, void* allocatorContext) const; void EnableProfiling(bool enable = true) const; void ResetKernelTime() const; void AccumKernelTime(float curr_time) const; float GetKernelTime() const; bool IsProfilingEnabled() const; KernelInvoke AddKernel(const std::string& algorithm, const std::string& network_config, const std::string& program_name, const std::string& kernel_name, const std::vector<size_t>& vld, const std::vector<size_t>& vgd, const std::string& params, std::size_t cache_index = 0, bool is_kernel_str = false, const std::string& kernel_src = "") const; bool HasKernel(const std::string& algorithm, const std::string& network_config) const; void ClearKernels(const std::string& algorithm, const std::string& network_config) const; auto GetKernels(const std::string& algorithm, const std::string& network_config) const { return this->GetKernelsImpl(algorithm, network_config) | boost::adaptors::transformed([this](Kernel k) { return this->Run(k); }); } KernelInvoke GetKernel(const std::string& algorithm, const std::string& network_config) const { auto ks = this->GetKernelsImpl(algorithm, network_config); if(ks.empty()) { MIOPEN_THROW("looking for default kernel (does not exist): " + algorithm + ", " + network_config); } return this->Run(ks.front()); } KernelInvoke Run(Kernel k) const; const std::vector<Kernel>& GetKernelsImpl(const std::string& algorithm, const std::string& network_config) const; Program LoadProgram(const std::string& program_name, std::string params, bool is_kernel_str, const std::string& kernel_src) const; bool HasProgram(const std::string& program_name, const std::string& params) const; void ClearProgram(const std::string& program_name, const std::string& params) const; void AddProgram(Program prog, const std::string& program_name, const std::string& params) const; void Finish() const; void Flush() const; std::size_t GetLocalMemorySize() const; std::size_t GetGlobalMemorySize() const; std::size_t GetImage3dMaxWidth() const; std::size_t GetWavefrontWidth() const; std::size_t GetMaxComputeUnits() const; std::size_t GetMaxHardwareComputeUnits() const { std::size_t num_cu = this->GetMaxComputeUnits(); std::string name = this->GetDeviceName(); return StartsWith(name, "gfx1") ? num_cu * 2 /* CUs per WGP */ : num_cu; } std::size_t m_MaxMemoryAllocSizeCached = 0; std::size_t GetMaxMemoryAllocSize(); std::string GetDeviceName() const; const TargetProperties& GetTargetProperties() const; private: std::string GetDeviceNameImpl() const; public: std::ostream& Print(std::ostream& os) const; void Copy(ConstData_t src, Data_t dest, std::size_t size) const; Allocator::ManageDataPtr Create(std::size_t sz) const; Allocator::ManageDataPtr& WriteTo(const void* data, Allocator::ManageDataPtr& ddata, std::size_t sz) const; void ReadTo(void* data, const Allocator::ManageDataPtr& ddata, std::size_t sz) const; shared<Data_t> CreateSubBuffer(Data_t data, std::size_t offset, std::size_t size) const; #if MIOPEN_BACKEND_HIP shared<ConstData_t> CreateSubBuffer(ConstData_t data, std::size_t offset, std::size_t size) const; #endif template <class T> Allocator::ManageDataPtr Create(std::size_t sz) { return this->Create(sz * sizeof(T)); } template <class Container> Allocator::ManageDataPtr Write(const Container& c) { using type = typename Container::value_type; auto buf = this->Create<type>(c.size()); return std::move( this->WriteTo(reinterpret_cast<const void*>(c.data()), buf, c.size() * sizeof(type))); } template <class T> std::vector<T> Read(const Allocator::ManageDataPtr& ddata, std::size_t sz) { std::vector<T> result(sz); this->ReadTo(result.data(), ddata, sz * sizeof(T)); return result; } static std::string GetDbBasename(const TargetProperties& target, size_t num_cu) { auto ret = target.DbId() + [&]() { std::ostringstream ss; if(num_cu <= 64) ss << '_' << num_cu; else ss << std::hex << num_cu; return std::string(ss.str()); }(); return ret; } std::string GetDbBasename() const { return GetDbBasename(GetTargetProperties(), GetMaxComputeUnits()); } std::unique_ptr<HandleImpl> impl; std::unordered_map<std::string, std::vector<miopenConvSolution_t>> find_map; #if MIOPEN_USE_MIOPENGEMM std::unordered_map<GemmKey, std::unique_ptr<GemmGeometry>, SimpleHash> geo_map; #endif Invoker PrepareInvoker(const InvokerFactory& factory, const std::vector<solver::KernelInfo>& kernels) const; void RegisterInvoker(const Invoker& invoker, const NetworkConfig& config, const std::string& solver, const boost::optional<AlgorithmName>& algo = boost::none) { invokers.Register({config, solver}, invoker); if(algo.has_value()) invokers.SetAsFound1_0(config, *algo, solver); } boost::optional<const Invoker&> GetInvoker(const NetworkConfig& config, const boost::optional<solver::Id>& solver, const boost::optional<AlgorithmName>& algo = boost::none) const { assert(solver || algo); assert(!(solver && algo)); if(solver) { MIOPEN_LOG_I2("Returning an invoker for problem " << config.ToString() << " and solver " << solver->ToString()); return invokers[std::make_pair(config.ToString(), solver->ToString())]; } MIOPEN_LOG_I2("Returning an invoker for problem " << config.ToString() << " and algorithm " << algo->ToString()); return invokers.GetFound1_0(config, *algo); } boost::optional<const std::string&> GetFound1_0SolverId(const NetworkConfig& config, const AlgorithmName& algo) const { return invokers.GetFound1_0SolverId(config, algo); } #if MIOPEN_USE_ROCBLAS const rocblas_handle_ptr& rhandle() const { return rhandle_; } private: rocblas_handle_ptr CreateRocblasHandle() const; rocblas_handle_ptr rhandle_; #else private: #endif InvokerCache invokers; }; inline std::ostream& operator<<(std::ostream& os, const Handle& handle) { return handle.Print(os); } struct AutoEnableProfiling { AutoEnableProfiling(const Handle& x) : h(x) { prev_state = h.IsProfilingEnabled(); h.EnableProfiling(); } ~AutoEnableProfiling() { h.EnableProfiling(prev_state); h.ResetKernelTime(); } private: const Handle& h; bool prev_state; }; } // namespace miopen MIOPEN_DEFINE_OBJECT(miopenHandle, miopen::Handle); #endif // GUARD_MIOPEN_CONTEXT_HPP_ <commit_msg>Fix handle include guard name (#1785)<commit_after>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, 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. * *******************************************************************************/ #ifndef GUARD_MIOPEN_HANDLE_HPP_ #define GUARD_MIOPEN_HANDLE_HPP_ #include <miopen/config.h> #include <miopen/kernel_info.hpp> #include <miopen/common.hpp> #include <miopen/invoker_cache.hpp> #include <miopen/kernel.hpp> #include <miopen/miopen.h> #include <miopen/names.hpp> #include <miopen/object.hpp> #include <miopen/allocator.hpp> #include <miopen/simple_hash.hpp> #include <miopen/solver_id.hpp> #include <miopen/stringutils.hpp> #include <miopen/target_properties.hpp> #include <boost/range/adaptor/transformed.hpp> #include <cstdio> #include <cstring> #include <ios> #include <sstream> #include <memory> #include <vector> #include <unordered_map> #if MIOPEN_USE_ROCBLAS #include <miopen/manage_ptr.hpp> #if MIOPEN_ROCBLAS_VERSION_FLAT < 2045000 #include <rocblas.h> #else #include <rocblas/rocblas.h> #endif #endif namespace miopen { struct HandleImpl; #if MIOPEN_USE_MIOPENGEMM struct GemmGeometry; using GemmKey = std::pair<std::string, std::string>; #endif #if MIOPEN_USE_ROCBLAS using rocblas_handle_ptr = MIOPEN_MANAGE_PTR(rocblas_handle, rocblas_destroy_handle); #endif struct Handle : miopenHandle { friend struct TargetProperties; Handle(); Handle(miopenAcceleratorQueue_t stream); Handle(Handle&&) noexcept; ~Handle(); miopenAcceleratorQueue_t GetStream() const; void SetStream(miopenAcceleratorQueue_t streamID) const; void SetAllocator(miopenAllocatorFunction allocator, miopenDeallocatorFunction deallocator, void* allocatorContext) const; void EnableProfiling(bool enable = true) const; void ResetKernelTime() const; void AccumKernelTime(float curr_time) const; float GetKernelTime() const; bool IsProfilingEnabled() const; KernelInvoke AddKernel(const std::string& algorithm, const std::string& network_config, const std::string& program_name, const std::string& kernel_name, const std::vector<size_t>& vld, const std::vector<size_t>& vgd, const std::string& params, std::size_t cache_index = 0, bool is_kernel_str = false, const std::string& kernel_src = "") const; bool HasKernel(const std::string& algorithm, const std::string& network_config) const; void ClearKernels(const std::string& algorithm, const std::string& network_config) const; auto GetKernels(const std::string& algorithm, const std::string& network_config) const { return this->GetKernelsImpl(algorithm, network_config) | boost::adaptors::transformed([this](Kernel k) { return this->Run(k); }); } KernelInvoke GetKernel(const std::string& algorithm, const std::string& network_config) const { auto ks = this->GetKernelsImpl(algorithm, network_config); if(ks.empty()) { MIOPEN_THROW("looking for default kernel (does not exist): " + algorithm + ", " + network_config); } return this->Run(ks.front()); } KernelInvoke Run(Kernel k) const; const std::vector<Kernel>& GetKernelsImpl(const std::string& algorithm, const std::string& network_config) const; Program LoadProgram(const std::string& program_name, std::string params, bool is_kernel_str, const std::string& kernel_src) const; bool HasProgram(const std::string& program_name, const std::string& params) const; void ClearProgram(const std::string& program_name, const std::string& params) const; void AddProgram(Program prog, const std::string& program_name, const std::string& params) const; void Finish() const; void Flush() const; std::size_t GetLocalMemorySize() const; std::size_t GetGlobalMemorySize() const; std::size_t GetImage3dMaxWidth() const; std::size_t GetWavefrontWidth() const; std::size_t GetMaxComputeUnits() const; std::size_t GetMaxHardwareComputeUnits() const { std::size_t num_cu = this->GetMaxComputeUnits(); std::string name = this->GetDeviceName(); return StartsWith(name, "gfx1") ? num_cu * 2 /* CUs per WGP */ : num_cu; } std::size_t m_MaxMemoryAllocSizeCached = 0; std::size_t GetMaxMemoryAllocSize(); std::string GetDeviceName() const; const TargetProperties& GetTargetProperties() const; private: std::string GetDeviceNameImpl() const; public: std::ostream& Print(std::ostream& os) const; void Copy(ConstData_t src, Data_t dest, std::size_t size) const; Allocator::ManageDataPtr Create(std::size_t sz) const; Allocator::ManageDataPtr& WriteTo(const void* data, Allocator::ManageDataPtr& ddata, std::size_t sz) const; void ReadTo(void* data, const Allocator::ManageDataPtr& ddata, std::size_t sz) const; shared<Data_t> CreateSubBuffer(Data_t data, std::size_t offset, std::size_t size) const; #if MIOPEN_BACKEND_HIP shared<ConstData_t> CreateSubBuffer(ConstData_t data, std::size_t offset, std::size_t size) const; #endif template <class T> Allocator::ManageDataPtr Create(std::size_t sz) { return this->Create(sz * sizeof(T)); } template <class Container> Allocator::ManageDataPtr Write(const Container& c) { using type = typename Container::value_type; auto buf = this->Create<type>(c.size()); return std::move( this->WriteTo(reinterpret_cast<const void*>(c.data()), buf, c.size() * sizeof(type))); } template <class T> std::vector<T> Read(const Allocator::ManageDataPtr& ddata, std::size_t sz) { std::vector<T> result(sz); this->ReadTo(result.data(), ddata, sz * sizeof(T)); return result; } static std::string GetDbBasename(const TargetProperties& target, size_t num_cu) { auto ret = target.DbId() + [&]() { std::ostringstream ss; if(num_cu <= 64) ss << '_' << num_cu; else ss << std::hex << num_cu; return std::string(ss.str()); }(); return ret; } std::string GetDbBasename() const { return GetDbBasename(GetTargetProperties(), GetMaxComputeUnits()); } std::unique_ptr<HandleImpl> impl; std::unordered_map<std::string, std::vector<miopenConvSolution_t>> find_map; #if MIOPEN_USE_MIOPENGEMM std::unordered_map<GemmKey, std::unique_ptr<GemmGeometry>, SimpleHash> geo_map; #endif Invoker PrepareInvoker(const InvokerFactory& factory, const std::vector<solver::KernelInfo>& kernels) const; void RegisterInvoker(const Invoker& invoker, const NetworkConfig& config, const std::string& solver, const boost::optional<AlgorithmName>& algo = boost::none) { invokers.Register({config, solver}, invoker); if(algo.has_value()) invokers.SetAsFound1_0(config, *algo, solver); } boost::optional<const Invoker&> GetInvoker(const NetworkConfig& config, const boost::optional<solver::Id>& solver, const boost::optional<AlgorithmName>& algo = boost::none) const { assert(solver || algo); assert(!(solver && algo)); if(solver) { MIOPEN_LOG_I2("Returning an invoker for problem " << config.ToString() << " and solver " << solver->ToString()); return invokers[std::make_pair(config.ToString(), solver->ToString())]; } MIOPEN_LOG_I2("Returning an invoker for problem " << config.ToString() << " and algorithm " << algo->ToString()); return invokers.GetFound1_0(config, *algo); } boost::optional<const std::string&> GetFound1_0SolverId(const NetworkConfig& config, const AlgorithmName& algo) const { return invokers.GetFound1_0SolverId(config, algo); } #if MIOPEN_USE_ROCBLAS const rocblas_handle_ptr& rhandle() const { return rhandle_; } private: rocblas_handle_ptr CreateRocblasHandle() const; rocblas_handle_ptr rhandle_; #else private: #endif InvokerCache invokers; }; inline std::ostream& operator<<(std::ostream& os, const Handle& handle) { return handle.Print(os); } struct AutoEnableProfiling { AutoEnableProfiling(const Handle& x) : h(x) { prev_state = h.IsProfilingEnabled(); h.EnableProfiling(); } ~AutoEnableProfiling() { h.EnableProfiling(prev_state); h.ResetKernelTime(); } private: const Handle& h; bool prev_state; }; } // namespace miopen MIOPEN_DEFINE_OBJECT(miopenHandle, miopen::Handle); #endif // GUARD_MIOPEN_HANDLE_HPP_ <|endoftext|>
<commit_before>//MIT License // //Copyright(c) 2016 Matthias Moeller // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files(the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and / or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions : // //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. #ifndef __TYTI_STEAM_VDF_PARSER_H__ #define __TYTI_STEAM_VDF_PARSER_H__ #include <unordered_map> #include <utility> #include <fstream> #include <memory> #include <system_error> #include <exception> //for wstring support #include <locale> #include <codecvt> #include <string> // internal #include <stack> //VS < 2015 has only partial C++11 support #if defined(_MSC_VER) && _MSC_VER < 1900 #ifndef CONSTEXPR #define CONSTEXPR #endif #ifndef NOEXCEPT #define NOEXCEPT #endif #else #ifndef CONSTEXPR #define CONSTEXPR constexpr #define TYTI_UNDEF_CONSTEXPR #endif #ifndef NOEXCEPT #define NOEXCEPT noexcept #define TYTI_UNDEF_NOEXCEPT #endif #endif namespace tyti { namespace vdf { namespace detail { /////////////////////////////////////////////////////////////////////////// // Helper functions selecting the right encoding (char/wchar_T) /////////////////////////////////////////////////////////////////////////// template<typename T> struct literal_macro_help { static CONSTEXPR const char* result(const char* c, const wchar_t* wc) NOEXCEPT { return c; } static CONSTEXPR const char result(const char c, const wchar_t wc) NOEXCEPT { return c; } }; template<> struct literal_macro_help<wchar_t> { static CONSTEXPR const wchar_t* result(const char* c, const wchar_t* wc) NOEXCEPT { return wc; } static CONSTEXPR const wchar_t result(const char c, const wchar_t wc) NOEXCEPT { return wc; } }; #define TYTI_L(type, text) vdf::detail::literal_macro_help<type>::result(text, L##text) inline std::string string_converter(const std::string& w) NOEXCEPT { return w; } inline std::string string_converter(const std::wstring& w) { std::wstring_convert<std::codecvt_utf8<wchar_t>> conv1; // maybe wrong econding return conv1.to_bytes(w); } /////////////////////////////////////////////////////////////////////////// // Writer helper functions /////////////////////////////////////////////////////////////////////////// template<typename charT> class tabs { size_t t; public: explicit tabs(size_t i) :t( i ) {} std::basic_string<charT> print() const { return std::basic_string<charT>(t, TYTI_L(charT,'\t')); } tabs operator+(size_t i) const NOEXCEPT { tabs r(*this); r.t += i; return r; } }; template<typename oStreamT> oStreamT& operator<<(oStreamT& s, const tabs<typename oStreamT::char_type> t) { s << t.print(); return s; } } // end namespace detail /////////////////////////////////////////////////////////////////////////// // Interface /////////////////////////////////////////////////////////////////////////// /// basic object node. Every object has a name and can contains attributes saved as key_value pairs or childrens template<typename CharT> struct basic_object { typedef CharT char_type; std::basic_string<char_type> name; std::unordered_map<std::basic_string<char_type>, std::basic_string<char_type> > attribs; std::unordered_map<std::basic_string<char_type>, std::shared_ptr< basic_object<char_type> > > childs; }; typedef basic_object<char> object; typedef basic_object<wchar_t> wobject; /** \brief writes given object tree in vdf format to given stream. Uses tabs instead of whitespaces. */ template<typename oStreamT> void write(oStreamT& s, const basic_object<typename oStreamT::char_type>& r, const detail::tabs<typename oStreamT::char_type> tab = detail::tabs<typename oStreamT::char_type>( 0 )) { typedef typename oStreamT::char_type charT; using namespace detail; typedef tabs<charT> tabs; s << tab << TYTI_L(charT, '"') << r.name << TYTI_L(charT, "\"\n") << tab << TYTI_L(charT, "{\n"); for (const auto& i : r.attribs) s << tab+1 << TYTI_L(charT, '"') << i.first << TYTI_L(charT, "\"\t\t\"") << i.second << TYTI_L(charT, "\"\n"); for (const auto& i : r.childs) write(s, *i.second, tab+1 ); s << tab << TYTI_L(charT, "}\n"); } //forward decls //forward decl template<typename iStreamT> basic_object<typename iStreamT::char_type> read(iStreamT& inStream, std::error_code& ec); /** \brief Read VDF formatted sequences defined by the range [first, last). If the file is mailformatted, parser will try to read it until it can. @param first begin iterator @param end end iterator @param ec output bool. 0 if ok, otherwise, holds an system error code Possible error codes: std::errc::protocol_error: file is mailformatted std::errc::not_enough_memory: not enough space std::errc::invalid_argument: iterators throws e.g. out of range */ template<typename IterT> basic_object<typename IterT::value_type> read(IterT first, IterT last, std::error_code& ec) NOEXCEPT { typedef typename IterT::value_type charT; ec.clear(); basic_object<charT> root; basic_object<charT>* cur = &root; std::stack< basic_object<charT>* > lvls; //read header // first, quoted name auto b = std::find(first, last, TYTI_L(charT, '\"')); auto bend = std::find(b + 1, last, TYTI_L(charT, '\"')); root.name = std::basic_string<charT>(b + 1, bend); // second, get {} b = std::find(bend, last, TYTI_L(charT, '{')); try { if (b == last) { ec = std::make_error_code(std::errc::protocol_error); return root; } else lvls.push(&root); while (!lvls.empty() && b != last) { const std::basic_string<charT> startsym = TYTI_L(charT, "\"}"); //find first starting attrib/child, or ending b = std::find_first_of(b, last, std::begin(startsym), std::end(startsym)); if (*b == '\"') { // get key bend = std::find(b + 1, last, TYTI_L(charT, '\"')); if (bend == last) { ec = std::make_error_code(std::errc::protocol_error);// could not find end of name return root; } std::basic_string<charT> key(b + 1, bend); b = bend + 1; const std::basic_string<charT> ecspsym = TYTI_L(charT, "\"{"); b = std::find_first_of(b, last, std::begin(ecspsym), std::end(ecspsym)); if (b == last) { ec = std::make_error_code(std::errc::protocol_error);// could not find 2nd part of pair return root; } // get value if (*b == '\"') { bend = std::find(b + 1, last, TYTI_L(charT, '\"')); if (bend == last) { ec = std::make_error_code(std::errc::protocol_error);//could not find end of name return root; } auto value = std::basic_string<charT>(b + 1, bend); b = bend + 1; // process value if (key != TYTI_L(charT, "#include") && key != TYTI_L(charT, "#base")) { cur->attribs[key] = std::move(value); } else { std::basic_ifstream<charT> i(detail::string_converter(std::move(value))); auto n = std::make_shared<basic_object<charT>>(read(i, ec)); if (ec) return root; cur->childs[n->name] = std::move(n); } } else if (*b == '{') { lvls.push(cur); auto n = std::make_shared<basic_object<charT>>(); cur->childs[key] = n; cur = n.get(); cur->name = std::move(key); ++b; } } else if (*b == '}') { cur = lvls.top(); lvls.pop(); ++b; } } } catch (std::bad_alloc& ) { ec = std::make_error_code(std::errc::not_enough_memory); } catch (...) { ec = std::make_error_code(std::errc::invalid_argument); } return root; } /** \brief Read VDF formatted sequences defined by the range [first, last). If the file is mailformatted, parser will try to read it until it can. @param first begin iterator @param end end iterator @param ok output bool. true, if parser successed, false, if parser failed */ template<typename IterT> basic_object<typename IterT::value_type> read(IterT first, const IterT last, bool* ok) NOEXCEPT { std::error_code ec; auto r = read(first, last, ec); if (ok) *ok = !ec; return r; } /** \brief Read VDF formatted sequences defined by the range [first, last). If the file is mailformatted, parser will try to read it until it can. @param first begin iterator @param end end iterator throws a "std::system_error" if a parsing error occured */ template<typename IterT> basic_object<typename IterT::value_type> read(IterT first, const IterT last) { std::error_code ec; const auto r = read(first, last, ec); if (!ec) throw std::system_error(ec); return r; } /** \brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data. throws "std::bad_alloc" if file buffer could not be allocated */ template<typename iStreamT> basic_object<typename iStreamT::char_type> read(iStreamT& inStream, std::error_code& ec) { // cache the file typedef typename iStreamT::char_type charT; std::basic_string<charT> str; inStream.seekg(0, std::ios::end); str.resize(static_cast<size_t>(inStream.tellg())); if (str.empty()) return basic_object<charT>(); inStream.seekg(0, std::ios::beg); inStream.read(&str[0], str.size()); inStream.close(); // parse it return read(str.begin(), str.end(), ec); } /** \brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data. throws "std::bad_alloc" if file buffer could not be allocated ok == false, if a parsing error occured */ template<typename iStreamT> basic_object<typename iStreamT::char_type> read(iStreamT& inStream, bool* ok) { std::error_code ec; const auto r = read(inStream, ec); if (ok) *ok = !ec; return r; } /** \brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data. throws "std::bad_alloc" if file buffer could not be allocated throws "std::system_error" if a parsing error occured */ template<typename iStreamT> basic_object<typename iStreamT::char_type> read(iStreamT& inStream) { std::error_code ec; const auto r = read(inStream, ec); if (!ec) throw std::system_error(ec); return r; } } // end namespace vdf } // end namespace tyti #ifndef TYTI_NO_L_UNDEF #undef TYTI_L #endif #ifdef TYTI_UNDEF_CONSTEXPR #undef CONSTEXPR #endif #ifdef TYTI_UNDEF_NOTHROW #undef NOTHROW #endif #endif //__TYTI_STEAM_VDF_PARSER_H__ <commit_msg>undef def guards<commit_after>//MIT License // //Copyright(c) 2016 Matthias Moeller // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files(the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and / or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions : // //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. #ifndef __TYTI_STEAM_VDF_PARSER_H__ #define __TYTI_STEAM_VDF_PARSER_H__ #include <unordered_map> #include <utility> #include <fstream> #include <memory> #include <system_error> #include <exception> //for wstring support #include <locale> #include <codecvt> #include <string> // internal #include <stack> //VS < 2015 has only partial C++11 support #if defined(_MSC_VER) && _MSC_VER < 1900 #ifndef CONSTEXPR #define CONSTEXPR #endif #ifndef NOEXCEPT #define NOEXCEPT #endif #else #ifndef CONSTEXPR #define CONSTEXPR constexpr #define TYTI_UNDEF_CONSTEXPR #endif #ifndef NOEXCEPT #define NOEXCEPT noexcept #define TYTI_UNDEF_NOEXCEPT #endif #endif namespace tyti { namespace vdf { namespace detail { /////////////////////////////////////////////////////////////////////////// // Helper functions selecting the right encoding (char/wchar_T) /////////////////////////////////////////////////////////////////////////// template<typename T> struct literal_macro_help { static CONSTEXPR const char* result(const char* c, const wchar_t* wc) NOEXCEPT { return c; } static CONSTEXPR const char result(const char c, const wchar_t wc) NOEXCEPT { return c; } }; template<> struct literal_macro_help<wchar_t> { static CONSTEXPR const wchar_t* result(const char* c, const wchar_t* wc) NOEXCEPT { return wc; } static CONSTEXPR const wchar_t result(const char c, const wchar_t wc) NOEXCEPT { return wc; } }; #define TYTI_L(type, text) vdf::detail::literal_macro_help<type>::result(text, L##text) inline std::string string_converter(const std::string& w) NOEXCEPT { return w; } inline std::string string_converter(const std::wstring& w) { std::wstring_convert<std::codecvt_utf8<wchar_t>> conv1; // maybe wrong econding return conv1.to_bytes(w); } /////////////////////////////////////////////////////////////////////////// // Writer helper functions /////////////////////////////////////////////////////////////////////////// template<typename charT> class tabs { size_t t; public: explicit tabs(size_t i) :t( i ) {} std::basic_string<charT> print() const { return std::basic_string<charT>(t, TYTI_L(charT,'\t')); } tabs operator+(size_t i) const NOEXCEPT { tabs r(*this); r.t += i; return r; } }; template<typename oStreamT> oStreamT& operator<<(oStreamT& s, const tabs<typename oStreamT::char_type> t) { s << t.print(); return s; } } // end namespace detail /////////////////////////////////////////////////////////////////////////// // Interface /////////////////////////////////////////////////////////////////////////// /// basic object node. Every object has a name and can contains attributes saved as key_value pairs or childrens template<typename CharT> struct basic_object { typedef CharT char_type; std::basic_string<char_type> name; std::unordered_map<std::basic_string<char_type>, std::basic_string<char_type> > attribs; std::unordered_map<std::basic_string<char_type>, std::shared_ptr< basic_object<char_type> > > childs; }; typedef basic_object<char> object; typedef basic_object<wchar_t> wobject; /** \brief writes given object tree in vdf format to given stream. Uses tabs instead of whitespaces. */ template<typename oStreamT> void write(oStreamT& s, const basic_object<typename oStreamT::char_type>& r, const detail::tabs<typename oStreamT::char_type> tab = detail::tabs<typename oStreamT::char_type>( 0 )) { typedef typename oStreamT::char_type charT; using namespace detail; typedef tabs<charT> tabs; s << tab << TYTI_L(charT, '"') << r.name << TYTI_L(charT, "\"\n") << tab << TYTI_L(charT, "{\n"); for (const auto& i : r.attribs) s << tab+1 << TYTI_L(charT, '"') << i.first << TYTI_L(charT, "\"\t\t\"") << i.second << TYTI_L(charT, "\"\n"); for (const auto& i : r.childs) write(s, *i.second, tab+1 ); s << tab << TYTI_L(charT, "}\n"); } //forward decls //forward decl template<typename iStreamT> basic_object<typename iStreamT::char_type> read(iStreamT& inStream, std::error_code& ec); /** \brief Read VDF formatted sequences defined by the range [first, last). If the file is mailformatted, parser will try to read it until it can. @param first begin iterator @param end end iterator @param ec output bool. 0 if ok, otherwise, holds an system error code Possible error codes: std::errc::protocol_error: file is mailformatted std::errc::not_enough_memory: not enough space std::errc::invalid_argument: iterators throws e.g. out of range */ template<typename IterT> basic_object<typename IterT::value_type> read(IterT first, IterT last, std::error_code& ec) NOEXCEPT { typedef typename IterT::value_type charT; ec.clear(); basic_object<charT> root; basic_object<charT>* cur = &root; std::stack< basic_object<charT>* > lvls; //read header // first, quoted name auto b = std::find(first, last, TYTI_L(charT, '\"')); auto bend = std::find(b + 1, last, TYTI_L(charT, '\"')); root.name = std::basic_string<charT>(b + 1, bend); // second, get {} b = std::find(bend, last, TYTI_L(charT, '{')); try { if (b == last) { ec = std::make_error_code(std::errc::protocol_error); return root; } else lvls.push(&root); while (!lvls.empty() && b != last) { const std::basic_string<charT> startsym = TYTI_L(charT, "\"}"); //find first starting attrib/child, or ending b = std::find_first_of(b, last, std::begin(startsym), std::end(startsym)); if (*b == '\"') { // get key bend = std::find(b + 1, last, TYTI_L(charT, '\"')); if (bend == last) { ec = std::make_error_code(std::errc::protocol_error);// could not find end of name return root; } std::basic_string<charT> key(b + 1, bend); b = bend + 1; const std::basic_string<charT> ecspsym = TYTI_L(charT, "\"{"); b = std::find_first_of(b, last, std::begin(ecspsym), std::end(ecspsym)); if (b == last) { ec = std::make_error_code(std::errc::protocol_error);// could not find 2nd part of pair return root; } // get value if (*b == '\"') { bend = std::find(b + 1, last, TYTI_L(charT, '\"')); if (bend == last) { ec = std::make_error_code(std::errc::protocol_error);//could not find end of name return root; } auto value = std::basic_string<charT>(b + 1, bend); b = bend + 1; // process value if (key != TYTI_L(charT, "#include") && key != TYTI_L(charT, "#base")) { cur->attribs[key] = std::move(value); } else { std::basic_ifstream<charT> i(detail::string_converter(std::move(value))); auto n = std::make_shared<basic_object<charT>>(read(i, ec)); if (ec) return root; cur->childs[n->name] = std::move(n); } } else if (*b == '{') { lvls.push(cur); auto n = std::make_shared<basic_object<charT>>(); cur->childs[key] = n; cur = n.get(); cur->name = std::move(key); ++b; } } else if (*b == '}') { cur = lvls.top(); lvls.pop(); ++b; } } } catch (std::bad_alloc& ) { ec = std::make_error_code(std::errc::not_enough_memory); } catch (...) { ec = std::make_error_code(std::errc::invalid_argument); } return root; } /** \brief Read VDF formatted sequences defined by the range [first, last). If the file is mailformatted, parser will try to read it until it can. @param first begin iterator @param end end iterator @param ok output bool. true, if parser successed, false, if parser failed */ template<typename IterT> basic_object<typename IterT::value_type> read(IterT first, const IterT last, bool* ok) NOEXCEPT { std::error_code ec; auto r = read(first, last, ec); if (ok) *ok = !ec; return r; } /** \brief Read VDF formatted sequences defined by the range [first, last). If the file is mailformatted, parser will try to read it until it can. @param first begin iterator @param end end iterator throws a "std::system_error" if a parsing error occured */ template<typename IterT> basic_object<typename IterT::value_type> read(IterT first, const IterT last) { std::error_code ec; const auto r = read(first, last, ec); if (!ec) throw std::system_error(ec); return r; } /** \brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data. throws "std::bad_alloc" if file buffer could not be allocated */ template<typename iStreamT> basic_object<typename iStreamT::char_type> read(iStreamT& inStream, std::error_code& ec) { // cache the file typedef typename iStreamT::char_type charT; std::basic_string<charT> str; inStream.seekg(0, std::ios::end); str.resize(static_cast<size_t>(inStream.tellg())); if (str.empty()) return basic_object<charT>(); inStream.seekg(0, std::ios::beg); inStream.read(&str[0], str.size()); inStream.close(); // parse it return read(str.begin(), str.end(), ec); } /** \brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data. throws "std::bad_alloc" if file buffer could not be allocated ok == false, if a parsing error occured */ template<typename iStreamT> basic_object<typename iStreamT::char_type> read(iStreamT& inStream, bool* ok) { std::error_code ec; const auto r = read(inStream, ec); if (ok) *ok = !ec; return r; } /** \brief Loads a stream (e.g. filestream) into the memory and parses the vdf formatted data. throws "std::bad_alloc" if file buffer could not be allocated throws "std::system_error" if a parsing error occured */ template<typename iStreamT> basic_object<typename iStreamT::char_type> read(iStreamT& inStream) { std::error_code ec; const auto r = read(inStream, ec); if (!ec) throw std::system_error(ec); return r; } } // end namespace vdf } // end namespace tyti #ifndef TYTI_NO_L_UNDEF #undef TYTI_L #endif #ifdef TYTI_UNDEF_CONSTEXPR #undef CONSTEXPR #undef TYTI_NO_L_UNDEF #endif #ifdef TYTI_UNDEF_NOTHROW #undef NOTHROW #undef TYTI_UNDEF_NOTHROW #endif #endif //__TYTI_STEAM_VDF_PARSER_H__ <|endoftext|>
<commit_before>/* indivudal.cpp - CS 472 Project #2: Genetic Programming * Copyright 2014 Andrew Schwartzmeyer * * Source file for individual namespace */ #include <algorithm> #include <cassert> #include <cmath> #include <iostream> #include <memory> #include <tuple> #include <vector> #include "individual.hpp" #include "../options/options.hpp" #include "../random_generator/random_generator.hpp" namespace individual { using std::vector; using std::string; using options::Options; using namespace random_generator; // vectors of same-arity function enums vector<Function> nullaries{constant, input}; vector<Function> unaries{sqrt, sin, cos, log, exp}; vector<Function> binaries{add, subtract, multiply, divide, pow}; vector<Function> quadnaries{lesser, greater}; vector<Function> internals{sin, cos, add, subtract, multiply, divide, lesser, greater}; template<typename I, typename S> bool contains(const I & item, const S & set) { return std::find(set.begin(), set.end(), item) != set.end(); } Function get_internal() { int_dist dist{0, int(internals.size()) - 1}; // closed interval return Function(internals[dist(rg.engine)]); } Function get_leaf() { int_dist dist{0, int(nullaries.size()) - 1}; // closed interval return Function(nullaries[dist(rg.engine)]); } double get_constant(const double & min, const double & max) { real_dist dist{min, max}; return dist(rg.engine); } int get_arity(const Function & function) { if (contains(function, nullaries)) return 0; else if (contains(function, unaries)) return 1; else if (contains(function, binaries)) return 2; else if (contains(function, quadnaries)) return 4; assert(false); } Node::Node(const Options & options, const Method & method, const int & max_depth) { real_dist dist{0, 1}; double grow_chance = double(nullaries.size()) / double(nullaries.size() + internals.size()); if (max_depth == 0 or (method == grow and dist(rg.engine) < grow_chance)) { function = get_leaf(); arity = get_arity(function); assert(arity == 0); // setup constant function; input is provided on evaluation if (function == constant) { // choose a random value between the options's min and max k = get_constant(options.constant_min, options.constant_max); } } else { function = get_internal(); assert(contains(function, internals)); // determine node's arity arity = get_arity(function); assert(arity != 0); // recursively create subtrees for (int i = 0; i < arity; ++i) children.emplace_back(Node{options, method, max_depth - 1}); } assert(int(children.size()) == arity); // ensure arity assert(function != null); // do not create null types } string Node::represent() const { switch(function) { case null: assert(false); // never represent empty node case constant: return std::to_string(k); case input: return "x"; case sqrt: return "sqrt"; case sin: return "sin"; case cos: return "cos"; case log: return "log"; case exp: return "exp"; case add: return "+"; case subtract: return "-"; case multiply: return "*"; case divide: return "%"; case pow: return "^"; case lesser: return "<"; case greater: return ">"; } assert(false); } string Node::print() const { // Pre-order traversal print of expression in Polish/prefix notation if (children.size() == 0) return represent(); string formula = "(" + represent(); for (const Node & child : children) formula += " " + child.print(); return formula + ")"; } double Node::evaluate(const double & x) const { // depth-first post-order recursive evaluation tree double a, b; if (arity == 1) a = children[0].evaluate(x); else if (arity == 2 or arity == 4) { // children c and d are evaluated conditionally a = children[0].evaluate(x); b = children[1].evaluate(x); } // calculate the result switch(function) { case null: assert(false); // never calculate empty node case constant: assert(arity == 0); return k; case input: assert(arity == 0); return x; case sqrt: assert(arity == 1); return std::sqrt(std::abs(a)); // protected case sin: assert(arity == 1); return std::sin(a); case cos: assert(arity == 1); return std::cos(a); case log: assert(arity == 1); return (a == 0) ? 0 : std::log(std::abs(a)); // protected case exp: assert(arity == 1); return std::exp(a); case add: assert(arity == 2); return a + b; case subtract: assert(arity == 2); return a - b; case multiply: assert(arity == 2); return a * b; case divide: assert(arity == 2); return (b == 0) ? 1 : a / b; // protected case pow: assert(arity == 2); return std::pow(std::abs(a), std::abs(b)); // protected case lesser: assert(arity == 4); return (a < b) ? children[2].evaluate(x) : children[3].evaluate(x); case greater: assert(arity == 4); return (a > b) ? children[2].evaluate(x) : children[3].evaluate(x); } assert(false); } const Size Node::size() const { // recursively count children via post-order traversal // keep track of internals and leafs via Size struct Size size; for (const Node & child : children) { Size temp = child.size(); // is this micro-optimizing? size.internals += temp.internals; size.leafs += temp.leafs; } if (children.size() == 0) ++size.leafs; else ++size.internals; return size; } Node empty; Node & Node::visit(const Size & i, Size & visiting) { // depth-first search for taget node, either internal or leaf for (Node & child : children) { // increase relevant count if (child.children.size() == 0) ++visiting.leafs; else ++visiting.internals; // return node reference if found if (visiting.internals == i.internals or visiting.leafs == i.leafs) return child; Node & temp = child.visit(i, visiting); // mark each node if (temp.function != null) return temp; // return found node } return empty; // need to indicate "not-found" } void Node::mutate_self() { // single node mutation to different function of same arity if (arity == 0) { // mutate constant to a value in its neighborhood, don't switch functions if (function == constant) { normal_dist dist{0, 1}; k *= 1 + dist(rg.engine); } } else if (arity == 1) { int_dist dist{0, int(unaries.size()) - 1}; Function prior = function; // ensure we're using a specified available function while (function == prior or not contains(function, internals)) function = Function(unaries[dist(rg.engine)]); } else if (arity == 2) { int_dist dist{0, int(binaries.size()) - 1}; Function prior = function; while (function == prior or not contains(function, internals)) function = Function(binaries[dist(rg.engine)]); } else if (arity == 4) { int_dist dist{0, int(quadnaries.size()) - 1}; Function prior = function; while (function == prior or not contains(function, internals)) function = Function(quadnaries[dist(rg.engine)]); } assert(function != null); } void Node::mutate_tree(const double & chance) { // recursively mutate nodes with options.mutate_chance probability real_dist dist{0, 1}; for (Node & child : children) { if (dist(rg.engine) < chance) child.mutate_self(); child.mutate_tree(chance); } } Individual::Individual(const Options & options, const Method method, const int depth): root{Node{options, method, depth}} { evaluate(options.values); } string Individual::print() const { using std::to_string; string info = "Size " + to_string(get_total()) + ", with " + to_string(get_internals()) + " internals, and " + to_string(get_leafs()) + " leafs.\n" + "Raw fitness: " + to_string(get_fitness()) + ", and adjusted: " + to_string(get_adjusted()) + ".\n"; return info; } string Individual::print_formula() const { return "Formula: " + root.print() + "\n"; } string Individual::evaluate(const options::pairs & values, const double & penalty, const bool & print) { using std::to_string; using std::get; string calculation = "# x - y - expected - error\n"; // update size on evaluation because it's incredibly convenient size = root.size(); fitness = penalty * get_total(); // reset fitness and apply scaled size penalty for (auto pair : values) { double x = std::get<0>(pair); double y = root.evaluate(x); assert(not std::isnan(y) and not std::isinf(y)); double expected = std::get<1>(pair); double error = std::pow(y - expected, 2); fitness += error; if (print) calculation += to_string(x) + "\t" + to_string(y) + "\t" + to_string(expected) + "\t" + to_string(error) + "\n"; } return calculation; } void Individual::mutate(const double & chance) { // mutate each node with a options.mutate_chance probability root.mutate_tree(chance); } Node & Individual::operator[](const Size & i) { assert(i.internals <= get_internals()); assert(i.leafs <= get_leafs()); Size visiting; if (i.internals == 0 and i.leafs == 0) // seeking root return root; return root.visit(i, visiting); } void crossover(const double & chance, Individual & a, Individual & b) { real_dist probability{0, 1}; Size target_a, target_b; // guaranteed to have at least 1 leaf, but may have 0 internals (root as leaf) if (a.get_internals() != 0 and probability(rg.engine) < chance) { // choose an internal node int_dist dist{0, a.get_internals() - 1}; target_a.internals = dist(rg.engine); } else { // otherwise we choose a leaf node int_dist dist{0, a.get_leafs() - 1}; target_a.leafs = dist(rg.engine); } // do the same thing for the second individual if (b.get_internals() != 0 and probability(rg.engine) < chance) { int_dist dist{0, b.get_internals() - 1}; target_b.internals = dist(rg.engine); } else { int_dist dist{0, b.get_leafs() - 1}; target_b.leafs = dist(rg.engine); } // replace nodes std::swap(a[target_a], b[target_b]); } } <commit_msg>Prepending "#" to lines from print() and print_formula()<commit_after>/* indivudal.cpp - CS 472 Project #2: Genetic Programming * Copyright 2014 Andrew Schwartzmeyer * * Source file for individual namespace */ #include <algorithm> #include <cassert> #include <cmath> #include <iostream> #include <memory> #include <tuple> #include <vector> #include "individual.hpp" #include "../options/options.hpp" #include "../random_generator/random_generator.hpp" namespace individual { using std::vector; using std::string; using options::Options; using namespace random_generator; // vectors of same-arity function enums vector<Function> nullaries{constant, input}; vector<Function> unaries{sqrt, sin, cos, log, exp}; vector<Function> binaries{add, subtract, multiply, divide, pow}; vector<Function> quadnaries{lesser, greater}; vector<Function> internals{sin, cos, add, subtract, multiply, divide, lesser, greater}; template<typename I, typename S> bool contains(const I & item, const S & set) { return std::find(set.begin(), set.end(), item) != set.end(); } Function get_internal() { int_dist dist{0, int(internals.size()) - 1}; // closed interval return Function(internals[dist(rg.engine)]); } Function get_leaf() { int_dist dist{0, int(nullaries.size()) - 1}; // closed interval return Function(nullaries[dist(rg.engine)]); } double get_constant(const double & min, const double & max) { real_dist dist{min, max}; return dist(rg.engine); } int get_arity(const Function & function) { if (contains(function, nullaries)) return 0; else if (contains(function, unaries)) return 1; else if (contains(function, binaries)) return 2; else if (contains(function, quadnaries)) return 4; assert(false); } Node::Node(const Options & options, const Method & method, const int & max_depth) { real_dist dist{0, 1}; double grow_chance = double(nullaries.size()) / double(nullaries.size() + internals.size()); if (max_depth == 0 or (method == grow and dist(rg.engine) < grow_chance)) { function = get_leaf(); arity = get_arity(function); assert(arity == 0); // setup constant function; input is provided on evaluation if (function == constant) { // choose a random value between the options's min and max k = get_constant(options.constant_min, options.constant_max); } } else { function = get_internal(); assert(contains(function, internals)); // determine node's arity arity = get_arity(function); assert(arity != 0); // recursively create subtrees for (int i = 0; i < arity; ++i) children.emplace_back(Node{options, method, max_depth - 1}); } assert(int(children.size()) == arity); // ensure arity assert(function != null); // do not create null types } string Node::represent() const { switch(function) { case null: assert(false); // never represent empty node case constant: return std::to_string(k); case input: return "x"; case sqrt: return "sqrt"; case sin: return "sin"; case cos: return "cos"; case log: return "log"; case exp: return "exp"; case add: return "+"; case subtract: return "-"; case multiply: return "*"; case divide: return "%"; case pow: return "^"; case lesser: return "<"; case greater: return ">"; } assert(false); } string Node::print() const { // Pre-order traversal print of expression in Polish/prefix notation if (children.size() == 0) return represent(); string formula = "(" + represent(); for (const Node & child : children) formula += " " + child.print(); return formula + ")"; } double Node::evaluate(const double & x) const { // depth-first post-order recursive evaluation tree double a, b; if (arity == 1) a = children[0].evaluate(x); else if (arity == 2 or arity == 4) { // children c and d are evaluated conditionally a = children[0].evaluate(x); b = children[1].evaluate(x); } // calculate the result switch(function) { case null: assert(false); // never calculate empty node case constant: assert(arity == 0); return k; case input: assert(arity == 0); return x; case sqrt: assert(arity == 1); return std::sqrt(std::abs(a)); // protected case sin: assert(arity == 1); return std::sin(a); case cos: assert(arity == 1); return std::cos(a); case log: assert(arity == 1); return (a == 0) ? 0 : std::log(std::abs(a)); // protected case exp: assert(arity == 1); return std::exp(a); case add: assert(arity == 2); return a + b; case subtract: assert(arity == 2); return a - b; case multiply: assert(arity == 2); return a * b; case divide: assert(arity == 2); return (b == 0) ? 1 : a / b; // protected case pow: assert(arity == 2); return std::pow(std::abs(a), std::abs(b)); // protected case lesser: assert(arity == 4); return (a < b) ? children[2].evaluate(x) : children[3].evaluate(x); case greater: assert(arity == 4); return (a > b) ? children[2].evaluate(x) : children[3].evaluate(x); } assert(false); } const Size Node::size() const { // recursively count children via post-order traversal // keep track of internals and leafs via Size struct Size size; for (const Node & child : children) { Size temp = child.size(); // is this micro-optimizing? size.internals += temp.internals; size.leafs += temp.leafs; } if (children.size() == 0) ++size.leafs; else ++size.internals; return size; } Node empty; Node & Node::visit(const Size & i, Size & visiting) { // depth-first search for taget node, either internal or leaf for (Node & child : children) { // increase relevant count if (child.children.size() == 0) ++visiting.leafs; else ++visiting.internals; // return node reference if found if (visiting.internals == i.internals or visiting.leafs == i.leafs) return child; Node & temp = child.visit(i, visiting); // mark each node if (temp.function != null) return temp; // return found node } return empty; // need to indicate "not-found" } void Node::mutate_self() { // single node mutation to different function of same arity if (arity == 0) { // mutate constant to a value in its neighborhood, don't switch functions if (function == constant) { normal_dist dist{0, 1}; k *= 1 + dist(rg.engine); } } else if (arity == 1) { int_dist dist{0, int(unaries.size()) - 1}; Function prior = function; // ensure we're using a specified available function while (function == prior or not contains(function, internals)) function = Function(unaries[dist(rg.engine)]); } else if (arity == 2) { int_dist dist{0, int(binaries.size()) - 1}; Function prior = function; while (function == prior or not contains(function, internals)) function = Function(binaries[dist(rg.engine)]); } else if (arity == 4) { int_dist dist{0, int(quadnaries.size()) - 1}; Function prior = function; while (function == prior or not contains(function, internals)) function = Function(quadnaries[dist(rg.engine)]); } assert(function != null); } void Node::mutate_tree(const double & chance) { // recursively mutate nodes with options.mutate_chance probability real_dist dist{0, 1}; for (Node & child : children) { if (dist(rg.engine) < chance) child.mutate_self(); child.mutate_tree(chance); } } Individual::Individual(const Options & options, const Method method, const int depth): root{Node{options, method, depth}} { evaluate(options.values); } string Individual::print() const { using std::to_string; string info = "# Size " + to_string(get_total()) + ", with " + to_string(get_internals()) + " internals, and " + to_string(get_leafs()) + " leafs.\n" + "# Raw fitness: " + to_string(get_fitness()) + ", and adjusted: " + to_string(get_adjusted()) + ".\n"; return info; } string Individual::print_formula() const { return "# Formula: " + root.print() + "\n"; } string Individual::evaluate(const options::pairs & values, const double & penalty, const bool & print) { using std::to_string; using std::get; string calculation = "# x - y - expected - error\n"; // update size on evaluation because it's incredibly convenient size = root.size(); fitness = penalty * get_total(); // reset fitness and apply scaled size penalty for (auto pair : values) { double x = std::get<0>(pair); double y = root.evaluate(x); assert(not std::isnan(y) and not std::isinf(y)); double expected = std::get<1>(pair); double error = std::pow(y - expected, 2); fitness += error; if (print) calculation += to_string(x) + "\t" + to_string(y) + "\t" + to_string(expected) + "\t" + to_string(error) + "\n"; } return calculation; } void Individual::mutate(const double & chance) { // mutate each node with a options.mutate_chance probability root.mutate_tree(chance); } Node & Individual::operator[](const Size & i) { assert(i.internals <= get_internals()); assert(i.leafs <= get_leafs()); Size visiting; if (i.internals == 0 and i.leafs == 0) // seeking root return root; return root.visit(i, visiting); } void crossover(const double & chance, Individual & a, Individual & b) { real_dist probability{0, 1}; Size target_a, target_b; // guaranteed to have at least 1 leaf, but may have 0 internals (root as leaf) if (a.get_internals() != 0 and probability(rg.engine) < chance) { // choose an internal node int_dist dist{0, a.get_internals() - 1}; target_a.internals = dist(rg.engine); } else { // otherwise we choose a leaf node int_dist dist{0, a.get_leafs() - 1}; target_a.leafs = dist(rg.engine); } // do the same thing for the second individual if (b.get_internals() != 0 and probability(rg.engine) < chance) { int_dist dist{0, b.get_internals() - 1}; target_b.internals = dist(rg.engine); } else { int_dist dist{0, b.get_leafs() - 1}; target_b.leafs = dist(rg.engine); } // replace nodes std::swap(a[target_a], b[target_b]); } } <|endoftext|>
<commit_before>#include "unittest.h" #include "rapidjson/document.h" #include "rapidjson/reader.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" using namespace rapidjson; TEST(Writer, Compact) { StringStream s("{ \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] } "); StringBuffer buffer; Writer<StringBuffer> writer(buffer); Reader reader; reader.Parse<0>(s, writer); EXPECT_STREQ("{\"hello\":\"world\",\"t\":true,\"f\":false,\"n\":null,\"i\":123,\"pi\":3.1416,\"a\":[1,2,3]}", buffer.GetString()); EXPECT_EQ(77u, buffer.GetSize()); } // json -> parse -> writer -> json #define TEST_ROUNDTRIP(json) \ { \ StringStream s(json); \ StringBuffer buffer; \ Writer<StringBuffer> writer(buffer); \ Reader reader; \ reader.Parse<0>(s, writer); \ EXPECT_STREQ(json, buffer.GetString()); \ } TEST(Writer, Int) { TEST_ROUNDTRIP("[-1]"); TEST_ROUNDTRIP("[-123]"); TEST_ROUNDTRIP("[-2147483648]"); } TEST(Writer, UInt) { TEST_ROUNDTRIP("[0]"); TEST_ROUNDTRIP("[1]"); TEST_ROUNDTRIP("[123]"); TEST_ROUNDTRIP("[2147483647]"); TEST_ROUNDTRIP("[4294967295]"); } TEST(Writer, Int64) { TEST_ROUNDTRIP("[-1234567890123456789]"); TEST_ROUNDTRIP("[-9223372036854775808]"); } TEST(Writer, Uint64) { TEST_ROUNDTRIP("[1234567890123456789]"); TEST_ROUNDTRIP("[9223372036854775807]"); } TEST(Writer, String) { TEST_ROUNDTRIP("[\"Hello\"]"); TEST_ROUNDTRIP("[\"Hello\\u0000World\"]"); TEST_ROUNDTRIP("[\"\\\"\\\\/\\b\\f\\n\\r\\t\"]"); } TEST(Writer,DoublePrecision) { const char json[] = "[1.2345,1.2345678,0.123456789012,1234567.8]"; StringBuffer buffer; Writer<StringBuffer> writer(buffer); const int kDefaultDoublePrecision = 6; // handling the double precision EXPECT_EQ(writer.GetDoublePrecision(), kDefaultDoublePrecision); writer.SetDoublePrecision(17); EXPECT_EQ(writer.GetDoublePrecision(), 17); writer.SetDoublePrecision(-1); // negative equivalent to reset EXPECT_EQ(writer.GetDoublePrecision(), kDefaultDoublePrecision); writer.SetDoublePrecision(1); writer.SetDoublePrecision(); // reset again EXPECT_EQ(writer.GetDoublePrecision(), kDefaultDoublePrecision); { // write with explicitly increased precision StringStream s(json); Reader reader; reader.Parse<0>(s, writer.SetDoublePrecision(12)); EXPECT_EQ(writer.GetDoublePrecision(), 12); EXPECT_STREQ(json, buffer.GetString()); buffer.Clear(); } { // explicit individual double precisions writer.SetDoublePrecision(2) .StartArray() .Double(1.2345,5) .Double(1.2345678,9) .Double(0.123456789012,12) .Double(1234567.8,8) .EndArray(); EXPECT_EQ(writer.GetDoublePrecision(), 2); EXPECT_STREQ(json, buffer.GetString()); buffer.Clear(); } { // write with default precision (output with precision loss) Document d; d.Parse<0>(json); d.Accept(writer.SetDoublePrecision()); // parsed again to avoid platform-dependent floating point outputs // (e.g. width of exponents) d.Parse<0>(buffer.GetString()); EXPECT_EQ(writer.GetDoublePrecision(), kDefaultDoublePrecision); EXPECT_DOUBLE_EQ(d[0u].GetDouble(), 1.2345); EXPECT_DOUBLE_EQ(d[1u].GetDouble(), 1.23457); EXPECT_DOUBLE_EQ(d[2u].GetDouble(), 0.123457); EXPECT_DOUBLE_EQ(d[3u].GetDouble(), 1234570); buffer.Clear(); } } TEST(Writer, Transcode) { // UTF8 -> UTF16 -> UTF8 StringStream s("{ \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3], \"dollar\":\"\x24\", \"cents\":\"\xC2\xA2\", \"euro\":\"\xE2\x82\xAC\", \"gclef\":\"\xF0\x9D\x84\x9E\" } "); StringBuffer buffer; Writer<StringBuffer, UTF16<>, UTF8<> > writer(buffer); GenericReader<UTF8<>, UTF16<> > reader; reader.Parse<0>(s, writer); EXPECT_STREQ("{\"hello\":\"world\",\"t\":true,\"f\":false,\"n\":null,\"i\":123,\"pi\":3.1416,\"a\":[1,2,3],\"dollar\":\"\x24\",\"cents\":\"\xC2\xA2\",\"euro\":\"\xE2\x82\xAC\",\"gclef\":\"\xF0\x9D\x84\x9E\"}", buffer.GetString()); } #include <sstream> class OStreamWrapper { public: typedef char Ch; OStreamWrapper(std::ostream& os) : os_(os) {} Ch Peek() const { assert(false); return '\0'; } Ch Take() { assert(false); return '\0'; } size_t Tell() const { } Ch* PutBegin() { assert(false); return 0; } void Put(Ch c) { os_.put(c); } void Flush() { os_.flush(); } size_t PutEnd(Ch*) { assert(false); return 0; } private: OStreamWrapper(const OStreamWrapper&); OStreamWrapper& operator=(const OStreamWrapper&); std::ostream& os_; }; TEST(Writer, OStreamWrapper) { StringStream s("{ \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] } "); std::stringstream ss; OStreamWrapper os(ss); Writer<OStreamWrapper> writer(os); Reader reader; reader.Parse<0>(s, writer); std::string actual = ss.str(); EXPECT_STREQ("{\"hello\":\"world\",\"t\":true,\"f\":false,\"n\":null,\"i\":123,\"pi\":3.1416,\"a\":[1,2,3]}", actual.c_str()); } <commit_msg>Fixes compilation error.<commit_after>#include "unittest.h" #include "rapidjson/document.h" #include "rapidjson/reader.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" using namespace rapidjson; TEST(Writer, Compact) { StringStream s("{ \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] } "); StringBuffer buffer; Writer<StringBuffer> writer(buffer); Reader reader; reader.Parse<0>(s, writer); EXPECT_STREQ("{\"hello\":\"world\",\"t\":true,\"f\":false,\"n\":null,\"i\":123,\"pi\":3.1416,\"a\":[1,2,3]}", buffer.GetString()); EXPECT_EQ(77u, buffer.GetSize()); } // json -> parse -> writer -> json #define TEST_ROUNDTRIP(json) \ { \ StringStream s(json); \ StringBuffer buffer; \ Writer<StringBuffer> writer(buffer); \ Reader reader; \ reader.Parse<0>(s, writer); \ EXPECT_STREQ(json, buffer.GetString()); \ } TEST(Writer, Int) { TEST_ROUNDTRIP("[-1]"); TEST_ROUNDTRIP("[-123]"); TEST_ROUNDTRIP("[-2147483648]"); } TEST(Writer, UInt) { TEST_ROUNDTRIP("[0]"); TEST_ROUNDTRIP("[1]"); TEST_ROUNDTRIP("[123]"); TEST_ROUNDTRIP("[2147483647]"); TEST_ROUNDTRIP("[4294967295]"); } TEST(Writer, Int64) { TEST_ROUNDTRIP("[-1234567890123456789]"); TEST_ROUNDTRIP("[-9223372036854775808]"); } TEST(Writer, Uint64) { TEST_ROUNDTRIP("[1234567890123456789]"); TEST_ROUNDTRIP("[9223372036854775807]"); } TEST(Writer, String) { TEST_ROUNDTRIP("[\"Hello\"]"); TEST_ROUNDTRIP("[\"Hello\\u0000World\"]"); TEST_ROUNDTRIP("[\"\\\"\\\\/\\b\\f\\n\\r\\t\"]"); } TEST(Writer,DoublePrecision) { const char json[] = "[1.2345,1.2345678,0.123456789012,1234567.8]"; StringBuffer buffer; Writer<StringBuffer> writer(buffer); const int kDefaultDoublePrecision = 6; // handling the double precision EXPECT_EQ(writer.GetDoublePrecision(), kDefaultDoublePrecision); writer.SetDoublePrecision(17); EXPECT_EQ(writer.GetDoublePrecision(), 17); writer.SetDoublePrecision(-1); // negative equivalent to reset EXPECT_EQ(writer.GetDoublePrecision(), kDefaultDoublePrecision); writer.SetDoublePrecision(1); writer.SetDoublePrecision(); // reset again EXPECT_EQ(writer.GetDoublePrecision(), kDefaultDoublePrecision); { // write with explicitly increased precision StringStream s(json); Reader reader; reader.Parse<0>(s, writer.SetDoublePrecision(12)); EXPECT_EQ(writer.GetDoublePrecision(), 12); EXPECT_STREQ(json, buffer.GetString()); buffer.Clear(); } { // explicit individual double precisions writer.SetDoublePrecision(2) .StartArray() .Double(1.2345,5) .Double(1.2345678,9) .Double(0.123456789012,12) .Double(1234567.8,8) .EndArray(); EXPECT_EQ(writer.GetDoublePrecision(), 2); EXPECT_STREQ(json, buffer.GetString()); buffer.Clear(); } { // write with default precision (output with precision loss) Document d; d.Parse<0>(json); d.Accept(writer.SetDoublePrecision()); // parsed again to avoid platform-dependent floating point outputs // (e.g. width of exponents) d.Parse<0>(buffer.GetString()); EXPECT_EQ(writer.GetDoublePrecision(), kDefaultDoublePrecision); EXPECT_DOUBLE_EQ(d[0u].GetDouble(), 1.2345); EXPECT_DOUBLE_EQ(d[1u].GetDouble(), 1.23457); EXPECT_DOUBLE_EQ(d[2u].GetDouble(), 0.123457); EXPECT_DOUBLE_EQ(d[3u].GetDouble(), 1234570); buffer.Clear(); } } TEST(Writer, Transcode) { // UTF8 -> UTF16 -> UTF8 StringStream s("{ \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3], \"dollar\":\"\x24\", \"cents\":\"\xC2\xA2\", \"euro\":\"\xE2\x82\xAC\", \"gclef\":\"\xF0\x9D\x84\x9E\" } "); StringBuffer buffer; Writer<StringBuffer, UTF16<>, UTF8<> > writer(buffer); GenericReader<UTF8<>, UTF16<> > reader; reader.Parse<0>(s, writer); EXPECT_STREQ("{\"hello\":\"world\",\"t\":true,\"f\":false,\"n\":null,\"i\":123,\"pi\":3.1416,\"a\":[1,2,3],\"dollar\":\"\x24\",\"cents\":\"\xC2\xA2\",\"euro\":\"\xE2\x82\xAC\",\"gclef\":\"\xF0\x9D\x84\x9E\"}", buffer.GetString()); } #include <sstream> class OStreamWrapper { public: typedef char Ch; OStreamWrapper(std::ostream& os) : os_(os) {} Ch Peek() const { assert(false); return '\0'; } Ch Take() { assert(false); return '\0'; } size_t Tell() const { return 0; } Ch* PutBegin() { assert(false); return 0; } void Put(Ch c) { os_.put(c); } void Flush() { os_.flush(); } size_t PutEnd(Ch*) { assert(false); return 0; } private: OStreamWrapper(const OStreamWrapper&); OStreamWrapper& operator=(const OStreamWrapper&); std::ostream& os_; }; TEST(Writer, OStreamWrapper) { StringStream s("{ \"hello\" : \"world\", \"t\" : true , \"f\" : false, \"n\": null, \"i\":123, \"pi\": 3.1416, \"a\":[1, 2, 3] } "); std::stringstream ss; OStreamWrapper os(ss); Writer<OStreamWrapper> writer(os); Reader reader; reader.Parse<0>(s, writer); std::string actual = ss.str(); EXPECT_STREQ("{\"hello\":\"world\",\"t\":true,\"f\":false,\"n\":null,\"i\":123,\"pi\":3.1416,\"a\":[1,2,3]}", actual.c_str()); } <|endoftext|>
<commit_before>#import <v8.h> #import <node.h> #import <AudioToolbox/AudioToolbox.h> #import <UIKit/UIKit.h> #import "graphicServices.h" #import "notifications.h" #import "telephony.h" #import "compatibility.h" // ...meh using namespace node; using namespace v8; class Binding { public: static void Init(v8::Handle<Object> target) { HandleScope scope; UIDevice *aDevice = [UIDevice currentDevice]; [aDevice beginGeneratingDeviceOrientationNotifications]; [aDevice setBatteryMonitoringEnabled:YES]; NODE_SET_METHOD(target, "vibrate", Vibrate); NODE_SET_METHOD(target, "device", Device); NODE_SET_METHOD(target, "sendSMS", Telephony::SendSMS); } static v8::Handle<Value> Vibrate(const Arguments& args) { AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); return Undefined(); } static v8::Handle<Value> Device(const Arguments& args) { HandleScope scope; Local<Object> result = Object::New(); UIDevice *aDevice = [UIDevice currentDevice]; result->Set(String::NewSymbol("batteryLevel"), Number::New([aDevice batteryLevel])); result->Set(String::NewSymbol("batteryState"), Integer::New([aDevice batteryState])); result->Set(String::NewSymbol("model"), String::NewSymbol([[aDevice model] UTF8String])); result->Set(String::NewSymbol("localizedModel"), String::NewSymbol([[aDevice localizedModel] UTF8String])); result->Set(String::NewSymbol("orientation"), Integer::New([aDevice orientation])); result->Set(String::NewSymbol("name"), String::NewSymbol([[aDevice name] UTF8String])); result->Set(String::NewSymbol("systemName"), String::NewSymbol([[aDevice systemName] UTF8String])); result->Set(String::NewSymbol("systemVersion"), String::NewSymbol([[aDevice systemVersion] UTF8String])); result->Set(String::NewSymbol("uniqueIdentifier"), String::NewSymbol([[aDevice uniqueIdentifier] UTF8String])); return scope.Close(result); } }; extern "C" { static void init (v8::Handle<Object> target) { Binding::Init(target); GraphicServices::Init(target); Notifications::Init(target); } NODE_MODULE(binding, init); } <commit_msg>Remove call to NODE_MODULES macro. WTF did that do anyways?<commit_after>#import <v8.h> #import <node.h> #import <AudioToolbox/AudioToolbox.h> #import <UIKit/UIKit.h> #import "graphicServices.h" #import "notifications.h" #import "telephony.h" #import "compatibility.h" // ...meh using namespace node; using namespace v8; class Binding { public: static void Init(v8::Handle<Object> target) { HandleScope scope; UIDevice *aDevice = [UIDevice currentDevice]; [aDevice beginGeneratingDeviceOrientationNotifications]; [aDevice setBatteryMonitoringEnabled:YES]; NODE_SET_METHOD(target, "vibrate", Vibrate); NODE_SET_METHOD(target, "device", Device); NODE_SET_METHOD(target, "sendSMS", Telephony::SendSMS); } static v8::Handle<Value> Vibrate(const Arguments& args) { AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); return Undefined(); } static v8::Handle<Value> Device(const Arguments& args) { HandleScope scope; Local<Object> result = Object::New(); UIDevice *aDevice = [UIDevice currentDevice]; result->Set(String::NewSymbol("batteryLevel"), Number::New([aDevice batteryLevel])); result->Set(String::NewSymbol("batteryState"), Integer::New([aDevice batteryState])); result->Set(String::NewSymbol("model"), String::NewSymbol([[aDevice model] UTF8String])); result->Set(String::NewSymbol("localizedModel"), String::NewSymbol([[aDevice localizedModel] UTF8String])); result->Set(String::NewSymbol("orientation"), Integer::New([aDevice orientation])); result->Set(String::NewSymbol("name"), String::NewSymbol([[aDevice name] UTF8String])); result->Set(String::NewSymbol("systemName"), String::NewSymbol([[aDevice systemName] UTF8String])); result->Set(String::NewSymbol("systemVersion"), String::NewSymbol([[aDevice systemVersion] UTF8String])); result->Set(String::NewSymbol("uniqueIdentifier"), String::NewSymbol([[aDevice uniqueIdentifier] UTF8String])); return scope.Close(result); } }; extern "C" void init (v8::Handle<Object> target) { Binding::Init(target); GraphicServices::Init(target); Notifications::Init(target); } <|endoftext|>
<commit_before>#include "bitmap.h" #include "except.h" Bitmap::Bitmap(std::string filepath) : _filepath(filepath) , _data(nullptr) , _width(0) , _height(0) { FILE * fptr = fopen(_filepath.c_str(), "rb"); if (fptr == nullptr) throw FileError(); uint8_t bmp_header[54]; fread(bmp_header, sizeof(uint8_t), 54, fptr); _width = *(int *)&bmp_header[18]; _height = *(int *)&bmp_header[22]; size_t num_bytes = 3 * _width * _height; _data = new uint8_t[num_bytes]; fread(_data, sizeof(uint8_t), num_bytes, fptr); fclose(fptr); } Bitmap::~Bitmap() { save(); if (_data != nullptr) delete [] _data; } uint8_t * const Bitmap::get_data() const { return _data; } size_t Bitmap::get_width() const { return _width; } size_t Bitmap::get_height() const { return _height; } std::string Bitmap::save() const { // TODO return ""; } <commit_msg>Issue #14: implemented save method<commit_after>#include "bitmap.h" #include "except.h" std::string timestamp(std::string filepath); Bitmap::Bitmap(std::string filepath) : _filepath(filepath) , _data(nullptr) , _width(0) , _height(0) { FILE * fptr = fopen(_filepath.c_str(), "rb"); if (fptr == nullptr) throw FileError(); uint8_t bmp_header[54]; fread(bmp_header, sizeof(uint8_t), 54, fptr); _width = *(int *)&bmp_header[18]; _height = *(int *)&bmp_header[22]; size_t num_bytes = 3 * _width * _height; _data = new uint8_t[num_bytes]; fread(_data, sizeof(uint8_t), num_bytes, fptr); fclose(fptr); } Bitmap::~Bitmap() { save(); if (_data != nullptr) delete [] _data; } uint8_t * const Bitmap::get_data() const { return _data; } size_t Bitmap::get_width() const { return _width; } size_t Bitmap::get_height() const { return _height; } std::string Bitmap::save() const { std::string filepath_ts = timestamp(_filepath); FILE * fptr = fopen(filepath_ts.c_str(), "wb"); if (fptr == nullptr) throw FileError(); unsigned char bmp_header[54] = {'B','M', 0, 0, 0, 0, 0, 0, 0, 0, 54, 0, 0, 0, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 24, 0}; size_t num_bytes = 3 * _width * _height; *(int *)&bmp_header[2] = (int)(54 + num_bytes); *(int *)&bmp_header[18] = (int) _width; *(int *)&bmp_header[22] = (int) _height; fwrite(bmp_header, sizeof(uint8_t), 54, fptr); fwrite(_data, sizeof(uint8_t), num_bytes, fptr); fclose(fptr); return filepath_ts; } std::string timestamp(std::string filepath) { // TODO return ""; } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * 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 <graphene/chain/asset_object.hpp> #include <graphene/chain/database.hpp> using namespace graphene::chain; using namespace boost::multiprecision; share_type asset_lock_data_object::get_profit(share_type tolocking_balance,uint32_t lock_period,const database &_db)const { return (asset(tolocking_balance, asset_id)*_get_interest(lock_period, _db) - asset(tolocking_balance, asset_id)).amount; } Interest asset_lock_data_object::_get_interest(uint32_t lock_period,const database &_db)const{ asset_object target_asset_obj=asset_id(_db); int32_t lock_days=lock_period/FCC_INTEREST_DAY; share_type max_to_deposit_balance_year = target_asset_obj.dynamic_data(_db).current_supply - (lock_coin_day / coin_day(FCC_INTEREST_YEAR)).value.to_uint64(); asset base_asset(FCC_INTEREST_BASE_SUPPLY, asset_id); static Interest top_of_interest = Interest(); if (top_of_interest == Interest()) // yet not calculated { asset result = base_asset; for (uint32_t i = 0; i<FCC_INTEREST_DAYS_YEAR; i++) { result = result*nominal_interest_perday; } top_of_interest = Interest(base_asset, result); } auto result = base_asset; for (uint32_t i = 0; i<lock_days; i++) { result = result*nominal_interest_perday; } int32_t pecent_of_year = (lock_days - FCC_INTEREST_DAYS_YEAR)*GRAPHENE_100_PERCENT / FCC_INTEREST_DAYS_YEAR; int64_t reward_rate = GRAPHENE_100_PERCENT + pecent_of_year * reward_coefficient / GRAPHENE_100_PERCENT; uint128_t pre_profile = uint128_t((result - base_asset).amount.value)*uint128_t(reward_rate) / GRAPHENE_100_PERCENT; auto actual_profile = pre_profile * interest_pool.value / (asset(max_to_deposit_balance_year, asset_id) * top_of_interest).amount.value; asset res_asset = asset(actual_profile.convert_to<uint64_t>(), asset_id) + base_asset; return Interest(base_asset,res_asset); } share_type asset_bitasset_data_object::max_force_settlement_volume(share_type current_supply) const { if( options.maximum_force_settlement_volume == 0 ) return 0; if( options.maximum_force_settlement_volume == GRAPHENE_100_PERCENT ) return current_supply + force_settled_volume; fc::uint128 volume = current_supply.value + force_settled_volume.value; volume *= options.maximum_force_settlement_volume; volume /= GRAPHENE_100_PERCENT; return volume.to_uint64(); } void graphene::chain::asset_bitasset_data_object::update_median_feeds(time_point_sec current_time) { current_feed_publication_time = current_time; vector<std::reference_wrapper<const price_feed>> current_feeds; for( const pair<account_id_type, pair<time_point_sec,price_feed>>& f : feeds ) { if( (current_time - f.second.first).to_seconds() < options.feed_lifetime_sec && f.second.first != time_point_sec() ) { current_feeds.emplace_back(f.second.second); current_feed_publication_time = std::min(current_feed_publication_time, f.second.first); } } // If there are no valid feeds, or the number available is less than the minimum to calculate a median... if( current_feeds.size() < options.minimum_feeds ) { //... don't calculate a median, and set a null feed current_feed_publication_time = current_time; current_feed = price_feed(); return; } if( current_feeds.size() == 1 ) { current_feed = std::move(current_feeds.front()); return; } // *** Begin Median Calculations *** price_feed median_feed; const auto median_itr = current_feeds.begin() + current_feeds.size() / 2; #define CALCULATE_MEDIAN_VALUE(r, data, field_name) \ std::nth_element( current_feeds.begin(), median_itr, current_feeds.end(), \ [](const price_feed& a, const price_feed& b) { \ return a.field_name < b.field_name; \ }); \ median_feed.field_name = median_itr->get().field_name; BOOST_PP_SEQ_FOR_EACH( CALCULATE_MEDIAN_VALUE, ~, GRAPHENE_PRICE_FEED_FIELDS ) #undef CALCULATE_MEDIAN_VALUE // *** End Median Calculations *** current_feed = median_feed; } asset asset_object::amount_from_string(string amount_string) const { try { bool negative_found = false; bool decimal_found = false; for( const char c : amount_string ) { if( isdigit( c ) ) continue; if( c == '-' && !negative_found ) { negative_found = true; continue; } if( c == '.' && !decimal_found ) { decimal_found = true; continue; } FC_THROW( (amount_string) ); } share_type satoshis = 0; share_type scaled_precision = asset::scaled_precision( precision ); const auto decimal_pos = amount_string.find( '.' ); const string lhs = amount_string.substr( negative_found, decimal_pos ); if( !lhs.empty() ) satoshis += fc::safe<int64_t>(std::stoll(lhs)) *= scaled_precision; if( decimal_found ) { const size_t max_rhs_size = std::to_string( scaled_precision.value ).substr( 1 ).size(); string rhs = amount_string.substr( decimal_pos + 1 ); FC_ASSERT( rhs.size() <= max_rhs_size ); while( rhs.size() < max_rhs_size ) rhs += '0'; if( !rhs.empty() ) satoshis += std::stoll( rhs ); } FC_ASSERT( satoshis <= GRAPHENE_MAX_SHARE_SUPPLY ); if( negative_found ) satoshis *= -1; return amount(satoshis); } FC_CAPTURE_AND_RETHROW( (amount_string) ) } string asset_object::amount_to_string(share_type amount) const { share_type scaled_precision = 1; for( uint8_t i = 0; i < precision; ++i ) scaled_precision *= 10; assert(scaled_precision > 0); string result = fc::to_string(amount.value / scaled_precision.value); auto decimals = amount.value % scaled_precision.value; if( decimals ) result += "." + fc::to_string(scaled_precision.value + decimals).erase(0,1); return result; } <commit_msg>fix asset overflow issue<commit_after>/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * 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 <graphene/chain/asset_object.hpp> #include <graphene/chain/database.hpp> using namespace graphene::chain; using namespace boost::multiprecision; share_type asset_lock_data_object::get_profit(share_type tolocking_balance,uint32_t lock_period,const database &_db)const { return (asset(tolocking_balance, asset_id)*_get_interest(lock_period, _db) - asset(tolocking_balance, asset_id)).amount; } Interest asset_lock_data_object::_get_interest(uint32_t lock_period,const database &_db)const{ asset_object target_asset_obj=asset_id(_db); int32_t lock_days=lock_period/FCC_INTEREST_DAY; share_type max_to_deposit_balance_year = target_asset_obj.dynamic_data(_db).current_supply - (lock_coin_day / coin_day(FCC_INTEREST_YEAR)).value.to_uint64(); asset base_asset(FCC_INTEREST_BASE_SUPPLY, asset_id); static Interest top_of_interest = Interest(); if (top_of_interest == Interest()) // yet not calculated { asset result = base_asset; for (uint32_t i = 0; i<FCC_INTEREST_DAYS_YEAR; i++) { result = result*nominal_interest_perday; } top_of_interest = Interest(base_asset, result); } auto result = base_asset; for (uint32_t i = 0; i<lock_days; i++) { result = result*nominal_interest_perday; } int32_t pecent_of_year = (lock_days - FCC_INTEREST_DAYS_YEAR)*GRAPHENE_100_PERCENT / FCC_INTEREST_DAYS_YEAR; int64_t reward_rate = GRAPHENE_100_PERCENT + pecent_of_year * reward_coefficient / GRAPHENE_100_PERCENT; uint128_t pre_profile = uint128_t((result - base_asset).amount.value)*uint128_t(reward_rate) / GRAPHENE_100_PERCENT; auto actual_profile = pre_profile * interest_pool.value / (asset(max_to_deposit_balance_year / 10, asset_id) * top_of_interest).amount.value /10; asset res_asset = asset(actual_profile.convert_to<uint64_t>(), asset_id) + base_asset; return Interest(base_asset,res_asset); } share_type asset_bitasset_data_object::max_force_settlement_volume(share_type current_supply) const { if( options.maximum_force_settlement_volume == 0 ) return 0; if( options.maximum_force_settlement_volume == GRAPHENE_100_PERCENT ) return current_supply + force_settled_volume; fc::uint128 volume = current_supply.value + force_settled_volume.value; volume *= options.maximum_force_settlement_volume; volume /= GRAPHENE_100_PERCENT; return volume.to_uint64(); } void graphene::chain::asset_bitasset_data_object::update_median_feeds(time_point_sec current_time) { current_feed_publication_time = current_time; vector<std::reference_wrapper<const price_feed>> current_feeds; for( const pair<account_id_type, pair<time_point_sec,price_feed>>& f : feeds ) { if( (current_time - f.second.first).to_seconds() < options.feed_lifetime_sec && f.second.first != time_point_sec() ) { current_feeds.emplace_back(f.second.second); current_feed_publication_time = std::min(current_feed_publication_time, f.second.first); } } // If there are no valid feeds, or the number available is less than the minimum to calculate a median... if( current_feeds.size() < options.minimum_feeds ) { //... don't calculate a median, and set a null feed current_feed_publication_time = current_time; current_feed = price_feed(); return; } if( current_feeds.size() == 1 ) { current_feed = std::move(current_feeds.front()); return; } // *** Begin Median Calculations *** price_feed median_feed; const auto median_itr = current_feeds.begin() + current_feeds.size() / 2; #define CALCULATE_MEDIAN_VALUE(r, data, field_name) \ std::nth_element( current_feeds.begin(), median_itr, current_feeds.end(), \ [](const price_feed& a, const price_feed& b) { \ return a.field_name < b.field_name; \ }); \ median_feed.field_name = median_itr->get().field_name; BOOST_PP_SEQ_FOR_EACH( CALCULATE_MEDIAN_VALUE, ~, GRAPHENE_PRICE_FEED_FIELDS ) #undef CALCULATE_MEDIAN_VALUE // *** End Median Calculations *** current_feed = median_feed; } asset asset_object::amount_from_string(string amount_string) const { try { bool negative_found = false; bool decimal_found = false; for( const char c : amount_string ) { if( isdigit( c ) ) continue; if( c == '-' && !negative_found ) { negative_found = true; continue; } if( c == '.' && !decimal_found ) { decimal_found = true; continue; } FC_THROW( (amount_string) ); } share_type satoshis = 0; share_type scaled_precision = asset::scaled_precision( precision ); const auto decimal_pos = amount_string.find( '.' ); const string lhs = amount_string.substr( negative_found, decimal_pos ); if( !lhs.empty() ) satoshis += fc::safe<int64_t>(std::stoll(lhs)) *= scaled_precision; if( decimal_found ) { const size_t max_rhs_size = std::to_string( scaled_precision.value ).substr( 1 ).size(); string rhs = amount_string.substr( decimal_pos + 1 ); FC_ASSERT( rhs.size() <= max_rhs_size ); while( rhs.size() < max_rhs_size ) rhs += '0'; if( !rhs.empty() ) satoshis += std::stoll( rhs ); } FC_ASSERT( satoshis <= GRAPHENE_MAX_SHARE_SUPPLY ); if( negative_found ) satoshis *= -1; return amount(satoshis); } FC_CAPTURE_AND_RETHROW( (amount_string) ) } string asset_object::amount_to_string(share_type amount) const { share_type scaled_precision = 1; for( uint8_t i = 0; i < precision; ++i ) scaled_precision *= 10; assert(scaled_precision > 0); string result = fc::to_string(amount.value / scaled_precision.value); auto decimals = amount.value % scaled_precision.value; if( decimals ) result += "." + fc::to_string(scaled_precision.value + decimals).erase(0,1); return result; } <|endoftext|>
<commit_before>/** * @file Severity.hpp * @brief Severity class prototype. * @author zer0 * @date 2016-07-09 */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_LOG_DETAILS_SEVERITY_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_LOG_DETAILS_SEVERITY_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/config.h> #include <libtbag/predef.hpp> #include <string> #include <numeric> #include <type_traits> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace log { namespace details { /** * Severity class prototype. * * @author zer0 * @date 2016-07-09 */ class Severity { public: char const * text; int level; public: // @formatter:off Severity() : text(), level() { /* EMPTY */ } Severity(char const * t, int l) : text(t), level(l) { /* EMPTY */ } Severity(Severity const & obj) : text(obj.text), level(obj.level) { /* EMPTY */ } ~Severity() { /* EMPTY */ } // @formatter:on public: Severity & operator =(Severity const & obj) { if (this != &obj) { level = obj.level; text = obj.text; } return *this; } public: // @formatter:off inline operator int() const TBAG_NOEXCEPT { return level; } inline operator std::string() const TBAG_NOEXCEPT { return std::string(text); } inline bool operator ==(Severity const & obj) const TBAG_NOEXCEPT { return level == obj.level; } inline bool operator !=(Severity const & obj) const TBAG_NOEXCEPT { return level != obj.level; } inline bool operator <(Severity const & obj) const TBAG_NOEXCEPT { return level < obj.level; } inline bool operator >(Severity const & obj) const TBAG_NOEXCEPT { return level > obj.level; } inline bool operator <=(Severity const & obj) const TBAG_NOEXCEPT { return level <= obj.level; } inline bool operator >=(Severity const & obj) const TBAG_NOEXCEPT { return level >= obj.level; } inline bool isContain(Severity const & obj) const TBAG_NOEXCEPT { return level >= obj.level; } // @formatter:on }; Severity const OFF_SEVERITY("OFF" , 0); // Hide all messages. Severity const EMERGENCY_SEVERITY("EMERGENCY", 100); // System is unusable. Severity const ALERT_SEVERITY("ALERT" , 200); // Action must be taken immediately. Severity const CRITICAL_SEVERITY("CRITICAL" , 300); // Critical conditions. Severity const ERROR_SEVERITY("ERROR" , 400); // Error conditions. Severity const WARNING_SEVERITY("WARNING" , 500); // Warning conditions. Severity const NOTICE_SEVERITY("NOTICE" , 600); // Normal but significant condition. Severity const INFORMATIONAL_SEVERITY("INFO" , 700); // Informational messages. Severity const DEBUG_SEVERITY("DEBUG" , 800); // Debug-level messages. } // namespace details } // namespace log // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- #endif // __INCLUDE_LIBTBAG__LIBTBAG_LOG_DETAILS_SEVERITY_HPP__ <commit_msg>Refactoring Severity class.<commit_after>/** * @file Severity.hpp * @brief Severity class prototype. * @author zer0 * @date 2016-07-09 */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_LOG_DETAILS_SEVERITY_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_LOG_DETAILS_SEVERITY_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/config.h> #include <libtbag/predef.hpp> #include <string> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace log { namespace details { /** * Severity class prototype. * * @author zer0 * @date 2016-07-09 */ class Severity { public: char const * text; int level; public: // @formatter:off Severity() : text(), level() { /* EMPTY */ } Severity(char const * t, int l) : text(t), level(l) { /* EMPTY */ } Severity(Severity const & obj) : text(obj.text), level(obj.level) { /* EMPTY */ } ~Severity() { /* EMPTY */ } // @formatter:on public: Severity & operator =(Severity const & obj) { if (this != &obj) { level = obj.level; text = obj.text; } return *this; } public: // @formatter:off inline operator int() const TBAG_NOEXCEPT { return level; } inline operator char const *() const TBAG_NOEXCEPT { return text; } inline friend bool operator ==(Severity const & lh, Severity const & rh) TBAG_NOEXCEPT { return lh.level == rh.level; } inline friend bool operator !=(Severity const & lh, Severity const & rh) TBAG_NOEXCEPT { return lh.level != rh.level; } inline friend bool operator <(Severity const & lh, Severity const & rh) TBAG_NOEXCEPT { return lh.level < rh.level; } inline friend bool operator >(Severity const & lh, Severity const & rh) TBAG_NOEXCEPT { return lh.level > rh.level; } inline friend bool operator <=(Severity const & lh, Severity const & rh) TBAG_NOEXCEPT { return lh.level <= rh.level; } inline friend bool operator >=(Severity const & lh, Severity const & rh) TBAG_NOEXCEPT { return lh.level >= rh.level; } inline bool isContain(Severity const & obj) const TBAG_NOEXCEPT { return level >= obj.level; } // @formatter:on }; Severity const OFF_SEVERITY("OFF" , 0); // Hide all messages. Severity const EMERGENCY_SEVERITY("EMERGENCY", 100); // System is unusable. Severity const ALERT_SEVERITY("ALERT" , 200); // Action must be taken immediately. Severity const CRITICAL_SEVERITY("CRITICAL" , 300); // Critical conditions. Severity const ERROR_SEVERITY("ERROR" , 400); // Error conditions. Severity const WARNING_SEVERITY("WARNING" , 500); // Warning conditions. Severity const NOTICE_SEVERITY("NOTICE" , 600); // Normal but significant condition. Severity const INFORMATIONAL_SEVERITY("INFO" , 700); // Informational messages. Severity const DEBUG_SEVERITY("DEBUG" , 800); // Debug-level messages. } // namespace details } // namespace log // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- #endif // __INCLUDE_LIBTBAG__LIBTBAG_LOG_DETAILS_SEVERITY_HPP__ <|endoftext|>
<commit_before>/** * @file SignalHandler.hpp * @brief SignalHandler class prototype. * @author zer0 * @date 2016-12-24 */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_SIGNAL_SIGNALHANDLER_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_SIGNAL_SIGNALHANDLER_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/config.h> #include <libtbag/predef.hpp> #include <csignal> #include <climits> #include <cstdlib> #include <string> #include <exception> #include <functional> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace signal { // ================== namespace __impl { /** @warning Don't use this method from user level developers. */ TBAG_API void createInstance(); TBAG_API void releaseInstance(); } // namespace __impl // ================== #ifndef TBAG_SIGNAL_MAP #define TBAG_SIGNAL_MAP(_TBAG_XX) \ _TBAG_XX(SIGNAL_INTERRUPT , SIGINT /* 2 */, "interrupt") \ _TBAG_XX(SIGNAL_ILLEGAL_INSTRUCTION , SIGILL /* 4 */, "illegal instruction (not reset when caught)") \ _TBAG_XX(SIGNAL_FLOATING_POINT_EXCEPTION, SIGFPE /* 8 */, "floating point exception") \ _TBAG_XX(SIGNAL_SEGMENTATION_VIOLATION , SIGSEGV/* 11 */, "segmentation violation") \ _TBAG_XX(SIGNAL_TERMINATION , SIGTERM/* 15 */, "software termination signal from kill") \ _TBAG_XX(SIGNAL_ABORT , SIGABRT/* ?? */, "abort()") /* Windows(22), OSX(6) */ \ /* -- END -- */ #endif #define _TBAG_XX(name, signal, message) TBAG_CONSTEXPR int const TBAG_##name = signal; TBAG_SIGNAL_MAP(_TBAG_XX) #undef _TBAG_XX // Don't use the std::numeric_limits class. // Avoid collisions of min & max symbol in MSVC. TBAG_CONSTEXPR int const SIGNAL_STD_TERMINATE = INT_MAX; // C++ terminate signal. TBAG_CONSTEXPR int const FIRST_ORDER = INT_MAX; TBAG_CONSTEXPR int const LAST_ORDER = INT_MIN; inline bool existSignalNumber(int signal_number) TBAG_NOEXCEPT { switch (signal_number) { #define _TBAG_XX(name, signal, message) case TBAG_##name: return true; TBAG_SIGNAL_MAP(_TBAG_XX) #undef _TBAG_XX default: return false; } } inline char const * const getSignalName(int signal_number) TBAG_NOEXCEPT { switch (signal_number) { #define _TBAG_XX(name, signal, message) case TBAG_##name: return #signal; TBAG_SIGNAL_MAP(_TBAG_XX) #undef _TBAG_XX default: return "UNKNOWN"; } } /** * Signal handler interface. * * @author zer0 * @date 2016-12-24 */ struct SignalHandler { virtual void run(int signal) = 0; }; using SignalCallback = std::function<void(int)>; /** * FunctionalSignalHandler handler interface. * * @author zer0 * @date 2017-07-14 */ struct FunctionalSignalHandler : public SignalHandler { public: SignalCallback signal_cb; public: FunctionalSignalHandler() : signal_cb() { /* EMPTY. */ } FunctionalSignalHandler(SignalCallback const & cb) : signal_cb(cb) { /* EMPTY. */ } public: virtual ~FunctionalSignalHandler() { /* EMPTY. */ } public: void setRun(SignalCallback const & cb) { signal_cb = cb; } public: virtual void run(int signal) override { if (signal_cb) { signal_cb(signal); } } }; /** * FuncSignalHandler typedef. * * @author zer0 * @date 2017-07-14 */ using FuncSignalHandler = FunctionalSignalHandler; TBAG_API void registerStdTerminateHandler(SignalHandler * handler, int order = 0); TBAG_API void registerStdTerminateFunctionalHandler(SignalCallback const & cb, int order = 0); TBAG_API void registerHandler(int signal, SignalHandler * handler, int order = 0); TBAG_API void registerFunctionalHandler(int signal, SignalCallback const & cb, int order = 0); TBAG_API void registerDefaultStdTerminateHandler(std::string const & logger_name = std::string()); TBAG_API void registerDefaultErrorHandler(std::string const & logger_name = std::string()); TBAG_API void registerDefaultHandler(std::string const & logger_name = std::string()); TBAG_API SignalHandler * createDefaultSignalHandler(std::string const & logger_name = std::string()); // clang-format off inline int raise(int signal) { return std::raise(signal); } [[ noreturn ]] inline void terminate() TBAG_NOEXCEPT_SP_OP(std::terminate()) { std::terminate(); } [[ noreturn ]] inline void exit(int code) TBAG_NOEXCEPT_SP_OP(std::exit(code)) { std::exit(code); } [[ noreturn ]] inline void exitForce(int code) TBAG_NOEXCEPT_SP_OP(std::_Exit(code)) { std::_Exit(code); } // clang-format on } // namespace signal // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- #endif // __INCLUDE_LIBTBAG__LIBTBAG_SIGNAL_SIGNALHANDLER_HPP__ <commit_msg>Add TBAG_SIGNAL_KILL const.<commit_after>/** * @file SignalHandler.hpp * @brief SignalHandler class prototype. * @author zer0 * @date 2016-12-24 */ #ifndef __INCLUDE_LIBTBAG__LIBTBAG_SIGNAL_SIGNALHANDLER_HPP__ #define __INCLUDE_LIBTBAG__LIBTBAG_SIGNAL_SIGNALHANDLER_HPP__ // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif #include <libtbag/config.h> #include <libtbag/predef.hpp> #include <csignal> #include <climits> #include <cstdlib> #include <string> #include <exception> #include <functional> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace signal { // ================== namespace __impl { /** @warning Don't use this method from user level developers. */ TBAG_API void createInstance(); TBAG_API void releaseInstance(); } // namespace __impl // ================== #ifndef TBAG_SIGNAL_MAP #define TBAG_SIGNAL_MAP(_TBAG_XX) \ _TBAG_XX(SIGNAL_INTERRUPT , SIGINT /* 2 */, "interrupt") \ _TBAG_XX(SIGNAL_ILLEGAL_INSTRUCTION , SIGILL /* 4 */, "illegal instruction (not reset when caught)") \ _TBAG_XX(SIGNAL_FLOATING_POINT_EXCEPTION, SIGFPE /* 8 */, "floating point exception") \ _TBAG_XX(SIGNAL_SEGMENTATION_VIOLATION , SIGSEGV/* 11 */, "segmentation violation") \ _TBAG_XX(SIGNAL_TERMINATION , SIGTERM/* 15 */, "software termination signal from kill") \ _TBAG_XX(SIGNAL_ABORT , SIGABRT/* ?? */, "abort()") /* Windows(22), OSX(6) */ \ /* -- END -- */ #endif #define _TBAG_XX(name, signal, message) TBAG_CONSTEXPR int const TBAG_##name = signal; TBAG_SIGNAL_MAP(_TBAG_XX) #undef _TBAG_XX // Don't use the std::numeric_limits class. // Avoid collisions of min & max symbol in MSVC. TBAG_CONSTEXPR int const SIGNAL_STD_TERMINATE = INT_MAX; // C++ terminate signal. TBAG_CONSTEXPR int const FIRST_ORDER = INT_MAX; TBAG_CONSTEXPR int const LAST_ORDER = INT_MIN; #ifndef TBAG_SIGNAL_KILL_NUMBER # if defined(TBAG_PLATFORM_WINDOWS) # define TBAG_SIGNAL_KILL_NUMBER SIGTERM // Windows does not have SIGKILL. # elif defined(SIGKILL) # define TBAG_SIGNAL_KILL_NUMBER SIGKILL // kill (cannot be caught or ignored) # else # define TBAG_SIGNAL_KILL_NUMBER 9 // SIGKILL is often numbered 9. # endif #endif TBAG_CONSTEXPR int const TBAG_SIGNAL_KILL = TBAG_SIGNAL_KILL_NUMBER; inline bool existSignalNumber(int signal_number) TBAG_NOEXCEPT { switch (signal_number) { #define _TBAG_XX(name, signal, message) case TBAG_##name: return true; TBAG_SIGNAL_MAP(_TBAG_XX) #undef _TBAG_XX default: return false; } } inline char const * const getSignalName(int signal_number) TBAG_NOEXCEPT { switch (signal_number) { #define _TBAG_XX(name, signal, message) case TBAG_##name: return #signal; TBAG_SIGNAL_MAP(_TBAG_XX) #undef _TBAG_XX default: return "UNKNOWN"; } } /** * Signal handler interface. * * @author zer0 * @date 2016-12-24 */ struct SignalHandler { virtual void run(int signal) = 0; }; using SignalCallback = std::function<void(int)>; /** * FunctionalSignalHandler handler interface. * * @author zer0 * @date 2017-07-14 */ struct FunctionalSignalHandler : public SignalHandler { public: SignalCallback signal_cb; public: FunctionalSignalHandler() : signal_cb() { /* EMPTY. */ } FunctionalSignalHandler(SignalCallback const & cb) : signal_cb(cb) { /* EMPTY. */ } public: virtual ~FunctionalSignalHandler() { /* EMPTY. */ } public: void setRun(SignalCallback const & cb) { signal_cb = cb; } public: virtual void run(int signal) override { if (signal_cb) { signal_cb(signal); } } }; /** * FuncSignalHandler typedef. * * @author zer0 * @date 2017-07-14 */ using FuncSignalHandler = FunctionalSignalHandler; TBAG_API void registerStdTerminateHandler(SignalHandler * handler, int order = 0); TBAG_API void registerStdTerminateFunctionalHandler(SignalCallback const & cb, int order = 0); TBAG_API void registerHandler(int signal, SignalHandler * handler, int order = 0); TBAG_API void registerFunctionalHandler(int signal, SignalCallback const & cb, int order = 0); TBAG_API void registerDefaultStdTerminateHandler(std::string const & logger_name = std::string()); TBAG_API void registerDefaultErrorHandler(std::string const & logger_name = std::string()); TBAG_API void registerDefaultHandler(std::string const & logger_name = std::string()); TBAG_API SignalHandler * createDefaultSignalHandler(std::string const & logger_name = std::string()); // clang-format off inline int raise(int signal) { return std::raise(signal); } [[ noreturn ]] inline void terminate() TBAG_NOEXCEPT_SP_OP(std::terminate()) { std::terminate(); } [[ noreturn ]] inline void exit(int code) TBAG_NOEXCEPT_SP_OP(std::exit(code)) { std::exit(code); } [[ noreturn ]] inline void exitForce(int code) TBAG_NOEXCEPT_SP_OP(std::_Exit(code)) { std::_Exit(code); } // clang-format on } // namespace signal // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- #endif // __INCLUDE_LIBTBAG__LIBTBAG_SIGNAL_SIGNALHANDLER_HPP__ <|endoftext|>
<commit_before>/**************************************************************************** atom.hpp - support file for writing LV2 plugins in C++ Copyright (C) 2012 Michael Fisher <mfisher31@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307 USA ****************************************************************************/ #ifndef LVTK_LV2_ATOM_HPP #define LVTK_LV2_ATOM_HPP #include <lv2/lv2plug.in/ns/ext/atom/atom.h> #include <lv2/lv2plug.in/ns/ext/atom/forge.h> #include <lv2/lv2plug.in/ns/ext/atom/util.h> namespace lvtk { } /* namespace lvtk */ #endif /* LVTK_LV2_ATOM_HPP */ <commit_msg>Added some typedefs and an AtomForge(basic) wrapper beginning<commit_after>/**************************************************************************** atom.hpp - support file for writing LV2 plugins in C++ Copyright (C) 2012 Michael Fisher <mfisher31@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307 USA ****************************************************************************/ #ifndef LVTK_LV2_ATOM_HPP #define LVTK_LV2_ATOM_HPP #include <lv2/lv2plug.in/ns/ext/atom/atom.h> #include <lv2/lv2plug.in/ns/ext/atom/forge.h> #include <lv2/lv2plug.in/ns/ext/atom/util.h> #include <lvtk/ext/midi.hpp> #include <lvtk/ext/patch.hpp> namespace lvtk { /** Typedef for an Atom */ typedef LV2_Atom Atom; /** Typedef for an Atom Forge */ typedef LV2_Atom_Forge_Frame AtomForgeFrame; typedef uint32_t (*MapFunc)(const char* symbol); typedef const char* (*UnmapFunc)(uint32_t id); class AtomForge { LV2_Atom_Forge forge; LV2_URID midi_MidiEvent, patch_Set, patch_Get, patch_body; public: AtomForge() : midi_MidiEvent(0) , patch_Set(0), patch_Get(0), patch_body(0) { } AtomForge (MapFunc map) { init (map); } /** * Initialize the underlying atom forge * @param map The mapping function needed for init */ inline void init (MapFunc map) { assert (map != NULL); midi_MidiEvent = map(LV2_MIDI__MidiEvent); patch_Set = map(LV2_PATCH__Set); patch_Get = map(LV2_PATCH__Get); lv2_atom_forge_set_buffer (&forge, NULL, 0); forge.Blank = map(LV2_ATOM__Blank); forge.Bool = map(LV2_ATOM__Bool); forge.Chunk = map(LV2_ATOM__Chunk); forge.Double = map(LV2_ATOM__Double); forge.Float = map(LV2_ATOM__Float); forge.Int = map(LV2_ATOM__Int); forge.Long = map(LV2_ATOM__Long); forge.Literal = map(LV2_ATOM__Literal); forge.Path = map(LV2_ATOM__Path); forge.Property = map(LV2_ATOM__Property); forge.Resource = map(LV2_ATOM__Resource); forge.Sequence = map(LV2_ATOM__Sequence); forge.String = map(LV2_ATOM__String); forge.Tuple = map(LV2_ATOM__Tuple); forge.URI = map(LV2_ATOM__URI); forge.URID = map(LV2_ATOM__URID); forge.Vector = map(LV2_ATOM__Vector); } inline LV2_Atom_Forge* cobj() { return &forge; } inline void set_buffer(uint8_t* buf, uint32_t size) { lv2_atom_forge_set_buffer (&forge, buf, size); } uint32_t atom_total_size (const LV2_Atom* atom) { return lv2_atom_total_size (atom); } /* MIDI Related */ const LV2_Atom* note_on (uint8_t key, uint8_t velocity) { uint8_t midi[3]; midi[0] = 0x90; midi[1] = key; midi[2] = velocity; LV2_Atom* atom = (LV2_Atom*) lv2_atom_forge_atom (&forge, 3, midi_MidiEvent); lv2_atom_forge_raw (&forge, midi, 3); return atom; } const LV2_Atom* note_off (uint8_t key) { uint8_t midi[3]; midi[0] = 0x80; midi[1] = key; midi[2] = 0x00; LV2_Atom* atom = (LV2_Atom*) lv2_atom_forge_atom (&forge, 3, midi_MidiEvent); lv2_atom_forge_raw (&forge, midi, 3); return atom; } inline LV2_Atom_Forge_Ref path (const std::string& path) { return lv2_atom_forge_path(&forge,path.c_str(),path.size()); } inline LV2_Atom_Forge_Ref resource (AtomForgeFrame *frame, uint32_t id, uint32_t otype) { // Write object header return lv2_atom_forge_resource (&forge, frame, id, otype); } inline LV2_Atom_Forge_Ref blank (AtomForgeFrame *frame, uint32_t id, uint32_t otype) { // Write object header return lv2_atom_forge_blank (&forge, frame, id, otype); } inline LV2_Atom_Forge_Ref property_head (uint32_t key, uint32_t context) { return lv2_atom_forge_property_head (&forge, key, context); } inline void pop (AtomForgeFrame *frame) { lv2_atom_forge_pop(&forge, frame); } inline LV2_Atom_Forge_Ref raw (const void* data, uint32_t size) { return lv2_atom_forge_raw (&forge, data, size); } }; } /* namespace lvtk */ #endif /* LVTK_LV2_ATOM_HPP */ <|endoftext|>
<commit_before> /*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2014 Igor Mironchik 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. */ // Qt include. #include <QObject> #include <QtTest/QtTest> #include <QSharedPointer> #include <QLabel> // QtMWidgets include. #include <QtMWidgets/PageView> class TestPageView : public QObject { Q_OBJECT private slots: void testView() { QtMWidgets::PageView p; p.show(); QVERIFY( QTest::qWaitForWindowActive( &p ) ); QVERIFY( p.currentIndex() == -1 ); QVERIFY( p.count() == 0 ); QVERIFY( p.showPageControl() == true ); p.setShowPageControl( false ); QVERIFY( p.showPageControl() == false ); p.resize( 300, 300 ); QLabel w1( QStringLiteral( "1" ) ); auto f = w1.font(); f.setPixelSize( 100 ); f.setBold( true ); w1.setFont( f ); w1.setAlignment( Qt::AlignCenter ); p.addWidget( &w1 ); QVERIFY( p.count() == 1 ); QVERIFY( p.currentIndex() == 0 ); QVERIFY( p.currentWidget() == &w1 ); QVERIFY( p.indexOf( &w1 ) == 0 ); QVERIFY( p.widget( 0 ) == &w1 ); QLabel w2( QStringLiteral( "2" ) ); w2.setFont( f ); w2.setAlignment( Qt::AlignCenter ); p.addWidget( &w2 ); p.setCurrentWidget( &w2 ); QVERIFY( p.currentIndex() == 1 ); QLabel w3( QStringLiteral( "3" ) ); w3.setFont( f ); w3.setAlignment( Qt::AlignCenter ); QTest::qWait( 350 ); p.addWidget( &w3 ); { const auto c = p.rect().center() - QPoint( p.rect().width() / 3, 0 ); QTest::mousePress( &p, Qt::LeftButton, {}, c, 20 ); const auto pos = c - QPoint( p.rect().width() - p.rect().width() / 4, 0 ); QMouseEvent me( QEvent::MouseMove, pos, Qt::LeftButton, Qt::LeftButton, {} ); QApplication::sendEvent( &p, &me ); QTest::mouseRelease( &p, Qt::LeftButton, {}, pos, 20 ); } QTest::qWait( 350 ); QVERIFY( p.currentWidget() == &w3 ); { const auto c = p.rect().center() - QPoint( p.rect().width() / 3, 0 ); QTest::mousePress( &p, Qt::LeftButton, {}, c, 20 ); const auto pos = c + QPoint( p.rect().width() - p.rect().width() / 4, 0 ); QMouseEvent me( QEvent::MouseMove, pos, Qt::LeftButton, Qt::LeftButton, {} ); QApplication::sendEvent( &p, &me ); QTest::mouseRelease( &p, Qt::LeftButton, {}, pos, 20 ); } QTest::qWait( 350 ); QVERIFY( p.currentIndex() == 1 ); p.removeWidget( &w3 ); QVERIFY( p.count() == 2 ); QVERIFY( p.widget( 1 ) == &w2 ); } }; QTEST_MAIN( TestPageView ) #include "main.moc" <commit_msg>Set bigger delays.<commit_after> /*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2014 Igor Mironchik 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. */ // Qt include. #include <QObject> #include <QtTest/QtTest> #include <QSharedPointer> #include <QLabel> // QtMWidgets include. #include <QtMWidgets/PageView> class TestPageView : public QObject { Q_OBJECT private slots: void testView() { QtMWidgets::PageView p; p.show(); QVERIFY( QTest::qWaitForWindowActive( &p ) ); QVERIFY( p.currentIndex() == -1 ); QVERIFY( p.count() == 0 ); QVERIFY( p.showPageControl() == true ); p.setShowPageControl( false ); QVERIFY( p.showPageControl() == false ); p.resize( 300, 300 ); QLabel w1( QStringLiteral( "1" ) ); auto f = w1.font(); f.setPixelSize( 100 ); f.setBold( true ); w1.setFont( f ); w1.setAlignment( Qt::AlignCenter ); p.addWidget( &w1 ); QVERIFY( p.count() == 1 ); QVERIFY( p.currentIndex() == 0 ); QVERIFY( p.currentWidget() == &w1 ); QVERIFY( p.indexOf( &w1 ) == 0 ); QVERIFY( p.widget( 0 ) == &w1 ); QLabel w2( QStringLiteral( "2" ) ); w2.setFont( f ); w2.setAlignment( Qt::AlignCenter ); p.addWidget( &w2 ); p.setCurrentWidget( &w2 ); QVERIFY( p.currentIndex() == 1 ); QLabel w3( QStringLiteral( "3" ) ); w3.setFont( f ); w3.setAlignment( Qt::AlignCenter ); QTest::qWait( 350 ); p.addWidget( &w3 ); { const auto c = p.rect().center() - QPoint( p.rect().width() / 3, 0 ); QTest::mousePress( &p, Qt::LeftButton, {}, c, 20 ); const auto pos = c - QPoint( p.rect().width() - p.rect().width() / 4, 0 ); QMouseEvent me( QEvent::MouseMove, pos, Qt::LeftButton, Qt::LeftButton, {} ); QApplication::sendEvent( &p, &me ); QTest::mouseRelease( &p, Qt::LeftButton, {}, pos, 20 ); } QTest::qWait( 1000 ); QVERIFY( p.currentWidget() == &w3 ); { const auto c = p.rect().center() - QPoint( p.rect().width() / 3, 0 ); QTest::mousePress( &p, Qt::LeftButton, {}, c, 20 ); const auto pos = c + QPoint( p.rect().width() - p.rect().width() / 4, 0 ); QMouseEvent me( QEvent::MouseMove, pos, Qt::LeftButton, Qt::LeftButton, {} ); QApplication::sendEvent( &p, &me ); QTest::mouseRelease( &p, Qt::LeftButton, {}, pos, 20 ); } QTest::qWait( 1000 ); QVERIFY( p.currentIndex() == 1 ); p.removeWidget( &w3 ); QVERIFY( p.count() == 2 ); QVERIFY( p.widget( 1 ) == &w2 ); } }; QTEST_MAIN( TestPageView ) #include "main.moc" <|endoftext|>
<commit_before>#include <stan/math/prim/mat.hpp> #include <stan/math/prim/arr.hpp> #include <gtest/gtest.h> TEST(ErrorHandlingOpenCL, checkThrows) { const char* function = "test_func"; const char* msg = "test"; EXPECT_THROW(stan::math::throw_openCL(function, msg), std::domain_error); } <commit_msg>ignore opencl test on travis<commit_after>#ifdef STAN_OPENCL #include <stan/math/prim/mat.hpp> #include <stan/math/prim/arr.hpp> #include <gtest/gtest.h> TEST(ErrorHandlingOpenCL, checkThrows) { const char* function = "test_func"; const char* msg = "test"; EXPECT_THROW(stan::math::throw_openCL(function, msg), std::domain_error); } #else TEST(ErrorHandlingOpenCL, checkThrows) { int a; EXPECT_NO_THROW(a = 1); } #endif <|endoftext|>
<commit_before>/* Copyright 2017 Thomas Krause <thomaskrause@posteo.de> 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 "queryconfig.h" #include "annis/types.h" // for Component annis::QueryConfig::QueryConfig() : optimize(true), forceFallback(false), avoidNestedBySwitch(true) , numOfBackgroundTasks(0), enableTaskIndexJoin(false), enableThreadIndexJoin(false), enableSIMDIndexJoin(false), threadPool(nullptr) { // size_t numOfCPUs = std::thread::hardware_concurrency(); // if(numOfCPUs > 0) // { // numOfBackgroundTasks = numOfCPUs-1; // threadPool = std::make_shared<ThreadPool>(numOfBackgroundTasks); // } } <commit_msg>Automatically enable SIMDIndexJoin in QueryConfig if current hardware supports it.<commit_after>/* Copyright 2017 Thomas Krause <thomaskrause@posteo.de> 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 "queryconfig.h" #include "annis/types.h" // for Component #include <Vc/global.h> #include <Vc/support.h> annis::QueryConfig::QueryConfig() : optimize(true), forceFallback(false), avoidNestedBySwitch(true) , numOfBackgroundTasks(0), enableTaskIndexJoin(false), enableThreadIndexJoin(false), enableSIMDIndexJoin(false), threadPool(nullptr) { if(Vc::isImplementationSupported(Vc::Implementation::AVX2Impl)) { enableSIMDIndexJoin = true; } // size_t numOfCPUs = std::thread::hardware_concurrency(); // if(numOfCPUs > 0) // { // numOfBackgroundTasks = numOfCPUs-1; // threadPool = std::make_shared<ThreadPool>(numOfBackgroundTasks); // } } <|endoftext|>
<commit_before>#ifndef VEXCL_UTIL_HPP #define VEXCL_UTIL_HPP /* The MIT License Copyright (c) 2012-2014 Denis Demidov <dennis.demidov@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file vexcl/util.hpp * \author Denis Demidov <dennis.demidov@gmail.com> * \brief OpenCL general utilities. */ #if defined(_MSC_VER) && ( defined(min) || defined(max) ) # error Please define NOMINMAX macro globally in your project #endif #include <iostream> #include <string> #include <vector> #include <array> #include <tuple> #include <map> #include <stdexcept> #include <algorithm> #include <type_traits> #include <boost/config.hpp> #ifdef BOOST_NO_VARIADIC_TEMPLATES # include <boost/proto/proto.hpp> # include <boost/preprocessor/repetition.hpp> # ifndef VEXCL_MAX_ARITY # define VEXCL_MAX_ARITY BOOST_PROTO_MAX_ARITY # endif #endif namespace vex { /// Check run-time condition. /** Throws std::runtime_error if condition is false */ template <class Condition, class Message> inline void precondition(const Condition &condition, const Message &fail_message) { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4800) #endif if (!condition) throw std::runtime_error(fail_message); #ifdef _MSC_VER # pragma warning(pop) #endif } /// Return next power of 2. inline size_t nextpow2(size_t x) { --x; x |= x >> 1U; x |= x >> 2U; x |= x >> 4U; x |= x >> 8U; x |= x >> 16U; return ++x; } /// Align n to the next multiple of m. inline size_t alignup(size_t n, size_t m = 16U) { return (n + m - 1) / m * m; } template <class T> struct is_tuple : std::false_type {}; #ifndef BOOST_NO_VARIADIC_TEMPLATES template <class... Elem> struct is_tuple < std::tuple<Elem...> > : std::true_type {}; #else #define VEXCL_IS_TUPLE(z, n, unused) \ template <BOOST_PP_ENUM_PARAMS(n, class Elem)> \ struct is_tuple< \ std::tuple<BOOST_PP_ENUM_PARAMS(n, Elem)> > : std::true_type { \ }; BOOST_PP_REPEAT_FROM_TO(1, VEXCL_MAX_ARITY, VEXCL_IS_TUPLE, ~) #undef VEXCL_IS_TUPLE #endif #ifndef BOOST_NO_VARIADIC_TEMPLATES /// Create std::array from arguments template <class T, class... Tail> std::array<T, 1 + sizeof...(Tail)> make_array(T t, Tail... tail) { std::array<T, 1 + sizeof...(Tail)> a = {{t, static_cast<T>(tail)...}}; return a; } #else #define VEXCL_PRINT_PARAM(z, n, data) T ## n t ## n #define VEXCL_INIT_ARRAY(z, n, data) static_cast<T0>(t ## n) #define VEXCL_MAKE_ARRAY(z, n, data) \ template <BOOST_PP_ENUM_PARAMS(n, class T)> \ std::array<T0, n> make_array(BOOST_PP_ENUM(n, VEXCL_PRINT_PARAM, ~)) { \ std::array<T0, n> a = { { BOOST_PP_ENUM(n, VEXCL_INIT_ARRAY, ~) } }; \ return a; \ } BOOST_PP_REPEAT_FROM_TO(1, VEXCL_MAX_ARITY, VEXCL_MAKE_ARRAY, ~) #undef VEXCL_MAKE_ARRAY #undef VEXCL_INIT_ARRAY #undef VEXCL_PRINT_PARAM #endif struct column_owner { const std::vector<size_t> &part; column_owner(const std::vector<size_t> &part) : part(part) {} size_t operator()(size_t c) const { return std::upper_bound(part.begin(), part.end(), c) - part.begin() - 1; } }; } // namespace vex #endif <commit_msg>Check that _VARIADIC_MAX is at least 10<commit_after>#ifndef VEXCL_UTIL_HPP #define VEXCL_UTIL_HPP /* The MIT License Copyright (c) 2012-2014 Denis Demidov <dennis.demidov@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file vexcl/util.hpp * \author Denis Demidov <dennis.demidov@gmail.com> * \brief OpenCL general utilities. */ #if defined(_MSC_VER) # if defined(min) || defined(max) # error Please define NOMINMAX macro globally in your project # endif # if defined(_VARIADIC_MAX) && (_VARIADIC_MAX < 10) # error Please define _VARIADIC_MAX=10 or greater in your project # endif #endif #include <iostream> #include <string> #include <vector> #include <array> #include <tuple> #include <map> #include <stdexcept> #include <algorithm> #include <type_traits> #include <boost/config.hpp> #ifdef BOOST_NO_VARIADIC_TEMPLATES # include <boost/proto/proto.hpp> # include <boost/preprocessor/repetition.hpp> # ifndef VEXCL_MAX_ARITY # define VEXCL_MAX_ARITY BOOST_PROTO_MAX_ARITY # endif #endif namespace vex { /// Check run-time condition. /** Throws std::runtime_error if condition is false */ template <class Condition, class Message> inline void precondition(const Condition &condition, const Message &fail_message) { #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4800) #endif if (!condition) throw std::runtime_error(fail_message); #ifdef _MSC_VER # pragma warning(pop) #endif } /// Return next power of 2. inline size_t nextpow2(size_t x) { --x; x |= x >> 1U; x |= x >> 2U; x |= x >> 4U; x |= x >> 8U; x |= x >> 16U; return ++x; } /// Align n to the next multiple of m. inline size_t alignup(size_t n, size_t m = 16U) { return (n + m - 1) / m * m; } template <class T> struct is_tuple : std::false_type {}; #ifndef BOOST_NO_VARIADIC_TEMPLATES template <class... Elem> struct is_tuple < std::tuple<Elem...> > : std::true_type {}; #else #define VEXCL_IS_TUPLE(z, n, unused) \ template <BOOST_PP_ENUM_PARAMS(n, class Elem)> \ struct is_tuple< \ std::tuple<BOOST_PP_ENUM_PARAMS(n, Elem)> > : std::true_type { \ }; BOOST_PP_REPEAT_FROM_TO(1, VEXCL_MAX_ARITY, VEXCL_IS_TUPLE, ~) #undef VEXCL_IS_TUPLE #endif #ifndef BOOST_NO_VARIADIC_TEMPLATES /// Create std::array from arguments template <class T, class... Tail> std::array<T, 1 + sizeof...(Tail)> make_array(T t, Tail... tail) { std::array<T, 1 + sizeof...(Tail)> a = {{t, static_cast<T>(tail)...}}; return a; } #else #define VEXCL_PRINT_PARAM(z, n, data) T ## n t ## n #define VEXCL_INIT_ARRAY(z, n, data) static_cast<T0>(t ## n) #define VEXCL_MAKE_ARRAY(z, n, data) \ template <BOOST_PP_ENUM_PARAMS(n, class T)> \ std::array<T0, n> make_array(BOOST_PP_ENUM(n, VEXCL_PRINT_PARAM, ~)) { \ std::array<T0, n> a = { { BOOST_PP_ENUM(n, VEXCL_INIT_ARRAY, ~) } }; \ return a; \ } BOOST_PP_REPEAT_FROM_TO(1, VEXCL_MAX_ARITY, VEXCL_MAKE_ARRAY, ~) #undef VEXCL_MAKE_ARRAY #undef VEXCL_INIT_ARRAY #undef VEXCL_PRINT_PARAM #endif struct column_owner { const std::vector<size_t> &part; column_owner(const std::vector<size_t> &part) : part(part) {} size_t operator()(size_t c) const { return std::upper_bound(part.begin(), part.end(), c) - part.begin() - 1; } }; } // namespace vex #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2010-2011 Dmitry Marakasov * * This file is part of glosm. * * glosm is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * glosm 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 glosm. If not, see <http://www.gnu.org/licenses/>. */ #include <err.h> #include <sys/time.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <getopt.h> #if defined(__APPLE__) # include <OpenGL/gl.h> # include <GLUT/glut.h> #else # include <GL/gl.h> # include <GL/glut.h> #endif #include <vector> #include <map> #include <glosm/geomath.h> #include <glosm/Math.hh> #include <glosm/SphericalProjection.hh> #include <glosm/MercatorProjection.hh> #include <glosm/PreloadedXmlDatasource.hh> #include <glosm/GeometryGenerator.hh> #include <glosm/FirstPersonViewer.hh> #include <glosm/GeometryLayer.hh> /* as glut has no OO concept and no feature like setUserData, * please forgive me using global variables pointing to * stack data for now */ FirstPersonViewer viewer; GeometryLayer* layer_p = NULL; int screenw = 1; int screenh = 1; int movementflags = 0; float speed = 200.0f; int lockheight = 0; struct timeval prevtime, curtime, fpstime; int nframes = 0; /* stuff that may eb changed with args */ Projection proj = MercatorProjection(); int tilelevel = -1; void Display(void) { /* update scene */ gettimeofday(&curtime, NULL); float dt = (float)(curtime.tv_sec - prevtime.tv_sec) + (float)(curtime.tv_usec - prevtime.tv_usec)/1000000.0f; /* render frame */ glClearColor(0.5, 0.5, 0.5, 0.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (layer_p) { if (tilelevel >= 0) { int radius = 5000000; layer_p->RequestVisible(BBoxi(viewer.GetPos(MercatorProjection()) - Vector2i(radius, radius), viewer.GetPos(MercatorProjection()) + Vector2i(radius, radius)), 0); layer_p->GarbageCollect(); } layer_p->Render(viewer); } glFlush(); glutSwapBuffers(); /* movement */ if (movementflags) { float myspeed = speed; float height = viewer.MutablePos().z / GEOM_UNITSINMETER; /* don't scale down under 100 meters */ if (height > 100.0) myspeed *= height / 100.0; viewer.Move(movementflags, myspeed, dt); } if (lockheight != 0) viewer.MutablePos().z = lockheight; /* update FPS */ float fpst = (float)(curtime.tv_sec - fpstime.tv_sec) + (float)(curtime.tv_usec - fpstime.tv_usec)/1000000.0f; if (fpst > 10.0) { fprintf(stderr, "FPS: %.3f\n", (float)nframes/fpst); fpstime = curtime; nframes = 0; } prevtime = curtime; nframes++; /* frame limiter */ usleep(10000); } void Reshape(int w, int h) { if (w <= 0) w = 1; if (h <= 0) h = 1; screenw = w; screenh = h; float wanted_fov = 70.0f/180.0f*M_PI; float wanted_aspect = 4.0f/3.0f; float fov, aspect; if ((float)w/(float)h > wanted_aspect) { // wider than wanted fov = wanted_fov; } else { // narrower than wanted float wanted_h = (float)w/wanted_aspect; fov = 2.0f*atanf((float)h / wanted_h * tanf(wanted_fov/2.0f)); } fov = wanted_fov; aspect = (float)w/(float)h; glViewport(0, 0, w, h); viewer.SetFov(fov); viewer.SetAspect(aspect); glutWarpPointer(screenw/2, screenh/2); } void Mouse(int x, int y) { int dx = x - screenw/2; int dy = y - screenh/2; float YawDelta = (float)dx / 500.0; float PitchDelta = -(float)dy / 500.0; viewer.HardRotate(YawDelta, PitchDelta); if (dx != 0 || dy != 0) glutWarpPointer(screenw/2, screenh/2); } void SpecialDown(int key, int, int) { switch (key) { case GLUT_KEY_UP: movementflags |= FirstPersonViewer::FORWARD; break; case GLUT_KEY_DOWN: movementflags |= FirstPersonViewer::BACKWARD; break; case GLUT_KEY_LEFT: movementflags |= FirstPersonViewer::LEFT; break; case GLUT_KEY_RIGHT: movementflags |= FirstPersonViewer::RIGHT; break; default: break; } } void SpecialUp(int key, int, int) { switch (key) { case GLUT_KEY_UP: movementflags &= ~FirstPersonViewer::FORWARD; break; case GLUT_KEY_DOWN: movementflags &= ~FirstPersonViewer::BACKWARD; break; case GLUT_KEY_LEFT: movementflags &= ~FirstPersonViewer::LEFT; break; case GLUT_KEY_RIGHT: movementflags &= ~FirstPersonViewer::RIGHT; break; default: break; } } void KeyDown(unsigned char key, int, int) { switch (key) { case 27: case 'q': exit(0); break; case 'w': movementflags |= FirstPersonViewer::FORWARD; break; case 's': movementflags |= FirstPersonViewer::BACKWARD; break; case 'a': movementflags |= FirstPersonViewer::LEFT; break; case 'd': movementflags |= FirstPersonViewer::RIGHT; break; case 'c': movementflags |= FirstPersonViewer::LOWER; break; case ' ': movementflags |= FirstPersonViewer::HIGHER; break; case 'l': lockheight = (lockheight == 0 ? viewer.MutablePos().z : 0); break; case 'h': lockheight = (lockheight == 0 ? 1750 : 0); break; case '+': speed *= 5.0f; break; case '-': speed /= 5.0f; break; default: break; } } void KeyUp(unsigned char key, int, int) { switch (key) { case 'w': movementflags &= ~FirstPersonViewer::FORWARD; break; case 's': movementflags &= ~FirstPersonViewer::BACKWARD; break; case 'a': movementflags &= ~FirstPersonViewer::LEFT; break; case 'd': movementflags &= ~FirstPersonViewer::RIGHT; break; case 'c': movementflags &= ~FirstPersonViewer::LOWER; break; case ' ': movementflags &= ~FirstPersonViewer::HIGHER; break; default: break; } } void usage(const char* progname) { fprintf(stderr, "Usage: %s [-s] file.osm\n", progname); exit(1); } int real_main(int argc, char** argv) { glutInit(&argc, argv); /* argument parsing */ int c; const char* progname = argv[0]; while ((c = getopt(argc, argv, "st:")) != -1) { switch (c) { case 's': proj = SphericalProjection(); break; case 't': tilelevel = strtol(optarg, NULL, 10); break; default: usage(progname); } } argc -= optind; argv += optind; if (argc != 1) usage(progname); /* load data */ fprintf(stderr, "Loading...\n"); PreloadedXmlDatasource osm_datasource; gettimeofday(&prevtime, NULL); osm_datasource.Load(argv[0]); gettimeofday(&curtime, NULL); fprintf(stderr, "Loaded XML in %.3f seconds\n", (float)(curtime.tv_sec - prevtime.tv_sec) + (float)(curtime.tv_usec - prevtime.tv_usec)/1000000.0f); prevtime = curtime; fpstime = curtime; /* glut init */ glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_MULTISAMPLE); glutInitWindowSize(800, 600); glutCreateWindow("glosm viewer"); glutIgnoreKeyRepeat(1); glutSetCursor(GLUT_CURSOR_NONE); glutDisplayFunc(Display); glutIdleFunc(Display); glutReshapeFunc(Reshape); glutPassiveMotionFunc(Mouse); glutKeyboardFunc(KeyDown); glutKeyboardUpFunc(KeyUp); glutSpecialFunc(SpecialDown); glutSpecialUpFunc(SpecialUp); /* glosm init */ GeometryGenerator geometry_generator(osm_datasource); GeometryLayer layer(proj, geometry_generator); if (tilelevel >= 0) layer.SetTargetLevel(tilelevel); else layer.RequestVisible(geometry_generator.GetBBox(), TileManager::EXPLICIT); layer_p = &layer; int height = fabs((float)geometry_generator.GetBBox().top - (float)geometry_generator.GetBBox().bottom) / GEOM_LONSPAN * WGS84_EARTH_EQ_LENGTH * GEOM_UNITSINMETER / 10.0; viewer.SetPos(Vector3i(geometry_generator.GetCenter(), height)); viewer.HardRotate(0, -M_PI_4); /* main loop */ /* note that this never returns and objects created above * are never properly destroyed; should dump GLUT ASAP */ glutMainLoop(); return 0; } int main(int argc, char** argv) { try { return real_main(argc, argv); } catch (std::exception &e) { fprintf(stderr, "Exception: %s\n", e.what()); } catch (...) { fprintf(stderr, "Unknown exception\n"); } return 1; } <commit_msg>Remove unused include<commit_after>/* * Copyright (C) 2010-2011 Dmitry Marakasov * * This file is part of glosm. * * glosm is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * glosm 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 glosm. If not, see <http://www.gnu.org/licenses/>. */ #include <sys/time.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <getopt.h> #if defined(__APPLE__) # include <OpenGL/gl.h> # include <GLUT/glut.h> #else # include <GL/gl.h> # include <GL/glut.h> #endif #include <vector> #include <map> #include <glosm/geomath.h> #include <glosm/Math.hh> #include <glosm/SphericalProjection.hh> #include <glosm/MercatorProjection.hh> #include <glosm/PreloadedXmlDatasource.hh> #include <glosm/GeometryGenerator.hh> #include <glosm/FirstPersonViewer.hh> #include <glosm/GeometryLayer.hh> /* as glut has no OO concept and no feature like setUserData, * please forgive me using global variables pointing to * stack data for now */ FirstPersonViewer viewer; GeometryLayer* layer_p = NULL; int screenw = 1; int screenh = 1; int movementflags = 0; float speed = 200.0f; int lockheight = 0; struct timeval prevtime, curtime, fpstime; int nframes = 0; /* stuff that may eb changed with args */ Projection proj = MercatorProjection(); int tilelevel = -1; void Display(void) { /* update scene */ gettimeofday(&curtime, NULL); float dt = (float)(curtime.tv_sec - prevtime.tv_sec) + (float)(curtime.tv_usec - prevtime.tv_usec)/1000000.0f; /* render frame */ glClearColor(0.5, 0.5, 0.5, 0.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (layer_p) { if (tilelevel >= 0) { int radius = 5000000; layer_p->RequestVisible(BBoxi(viewer.GetPos(MercatorProjection()) - Vector2i(radius, radius), viewer.GetPos(MercatorProjection()) + Vector2i(radius, radius)), 0); layer_p->GarbageCollect(); } layer_p->Render(viewer); } glFlush(); glutSwapBuffers(); /* movement */ if (movementflags) { float myspeed = speed; float height = viewer.MutablePos().z / GEOM_UNITSINMETER; /* don't scale down under 100 meters */ if (height > 100.0) myspeed *= height / 100.0; viewer.Move(movementflags, myspeed, dt); } if (lockheight != 0) viewer.MutablePos().z = lockheight; /* update FPS */ float fpst = (float)(curtime.tv_sec - fpstime.tv_sec) + (float)(curtime.tv_usec - fpstime.tv_usec)/1000000.0f; if (fpst > 10.0) { fprintf(stderr, "FPS: %.3f\n", (float)nframes/fpst); fpstime = curtime; nframes = 0; } prevtime = curtime; nframes++; /* frame limiter */ usleep(10000); } void Reshape(int w, int h) { if (w <= 0) w = 1; if (h <= 0) h = 1; screenw = w; screenh = h; float wanted_fov = 70.0f/180.0f*M_PI; float wanted_aspect = 4.0f/3.0f; float fov, aspect; if ((float)w/(float)h > wanted_aspect) { // wider than wanted fov = wanted_fov; } else { // narrower than wanted float wanted_h = (float)w/wanted_aspect; fov = 2.0f*atanf((float)h / wanted_h * tanf(wanted_fov/2.0f)); } fov = wanted_fov; aspect = (float)w/(float)h; glViewport(0, 0, w, h); viewer.SetFov(fov); viewer.SetAspect(aspect); glutWarpPointer(screenw/2, screenh/2); } void Mouse(int x, int y) { int dx = x - screenw/2; int dy = y - screenh/2; float YawDelta = (float)dx / 500.0; float PitchDelta = -(float)dy / 500.0; viewer.HardRotate(YawDelta, PitchDelta); if (dx != 0 || dy != 0) glutWarpPointer(screenw/2, screenh/2); } void SpecialDown(int key, int, int) { switch (key) { case GLUT_KEY_UP: movementflags |= FirstPersonViewer::FORWARD; break; case GLUT_KEY_DOWN: movementflags |= FirstPersonViewer::BACKWARD; break; case GLUT_KEY_LEFT: movementflags |= FirstPersonViewer::LEFT; break; case GLUT_KEY_RIGHT: movementflags |= FirstPersonViewer::RIGHT; break; default: break; } } void SpecialUp(int key, int, int) { switch (key) { case GLUT_KEY_UP: movementflags &= ~FirstPersonViewer::FORWARD; break; case GLUT_KEY_DOWN: movementflags &= ~FirstPersonViewer::BACKWARD; break; case GLUT_KEY_LEFT: movementflags &= ~FirstPersonViewer::LEFT; break; case GLUT_KEY_RIGHT: movementflags &= ~FirstPersonViewer::RIGHT; break; default: break; } } void KeyDown(unsigned char key, int, int) { switch (key) { case 27: case 'q': exit(0); break; case 'w': movementflags |= FirstPersonViewer::FORWARD; break; case 's': movementflags |= FirstPersonViewer::BACKWARD; break; case 'a': movementflags |= FirstPersonViewer::LEFT; break; case 'd': movementflags |= FirstPersonViewer::RIGHT; break; case 'c': movementflags |= FirstPersonViewer::LOWER; break; case ' ': movementflags |= FirstPersonViewer::HIGHER; break; case 'l': lockheight = (lockheight == 0 ? viewer.MutablePos().z : 0); break; case 'h': lockheight = (lockheight == 0 ? 1750 : 0); break; case '+': speed *= 5.0f; break; case '-': speed /= 5.0f; break; default: break; } } void KeyUp(unsigned char key, int, int) { switch (key) { case 'w': movementflags &= ~FirstPersonViewer::FORWARD; break; case 's': movementflags &= ~FirstPersonViewer::BACKWARD; break; case 'a': movementflags &= ~FirstPersonViewer::LEFT; break; case 'd': movementflags &= ~FirstPersonViewer::RIGHT; break; case 'c': movementflags &= ~FirstPersonViewer::LOWER; break; case ' ': movementflags &= ~FirstPersonViewer::HIGHER; break; default: break; } } void usage(const char* progname) { fprintf(stderr, "Usage: %s [-s] file.osm\n", progname); exit(1); } int real_main(int argc, char** argv) { glutInit(&argc, argv); /* argument parsing */ int c; const char* progname = argv[0]; while ((c = getopt(argc, argv, "st:")) != -1) { switch (c) { case 's': proj = SphericalProjection(); break; case 't': tilelevel = strtol(optarg, NULL, 10); break; default: usage(progname); } } argc -= optind; argv += optind; if (argc != 1) usage(progname); /* load data */ fprintf(stderr, "Loading...\n"); PreloadedXmlDatasource osm_datasource; gettimeofday(&prevtime, NULL); osm_datasource.Load(argv[0]); gettimeofday(&curtime, NULL); fprintf(stderr, "Loaded XML in %.3f seconds\n", (float)(curtime.tv_sec - prevtime.tv_sec) + (float)(curtime.tv_usec - prevtime.tv_usec)/1000000.0f); prevtime = curtime; fpstime = curtime; /* glut init */ glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_MULTISAMPLE); glutInitWindowSize(800, 600); glutCreateWindow("glosm viewer"); glutIgnoreKeyRepeat(1); glutSetCursor(GLUT_CURSOR_NONE); glutDisplayFunc(Display); glutIdleFunc(Display); glutReshapeFunc(Reshape); glutPassiveMotionFunc(Mouse); glutKeyboardFunc(KeyDown); glutKeyboardUpFunc(KeyUp); glutSpecialFunc(SpecialDown); glutSpecialUpFunc(SpecialUp); /* glosm init */ GeometryGenerator geometry_generator(osm_datasource); GeometryLayer layer(proj, geometry_generator); if (tilelevel >= 0) layer.SetTargetLevel(tilelevel); else layer.RequestVisible(geometry_generator.GetBBox(), TileManager::EXPLICIT); layer_p = &layer; int height = fabs((float)geometry_generator.GetBBox().top - (float)geometry_generator.GetBBox().bottom) / GEOM_LONSPAN * WGS84_EARTH_EQ_LENGTH * GEOM_UNITSINMETER / 10.0; viewer.SetPos(Vector3i(geometry_generator.GetCenter(), height)); viewer.HardRotate(0, -M_PI_4); /* main loop */ /* note that this never returns and objects created above * are never properly destroyed; should dump GLUT ASAP */ glutMainLoop(); return 0; } int main(int argc, char** argv) { try { return real_main(argc, argv); } catch (std::exception &e) { fprintf(stderr, "Exception: %s\n", e.what()); } catch (...) { fprintf(stderr, "Unknown exception\n"); } return 1; } <|endoftext|>
<commit_before>/* Copyright (C) 2016 Volker Krause <vkrause@kde.org> This program 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 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 Library General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "syntaxhighlighter.h" #include "abstracthighlighter_p.h" #include "definition.h" #include "foldingregion.h" #include "format.h" #include "state.h" #include "theme.h" #include <QDebug> Q_DECLARE_METATYPE(QTextBlock) using namespace KSyntaxHighlighting; namespace KSyntaxHighlighting { class TextBlockUserData : public QTextBlockUserData { public: State state; QVector<FoldingRegion> foldingRegions; }; class SyntaxHighlighterPrivate : public AbstractHighlighterPrivate { public: static FoldingRegion foldingRegion(const QTextBlock &startBlock); QVector<FoldingRegion> foldingRegions; }; } FoldingRegion SyntaxHighlighterPrivate::foldingRegion(const QTextBlock& startBlock) { const auto data = dynamic_cast<TextBlockUserData*>(startBlock.userData()); if (!data) return FoldingRegion(); for (int i = data->foldingRegions.size() - 1; i >= 0; --i) { if (data->foldingRegions.at(i).type() == FoldingRegion::Begin) return data->foldingRegions.at(i); } return FoldingRegion(); } SyntaxHighlighter::SyntaxHighlighter(QObject* parent) : QSyntaxHighlighter(parent), AbstractHighlighter(new SyntaxHighlighterPrivate) { qRegisterMetaType<QTextBlock>(); } SyntaxHighlighter::SyntaxHighlighter(QTextDocument *document) : QSyntaxHighlighter(document), AbstractHighlighter(new SyntaxHighlighterPrivate) { qRegisterMetaType<QTextBlock>(); } SyntaxHighlighter::~SyntaxHighlighter() { } void SyntaxHighlighter::setDefinition(const Definition& def) { const auto needsRehighlight = definition() != def; AbstractHighlighter::setDefinition(def); if (needsRehighlight) rehighlight(); } bool SyntaxHighlighter::startsFoldingRegion(const QTextBlock &startBlock) const { return SyntaxHighlighterPrivate::foldingRegion(startBlock).type() == FoldingRegion::Begin; } QTextBlock SyntaxHighlighter::findFoldingRegionEnd(const QTextBlock &startBlock) const { const auto region = SyntaxHighlighterPrivate::foldingRegion(startBlock); auto block = startBlock; int depth = 1; while (block.isValid()) { block = block.next(); const auto data = dynamic_cast<TextBlockUserData*>(block.userData()); if (!data) continue; for (auto it = data->foldingRegions.constBegin(); it != data->foldingRegions.constEnd(); ++it) { if ((*it).id() != region.id()) continue; if ((*it).type() == FoldingRegion::End) --depth; else if ((*it).type() == FoldingRegion::Begin) ++depth; if (depth == 0) return block; } } return QTextBlock(); } void SyntaxHighlighter::highlightBlock(const QString& text) { Q_D(SyntaxHighlighter); State state; if (currentBlock().position() > 0) { const auto prevBlock = currentBlock().previous(); const auto prevData = dynamic_cast<TextBlockUserData*>(prevBlock.userData()); if (prevData) state = prevData->state; } d->foldingRegions.clear(); state = highlightLine(text, state); auto data = dynamic_cast<TextBlockUserData*>(currentBlockUserData()); if (!data) { // first time we highlight this data = new TextBlockUserData; data->state = state; data->foldingRegions = d->foldingRegions; setCurrentBlockUserData(data); return; } if (data->state == state && data->foldingRegions == d->foldingRegions) // we ended up in the same state, so we are done here return; data->state = state; data->foldingRegions = d->foldingRegions; const auto nextBlock = currentBlock().next(); if (nextBlock.isValid()) QMetaObject::invokeMethod(this, "rehighlightBlock", Qt::QueuedConnection, Q_ARG(QTextBlock, nextBlock)); } void SyntaxHighlighter::applyFormat(int offset, int length, const KSyntaxHighlighting::Format& format) { if (format.isDefaultTextStyle(theme()) || length == 0) return; QTextCharFormat tf; if (format.hasTextColor(theme())) tf.setForeground(format.textColor(theme())); if (format.hasBackgroundColor(theme())) tf.setBackground(format.backgroundColor(theme())); if (format.isBold(theme())) tf.setFontWeight(QFont::Bold); if (format.isItalic(theme())) tf.setFontItalic(true); if (format.isUnderline(theme())) tf.setFontUnderline(true); if (format.isStrikeThrough(theme())) tf.setFontStrikeOut(true); QSyntaxHighlighter::setFormat(offset, length, tf); } void SyntaxHighlighter::applyFolding(int offset, int length, FoldingRegion region) { Q_UNUSED(offset); Q_UNUSED(length); Q_D(SyntaxHighlighter); if (region.type() == FoldingRegion::Begin) d->foldingRegions.push_back(region); if (region.type() == FoldingRegion::End) { for (int i = d->foldingRegions.size() - 1; i >= 0; --i) { if (d->foldingRegions.at(i).id() != region.id() || d->foldingRegions.at(i).type() != FoldingRegion::End) continue; d->foldingRegions.remove(i); return; } d->foldingRegions.push_back(region); } } <commit_msg>Fix folding region merging<commit_after>/* Copyright (C) 2016 Volker Krause <vkrause@kde.org> This program 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 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 Library General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "syntaxhighlighter.h" #include "abstracthighlighter_p.h" #include "definition.h" #include "foldingregion.h" #include "format.h" #include "state.h" #include "theme.h" #include <QDebug> Q_DECLARE_METATYPE(QTextBlock) using namespace KSyntaxHighlighting; namespace KSyntaxHighlighting { class TextBlockUserData : public QTextBlockUserData { public: State state; QVector<FoldingRegion> foldingRegions; }; class SyntaxHighlighterPrivate : public AbstractHighlighterPrivate { public: static FoldingRegion foldingRegion(const QTextBlock &startBlock); QVector<FoldingRegion> foldingRegions; }; } FoldingRegion SyntaxHighlighterPrivate::foldingRegion(const QTextBlock& startBlock) { const auto data = dynamic_cast<TextBlockUserData*>(startBlock.userData()); if (!data) return FoldingRegion(); for (int i = data->foldingRegions.size() - 1; i >= 0; --i) { if (data->foldingRegions.at(i).type() == FoldingRegion::Begin) return data->foldingRegions.at(i); } return FoldingRegion(); } SyntaxHighlighter::SyntaxHighlighter(QObject* parent) : QSyntaxHighlighter(parent), AbstractHighlighter(new SyntaxHighlighterPrivate) { qRegisterMetaType<QTextBlock>(); } SyntaxHighlighter::SyntaxHighlighter(QTextDocument *document) : QSyntaxHighlighter(document), AbstractHighlighter(new SyntaxHighlighterPrivate) { qRegisterMetaType<QTextBlock>(); } SyntaxHighlighter::~SyntaxHighlighter() { } void SyntaxHighlighter::setDefinition(const Definition& def) { const auto needsRehighlight = definition() != def; AbstractHighlighter::setDefinition(def); if (needsRehighlight) rehighlight(); } bool SyntaxHighlighter::startsFoldingRegion(const QTextBlock &startBlock) const { return SyntaxHighlighterPrivate::foldingRegion(startBlock).type() == FoldingRegion::Begin; } QTextBlock SyntaxHighlighter::findFoldingRegionEnd(const QTextBlock &startBlock) const { const auto region = SyntaxHighlighterPrivate::foldingRegion(startBlock); auto block = startBlock; int depth = 1; while (block.isValid()) { block = block.next(); const auto data = dynamic_cast<TextBlockUserData*>(block.userData()); if (!data) continue; for (auto it = data->foldingRegions.constBegin(); it != data->foldingRegions.constEnd(); ++it) { if ((*it).id() != region.id()) continue; if ((*it).type() == FoldingRegion::End) --depth; else if ((*it).type() == FoldingRegion::Begin) ++depth; if (depth == 0) return block; } } return QTextBlock(); } void SyntaxHighlighter::highlightBlock(const QString& text) { Q_D(SyntaxHighlighter); State state; if (currentBlock().position() > 0) { const auto prevBlock = currentBlock().previous(); const auto prevData = dynamic_cast<TextBlockUserData*>(prevBlock.userData()); if (prevData) state = prevData->state; } d->foldingRegions.clear(); state = highlightLine(text, state); auto data = dynamic_cast<TextBlockUserData*>(currentBlockUserData()); if (!data) { // first time we highlight this data = new TextBlockUserData; data->state = state; data->foldingRegions = d->foldingRegions; setCurrentBlockUserData(data); return; } if (data->state == state && data->foldingRegions == d->foldingRegions) // we ended up in the same state, so we are done here return; data->state = state; data->foldingRegions = d->foldingRegions; const auto nextBlock = currentBlock().next(); if (nextBlock.isValid()) QMetaObject::invokeMethod(this, "rehighlightBlock", Qt::QueuedConnection, Q_ARG(QTextBlock, nextBlock)); } void SyntaxHighlighter::applyFormat(int offset, int length, const KSyntaxHighlighting::Format& format) { if (format.isDefaultTextStyle(theme()) || length == 0) return; QTextCharFormat tf; if (format.hasTextColor(theme())) tf.setForeground(format.textColor(theme())); if (format.hasBackgroundColor(theme())) tf.setBackground(format.backgroundColor(theme())); if (format.isBold(theme())) tf.setFontWeight(QFont::Bold); if (format.isItalic(theme())) tf.setFontItalic(true); if (format.isUnderline(theme())) tf.setFontUnderline(true); if (format.isStrikeThrough(theme())) tf.setFontStrikeOut(true); QSyntaxHighlighter::setFormat(offset, length, tf); } void SyntaxHighlighter::applyFolding(int offset, int length, FoldingRegion region) { Q_UNUSED(offset); Q_UNUSED(length); Q_D(SyntaxHighlighter); if (region.type() == FoldingRegion::Begin) d->foldingRegions.push_back(region); if (region.type() == FoldingRegion::End) { for (int i = d->foldingRegions.size() - 1; i >= 0; --i) { if (d->foldingRegions.at(i).id() != region.id() || d->foldingRegions.at(i).type() != FoldingRegion::Begin) continue; d->foldingRegions.remove(i); return; } d->foldingRegions.push_back(region); } } <|endoftext|>
<commit_before>/* * A Remote Debugger for SpiderMonkey Java Script engine. * Copyright (C) 2014-2015 Sławomir Wojtasiak * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "client.hpp" #include <vector> #include <map> #include <string> #include <jsrdbg.h> using namespace JSR; using namespace Utils; using namespace std; /* Client event */ ClientEvent::ClientEvent(int code, int clientId) : Event(code), _clientId(clientId) { } ClientEvent::~ClientEvent() { } int ClientEvent::getID() const { return _clientId; } /* Command. */ Command::Command() : _clientId(0), _contextId(0) { } Command::Command( int clientId, int engineId, const std::string &command ) : _command( command ), _clientId( clientId ), _contextId( engineId ){ } Command::Command( int clientId, int engineId, char *buffer, int offset, size_t size ) : _command( buffer, offset, size ), _clientId( clientId ), _contextId( engineId ) { } Command::Command( const Command &command ) : _command(command._command), _clientId(command._clientId), _contextId(command._contextId) { } Command& Command::operator=( const Command &command ) { if (this != &command) { _command = command._command; _clientId = command._clientId; _contextId = command._contextId; } return *this; } Command::~Command() { } int Command::getClientId() const { return _clientId; } int Command::getContextId() const { return _contextId; } const std::string& Command::getValue() const { return _command; } /* Client. */ Client::Client( int id ) : _inCommands(MAX_CLIENT_QUEUE_LENGTH), _outCommands(MAX_CLIENT_QUEUE_LENGTH), _clientID(id) { } Client::~Client() { } void Client::disconnect() { } bool Client::isConnected() const { return true; } int Client::getID() const { return _clientID; } BlockingQueue<Command>& Client::getInQueue() { return _inCommands; } BlockingQueue<Command>& Client::getOutQueue() { return _outCommands; } /* Client's manager */ ClientManager::ClientManager() : _log(LoggerFactory::getLogger()) { } ClientManager::~ClientManager() { } void ClientManager::start() { } int ClientManager::addClient( Client *client ) { if( !client ) { _log.error( "Cannot add NULL client." ); return JSR_ERROR_ILLEGAL_ARGUMENT; } _mutex.lock(); _clients.insert( std::pair<int,ClientWrapper>( client->getID(), ClientWrapper( client ) ) ); _mutex.unlock(); ClientEvent event(EVENT_CODE_CLIENT_ADDED, client->getID()); fire(event); return JSR_ERROR_NO_ERROR; } void ClientManager::broadcast( Command &command ) { vector<int> ids; // Collect all clients identificators. _mutex.lock(); for( map<int,ClientWrapper>::iterator it = _clients.begin(); it != _clients.end(); it++ ) { ids.push_back(it->first); } _mutex.unlock(); // Now having all identificators collected, try to send commands to clients // that are in conjunction with these identificators. for( vector<int>::iterator it = ids.begin(); it != ids.end(); it++ ) { ClientPtrHolder<Client> client( *this, *it ); // Ignore clients that have been removed in this time window. if( client ) { client->getOutQueue().add( command ); } } } bool ClientManager::sendCommand( Command &command ) { bool result = true; if( command.getClientId() == Command::BROADCAST ) { broadcast( command ); } else { ClientPtrHolder<Client> client( *this, command.getClientId() ); if( client ) { client->getOutQueue().push( command ); } else { result = false; } } return result; } void ClientManager::removeClient( Client *client ) { if( !client ) { _log.error( "Cannot remove NULL client." ); return; } int clientId = 0; int eventCode = 0; tryRemoveClient( client, eventCode ); // Events cannot be fired inside the critical section // just because they might be blocked by actions which use // client manager from different threads, so it could // cause deadlocks. if( eventCode ) { ClientEvent event(eventCode, clientId); fire(event); } } bool ClientManager::tryRemoveClient(Client *client, int &eventCode) { // Only this block should be synchronized. MutexLock lock( _mutex ); int clientId = client->getID(); bool remove = false; // Remove the client if it exists. std::map<int,ClientWrapper>::iterator it = _clients.find( clientId ); if( it != _clients.end() ) { ClientWrapper &wrapper = it->second; if( !wrapper.isMarkedToRemove() ) { if( wrapper.isRemovable() ) { remove = true; } else { wrapper.markRemove(); eventCode = EVENT_CODE_CLIENT_MARKED_TO_REMOVE; } } else if ( wrapper.isRemovable() ) { remove = true; } if( remove ) { _clients.erase( it ); wrapper.deleteClient(); eventCode = EVENT_CODE_CLIENT_REMOVED; } } return remove; } Client* ClientManager::getClient( int id ) { MutexLock lock( _mutex ); std::map<int,ClientWrapper>::iterator it = _clients.find( id ); if( it != _clients.end() ) { return it->second.getClient(); } return NULL; } void ClientManager::returnClient( Client *client ) { if( !client ) { _log.error( "Cannot return NULL client." ); return; } MutexLock lock( _mutex ); std::map<int,ClientWrapper>::iterator it = _clients.find( client->getID() ); if( it != _clients.end() ) { it->second.returnClient( client ); } else { _log.error( "Cannot return client with id: %d, because it doesn't exist in the manager.", client->getID() ); } } void ClientManager::periodicCleanup() { // Vector of clients that were removed. vector<int> removedClients; _mutex.lock(); // Remove client's as soon as they can be removed. map<int,ClientWrapper>::iterator it = _clients.begin(); while (it != _clients.end()) { if (it->second.isMarkedToRemove() && it->second.isRemovable()) { int clientId = it->second.getClient()->getID(); it->second.deleteClient(); map<int,ClientWrapper>::iterator toErase = it; ++it; _clients.erase(toErase); removedClients.push_back(clientId); } else { ++it; } } _mutex.unlock(); // Fire events about removed clients. for( vector<int>::iterator it = removedClients.begin(); it != removedClients.end(); it++ ) { ClientEvent event(EVENT_CODE_CLIENT_REMOVED, *it); fire(event); } } int ClientManager::stop() { // Try to close and delete all existing clients. If any of them are in use yet, // they will be marked as 'to be removed' and can be removed further by calls // to 'periodicCleanup' its why the error code is returned. _mutex.lock(); map<int,ClientWrapper> clients = _clients; vector<int> removedClients; for( map<int,ClientWrapper>::iterator it = clients.begin(); it != clients.end(); it++ ) { int eventCode; Client *client = it->second.getClient(); int clientId = client->getID(); if( tryRemoveClient( client, eventCode ) ) { removedClients.push_back( clientId ); } } bool empty = _clients.empty(); _mutex.unlock(); // Fire events about removed clients. for( vector<int>::iterator it = removedClients.begin(); it != removedClients.end(); it++ ) { ClientEvent event(EVENT_CODE_CLIENT_REMOVED, *it); fire(event); } if( !empty ) { return JSR_ERROR_CANNOT_REMOVE_CONNECTIONS; } return JSR_ERROR_NO_ERROR; } int ClientManager::getClientsCount() { MutexLock lock( _mutex ); int clients = _clients.size(); return clients; } ClientManager::ClientWrapper::ClientWrapper(Client *client) { this->client = client; this->counter = 0; this->removed = false; } ClientManager::ClientWrapper::ClientWrapper(const ClientWrapper &cpy) { this->client = cpy.client; this->counter = cpy.counter; this->removed = cpy.removed; } Client* ClientManager::ClientWrapper::getClient() { counter++; return client; } void ClientManager::ClientWrapper::returnClient( Client *client ) { counter--; } bool ClientManager::ClientWrapper::isConnected() { return client && client->isConnected(); } bool ClientManager::ClientWrapper::isRemovable() { return counter == 0; } void ClientManager::ClientWrapper::markRemove() { removed = true; } bool ClientManager::ClientWrapper::isMarkedToRemove() { return removed; } void ClientManager::ClientWrapper::deleteClient() { delete client; client = NULL; } <commit_msg>Fix dangling reference<commit_after>/* * A Remote Debugger for SpiderMonkey Java Script engine. * Copyright (C) 2014-2015 Sławomir Wojtasiak * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "client.hpp" #include <vector> #include <map> #include <string> #include <jsrdbg.h> using namespace JSR; using namespace Utils; using namespace std; /* Client event */ ClientEvent::ClientEvent(int code, int clientId) : Event(code), _clientId(clientId) { } ClientEvent::~ClientEvent() { } int ClientEvent::getID() const { return _clientId; } /* Command. */ Command::Command() : _clientId(0), _contextId(0) { } Command::Command( int clientId, int engineId, const std::string &command ) : _command( command ), _clientId( clientId ), _contextId( engineId ){ } Command::Command( int clientId, int engineId, char *buffer, int offset, size_t size ) : _command( buffer, offset, size ), _clientId( clientId ), _contextId( engineId ) { } Command::Command( const Command &command ) : _command(command._command), _clientId(command._clientId), _contextId(command._contextId) { } Command& Command::operator=( const Command &command ) { if (this != &command) { _command = command._command; _clientId = command._clientId; _contextId = command._contextId; } return *this; } Command::~Command() { } int Command::getClientId() const { return _clientId; } int Command::getContextId() const { return _contextId; } const std::string& Command::getValue() const { return _command; } /* Client. */ Client::Client( int id ) : _inCommands(MAX_CLIENT_QUEUE_LENGTH), _outCommands(MAX_CLIENT_QUEUE_LENGTH), _clientID(id) { } Client::~Client() { } void Client::disconnect() { } bool Client::isConnected() const { return true; } int Client::getID() const { return _clientID; } BlockingQueue<Command>& Client::getInQueue() { return _inCommands; } BlockingQueue<Command>& Client::getOutQueue() { return _outCommands; } /* Client's manager */ ClientManager::ClientManager() : _log(LoggerFactory::getLogger()) { } ClientManager::~ClientManager() { } void ClientManager::start() { } int ClientManager::addClient( Client *client ) { if( !client ) { _log.error( "Cannot add NULL client." ); return JSR_ERROR_ILLEGAL_ARGUMENT; } _mutex.lock(); _clients.insert( std::pair<int,ClientWrapper>( client->getID(), ClientWrapper( client ) ) ); _mutex.unlock(); ClientEvent event(EVENT_CODE_CLIENT_ADDED, client->getID()); fire(event); return JSR_ERROR_NO_ERROR; } void ClientManager::broadcast( Command &command ) { vector<int> ids; // Collect all clients identificators. _mutex.lock(); for( map<int,ClientWrapper>::iterator it = _clients.begin(); it != _clients.end(); it++ ) { ids.push_back(it->first); } _mutex.unlock(); // Now having all identificators collected, try to send commands to clients // that are in conjunction with these identificators. for( vector<int>::iterator it = ids.begin(); it != ids.end(); it++ ) { ClientPtrHolder<Client> client( *this, *it ); // Ignore clients that have been removed in this time window. if( client ) { client->getOutQueue().add( command ); } } } bool ClientManager::sendCommand( Command &command ) { bool result = true; if( command.getClientId() == Command::BROADCAST ) { broadcast( command ); } else { ClientPtrHolder<Client> client( *this, command.getClientId() ); if( client ) { client->getOutQueue().push( command ); } else { result = false; } } return result; } void ClientManager::removeClient( Client *client ) { if( !client ) { _log.error( "Cannot remove NULL client." ); return; } int clientId = 0; int eventCode = 0; tryRemoveClient( client, eventCode ); // Events cannot be fired inside the critical section // just because they might be blocked by actions which use // client manager from different threads, so it could // cause deadlocks. if( eventCode ) { ClientEvent event(eventCode, clientId); fire(event); } } bool ClientManager::tryRemoveClient(Client *client, int &eventCode) { // Only this block should be synchronized. MutexLock lock( _mutex ); int clientId = client->getID(); bool remove = false; // Remove the client if it exists. std::map<int,ClientWrapper>::iterator it = _clients.find( clientId ); if( it != _clients.end() ) { ClientWrapper &wrapper = it->second; if( !wrapper.isMarkedToRemove() ) { if( wrapper.isRemovable() ) { remove = true; } else { wrapper.markRemove(); eventCode = EVENT_CODE_CLIENT_MARKED_TO_REMOVE; } } else if ( wrapper.isRemovable() ) { remove = true; } if( remove ) { wrapper.deleteClient(); _clients.erase( it ); eventCode = EVENT_CODE_CLIENT_REMOVED; } } return remove; } Client* ClientManager::getClient( int id ) { MutexLock lock( _mutex ); std::map<int,ClientWrapper>::iterator it = _clients.find( id ); if( it != _clients.end() ) { return it->second.getClient(); } return NULL; } void ClientManager::returnClient( Client *client ) { if( !client ) { _log.error( "Cannot return NULL client." ); return; } MutexLock lock( _mutex ); std::map<int,ClientWrapper>::iterator it = _clients.find( client->getID() ); if( it != _clients.end() ) { it->second.returnClient( client ); } else { _log.error( "Cannot return client with id: %d, because it doesn't exist in the manager.", client->getID() ); } } void ClientManager::periodicCleanup() { // Vector of clients that were removed. vector<int> removedClients; _mutex.lock(); // Remove client's as soon as they can be removed. map<int,ClientWrapper>::iterator it = _clients.begin(); while (it != _clients.end()) { if (it->second.isMarkedToRemove() && it->second.isRemovable()) { int clientId = it->second.getClient()->getID(); it->second.deleteClient(); map<int,ClientWrapper>::iterator toErase = it; ++it; _clients.erase(toErase); removedClients.push_back(clientId); } else { ++it; } } _mutex.unlock(); // Fire events about removed clients. for( vector<int>::iterator it = removedClients.begin(); it != removedClients.end(); it++ ) { ClientEvent event(EVENT_CODE_CLIENT_REMOVED, *it); fire(event); } } int ClientManager::stop() { // Try to close and delete all existing clients. If any of them are in use yet, // they will be marked as 'to be removed' and can be removed further by calls // to 'periodicCleanup' its why the error code is returned. _mutex.lock(); map<int,ClientWrapper> clients = _clients; vector<int> removedClients; for( map<int,ClientWrapper>::iterator it = clients.begin(); it != clients.end(); it++ ) { int eventCode; Client *client = it->second.getClient(); int clientId = client->getID(); if( tryRemoveClient( client, eventCode ) ) { removedClients.push_back( clientId ); } } bool empty = _clients.empty(); _mutex.unlock(); // Fire events about removed clients. for( vector<int>::iterator it = removedClients.begin(); it != removedClients.end(); it++ ) { ClientEvent event(EVENT_CODE_CLIENT_REMOVED, *it); fire(event); } if( !empty ) { return JSR_ERROR_CANNOT_REMOVE_CONNECTIONS; } return JSR_ERROR_NO_ERROR; } int ClientManager::getClientsCount() { MutexLock lock( _mutex ); int clients = _clients.size(); return clients; } ClientManager::ClientWrapper::ClientWrapper(Client *client) { this->client = client; this->counter = 0; this->removed = false; } ClientManager::ClientWrapper::ClientWrapper(const ClientWrapper &cpy) { this->client = cpy.client; this->counter = cpy.counter; this->removed = cpy.removed; } Client* ClientManager::ClientWrapper::getClient() { counter++; return client; } void ClientManager::ClientWrapper::returnClient( Client *client ) { counter--; } bool ClientManager::ClientWrapper::isConnected() { return client && client->isConnected(); } bool ClientManager::ClientWrapper::isRemovable() { return counter == 0; } void ClientManager::ClientWrapper::markRemove() { removed = true; } bool ClientManager::ClientWrapper::isMarkedToRemove() { return removed; } void ClientManager::ClientWrapper::deleteClient() { delete client; client = NULL; } <|endoftext|>
<commit_before>#include <glib.h> #include <nan.h> #include "closure.h" #include "macros.h" #include "loop.h" #include "type.h" #include "value.h" using v8::Context; using v8::Function; using v8::HandleScope; using v8::Isolate; using v8::Local; using v8::Object; using v8::Value; using Nan::Persistent; namespace GNodeJS { GClosure *Closure::New(Local<Function> function, guint signalId) { Closure *closure = (Closure *) g_closure_new_simple (sizeof(Closure), NULL); closure->persistent.Reset(function); GClosure *gclosure = &closure->base; g_closure_set_marshal (gclosure, Closure::Marshal); g_closure_add_invalidate_notifier (gclosure, NULL, Closure::Invalidated); return gclosure; } void Closure::Execute(const Nan::Persistent<v8::Function>& persFn, GValue *returnValue, uint nValues, const GValue *values) { Nan::HandleScope scope; auto fn = Nan::New<Function>(persFn); #ifndef __linux__ Local<Value>* jsArgs = new Local<Value>[nValues]; #else Local<Value> jsArgs[nValues]; #endif for (uint i = 0; i < nValues; i++) { bool mustCopy = true; // TODO: get information about mustCopy jsArgs[i] = GValueToV8(&values[i], mustCopy); } Local<Object> self = fn; Local<Value> return_value; Nan::TryCatch try_catch; auto result = Nan::Call(fn, self, nValues, jsArgs); if (!try_catch.HasCaught() && result.ToLocal(&return_value)) { if (returnValue) { if (G_VALUE_TYPE(returnValue) == G_TYPE_INVALID) WARN ("Marshal: return value has invalid g_type"); else if (!V8ToGValue (returnValue, return_value, true)) WARN ("Marshal: could not convert return value"); } CallMicrotaskHandlers(); } else { GNodeJS::QuitLoopStack(); Nan::FatalException(try_catch); } #ifndef __linux__ delete[] jsArgs; #endif } void Closure::Marshal(GClosure *base, GValue *g_return_value, uint n_param_values, const GValue *param_values, gpointer invocation_hint, gpointer marshal_data) { auto closure = (Closure *) base; // We don't pass the implicit instance as first argument AsyncCallEnvironment* env = reinterpret_cast<AsyncCallEnvironment *>(Closure::asyncHandle.data); uv_thread_t thread = uv_thread_self(); if (uv_thread_equal(&thread, &env->mainThread)) { Closure::Execute(closure->persistent, g_return_value, n_param_values - 1, param_values + 1); } else { CallbackWrapper* cb = new CallbackWrapper(); cb->Prepare(&closure->persistent, g_return_value, n_param_values - 1, param_values + 1); uv_mutex_lock(&env->mutex); env->queue.push(cb); uv_mutex_unlock(&env->mutex); uv_async_send(&Closure::asyncHandle); cb->Wait(); } } void Closure::Invalidated (gpointer data, GClosure *base) { Closure *closure = (Closure *) base; closure->~Closure(); } uv_async_t Closure::asyncHandle; void Closure::QueueHandler(uv_async_t* handle) { AsyncCallEnvironment* data = reinterpret_cast<AsyncCallEnvironment *>(handle->data); uv_mutex_lock(&data->mutex); while (!data->queue.empty()) { CallbackWrapper* cb = data->queue.front(); cb->Execute(); data->queue.pop(); delete cb; } uv_mutex_unlock(&data->mutex); } void Closure::Initialize() { auto& handle = Closure::asyncHandle; AsyncCallEnvironment* env = new AsyncCallEnvironment(); handle.data = env; env->mainThread = uv_thread_self(); uv_loop_t* loop = uv_default_loop(); uv_async_init(loop, &handle, Closure::QueueHandler); uv_mutex_init(&env->mutex); uv_unref(reinterpret_cast<uv_handle_t *>(&handle)); uv_async_send(&handle); } CallbackWrapper::CallbackWrapper() { uv_mutex_init(&mutex); // uv_mutex_lock(&mutex); uv_cond_init(&cond); } CallbackWrapper::~CallbackWrapper() { // uv_mutex_unlock(&mutex); uv_cond_destroy(&cond); uv_mutex_destroy(&mutex); } void CallbackWrapper::Execute() { Closure::Execute(*persistent, returnValue, nValues, values); Done(); } void CallbackWrapper::Prepare(const Nan::Persistent<v8::Function>* persistentIn, GValue* returnValueIn, uint nValuesIn, const GValue* valuesIn) { // copy values persistent = persistentIn; returnValue = returnValueIn; nValues = nValuesIn; values = new GValue[nValues]; for (uint i = 0; i < nValues; ++i) { values[i] = G_VALUE_INIT; g_value_init(&values[i], G_VALUE_TYPE(&valuesIn[i])); g_value_copy(&valuesIn[i], &values[i]); } } void CallbackWrapper::Done() { uv_mutex_lock(&mutex); uv_cond_signal(&cond); uv_mutex_unlock(&mutex); } void CallbackWrapper::Wait() { uv_cond_wait(&cond, &mutex); } }; <commit_msg>Remove old locking code<commit_after>#include <glib.h> #include <nan.h> #include "closure.h" #include "macros.h" #include "loop.h" #include "type.h" #include "value.h" using v8::Context; using v8::Function; using v8::HandleScope; using v8::Isolate; using v8::Local; using v8::Object; using v8::Value; using Nan::Persistent; namespace GNodeJS { GClosure *Closure::New(Local<Function> function, guint signalId) { Closure *closure = (Closure *) g_closure_new_simple (sizeof(Closure), NULL); closure->persistent.Reset(function); GClosure *gclosure = &closure->base; g_closure_set_marshal (gclosure, Closure::Marshal); g_closure_add_invalidate_notifier (gclosure, NULL, Closure::Invalidated); return gclosure; } void Closure::Execute(const Nan::Persistent<v8::Function>& persFn, GValue *returnValue, uint nValues, const GValue *values) { Nan::HandleScope scope; auto fn = Nan::New<Function>(persFn); #ifndef __linux__ Local<Value>* jsArgs = new Local<Value>[nValues]; #else Local<Value> jsArgs[nValues]; #endif for (uint i = 0; i < nValues; i++) { bool mustCopy = true; // TODO: get information about mustCopy jsArgs[i] = GValueToV8(&values[i], mustCopy); } Local<Object> self = fn; Local<Value> return_value; Nan::TryCatch try_catch; auto result = Nan::Call(fn, self, nValues, jsArgs); if (!try_catch.HasCaught() && result.ToLocal(&return_value)) { if (returnValue) { if (G_VALUE_TYPE(returnValue) == G_TYPE_INVALID) WARN ("Marshal: return value has invalid g_type"); else if (!V8ToGValue (returnValue, return_value, true)) WARN ("Marshal: could not convert return value"); } CallMicrotaskHandlers(); } else { GNodeJS::QuitLoopStack(); Nan::FatalException(try_catch); } #ifndef __linux__ delete[] jsArgs; #endif } void Closure::Marshal(GClosure *base, GValue *g_return_value, uint n_param_values, const GValue *param_values, gpointer invocation_hint, gpointer marshal_data) { auto closure = (Closure *) base; // We don't pass the implicit instance as first argument AsyncCallEnvironment* env = reinterpret_cast<AsyncCallEnvironment *>(Closure::asyncHandle.data); uv_thread_t thread = uv_thread_self(); if (uv_thread_equal(&thread, &env->mainThread)) { Closure::Execute(closure->persistent, g_return_value, n_param_values - 1, param_values + 1); } else { CallbackWrapper* cb = new CallbackWrapper(); cb->Prepare(&closure->persistent, g_return_value, n_param_values - 1, param_values + 1); uv_mutex_lock(&env->mutex); env->queue.push(cb); uv_mutex_unlock(&env->mutex); uv_async_send(&Closure::asyncHandle); cb->Wait(); } } void Closure::Invalidated (gpointer data, GClosure *base) { Closure *closure = (Closure *) base; closure->~Closure(); } uv_async_t Closure::asyncHandle; void Closure::QueueHandler(uv_async_t* handle) { AsyncCallEnvironment* data = reinterpret_cast<AsyncCallEnvironment *>(handle->data); uv_mutex_lock(&data->mutex); while (!data->queue.empty()) { CallbackWrapper* cb = data->queue.front(); cb->Execute(); data->queue.pop(); delete cb; } uv_mutex_unlock(&data->mutex); } void Closure::Initialize() { auto& handle = Closure::asyncHandle; AsyncCallEnvironment* env = new AsyncCallEnvironment(); handle.data = env; env->mainThread = uv_thread_self(); uv_loop_t* loop = uv_default_loop(); uv_async_init(loop, &handle, Closure::QueueHandler); uv_mutex_init(&env->mutex); uv_unref(reinterpret_cast<uv_handle_t *>(&handle)); uv_async_send(&handle); } CallbackWrapper::CallbackWrapper() { uv_mutex_init(&mutex); uv_cond_init(&cond); } CallbackWrapper::~CallbackWrapper() { uv_cond_destroy(&cond); uv_mutex_destroy(&mutex); } void CallbackWrapper::Execute() { Closure::Execute(*persistent, returnValue, nValues, values); Done(); } void CallbackWrapper::Prepare(const Nan::Persistent<v8::Function>* persistentIn, GValue* returnValueIn, uint nValuesIn, const GValue* valuesIn) { // copy values persistent = persistentIn; returnValue = returnValueIn; nValues = nValuesIn; values = new GValue[nValues]; for (uint i = 0; i < nValues; ++i) { values[i] = G_VALUE_INIT; g_value_init(&values[i], G_VALUE_TYPE(&valuesIn[i])); g_value_copy(&valuesIn[i], &values[i]); } } void CallbackWrapper::Done() { uv_mutex_lock(&mutex); uv_cond_signal(&cond); uv_mutex_unlock(&mutex); } void CallbackWrapper::Wait() { uv_cond_wait(&cond, &mutex); } }; <|endoftext|>
<commit_before>#include <tests/lib/test.h> #include <tests/lib/glib-helpers/test-conn-helper.h> #include <tests/lib/glib/contacts-conn.h> #include <TelepathyQt4/Connection> #include <TelepathyQt4/Contact> #include <TelepathyQt4/ContactManager> #include <TelepathyQt4/PendingContacts> #include <TelepathyQt4/PendingContactInfo> #include <telepathy-glib/debug.h> using namespace Tp; class TestContactsInfo : public Test { Q_OBJECT public: TestContactsInfo(QObject *parent = 0) : Test(parent), mConn(0), mContactsInfoFieldsUpdated(0) { } protected Q_SLOTS: void onContactInfoFieldsChanged(const Tp::Contact::InfoFields &); private Q_SLOTS: void initTestCase(); void init(); void testInfo(); void cleanup(); void cleanupTestCase(); private: TestConnHelper *mConn; int mContactsInfoFieldsUpdated; }; void TestContactsInfo::onContactInfoFieldsChanged(const Tp::Contact::InfoFields &info) { Q_UNUSED(info); mContactsInfoFieldsUpdated++; mLoop->exit(0); } void TestContactsInfo::initTestCase() { initTestCaseImpl(); g_type_init(); g_set_prgname("contacts-info"); tp_debug_set_flags("all"); dbus_g_bus_get(DBUS_BUS_STARTER, 0); mConn = new TestConnHelper(this, TP_TESTS_TYPE_CONTACTS_CONNECTION, "account", "me@example.com", "protocol", "foo", NULL); QCOMPARE(mConn->connect(), true); } void TestContactsInfo::init() { initImpl(); mContactsInfoFieldsUpdated = 0; } void TestContactsInfo::testInfo() { ContactManagerPtr contactManager = mConn->client()->contactManager(); QVERIFY(contactManager->supportedFeatures().contains(Contact::FeatureInfo)); QStringList validIDs = QStringList() << QLatin1String("foo") << QLatin1String("bar"); QList<ContactPtr> contacts = mConn->contacts(validIDs, Contact::FeatureInfo); QCOMPARE(contacts.size(), validIDs.size()); for (int i = 0; i < contacts.size(); i++) { ContactPtr contact = contacts[i]; QCOMPARE(contact->requestedFeatures().contains(Contact::FeatureInfo), true); QCOMPARE(contact->actualFeatures().contains(Contact::FeatureInfo), true); QVERIFY(contact->infoFields().allFields().isEmpty()); QVERIFY(connect(contact.data(), SIGNAL(infoFieldsChanged(const Tp::Contact::InfoFields &)), SLOT(onContactInfoFieldsChanged(const Tp::Contact::InfoFields &)))); } GPtrArray *info_1 = (GPtrArray *) dbus_g_type_specialized_construct ( TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST); { const gchar * const field_values[2] = { "Foo", NULL }; g_ptr_array_add (info_1, tp_value_array_build (3, G_TYPE_STRING, "n", G_TYPE_STRV, NULL, G_TYPE_STRV, field_values, G_TYPE_INVALID)); } GPtrArray *info_2 = (GPtrArray *) dbus_g_type_specialized_construct ( TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST); { const gchar * const field_values[2] = { "Bar", NULL }; g_ptr_array_add (info_2, tp_value_array_build (3, G_TYPE_STRING, "n", G_TYPE_STRV, NULL, G_TYPE_STRV, field_values, G_TYPE_INVALID)); } TpHandle handles[] = { 0, 0 }; TpHandleRepoIface *serviceRepo = tp_base_connection_get_handles( TP_BASE_CONNECTION(mConn->service()), TP_HANDLE_TYPE_CONTACT); for (unsigned i = 0; i < 2; i++) { handles[i] = tp_handle_ensure(serviceRepo, qPrintable(validIDs[i]), NULL, NULL); } tp_tests_contacts_connection_change_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()), handles[0], info_1); tp_tests_contacts_connection_change_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()), handles[1], info_2); while (mContactsInfoFieldsUpdated != 2) { QCOMPARE(mLoop->exec(), 0); } QCOMPARE(mContactsInfoFieldsUpdated, 2); mContactsInfoFieldsUpdated = 0; ContactPtr contactFoo = contacts[0]; ContactPtr contactBar = contacts[1]; QCOMPARE(contactFoo->infoFields().isValid(), true); QCOMPARE(contactFoo->infoFields().allFields().size(), 1); QCOMPARE(contactFoo->infoFields().allFields()[0].fieldName, QLatin1String("n")); QCOMPARE(contactFoo->infoFields().allFields()[0].fieldValue[0], QLatin1String("Foo")); QCOMPARE(contactBar->infoFields().isValid(), true); QCOMPARE(contactBar->infoFields().allFields().size(), 1); QCOMPARE(contactBar->infoFields().allFields()[0].fieldName, QLatin1String("n")); QCOMPARE(contactBar->infoFields().allFields()[0].fieldValue[0], QLatin1String("Bar")); Q_FOREACH (const ContactPtr &contact, contacts) { PendingOperation *op = contact->refreshInfo(); QVERIFY(connect(op, SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); } /* nothing changed */ QCOMPARE(mContactsInfoFieldsUpdated, 0); for (int i = 0; i < contacts.size(); i++) { ContactPtr contact = contacts[i]; disconnect(contact.data(), SIGNAL(infoChanged(const Tp::ContactInfoFieldList &)), this, SLOT(onContactInfoChanged(const Tp::ContactInfoFieldList &))); } PendingContactInfo *pci = contactFoo->requestInfo(); QVERIFY(connect(pci, SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); while (!pci->isFinished()) { QCOMPARE(mLoop->exec(), 0); } QCOMPARE(pci->infoFields().isValid(), true); QCOMPARE(pci->infoFields().allFields().size(), 1); QCOMPARE(pci->infoFields().allFields()[0].fieldName, QLatin1String("n")); QCOMPARE(pci->infoFields().allFields()[0].fieldValue[0], QLatin1String("Foo")); g_boxed_free (TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_1); g_ptr_array_unref (info_1); g_boxed_free (TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_2); g_ptr_array_unref (info_2); } void TestContactsInfo::cleanup() { cleanupImpl(); } void TestContactsInfo::cleanupTestCase() { QCOMPARE(mConn->disconnect(), true); delete mConn; cleanupTestCaseImpl(); } QTEST_MAIN(TestContactsInfo) #include "_gen/contacts-info.cpp.moc.hpp" <commit_msg>contacts-info test: Fix signal disconnection.<commit_after>#include <tests/lib/test.h> #include <tests/lib/glib-helpers/test-conn-helper.h> #include <tests/lib/glib/contacts-conn.h> #include <TelepathyQt4/Connection> #include <TelepathyQt4/Contact> #include <TelepathyQt4/ContactManager> #include <TelepathyQt4/PendingContacts> #include <TelepathyQt4/PendingContactInfo> #include <telepathy-glib/debug.h> using namespace Tp; class TestContactsInfo : public Test { Q_OBJECT public: TestContactsInfo(QObject *parent = 0) : Test(parent), mConn(0), mContactsInfoFieldsUpdated(0) { } protected Q_SLOTS: void onContactInfoFieldsChanged(const Tp::Contact::InfoFields &); private Q_SLOTS: void initTestCase(); void init(); void testInfo(); void cleanup(); void cleanupTestCase(); private: TestConnHelper *mConn; int mContactsInfoFieldsUpdated; }; void TestContactsInfo::onContactInfoFieldsChanged(const Tp::Contact::InfoFields &info) { Q_UNUSED(info); mContactsInfoFieldsUpdated++; mLoop->exit(0); } void TestContactsInfo::initTestCase() { initTestCaseImpl(); g_type_init(); g_set_prgname("contacts-info"); tp_debug_set_flags("all"); dbus_g_bus_get(DBUS_BUS_STARTER, 0); mConn = new TestConnHelper(this, TP_TESTS_TYPE_CONTACTS_CONNECTION, "account", "me@example.com", "protocol", "foo", NULL); QCOMPARE(mConn->connect(), true); } void TestContactsInfo::init() { initImpl(); mContactsInfoFieldsUpdated = 0; } void TestContactsInfo::testInfo() { ContactManagerPtr contactManager = mConn->client()->contactManager(); QVERIFY(contactManager->supportedFeatures().contains(Contact::FeatureInfo)); QStringList validIDs = QStringList() << QLatin1String("foo") << QLatin1String("bar"); QList<ContactPtr> contacts = mConn->contacts(validIDs, Contact::FeatureInfo); QCOMPARE(contacts.size(), validIDs.size()); for (int i = 0; i < contacts.size(); i++) { ContactPtr contact = contacts[i]; QCOMPARE(contact->requestedFeatures().contains(Contact::FeatureInfo), true); QCOMPARE(contact->actualFeatures().contains(Contact::FeatureInfo), true); QVERIFY(contact->infoFields().allFields().isEmpty()); QVERIFY(connect(contact.data(), SIGNAL(infoFieldsChanged(const Tp::Contact::InfoFields &)), SLOT(onContactInfoFieldsChanged(const Tp::Contact::InfoFields &)))); } GPtrArray *info_1 = (GPtrArray *) dbus_g_type_specialized_construct ( TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST); { const gchar * const field_values[2] = { "Foo", NULL }; g_ptr_array_add (info_1, tp_value_array_build (3, G_TYPE_STRING, "n", G_TYPE_STRV, NULL, G_TYPE_STRV, field_values, G_TYPE_INVALID)); } GPtrArray *info_2 = (GPtrArray *) dbus_g_type_specialized_construct ( TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST); { const gchar * const field_values[2] = { "Bar", NULL }; g_ptr_array_add (info_2, tp_value_array_build (3, G_TYPE_STRING, "n", G_TYPE_STRV, NULL, G_TYPE_STRV, field_values, G_TYPE_INVALID)); } TpHandle handles[] = { 0, 0 }; TpHandleRepoIface *serviceRepo = tp_base_connection_get_handles( TP_BASE_CONNECTION(mConn->service()), TP_HANDLE_TYPE_CONTACT); for (unsigned i = 0; i < 2; i++) { handles[i] = tp_handle_ensure(serviceRepo, qPrintable(validIDs[i]), NULL, NULL); } tp_tests_contacts_connection_change_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()), handles[0], info_1); tp_tests_contacts_connection_change_contact_info(TP_TESTS_CONTACTS_CONNECTION(mConn->service()), handles[1], info_2); while (mContactsInfoFieldsUpdated != 2) { QCOMPARE(mLoop->exec(), 0); } QCOMPARE(mContactsInfoFieldsUpdated, 2); mContactsInfoFieldsUpdated = 0; ContactPtr contactFoo = contacts[0]; ContactPtr contactBar = contacts[1]; QCOMPARE(contactFoo->infoFields().isValid(), true); QCOMPARE(contactFoo->infoFields().allFields().size(), 1); QCOMPARE(contactFoo->infoFields().allFields()[0].fieldName, QLatin1String("n")); QCOMPARE(contactFoo->infoFields().allFields()[0].fieldValue[0], QLatin1String("Foo")); QCOMPARE(contactBar->infoFields().isValid(), true); QCOMPARE(contactBar->infoFields().allFields().size(), 1); QCOMPARE(contactBar->infoFields().allFields()[0].fieldName, QLatin1String("n")); QCOMPARE(contactBar->infoFields().allFields()[0].fieldValue[0], QLatin1String("Bar")); Q_FOREACH (const ContactPtr &contact, contacts) { PendingOperation *op = contact->refreshInfo(); QVERIFY(connect(op, SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); QCOMPARE(mLoop->exec(), 0); } /* nothing changed */ QCOMPARE(mContactsInfoFieldsUpdated, 0); for (int i = 0; i < contacts.size(); i++) { ContactPtr contact = contacts[i]; QVERIFY(disconnect(contact.data(), SIGNAL(infoFieldsChanged(const Tp::Contact::InfoFields &)), this, SLOT(onContactInfoFieldsChanged(const Tp::Contact::InfoFields &)))); } PendingContactInfo *pci = contactFoo->requestInfo(); QVERIFY(connect(pci, SIGNAL(finished(Tp::PendingOperation*)), SLOT(expectSuccessfulCall(Tp::PendingOperation*)))); while (!pci->isFinished()) { QCOMPARE(mLoop->exec(), 0); } QCOMPARE(pci->infoFields().isValid(), true); QCOMPARE(pci->infoFields().allFields().size(), 1); QCOMPARE(pci->infoFields().allFields()[0].fieldName, QLatin1String("n")); QCOMPARE(pci->infoFields().allFields()[0].fieldValue[0], QLatin1String("Foo")); g_boxed_free (TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_1); g_ptr_array_unref (info_1); g_boxed_free (TP_ARRAY_TYPE_CONTACT_INFO_FIELD_LIST, info_2); g_ptr_array_unref (info_2); } void TestContactsInfo::cleanup() { cleanupImpl(); } void TestContactsInfo::cleanupTestCase() { QCOMPARE(mConn->disconnect(), true); delete mConn; cleanupTestCaseImpl(); } QTEST_MAIN(TestContactsInfo) #include "_gen/contacts-info.cpp.moc.hpp" <|endoftext|>
<commit_before>/* Copyright (c) 2015-2017 Advanced Micro Devices, Inc. All rights reserved. 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 WARRANNTY OF ANY KIND, EXPRESS OR IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* * Conformance test for checking functionality of * hipError_t hipGetDevice(int *device); */ /* HIT_START * BUILD: %t %s ../../test_common.cpp * RUN: %t * HIT_END */ #include "test_common.h" int main() { hipSetDevice(-1); if( hipPeekAtLastError() != hipSuccess) passed(); } <commit_msg>identation change in hipPeekAtLastError<commit_after>/* Copyright (c) 2015-2017 Advanced Micro Devices, Inc. All rights reserved. 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 WARRANNTY OF ANY KIND, EXPRESS OR IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* * Conformance test for checking functionality of * hipError_t hipGetDevice(int *device); */ /* HIT_START * BUILD: %t %s ../../test_common.cpp * RUN: %t * HIT_END */ #include "test_common.h" int main() { hipSetDevice(-1); if(hipPeekAtLastError() != hipSuccess) passed(); } <|endoftext|>
<commit_before>/* vi:set ts=8 sts=8 sw=8: * * Practical Music Search * Copyright (c) 2006-2011 Kim Tore Jensen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "config.h" #include "field.h" #include "console.h" #include "song.h" #include "window.h" #include "topbar.h" #include <stdlib.h> #include <algorithm> using namespace std; extern Fieldtypes fieldtypes; extern Windowmanager wm; Topbar topbar; Config::Config() { setup_default_connection_info(); quit = false; reconnect_delay = 5; use_bell = true; visual_bell = false; show_column_headers = true; show_window_title = true; topbar_height = 1; add_next_interval = 5; autoadvance = true; status_reset_interval = 3; random = false; repeat = false; consume = false; single = false; set_column_headers("artist track title album year length"); topbar.set("{PMS $state [$modes] $elapsed / $length}{$artist / $title / $album / $year}{Queue has $queuesize songs ($queuelength)}"); /* Set up options array */ add_option("host", OPTION_TYPE_STRING, (void *)&host); add_option("port", OPTION_TYPE_STRING, (void *)&port); add_option("password", OPTION_TYPE_STRING, (void *)&password); add_option("reconnectdelay", OPTION_TYPE_UINT, (void *)&reconnect_delay); add_option("addnextinterval", OPTION_TYPE_UINT, (void *)&add_next_interval); add_option("bell", OPTION_TYPE_BOOL, (void *)&use_bell); add_option("visualbell", OPTION_TYPE_BOOL, (void *)&visual_bell); add_option("columnheaders", OPTION_TYPE_BOOL, (void *)&show_column_headers); add_option("windowtitle", OPTION_TYPE_BOOL, (void *)&show_window_title); add_option("autoadvance", OPTION_TYPE_BOOL, (void *)&autoadvance); add_option("resetstatus", OPTION_TYPE_UINT, (void *)&status_reset_interval); add_option("random", OPTION_TYPE_BOOL, (void *)&random); add_option("repeat", OPTION_TYPE_BOOL, (void *)&repeat); add_option("consume", OPTION_TYPE_BOOL, (void *)&consume); add_option("single", OPTION_TYPE_BOOL, (void *)&single); add_option("columns", OPTION_TYPE_COLUMNHEADERS, (void *)&songlist_columns); add_option("topbar", OPTION_TYPE_TOPBAR, (void *)&topbar); add_option("topbarlines", OPTION_TYPE_UINT, (void *)&topbar_height); } int Config::readline(string line) { string optstr; string optval = ""; option_t * opt; size_t pos; bool invert = false; bool show = false; bool negative = false; bool * bopt; int result; /* Locate the identifier */ if (line.size() == 0) { return print_all_options(); } else if ((pos = line.find('=')) != string::npos) { optstr = line.substr(0, pos); if (line.size() > pos + 1) optval = line.substr(pos + 1); } else { optstr = line; } /* Invert or return value? */ switch(optstr[optstr.size()-1] ) { case '?': show = true; optstr = optstr.substr(0, optstr.size() - 1); break; case '!': invert = true; optstr = optstr.substr(0, optstr.size() - 1); break; default: break; } /* Return the option struct if this is a valid option */ if ((opt = get_opt_ptr(optstr)) == NULL) { /* Check if this is a negative boolean (no<option>) */ if (optstr.size() > 2 && optstr.substr(0, 2) == "no" && ((opt = get_opt_ptr(optstr.substr(2))) != NULL) && opt->type == OPTION_TYPE_BOOL) { negative = !invert; optstr = optstr.substr(2); } /* Check if this is an invertion (inv<option>) */ else if (optstr.size() > 3 && optstr.substr(0, 3) == "inv" && ((opt = get_opt_ptr(optstr.substr(3))) != NULL) && opt->type == OPTION_TYPE_BOOL) { invert = true; optstr = optstr.substr(3); } else { sterr("Unknown option: %s", line.c_str()); return false; } } /* Print the option to statusbar */ if (show) { print_option(opt); return true; } /* Invert an option if boolean */ if (invert) { if (opt->type != OPTION_TYPE_BOOL) { stinfo("%s=%s", optstr.c_str(), get_opt_str(opt).c_str()); sterr("Trailing characters: %s", line.c_str()); return false; } bopt = (bool *)opt->ptr; *bopt = !(*bopt); print_option(opt); return true; } /* Check for (negative) boolean options */ if (optval.size() == 0 && pos == string::npos) { /* Show option instead */ if (opt->type != OPTION_TYPE_BOOL) { print_option(opt); return true; } bopt = (bool *)opt->ptr; *bopt = !negative; print_option(opt); return true; } /* Set the new string value */ result = set_opt_str(opt, optval); if (result) print_option(opt); return result; } option_t * Config::add_option(string name, option_type_t type, void * ptr) { option_t * o = new option_t; o->name = name; o->type = type; o->ptr = ptr; options.push_back(o); return o; } string Config::get_opt_str(option_t * opt) { vector<Field *>::const_iterator field_it; string str = ""; unsigned int * ui; int * i; bool * b; if (opt == NULL) return str; switch(opt->type) { case OPTION_TYPE_STRING: str = (*(string *)opt->ptr); break; case OPTION_TYPE_BOOL: b = (bool *)opt->ptr; str = !(*b) ? "no" : ""; str += opt->name; break; case OPTION_TYPE_UINT: ui = (unsigned int *)opt->ptr; str = tostring(*ui); break; case OPTION_TYPE_INT: i = (int *)opt->ptr; str = tostring(*i); break; /* Exotic data types */ case OPTION_TYPE_COLUMNHEADERS: for (field_it = songlist_columns.begin(); field_it != songlist_columns.end(); ++field_it) str = str + (*field_it)->str + " "; str = str.substr(0, str.size() - 1); break; case OPTION_TYPE_TOPBAR: str = topbar.cached_format; break; default: str = "<unknown>"; break; } return str; } int Config::set_opt_str(option_t * opt, string value) { string * s; int * i; unsigned int * ui; if (opt == NULL) return false; switch(opt->type) { case OPTION_TYPE_STRING: s = (string *)opt->ptr; *s = value; return true; case OPTION_TYPE_INT: i = (int *)opt->ptr; *i = atoi(value.c_str()); return true; case OPTION_TYPE_UINT: ui = (unsigned int *)opt->ptr; *ui = atoi(value.c_str()); return true; case OPTION_TYPE_COLUMNHEADERS: set_column_headers(value); wm.update_column_length(); return true; case OPTION_TYPE_TOPBAR: topbar.set(value); if (topbar.lines[0].size() > topbar_height) { topbar_height = topbar.lines[0].size(); print_option(get_opt_ptr("topbarlines")); } return true; default: return false; } return false; } option_t * Config::get_opt_ptr(string opt) { vector<option_t *>::const_iterator i; for (i = options.begin(); i != options.end(); ++i) if ((*i)->name == opt) return *i; return NULL; } unsigned int Config::grep_opt(string opt, vector<option_t *> * list, string * prefix) { vector<option_t *>::const_iterator i; if (!list) return 0; list->clear(); /* Check for "no..." and "inv..." options, which also needs to be tab-completed. */ if (opt.size() >= 2 && opt.substr(0, 2) == "no") *prefix = "no"; else if (opt.size() >= 3 && opt.substr(0, 3) == "inv") *prefix = "inv"; else prefix->clear(); if (prefix->size() > 0) { if (opt.size() == prefix->size()) opt.clear(); else opt = opt.substr(prefix->size()); } for (i = options.begin(); i != options.end(); i++) { if (opt.size() > (*i)->name.size()) continue; if (opt == (*i)->name.substr(0, opt.size())) { if (prefix->size() == 0 || (*i)->type == OPTION_TYPE_BOOL || ((*i)->name.size() > prefix->size() && (*i)->name.substr(0, prefix->size()) == *prefix)) list->push_back(*i); } } return list->size(); } void Config::print_option(option_t * opt) { if (opt == NULL) return; else if (opt->type == OPTION_TYPE_BOOL) stinfo(" %s", get_opt_str(opt).c_str()); else stinfo(" %s=%s", opt->name.c_str(), get_opt_str(opt).c_str()); } int Config::print_all_options() { vector<option_t *>::const_iterator i; debug("--- Options ---", NULL); for (i = options.begin(); i != options.end(); ++i) print_option(*i); return true; } void Config::set_column_headers(string hdr) { size_t start = 0; size_t pos; string f; Field * field; songlist_columns.clear(); while (start + 1 < hdr.size()) { if (pos == string::npos) break; if ((pos = hdr.find(' ', start)) != string::npos) f = hdr.substr(start, pos - start); else f = hdr.substr(start); if ((field = fieldtypes.find(f)) != NULL && field->type < FIELD_COLUMN_VALUES) songlist_columns.push_back(field); else sterr("Ignoring invalid header field '%s'.", f.c_str()); start = pos + 1; } if (songlist_columns.size() == 0) { f = "title"; sterr("Warning: at least one column type needs to be specified, falling back to `%s'.", f.c_str()); songlist_columns.push_back(fieldtypes.find(f)); } } void Config::setup_default_connection_info() { char * env; size_t i; password = ""; if ((env = getenv("MPD_HOST")) == NULL) { host = "localhost"; } else { host = env; if ((i = host.rfind('@')) != string::npos) { password = host.substr(0, i); host = host.substr(i + 1); } } if ((env = getenv("MPD_PORT")) == NULL) port = "6600"; else port = env; } <commit_msg>Options can be set with set opt=val and set opt:val.<commit_after>/* vi:set ts=8 sts=8 sw=8: * * Practical Music Search * Copyright (c) 2006-2011 Kim Tore Jensen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "config.h" #include "field.h" #include "console.h" #include "song.h" #include "window.h" #include "topbar.h" #include <stdlib.h> #include <algorithm> using namespace std; extern Fieldtypes fieldtypes; extern Windowmanager wm; Topbar topbar; Config::Config() { setup_default_connection_info(); quit = false; reconnect_delay = 5; use_bell = true; visual_bell = false; show_column_headers = true; show_window_title = true; topbar_height = 1; add_next_interval = 5; autoadvance = true; status_reset_interval = 3; random = false; repeat = false; consume = false; single = false; set_column_headers("artist track title album year length"); topbar.set("{PMS $state [$modes] $elapsed / $length}{$artist / $title / $album / $year}{Queue has $queuesize songs ($queuelength)}"); /* Set up options array */ add_option("host", OPTION_TYPE_STRING, (void *)&host); add_option("port", OPTION_TYPE_STRING, (void *)&port); add_option("password", OPTION_TYPE_STRING, (void *)&password); add_option("reconnectdelay", OPTION_TYPE_UINT, (void *)&reconnect_delay); add_option("addnextinterval", OPTION_TYPE_UINT, (void *)&add_next_interval); add_option("bell", OPTION_TYPE_BOOL, (void *)&use_bell); add_option("visualbell", OPTION_TYPE_BOOL, (void *)&visual_bell); add_option("columnheaders", OPTION_TYPE_BOOL, (void *)&show_column_headers); add_option("windowtitle", OPTION_TYPE_BOOL, (void *)&show_window_title); add_option("autoadvance", OPTION_TYPE_BOOL, (void *)&autoadvance); add_option("resetstatus", OPTION_TYPE_UINT, (void *)&status_reset_interval); add_option("random", OPTION_TYPE_BOOL, (void *)&random); add_option("repeat", OPTION_TYPE_BOOL, (void *)&repeat); add_option("consume", OPTION_TYPE_BOOL, (void *)&consume); add_option("single", OPTION_TYPE_BOOL, (void *)&single); add_option("columns", OPTION_TYPE_COLUMNHEADERS, (void *)&songlist_columns); add_option("topbar", OPTION_TYPE_TOPBAR, (void *)&topbar); add_option("topbarlines", OPTION_TYPE_UINT, (void *)&topbar_height); } int Config::readline(string line) { string optstr; string optval = ""; option_t * opt; size_t pos; bool invert = false; bool show = false; bool negative = false; bool * bopt; int result; /* Locate the identifier */ if (line.size() == 0) { return print_all_options(); } else if ((pos = line.find_first_of("=:")) != string::npos) { optstr = line.substr(0, pos); if (line.size() > pos + 1) optval = line.substr(pos + 1); } else { optstr = line; } /* Invert or return value? */ switch(optstr[optstr.size()-1] ) { case '?': show = true; optstr = optstr.substr(0, optstr.size() - 1); break; case '!': invert = true; optstr = optstr.substr(0, optstr.size() - 1); break; default: break; } /* Return the option struct if this is a valid option */ if ((opt = get_opt_ptr(optstr)) == NULL) { /* Check if this is a negative boolean (no<option>) */ if (optstr.size() > 2 && optstr.substr(0, 2) == "no" && ((opt = get_opt_ptr(optstr.substr(2))) != NULL) && opt->type == OPTION_TYPE_BOOL) { negative = !invert; optstr = optstr.substr(2); } /* Check if this is an invertion (inv<option>) */ else if (optstr.size() > 3 && optstr.substr(0, 3) == "inv" && ((opt = get_opt_ptr(optstr.substr(3))) != NULL) && opt->type == OPTION_TYPE_BOOL) { invert = true; optstr = optstr.substr(3); } else { sterr("Unknown option: %s", line.c_str()); return false; } } /* Print the option to statusbar */ if (show) { print_option(opt); return true; } /* Invert an option if boolean */ if (invert) { if (opt->type != OPTION_TYPE_BOOL) { stinfo("%s=%s", optstr.c_str(), get_opt_str(opt).c_str()); sterr("Trailing characters: %s", line.c_str()); return false; } bopt = (bool *)opt->ptr; *bopt = !(*bopt); print_option(opt); return true; } /* Check for (negative) boolean options */ if (optval.size() == 0 && pos == string::npos) { /* Show option instead */ if (opt->type != OPTION_TYPE_BOOL) { print_option(opt); return true; } bopt = (bool *)opt->ptr; *bopt = !negative; print_option(opt); return true; } /* Set the new string value */ result = set_opt_str(opt, optval); if (result) print_option(opt); return result; } option_t * Config::add_option(string name, option_type_t type, void * ptr) { option_t * o = new option_t; o->name = name; o->type = type; o->ptr = ptr; options.push_back(o); return o; } string Config::get_opt_str(option_t * opt) { vector<Field *>::const_iterator field_it; string str = ""; unsigned int * ui; int * i; bool * b; if (opt == NULL) return str; switch(opt->type) { case OPTION_TYPE_STRING: str = (*(string *)opt->ptr); break; case OPTION_TYPE_BOOL: b = (bool *)opt->ptr; str = !(*b) ? "no" : ""; str += opt->name; break; case OPTION_TYPE_UINT: ui = (unsigned int *)opt->ptr; str = tostring(*ui); break; case OPTION_TYPE_INT: i = (int *)opt->ptr; str = tostring(*i); break; /* Exotic data types */ case OPTION_TYPE_COLUMNHEADERS: for (field_it = songlist_columns.begin(); field_it != songlist_columns.end(); ++field_it) str = str + (*field_it)->str + " "; str = str.substr(0, str.size() - 1); break; case OPTION_TYPE_TOPBAR: str = topbar.cached_format; break; default: str = "<unknown>"; break; } return str; } int Config::set_opt_str(option_t * opt, string value) { string * s; int * i; unsigned int * ui; if (opt == NULL) return false; switch(opt->type) { case OPTION_TYPE_STRING: s = (string *)opt->ptr; *s = value; return true; case OPTION_TYPE_INT: i = (int *)opt->ptr; *i = atoi(value.c_str()); return true; case OPTION_TYPE_UINT: ui = (unsigned int *)opt->ptr; *ui = atoi(value.c_str()); return true; case OPTION_TYPE_COLUMNHEADERS: set_column_headers(value); wm.update_column_length(); return true; case OPTION_TYPE_TOPBAR: topbar.set(value); if (topbar.lines[0].size() > topbar_height) { topbar_height = topbar.lines[0].size(); print_option(get_opt_ptr("topbarlines")); } return true; default: return false; } return false; } option_t * Config::get_opt_ptr(string opt) { vector<option_t *>::const_iterator i; for (i = options.begin(); i != options.end(); ++i) if ((*i)->name == opt) return *i; return NULL; } unsigned int Config::grep_opt(string opt, vector<option_t *> * list, string * prefix) { vector<option_t *>::const_iterator i; if (!list) return 0; list->clear(); /* Check for "no..." and "inv..." options, which also needs to be tab-completed. */ if (opt.size() >= 2 && opt.substr(0, 2) == "no") *prefix = "no"; else if (opt.size() >= 3 && opt.substr(0, 3) == "inv") *prefix = "inv"; else prefix->clear(); if (prefix->size() > 0) { if (opt.size() == prefix->size()) opt.clear(); else opt = opt.substr(prefix->size()); } for (i = options.begin(); i != options.end(); i++) { if (opt.size() > (*i)->name.size()) continue; if (opt == (*i)->name.substr(0, opt.size())) { if (prefix->size() == 0 || (*i)->type == OPTION_TYPE_BOOL || ((*i)->name.size() > prefix->size() && (*i)->name.substr(0, prefix->size()) == *prefix)) list->push_back(*i); } } return list->size(); } void Config::print_option(option_t * opt) { if (opt == NULL) return; else if (opt->type == OPTION_TYPE_BOOL) stinfo(" %s", get_opt_str(opt).c_str()); else stinfo(" %s=%s", opt->name.c_str(), get_opt_str(opt).c_str()); } int Config::print_all_options() { vector<option_t *>::const_iterator i; debug("--- Options ---", NULL); for (i = options.begin(); i != options.end(); ++i) print_option(*i); return true; } void Config::set_column_headers(string hdr) { size_t start = 0; size_t pos; string f; Field * field; songlist_columns.clear(); while (start + 1 < hdr.size()) { if (pos == string::npos) break; if ((pos = hdr.find(' ', start)) != string::npos) f = hdr.substr(start, pos - start); else f = hdr.substr(start); if ((field = fieldtypes.find(f)) != NULL && field->type < FIELD_COLUMN_VALUES) songlist_columns.push_back(field); else sterr("Ignoring invalid header field '%s'.", f.c_str()); start = pos + 1; } if (songlist_columns.size() == 0) { f = "title"; sterr("Warning: at least one column type needs to be specified, falling back to `%s'.", f.c_str()); songlist_columns.push_back(fieldtypes.find(f)); } } void Config::setup_default_connection_info() { char * env; size_t i; password = ""; if ((env = getenv("MPD_HOST")) == NULL) { host = "localhost"; } else { host = env; if ((i = host.rfind('@')) != string::npos) { password = host.substr(0, i); host = host.substr(i + 1); } } if ((env = getenv("MPD_PORT")) == NULL) port = "6600"; else port = env; } <|endoftext|>
<commit_before><commit_msg>pre-select name filter in import/export file dialog<commit_after><|endoftext|>
<commit_before> typedef float vec16f __attribute__((__vector_size__(16 * sizeof(int)))); typedef int vec16i __attribute__((__vector_size__(16 * sizeof(int)))); #define PI 3.141579 vec16f fmodv(vec16f val1, vec16f val2) { vec16f multiple = __builtin_vp_vitof(__builtin_vp_vftoi(val1 / val2)); return val1 - (multiple * val2); } // // Use taylor series to approximate sine // x**3/3! + x**5/5! - x**7/7! ... // #define NUM_TERMS 4 float denominators[] = { 0.166666666666667f, // 1 / 3! 0.008333333333333f, // 1 / 5! 0.000198412698413f, // 1 / 7! 0.000002755731922f // 1 / 9! }; vec16f sinev(vec16f angle) { // Works better if angle is smaller angle = fmodv(angle, __builtin_vp_makevectorf(PI)); vec16f numerator = angle * angle * angle; vec16f result = numerator * __builtin_vp_makevectorf(denominators[0]); for (int i = 1; i < NUM_TERMS; i++) { numerator *= numerator; numerator *= numerator; vec16f term = numerator * __builtin_vp_makevectorf(denominators[i]); if (i & 1) result += term; else result -= term; } return result; } vec16f cosv(vec16f angle) { return sinev(angle + __builtin_vp_makevectorf(PI * 0.5f)); } vec16i* const kFrameBufferAddress = (vec16i*) 0x10000000; const vec16i kXOffsets = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; int main() { // Strands work on interleaved chunks of pixels. The strand ID determines // the starting point. int myStrandId = __builtin_vp_get_current_strand(); for (int frameNum = 0; ; frameNum++) { vec16i *ptr = kFrameBufferAddress + myStrandId; for (int y = 0; y < 480; y++) { for (int x = myStrandId * 16; x < 640; x += 64) { vec16i xv = kXOffsets + __builtin_vp_makevectori(x); vec16i yv = __builtin_vp_makevectori(y); vec16i fv = __builtin_vp_makevectori(frameNum); vec16f xfv = __builtin_vp_vitof(xv); vec16f yfv = __builtin_vp_vitof(yv); vec16f intensity = sinev(xfv * __builtin_vp_makevectorf(0.001f)); intensity += sinev(yfv * __builtin_vp_makevectorf(0.01f)); intensity = intensity * __builtin_vp_makevectorf(128.0f) + __builtin_vp_makevectorf(128.0f); vec16i iintensity = __builtin_vp_vftoi(intensity); vec16i pixelValues = iintensity; pixelValues |= iintensity << __builtin_vp_makevectori(8); pixelValues |= iintensity << __builtin_vp_makevectori(16); *ptr = pixelValues; ptr += 4; // Skip over four chunks because there are four threads. } } } return 0; } <commit_msg>Tweaks<commit_after> typedef float vec16f __attribute__((__vector_size__(16 * sizeof(int)))); typedef int vec16i __attribute__((__vector_size__(16 * sizeof(int)))); #define PI 3.141579 vec16f fmodv(vec16f val1, vec16f val2) { vec16f multiple = __builtin_vp_vitof(__builtin_vp_vftoi(val1 / val2)); return val1 - (multiple * val2); } // // Use taylor series to approximate sine // x**3/3! + x**5/5! - x**7/7! ... // #define NUM_TERMS 6 float denominators[] = { 0.166666666666667f, // 1 / 3! 0.008333333333333f, // 1 / 5! 0.000198412698413f, // 1 / 7! 0.000002755731922f, // 1 / 9! 2.50521084e-8f, // 1 / 11! 1.6059044e-10f // 1 / 13! }; vec16f sinev(vec16f angle) { // Works better if angle is smaller angle = fmodv(angle, __builtin_vp_makevectorf(PI)); vec16f angleSquared = angle * angle; vec16f numerator = angle; vec16f result = angle; for (int i = 0; i < NUM_TERMS; i++) { numerator *= angleSquared; vec16f term = numerator * __builtin_vp_makevectorf(denominators[i]); if (i & 1) result += term; else result -= term; } return result; } vec16f cosv(vec16f angle) { return sinev(angle + __builtin_vp_makevectorf(PI * 0.5f)); } vec16i* const kFrameBufferAddress = (vec16i*) 0x10000000; const vec16i kXOffsets = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; int main() { // Strands work on interleaved chunks of pixels. The strand ID determines // the starting point. int myStrandId = __builtin_vp_get_current_strand(); for (int frameNum = 0; ; frameNum++) { vec16i *ptr = kFrameBufferAddress + myStrandId; for (int y = 0; y < 480; y++) { for (int x = myStrandId * 16; x < 640; x += 64) { vec16i xv = kXOffsets + __builtin_vp_makevectori(x); vec16i yv = __builtin_vp_makevectori(y); vec16f ffv = __builtin_vp_makevectorf((float) frameNum); vec16f xfv = __builtin_vp_vitof(xv); vec16f yfv = __builtin_vp_vitof(yv); vec16f intensity = sinev(xfv * __builtin_vp_makevectorf(0.005f)); intensity += sinev((yfv + ffv) * __builtin_vp_makevectorf(0.01f)); intensity = intensity * __builtin_vp_makevectorf(48.0f) + __builtin_vp_makevectorf(128.0f); vec16i iintensity = __builtin_vp_vftoi(intensity); vec16i pixelValues = iintensity; pixelValues |= iintensity << __builtin_vp_makevectori(8); pixelValues |= iintensity << __builtin_vp_makevectori(16); *ptr = pixelValues; ptr += 4; // Skip over four chunks because there are four threads. } } } return 0; } <|endoftext|>
<commit_before>#include <v8.h> #include <node.h> #include <node_version.h> #if !(NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 8) #include "context.h" using namespace node; using namespace v8; static struct gcontext g_context; static uv_prepare_t prepare_handle; static uv_check_t check_handle; GContext::GContext() {} void GContext::Init() { GMainContext *gc = g_main_context_default(); struct gcontext *ctx = &g_context; if (!g_thread_supported()) g_thread_init(NULL); g_main_context_acquire(gc); ctx->gc = g_main_context_ref(gc); ctx->fds = NULL; /* Prepare */ uv_prepare_init(uv_default_loop(), &prepare_handle); uv_prepare_start(&prepare_handle, prepare_cb); /* Check */ uv_check_init(uv_default_loop(), &check_handle); uv_check_start(&check_handle, check_cb); } void GContext::Uninit() { struct gcontext *ctx = &g_context; uv_check_stop(&check_handle); uv_close((uv_handle_t *)&check_handle, NULL); uv_prepare_stop(&prepare_handle); uv_close((uv_handle_t *)&prepare_handle, NULL); g_main_context_unref(ctx->gc); } void GContext::poll_cb(uv_poll_t *handle, int status, int events) { struct gcontext_pollfd *_pfd = (struct gcontext_pollfd *)handle->data; GPollFD *pfd = _pfd->pfd; pfd->revents |= pfd->events & ((events & UV_READABLE ? G_IO_IN : 0) | (events & UV_WRITABLE ? G_IO_OUT : 0)); uv_poll_stop(handle); uv_close((uv_handle_t *)handle, NULL); delete _pfd; } void GContext::prepare_cb(uv_prepare_t *handle, int status) { gint i; gint timeout; struct gcontext *ctx = &g_context; g_main_context_dispatch(ctx->gc); g_main_context_prepare(ctx->gc, &ctx->max_priority); /* Getting all sources from GLib main context */ while(ctx->allocated_nfds < (ctx->nfds = g_main_context_query(ctx->gc, ctx->max_priority, &timeout, ctx->fds, ctx->allocated_nfds))) { g_free(ctx->fds); g_free(ctx->poll_handles); ctx->allocated_nfds = 1; while (ctx->allocated_nfds < ctx->nfds) { ctx->allocated_nfds <<= 1; } ctx->fds = g_new(GPollFD, ctx->allocated_nfds); ctx->poll_handles = g_new(uv_poll_t, ctx->allocated_nfds); } /* Poll */ for (i = 0; i < ctx->nfds; ++i) { GPollFD *pfd = ctx->fds + i; uv_poll_t *pt = ctx->poll_handles + i; struct gcontext_pollfd *data = new gcontext_pollfd; data->pfd = pfd; pt->data = data; pfd->revents = 0; uv_poll_init(uv_default_loop(), pt, pfd->fd); uv_poll_start(pt, UV_READABLE | UV_WRITABLE, poll_cb); } } void GContext::check_cb(uv_check_t *handle, int status) { struct gcontext *ctx = &g_context; g_main_context_check(ctx->gc, ctx->max_priority, ctx->fds, ctx->nfds); } #endif <commit_msg>Fixed a bug that hangs when other module needs glib main context as well.<commit_after>#include <v8.h> #include <node.h> #include <node_version.h> #if !(NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 8) #include "context.h" using namespace node; using namespace v8; static struct gcontext g_context; static uv_prepare_t prepare_handle; static uv_check_t check_handle; GContext::GContext() {} void GContext::Init() { GMainContext *gc = g_main_context_default(); struct gcontext *ctx = &g_context; if (!g_thread_supported()) g_thread_init(NULL); g_main_context_acquire(gc); ctx->gc = g_main_context_ref(gc); ctx->fds = NULL; /* Prepare */ uv_prepare_init(uv_default_loop(), &prepare_handle); uv_prepare_start(&prepare_handle, prepare_cb); /* Check */ uv_check_init(uv_default_loop(), &check_handle); uv_check_start(&check_handle, check_cb); } void GContext::Uninit() { struct gcontext *ctx = &g_context; uv_check_stop(&check_handle); uv_close((uv_handle_t *)&check_handle, NULL); uv_prepare_stop(&prepare_handle); uv_close((uv_handle_t *)&prepare_handle, NULL); g_main_context_unref(ctx->gc); } void GContext::poll_cb(uv_poll_t *handle, int status, int events) { struct gcontext_pollfd *_pfd = (struct gcontext_pollfd *)handle->data; GPollFD *pfd = _pfd->pfd; pfd->revents |= pfd->events & ((events & UV_READABLE ? G_IO_IN : 0) | (events & UV_WRITABLE ? G_IO_OUT : 0)); uv_poll_stop(handle); uv_close((uv_handle_t *)handle, NULL); delete _pfd; } void GContext::prepare_cb(uv_prepare_t *handle, int status) { gint i; gint timeout; struct gcontext *ctx = &g_context; g_main_context_dispatch(ctx->gc); g_main_context_prepare(ctx->gc, &ctx->max_priority); /* Getting all sources from GLib main context */ while(ctx->allocated_nfds < (ctx->nfds = g_main_context_query(ctx->gc, ctx->max_priority, &timeout, ctx->fds, ctx->allocated_nfds))) { g_free(ctx->fds); g_free(ctx->poll_handles); ctx->allocated_nfds = 1; while (ctx->allocated_nfds < ctx->nfds) { ctx->allocated_nfds <<= 1; } ctx->fds = g_new(GPollFD, ctx->allocated_nfds); ctx->poll_handles = g_new(uv_poll_t, ctx->allocated_nfds); } /* Poll */ for (i = 0; i < ctx->nfds; ++i) { GPollFD *pfd = ctx->fds + i; uv_poll_t *pt = ctx->poll_handles + i; struct gcontext_pollfd *data = new gcontext_pollfd; data->pfd = pfd; pt->data = data; pfd->revents = 0; uv_poll_init(uv_default_loop(), pt, pfd->fd); uv_poll_start(pt, UV_READABLE | UV_WRITABLE, poll_cb); } } void GContext::check_cb(uv_check_t *handle, int status) { gint i; struct gcontext *ctx = &g_context; /* Release all polling events which aren't finished yet. */ for (i = 0; i < ctx->nfds; ++i) { GPollFD *pfd = ctx->fds + i; uv_poll_t *pt = ctx->poll_handles + i; if (uv_is_active((uv_handle_t *)pt)) { uv_poll_stop(pt); uv_close((uv_handle_t *)pt, NULL); delete (struct gcontext_pollfd *)pt->data; } } g_main_context_check(ctx->gc, ctx->max_priority, ctx->fds, ctx->nfds); } #endif <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <memory> #include "HexagonOffload.h" #include "IRMutator.h" #include "Substitute.h" #include "Closure.h" #include "Param.h" #include "Image.h" #include "LLVM_Output.h" #include "RemoveTrivialForLoops.h" namespace Halide { namespace Internal { using std::string; using std::vector; namespace { // Replace the parameter objects of loads/stores witha new parameter // object. class ReplaceParams : public IRMutator { const std::map<std::string, Parameter> &replacements; using IRMutator::visit; void visit(const Load *op) { auto i = replacements.find(op->name); if (i != replacements.end()) { expr = Load::make(op->type, op->name, mutate(op->index), op->image, i->second); } else { IRMutator::visit(op); } } void visit(const Store *op) { auto i = replacements.find(op->name); if (i != replacements.end()) { stmt = Store::make(op->name, mutate(op->value), mutate(op->index), i->second); } else { IRMutator::visit(op); } } public: ReplaceParams(const std::map<std::string, Parameter> &replacements) : replacements(replacements) {} }; Stmt replace_params(Stmt s, const std::map<std::string, Parameter> &replacements) { return ReplaceParams(replacements).mutate(s); } class InjectHexagonRpc : public IRMutator { std::map<std::string, Expr> state_vars; Module device_code; /** Alignment info for Int(32) variables in scope, so we don't * lose the information when creating Hexagon kernels. */ Scope<ModulusRemainder> alignment_info; Expr state_var(const std::string& name, Type type) { Expr& var = state_vars[name]; if (!var.defined()) { Buffer storage(type, {}, nullptr, name + "_buf"); *(void **)storage.host_ptr() = nullptr; var = Load::make(type_of<void*>(), name + "_buf", 0, storage, Parameter()); } return var; } Expr state_var_ptr(const std::string& name, Type type) { Expr var = state_var(name, type); return Call::make(Handle(), Call::address_of, {var}, Call::Intrinsic); } Expr module_state() { return state_var("hexagon_module_state", type_of<void*>()); } Expr module_state_ptr() { return state_var_ptr("hexagon_module_state", type_of<void*>()); } // Create a Buffer containing the given buffer/size, and return an // expression for a pointer to the first element. Expr buffer_ptr(const uint8_t* buffer, size_t size, const char* name) { Buffer code(type_of<uint8_t>(), {(int)size}, nullptr, name); memcpy(code.host_ptr(), buffer, (int)size); Expr ptr_0 = Load::make(type_of<uint8_t>(), name, 0, code, Parameter()); return Call::make(Handle(), Call::address_of, {ptr_0}, Call::Intrinsic); } Stmt call_extern_and_assert(const std::string& name, const std::vector<Expr>& args) { Expr call = Call::make(Int(32), name, args, Call::Extern); string call_result_name = unique_name(name + "_result"); Expr call_result_var = Variable::make(Int(32), call_result_name); return LetStmt::make(call_result_name, call, AssertStmt::make(EQ::make(call_result_var, 0), call_result_var)); } using IRMutator::visit; void visit(const For *loop) { if (loop->device_api == DeviceAPI::Hexagon) { // Unrolling or loop partitioning might generate multiple // loops with the same name, so we need to unique them. std::string hex_name = "hex_" + loop->name; Stmt body = remove_trivial_for_loops(loop, true /*device_loops*/); // Build a closure for the device code. // TODO: Should this move the body of the loop to Hexagon, // or the loop itself? Currently, this moves the loop itself. Closure c(body); // Make an argument list, and generate a function in the // device_code module. The hexagon runtime code expects // the arguments to appear in the order of (input buffers, // output buffers, input scalars). There's a huge hack // here, in that the scalars must be last for the scalar // arguments to shadow the symbols of the buffer. std::vector<LoweredArgument> input_buffers, output_buffers; std::map<std::string, Parameter> replacement_params; for (const auto& i : c.buffers) { if (i.second.write) { Argument::Kind kind = Argument::OutputBuffer; output_buffers.push_back(LoweredArgument(i.first, kind, i.second.type, i.second.dimensions)); } else { Argument::Kind kind = Argument::InputBuffer; input_buffers.push_back(LoweredArgument(i.first, kind, i.second.type, i.second.dimensions)); } // Build a parameter to replace. Parameter p(i.second.type, true, i.second.dimensions); // Assert that buffers are aligned to one HVX // vector. Generally, they should be page aligned ION // buffers, so this should be a reasonable // requirement. const int alignment = 128; p.set_host_alignment(alignment); // The other parameter constraints are already // accounted for by the closure grabbing those // arguments, so we only need to provide the host // alignment. replacement_params[i.first] = p; // Add an assert to the body that validates the // alignment of the buffer. if (!device_code.target().has_feature(Target::NoAsserts)) { Expr host_ptr = reinterpret<uint64_t>(Variable::make(Handle(), i.first + ".host")); Expr error = Call::make(Int(32), "halide_error_unaligned_host_ptr", {i.first, alignment}, Call::Extern); body = Block::make(AssertStmt::make(host_ptr % alignment == 0, error), body); } } body = replace_params(body, replacement_params); std::vector<LoweredArgument> args; args.insert(args.end(), input_buffers.begin(), input_buffers.end()); args.insert(args.end(), output_buffers.begin(), output_buffers.end()); for (const auto& i : c.vars) { LoweredArgument arg(i.first, Argument::InputScalar, i.second, 0); if (alignment_info.contains(i.first)) { arg.alignment = alignment_info.get(i.first); } args.push_back(arg); } device_code.append(LoweredFunc(hex_name, args, body, LoweredFunc::External)); // Generate a call to hexagon_device_run. std::vector<Expr> arg_sizes; std::vector<Expr> arg_ptrs; std::vector<Expr> arg_flags; for (const auto& i : c.buffers) { arg_sizes.push_back(Expr((size_t)sizeof(buffer_t*))); arg_ptrs.push_back(Variable::make(type_of<buffer_t *>(), i.first + ".buffer")); int flags = 0; if (i.second.read) flags |= 0x1; if (i.second.write) flags |= 0x2; arg_flags.push_back(flags); } for (const auto& i : c.vars) { Expr arg = Variable::make(i.second, i.first); Expr arg_ptr = Call::make(type_of<void *>(), Call::make_struct, {arg}, Call::Intrinsic); arg_sizes.push_back(Expr((size_t)i.second.bytes())); arg_ptrs.push_back(arg_ptr); arg_flags.push_back(0x0); } // The argument list is terminated with an argument of size 0. arg_sizes.push_back(Expr((size_t)0)); std::string pipeline_name = hex_name + "_argv"; std::vector<Expr> params; params.push_back(module_state()); params.push_back(pipeline_name); params.push_back(state_var_ptr(hex_name, type_of<int>())); params.push_back(Call::make(type_of<size_t*>(), Call::make_struct, arg_sizes, Call::Intrinsic)); params.push_back(Call::make(type_of<void**>(), Call::make_struct, arg_ptrs, Call::Intrinsic)); params.push_back(Call::make(type_of<int*>(), Call::make_struct, arg_flags, Call::Intrinsic)); stmt = call_extern_and_assert("halide_hexagon_run", params); } else { IRMutator::visit(loop); } } void visit(const Let *op) { if (op->value.type() == Int(32)) { alignment_info.push(op->name, modulus_remainder(op->value, alignment_info)); } IRMutator::visit(op); if (op->value.type() == Int(32)) { alignment_info.pop(op->name); } } void visit(const LetStmt *op) { if (op->value.type() == Int(32)) { alignment_info.push(op->name, modulus_remainder(op->value, alignment_info)); } IRMutator::visit(op); if (op->value.type() == Int(32)) { alignment_info.pop(op->name); } } public: InjectHexagonRpc(const Target &target) : device_code("hexagon", target) {} Stmt inject(Stmt s) { s = mutate(s); // Skip if there are no device kernels. if (device_code.functions().empty()) { return s; } // Compile the device code. std::vector<uint8_t> object; #if 0 compile_module_to_shared_object(device_code, object); //compile_module_to_shared_object(device_code, "/tmp/hex.so"); #else debug(1) << "Hexagon device code module: " << device_code << "\n"; device_code.compile(Outputs().bitcode("hex.bc")); string hex_command = "${HL_HEXAGON_TOOLS}/bin/hexagon-clang hex.bc -fPIC -O3 -Wno-override-module -shared -o hex.so"; if (device_code.target().has_feature(Target::HVX_v62)) { hex_command += " -mv62"; } if (device_code.target().has_feature(Target::HVX_128)) { hex_command += " -mhvx-double"; } int result = system(hex_command.c_str()); internal_assert(result == 0) << "hexagon-clang failed\n"; std::ifstream so("hex.so", std::ios::binary | std::ios::ate); object.resize(so.tellg()); so.seekg(0, std::ios::beg); so.read(reinterpret_cast<char*>(&object[0]), object.size()); #endif // Put the compiled object into a buffer. size_t code_size = object.size(); Expr code_ptr = buffer_ptr(&object[0], code_size, "hexagon_code"); // Wrap the statement in calls to halide_initialize_kernels. Stmt init_kernels = call_extern_and_assert("halide_hexagon_initialize_kernels", {module_state_ptr(), code_ptr, Expr(code_size)}); s = Block::make(init_kernels, s); return s; } }; } Stmt inject_hexagon_rpc(Stmt s, const Target &host_target) { Target target(Target::NoOS, Target::Hexagon, 32); for (Target::Feature i : {Target::Debug, Target::NoAsserts, Target::HVX_64, Target::HVX_128, Target::HVX_v62}) { if (host_target.has_feature(i)) { target = target.with_feature(i); } } InjectHexagonRpc injector(target); s = injector.inject(s); return s; } } // namespace Internal } // namespace Halide <commit_msg>Casting to size_t is ambiguous for some compile environments<commit_after>#include <iostream> #include <fstream> #include <memory> #include "HexagonOffload.h" #include "IRMutator.h" #include "Substitute.h" #include "Closure.h" #include "Param.h" #include "Image.h" #include "LLVM_Output.h" #include "RemoveTrivialForLoops.h" namespace Halide { namespace Internal { using std::string; using std::vector; namespace { // Replace the parameter objects of loads/stores witha new parameter // object. class ReplaceParams : public IRMutator { const std::map<std::string, Parameter> &replacements; using IRMutator::visit; void visit(const Load *op) { auto i = replacements.find(op->name); if (i != replacements.end()) { expr = Load::make(op->type, op->name, mutate(op->index), op->image, i->second); } else { IRMutator::visit(op); } } void visit(const Store *op) { auto i = replacements.find(op->name); if (i != replacements.end()) { stmt = Store::make(op->name, mutate(op->value), mutate(op->index), i->second); } else { IRMutator::visit(op); } } public: ReplaceParams(const std::map<std::string, Parameter> &replacements) : replacements(replacements) {} }; Stmt replace_params(Stmt s, const std::map<std::string, Parameter> &replacements) { return ReplaceParams(replacements).mutate(s); } class InjectHexagonRpc : public IRMutator { std::map<std::string, Expr> state_vars; Module device_code; /** Alignment info for Int(32) variables in scope, so we don't * lose the information when creating Hexagon kernels. */ Scope<ModulusRemainder> alignment_info; Expr state_var(const std::string& name, Type type) { Expr& var = state_vars[name]; if (!var.defined()) { Buffer storage(type, {}, nullptr, name + "_buf"); *(void **)storage.host_ptr() = nullptr; var = Load::make(type_of<void*>(), name + "_buf", 0, storage, Parameter()); } return var; } Expr state_var_ptr(const std::string& name, Type type) { Expr var = state_var(name, type); return Call::make(Handle(), Call::address_of, {var}, Call::Intrinsic); } Expr module_state() { return state_var("hexagon_module_state", type_of<void*>()); } Expr module_state_ptr() { return state_var_ptr("hexagon_module_state", type_of<void*>()); } // Create a Buffer containing the given buffer/size, and return an // expression for a pointer to the first element. Expr buffer_ptr(const uint8_t* buffer, size_t size, const char* name) { Buffer code(type_of<uint8_t>(), {(int)size}, nullptr, name); memcpy(code.host_ptr(), buffer, (int)size); Expr ptr_0 = Load::make(type_of<uint8_t>(), name, 0, code, Parameter()); return Call::make(Handle(), Call::address_of, {ptr_0}, Call::Intrinsic); } Stmt call_extern_and_assert(const std::string& name, const std::vector<Expr>& args) { Expr call = Call::make(Int(32), name, args, Call::Extern); string call_result_name = unique_name(name + "_result"); Expr call_result_var = Variable::make(Int(32), call_result_name); return LetStmt::make(call_result_name, call, AssertStmt::make(EQ::make(call_result_var, 0), call_result_var)); } using IRMutator::visit; void visit(const For *loop) { if (loop->device_api == DeviceAPI::Hexagon) { // Unrolling or loop partitioning might generate multiple // loops with the same name, so we need to unique them. std::string hex_name = "hex_" + loop->name; Stmt body = remove_trivial_for_loops(loop, true /*device_loops*/); // Build a closure for the device code. // TODO: Should this move the body of the loop to Hexagon, // or the loop itself? Currently, this moves the loop itself. Closure c(body); // Make an argument list, and generate a function in the // device_code module. The hexagon runtime code expects // the arguments to appear in the order of (input buffers, // output buffers, input scalars). There's a huge hack // here, in that the scalars must be last for the scalar // arguments to shadow the symbols of the buffer. std::vector<LoweredArgument> input_buffers, output_buffers; std::map<std::string, Parameter> replacement_params; for (const auto& i : c.buffers) { if (i.second.write) { Argument::Kind kind = Argument::OutputBuffer; output_buffers.push_back(LoweredArgument(i.first, kind, i.second.type, i.second.dimensions)); } else { Argument::Kind kind = Argument::InputBuffer; input_buffers.push_back(LoweredArgument(i.first, kind, i.second.type, i.second.dimensions)); } // Build a parameter to replace. Parameter p(i.second.type, true, i.second.dimensions); // Assert that buffers are aligned to one HVX // vector. Generally, they should be page aligned ION // buffers, so this should be a reasonable // requirement. const int alignment = 128; p.set_host_alignment(alignment); // The other parameter constraints are already // accounted for by the closure grabbing those // arguments, so we only need to provide the host // alignment. replacement_params[i.first] = p; // Add an assert to the body that validates the // alignment of the buffer. if (!device_code.target().has_feature(Target::NoAsserts)) { Expr host_ptr = reinterpret<uint64_t>(Variable::make(Handle(), i.first + ".host")); Expr error = Call::make(Int(32), "halide_error_unaligned_host_ptr", {i.first, alignment}, Call::Extern); body = Block::make(AssertStmt::make(host_ptr % alignment == 0, error), body); } } body = replace_params(body, replacement_params); std::vector<LoweredArgument> args; args.insert(args.end(), input_buffers.begin(), input_buffers.end()); args.insert(args.end(), output_buffers.begin(), output_buffers.end()); for (const auto& i : c.vars) { LoweredArgument arg(i.first, Argument::InputScalar, i.second, 0); if (alignment_info.contains(i.first)) { arg.alignment = alignment_info.get(i.first); } args.push_back(arg); } device_code.append(LoweredFunc(hex_name, args, body, LoweredFunc::External)); // Generate a call to hexagon_device_run. std::vector<Expr> arg_sizes; std::vector<Expr> arg_ptrs; std::vector<Expr> arg_flags; for (const auto& i : c.buffers) { // sizeof(pointer) will always fit into int32 arg_sizes.push_back(Expr((int32_t)sizeof(buffer_t*))); arg_ptrs.push_back(Variable::make(type_of<buffer_t *>(), i.first + ".buffer")); int flags = 0; if (i.second.read) flags |= 0x1; if (i.second.write) flags |= 0x2; arg_flags.push_back(flags); } for (const auto& i : c.vars) { Expr arg = Variable::make(i.second, i.first); Expr arg_ptr = Call::make(type_of<void *>(), Call::make_struct, {arg}, Call::Intrinsic); // sizeof(scalar-type) will always fit into int32 arg_sizes.push_back(Expr((int32_t)i.second.bytes())); arg_ptrs.push_back(arg_ptr); arg_flags.push_back(0x0); } // The argument list is terminated with an argument of size 0. arg_sizes.push_back(Expr((int32_t)0)); std::string pipeline_name = hex_name + "_argv"; std::vector<Expr> params; params.push_back(module_state()); params.push_back(pipeline_name); params.push_back(state_var_ptr(hex_name, type_of<int>())); params.push_back(Call::make(type_of<size_t*>(), Call::make_struct, arg_sizes, Call::Intrinsic)); params.push_back(Call::make(type_of<void**>(), Call::make_struct, arg_ptrs, Call::Intrinsic)); params.push_back(Call::make(type_of<int*>(), Call::make_struct, arg_flags, Call::Intrinsic)); stmt = call_extern_and_assert("halide_hexagon_run", params); } else { IRMutator::visit(loop); } } void visit(const Let *op) { if (op->value.type() == Int(32)) { alignment_info.push(op->name, modulus_remainder(op->value, alignment_info)); } IRMutator::visit(op); if (op->value.type() == Int(32)) { alignment_info.pop(op->name); } } void visit(const LetStmt *op) { if (op->value.type() == Int(32)) { alignment_info.push(op->name, modulus_remainder(op->value, alignment_info)); } IRMutator::visit(op); if (op->value.type() == Int(32)) { alignment_info.pop(op->name); } } public: InjectHexagonRpc(const Target &target) : device_code("hexagon", target) {} Stmt inject(Stmt s) { s = mutate(s); // Skip if there are no device kernels. if (device_code.functions().empty()) { return s; } // Compile the device code. std::vector<uint8_t> object; #if 0 compile_module_to_shared_object(device_code, object); //compile_module_to_shared_object(device_code, "/tmp/hex.so"); #else debug(1) << "Hexagon device code module: " << device_code << "\n"; device_code.compile(Outputs().bitcode("hex.bc")); string hex_command = "${HL_HEXAGON_TOOLS}/bin/hexagon-clang hex.bc -fPIC -O3 -Wno-override-module -shared -o hex.so"; if (device_code.target().has_feature(Target::HVX_v62)) { hex_command += " -mv62"; } if (device_code.target().has_feature(Target::HVX_128)) { hex_command += " -mhvx-double"; } int result = system(hex_command.c_str()); internal_assert(result == 0) << "hexagon-clang failed\n"; std::ifstream so("hex.so", std::ios::binary | std::ios::ate); object.resize(so.tellg()); so.seekg(0, std::ios::beg); so.read(reinterpret_cast<char*>(&object[0]), object.size()); #endif // Put the compiled object into a buffer. size_t code_size = object.size(); Expr code_ptr = buffer_ptr(&object[0], code_size, "hexagon_code"); // Wrap the statement in calls to halide_initialize_kernels. Stmt init_kernels = call_extern_and_assert("halide_hexagon_initialize_kernels", {module_state_ptr(), code_ptr, Expr((uint64_t) code_size)}); s = Block::make(init_kernels, s); return s; } }; } Stmt inject_hexagon_rpc(Stmt s, const Target &host_target) { Target target(Target::NoOS, Target::Hexagon, 32); for (Target::Feature i : {Target::Debug, Target::NoAsserts, Target::HVX_64, Target::HVX_128, Target::HVX_v62}) { if (host_target.has_feature(i)) { target = target.with_feature(i); } } InjectHexagonRpc injector(target); s = injector.inject(s); return s; } } // namespace Internal } // namespace Halide <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2012-2020 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 "config.h" #include "iotests.h" #include <map> #include <libcouchbase/utils.h> #include "internal.h" class ServeropsUnitTest : public MockUnitTest { }; extern "C" { static void testServerStatsCallback(lcb_INSTANCE *, lcb_CALLBACK_TYPE, const lcb_RESPSTATS *resp) { int *counter; lcb_respstats_cookie(resp, (void **)&counter); EXPECT_EQ(LCB_SUCCESS, lcb_respstats_status(resp)); ++(*counter); } static void statKey_callback(lcb_INSTANCE *, int, const lcb_RESPSTATS *resp) { const char *server; size_t server_len; lcb_respstats_server(resp, &server, &server_len); if (server == nullptr) { return; } EXPECT_EQ(LCB_SUCCESS, lcb_respstats_status(resp)); std::map<std::string, bool> *mm; lcb_respstats_cookie(resp, (void **)&mm); (*mm)[std::string(server, server_len)] = true; } } /** * @test Server Statistics * @pre Schedule a server statistics command * @post The response is a valid statistics structure and its status is * @c SUCCESS. * * @post the statistics callback is invoked more than once. */ TEST_F(ServeropsUnitTest, testServerStats) { lcb_INSTANCE *instance; HandleWrap hw; createConnection(hw, &instance); lcb_install_callback(instance, LCB_CALLBACK_STATS, (lcb_RESPCALLBACK)testServerStatsCallback); int numcallbacks = 0; lcb_CMDSTATS *cmd; lcb_cmdstats_create(&cmd); EXPECT_EQ(LCB_SUCCESS, lcb_stats(instance, &numcallbacks, cmd)); lcb_cmdstats_destroy(cmd); lcb_wait(instance, LCB_WAIT_DEFAULT); EXPECT_LT(1, numcallbacks); } TEST_F(ServeropsUnitTest, testKeyStats) { SKIP_UNLESS_MOCK(); // FIXME: works on 5.5.0, fails on 6.0.0 lcb_INSTANCE *instance; HandleWrap hw; createConnection(hw, &instance); lcb_install_callback(instance, LCB_CALLBACK_STATS, (lcb_RESPCALLBACK)statKey_callback); lcb_CMDSTATS *cmd; lcb_cmdstats_create(&cmd); std::string key = "keystats_test"; storeKey(instance, key, "blah blah"); lcb_cmdstats_key(cmd, key.c_str(), key.size()); lcb_cmdstats_is_keystats(cmd, true); std::map<std::string, bool> mm; lcb_sched_enter(instance); lcb_STATUS err = lcb_stats(instance, &mm, cmd); ASSERT_EQ(LCB_SUCCESS, err); lcb_sched_leave(instance); lcb_wait(instance, LCB_WAIT_DEFAULT); ASSERT_EQ(lcb_get_num_replicas(instance) + 1, mm.size()); // Ensure that a key with an embedded space fails key = "key with space"; lcb_cmdstats_key(cmd, key.c_str(), key.size()); lcb_cmdstats_is_keystats(cmd, true); err = lcb_stats(instance, nullptr, cmd); ASSERT_NE(LCB_SUCCESS, err); lcb_cmdstats_create(&cmd); } <commit_msg>tests: fix minor memory leak<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2012-2020 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 "config.h" #include "iotests.h" #include <map> #include <libcouchbase/utils.h> #include "internal.h" class ServeropsUnitTest : public MockUnitTest { }; extern "C" { static void testServerStatsCallback(lcb_INSTANCE *, lcb_CALLBACK_TYPE, const lcb_RESPSTATS *resp) { int *counter; lcb_respstats_cookie(resp, (void **)&counter); EXPECT_EQ(LCB_SUCCESS, lcb_respstats_status(resp)); ++(*counter); } static void statKey_callback(lcb_INSTANCE *, int, const lcb_RESPSTATS *resp) { const char *server; size_t server_len; lcb_respstats_server(resp, &server, &server_len); if (server == nullptr) { return; } EXPECT_EQ(LCB_SUCCESS, lcb_respstats_status(resp)); std::map<std::string, bool> *mm; lcb_respstats_cookie(resp, (void **)&mm); (*mm)[std::string(server, server_len)] = true; } } /** * @test Server Statistics * @pre Schedule a server statistics command * @post The response is a valid statistics structure and its status is * @c SUCCESS. * * @post the statistics callback is invoked more than once. */ TEST_F(ServeropsUnitTest, testServerStats) { lcb_INSTANCE *instance; HandleWrap hw; createConnection(hw, &instance); lcb_install_callback(instance, LCB_CALLBACK_STATS, (lcb_RESPCALLBACK)testServerStatsCallback); int numcallbacks = 0; lcb_CMDSTATS *cmd; lcb_cmdstats_create(&cmd); EXPECT_EQ(LCB_SUCCESS, lcb_stats(instance, &numcallbacks, cmd)); lcb_cmdstats_destroy(cmd); lcb_wait(instance, LCB_WAIT_DEFAULT); EXPECT_LT(1, numcallbacks); } TEST_F(ServeropsUnitTest, testKeyStats) { SKIP_UNLESS_MOCK(); // FIXME: works on 5.5.0, fails on 6.0.0 lcb_INSTANCE *instance; HandleWrap hw; createConnection(hw, &instance); lcb_install_callback(instance, LCB_CALLBACK_STATS, (lcb_RESPCALLBACK)statKey_callback); lcb_CMDSTATS *cmd; lcb_cmdstats_create(&cmd); std::string key = "keystats_test"; storeKey(instance, key, "blah blah"); lcb_cmdstats_key(cmd, key.c_str(), key.size()); lcb_cmdstats_is_keystats(cmd, true); std::map<std::string, bool> mm; lcb_sched_enter(instance); lcb_STATUS err = lcb_stats(instance, &mm, cmd); ASSERT_EQ(LCB_SUCCESS, err); lcb_sched_leave(instance); lcb_wait(instance, LCB_WAIT_DEFAULT); ASSERT_EQ(lcb_get_num_replicas(instance) + 1, mm.size()); // Ensure that a key with an embedded space fails key = "key with space"; lcb_cmdstats_key(cmd, key.c_str(), key.size()); lcb_cmdstats_is_keystats(cmd, true); err = lcb_stats(instance, nullptr, cmd); ASSERT_NE(LCB_SUCCESS, err); lcb_cmdstats_destroy(cmd); } <|endoftext|>
<commit_before>#include "test.hpp" #include "../compiler_macro.hpp" namespace frea { namespace test { // template <class T> // using SMatrix = RMatrix<T>; // using SqTypes_t = seq::ExpandTypes_t2< // types::SquareMat_t, // std::tuple< // types::Reg_t, // seq::Range_t<2,5>, // std::tuple<BConst<false>> // > // >; // using SqTypes = ToTestTypes_t<SqTypes_t>; // TYPED_TEST_CASE(SMatrix, SqTypes); // TYPED_TEST(SMatrix, Transpose) { // using value_t = typename TestFixture::value_t; // using array_t = typename TestFixture::array_t; // using mat_t = typename TestFixture::mat_t; // // // 転置行列を二次元配列で計算した結果と比較 // constexpr auto range = Range<value_t>{-1e3, 1e3}; // auto mat = this->makeRMat(range); // array_t raw(mat); // // raw.transpose(); // mat.transpose(); // ASSERT_LT(AbsMax(raw - mat), Threshold<value_t>()); // // // (AB)t と (B)t(A)tの結果は同じ // mat = this->makeRMat(range); // auto mat2 = this->makeRMat(range); // const mat_t result0 = (mat * mat2).transposition(); // mat.transpose(); // mat2.transpose(); // const mat_t result1 = mat2 * mat; // ASSERT_LT(AbsMax(mat_t(result0 - result1)), Threshold<value_t>()); // } } } <commit_msg>コメントアウトしたままになっていたテストコードを有効化<commit_after>#include "test.hpp" namespace frea { namespace test { template <class T> using SMatrix = RMatrix<T>; using SqTypes_t = seq::ExpandTypes_t2< types::SquareMat_t, std::tuple< types::Reg_t, seq::Range_t<2,5>, std::tuple<BConst<false>> > >; using SqTypes = ToTestTypes_t<SqTypes_t>; TYPED_TEST_CASE(SMatrix, SqTypes); TYPED_TEST(SMatrix, Transpose) { using value_t = typename TestFixture::value_t; using array_t = typename TestFixture::array_t; using mat_t = typename TestFixture::mat_t; // 転置行列を二次元配列で計算した結果と比較 constexpr auto range = Range<value_t>{-1e3, 1e3}; auto mat = this->makeRMat(range); array_t raw(mat); raw.transpose(); mat.transpose(); ASSERT_LE(AbsMax(raw - mat), Threshold<value_t>(1<<5,0)); // (AB)t と (B)t(A)tの結果は同じ mat = this->makeRMat(range); auto mat2 = this->makeRMat(range); const mat_t result0 = (mat * mat2).transposition(); mat.transpose(); mat2.transpose(); const mat_t result1 = mat2 * mat; ASSERT_LE(AbsMax(mat_t(result0 - result1)), Threshold<value_t>(1<<5,0)); } } } <|endoftext|>
<commit_before>extern "C" { #include "packet_queue.h" #include "error.h" #include "nrf51.h" #include "nrf51_bitfields.h" } #include "CppUTest/TestHarness.h" #include <limits.h> #include <string.h> extern "C" { void error_handler(uint32_t err_code, uint32_t line_num, char * file_name) { } } TEST_GROUP(packet_queue) { packet_queue_t queue; void setup(void) { packet_queue_init(&queue); } void teardown(void) { } }; TEST(packet_queue, test_queue_init_succeed) { packet_queue_t queue; LONGS_EQUAL(SUCCESS, packet_queue_init(&queue)); } TEST(packet_queue, test_queue_new_queue_is_empty) { LONGS_EQUAL(true, packet_queue_is_empty(&queue)); radio_packet_t packet; packet_queue_add(&queue, &packet); LONGS_EQUAL(false, packet_queue_is_empty(&queue)); } TEST(packet_queue, test_queue_full_queue_is_full) { LONGS_EQUAL(false, packet_queue_is_full(&queue)); for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++) { radio_packet_t packet; packet_queue_add(&queue, &packet); } LONGS_EQUAL(true, packet_queue_is_full(&queue)); } TEST(packet_queue, test_queue_add_succeeds_on_empty_queue) { radio_packet_t packet; packet.data[0] = rand()*INT_MAX; LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &packet)); LONGS_EQUAL(0, memcmp(&packet, &queue.packets[0], sizeof(packet))); } TEST(packet_queue, test_queue_add_succeeds_on_non_empty_queue) { radio_packet_t packet; packet_queue_add(&queue, &packet); packet.data[0] = rand()*INT_MAX; LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &packet)); LONGS_EQUAL(0, memcmp(&packet, &queue.packets[queue.tail-1], sizeof(packet))); } TEST(packet_queue, test_queue_add_fails_on_full_queue) { for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++) { radio_packet_t packet; LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &packet)); } radio_packet_t packet; LONGS_EQUAL(NO_MEMORY, packet_queue_add(&queue, &packet)); } TEST(packet_queue, test_queue_get_fails_on_empty_queue) { radio_packet_t * packet; LONGS_EQUAL(NOT_FOUND, packet_queue_get(&queue, &packet)); } TEST(packet_queue, test_queue_get_returns_correct_pointer) { radio_packet_t in_packet; packet_queue_add(&queue, &in_packet); radio_packet_t * out_packet = 0; packet_queue_get(&queue, &out_packet); POINTERS_EQUAL(out_packet, &queue.packets[0]); } TEST(packet_queue, test_queue_add_get_packet) { radio_packet_t in_packet; in_packet.data[0] = rand()*INT_MAX; packet_queue_add(&queue, &in_packet); radio_packet_t * out_packet; packet_queue_get(&queue, &out_packet); LONGS_EQUAL(0, memcmp(&in_packet, out_packet, sizeof(in_packet))); } TEST(packet_queue, test_queue_is_fifo) { radio_packet_t in_packets[PACKET_QUEUE_ELEMENTS]; for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++) { in_packets[i].data[0] = rand()*INT_MAX; LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &in_packets[i])); } radio_packet_t * out_packets[PACKET_QUEUE_ELEMENTS] = {0}; for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++) { LONGS_EQUAL(SUCCESS, packet_queue_get(&queue, &out_packets[i])); } CHECK(0 != out_packets[0]); LONGS_EQUAL(0, memcmp(out_packets[0], &in_packets[0], sizeof(in_packets[0]))); CHECK(0 != out_packets[1]); LONGS_EQUAL(0, memcmp(out_packets[1], &in_packets[1], sizeof(in_packets[1]))); CHECK(0 != out_packets[2]); LONGS_EQUAL(0, memcmp(out_packets[2], &in_packets[2], sizeof(in_packets[2]))); CHECK(0 != out_packets[3]); LONGS_EQUAL(0, memcmp(out_packets[3], &in_packets[3], sizeof(in_packets[3]))); CHECK(0 != out_packets[4]); LONGS_EQUAL(0, memcmp(out_packets[4], &in_packets[4], sizeof(in_packets[4]))); CHECK(0 != out_packets[5]); LONGS_EQUAL(0, memcmp(out_packets[5], &in_packets[5], sizeof(in_packets[5]))); CHECK(0 != out_packets[6]); LONGS_EQUAL(0, memcmp(out_packets[6], &in_packets[6], sizeof(in_packets[6]))); CHECK(0 != out_packets[7]); LONGS_EQUAL(0, memcmp(out_packets[7], &in_packets[7], sizeof(in_packets[7]))); CHECK(0 != out_packets[8]); LONGS_EQUAL(0, memcmp(out_packets[8], &in_packets[8], sizeof(in_packets[8]))); CHECK(0 != out_packets[9]); LONGS_EQUAL(0, memcmp(out_packets[9], &in_packets[9], sizeof(in_packets[9]))); } <commit_msg>Accomodate smaller queue in tests.<commit_after>extern "C" { #include "packet_queue.h" #include "error.h" #include "nrf51.h" #include "nrf51_bitfields.h" } #include "CppUTest/TestHarness.h" #include <limits.h> #include <string.h> extern "C" { void error_handler(uint32_t err_code, uint32_t line_num, char * file_name) { } } TEST_GROUP(packet_queue) { packet_queue_t queue; void setup(void) { packet_queue_init(&queue); } void teardown(void) { } }; TEST(packet_queue, test_queue_init_succeed) { packet_queue_t queue; LONGS_EQUAL(SUCCESS, packet_queue_init(&queue)); } TEST(packet_queue, test_queue_new_queue_is_empty) { LONGS_EQUAL(true, packet_queue_is_empty(&queue)); radio_packet_t packet; packet_queue_add(&queue, &packet); LONGS_EQUAL(false, packet_queue_is_empty(&queue)); } TEST(packet_queue, test_queue_full_queue_is_full) { LONGS_EQUAL(false, packet_queue_is_full(&queue)); for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++) { radio_packet_t packet; packet_queue_add(&queue, &packet); } LONGS_EQUAL(true, packet_queue_is_full(&queue)); } TEST(packet_queue, test_queue_add_succeeds_on_empty_queue) { radio_packet_t packet; packet.data[0] = rand()*INT_MAX; LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &packet)); LONGS_EQUAL(0, memcmp(&packet, &queue.packets[0], sizeof(packet))); } TEST(packet_queue, test_queue_add_succeeds_on_non_empty_queue) { radio_packet_t packet; packet_queue_add(&queue, &packet); packet.data[0] = rand()*INT_MAX; LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &packet)); LONGS_EQUAL(0, memcmp(&packet, &queue.packets[queue.tail-1], sizeof(packet))); } TEST(packet_queue, test_queue_add_fails_on_full_queue) { for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++) { radio_packet_t packet; LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &packet)); } radio_packet_t packet; LONGS_EQUAL(NO_MEMORY, packet_queue_add(&queue, &packet)); } TEST(packet_queue, test_queue_get_fails_on_empty_queue) { radio_packet_t * packet; LONGS_EQUAL(NOT_FOUND, packet_queue_get(&queue, &packet)); } TEST(packet_queue, test_queue_get_returns_correct_pointer) { radio_packet_t in_packet; packet_queue_add(&queue, &in_packet); radio_packet_t * out_packet = 0; packet_queue_get(&queue, &out_packet); POINTERS_EQUAL(out_packet, &queue.packets[0]); } TEST(packet_queue, test_queue_add_get_packet) { radio_packet_t in_packet; in_packet.data[0] = rand()*INT_MAX; packet_queue_add(&queue, &in_packet); radio_packet_t * out_packet; packet_queue_get(&queue, &out_packet); LONGS_EQUAL(0, memcmp(&in_packet, out_packet, sizeof(in_packet))); } TEST(packet_queue, test_queue_is_fifo) { radio_packet_t in_packets[PACKET_QUEUE_ELEMENTS]; for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++) { in_packets[i].data[0] = rand()*INT_MAX; LONGS_EQUAL(SUCCESS, packet_queue_add(&queue, &in_packets[i])); } radio_packet_t * out_packets[PACKET_QUEUE_ELEMENTS] = {0}; for (int i = 0; i < PACKET_QUEUE_ELEMENTS; i++) { LONGS_EQUAL(SUCCESS, packet_queue_get(&queue, &out_packets[i])); } CHECK(0 != out_packets[0]); LONGS_EQUAL(0, memcmp(out_packets[0], &in_packets[0], sizeof(in_packets[0]))); CHECK(0 != out_packets[1]); LONGS_EQUAL(0, memcmp(out_packets[1], &in_packets[1], sizeof(in_packets[1]))); CHECK(0 != out_packets[2]); LONGS_EQUAL(0, memcmp(out_packets[2], &in_packets[2], sizeof(in_packets[2]))); CHECK(0 != out_packets[3]); LONGS_EQUAL(0, memcmp(out_packets[3], &in_packets[3], sizeof(in_packets[3]))); CHECK(0 != out_packets[4]); LONGS_EQUAL(0, memcmp(out_packets[4], &in_packets[4], sizeof(in_packets[4]))); CHECK(0 != out_packets[5]); LONGS_EQUAL(0, memcmp(out_packets[5], &in_packets[5], sizeof(in_packets[5]))); CHECK(0 != out_packets[6]); LONGS_EQUAL(0, memcmp(out_packets[6], &in_packets[6], sizeof(in_packets[6]))); } <|endoftext|>
<commit_before>/// /// @file IteratorHelper.cpp /// Functions used to calculate the next start and stop /// numbers for primesieve::iterator. /// /// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesieve/config.hpp> #include <primesieve/IteratorHelper.hpp> #include <primesieve/PrimeGenerator.hpp> #include <primesieve/pmath.hpp> #include <stdint.h> #include <algorithm> #include <cmath> #include <limits> using namespace std; using namespace primesieve; namespace { uint64_t getNextDist(uint64_t n, uint64_t dist) { double x = (double) n; uint64_t tinyDist = PrimeGenerator::maxCachedPrime() * 4; uint64_t minDist = (uint64_t) sqrt(x); uint64_t maxDist = 1ull << 60; dist *= 4; dist = max(dist, tinyDist); dist = max(dist, minDist); dist = min(dist, maxDist); return dist; } uint64_t getPrevDist(uint64_t n, uint64_t dist) { double x = (double) n; x = max(x, 10.0); double logx = ceil(log(x)); uint64_t minDist = config::MIN_CACHE_ITERATOR; uint64_t maxDist = config::MAX_CACHE_ITERATOR; minDist /= sizeof(uint64_t); maxDist /= sizeof(uint64_t); minDist *= (uint64_t) logx; maxDist *= (uint64_t) logx; uint64_t tinyDist = PrimeGenerator::maxCachedPrime() * 4; uint64_t defaultDist = (uint64_t) (sqrt(x) * 2); dist *= 4; dist = max(dist, tinyDist); dist = min(dist, minDist); dist = max(dist, defaultDist); dist = min(dist, maxDist); return dist; } bool useStopHint(uint64_t start, uint64_t stopHint) { return stopHint >= start && stopHint < numeric_limits<uint64_t>::max(); } bool useStopHint(uint64_t start, uint64_t stop, uint64_t stopHint) { return stopHint >= start && stopHint <= stop; } } // namespace namespace primesieve { void IteratorHelper::next(uint64_t* start, uint64_t* stop, uint64_t stopHint, uint64_t* dist) { *start = checkedAdd(*stop, 1); uint64_t maxCachedPrime = PrimeGenerator::maxCachedPrime(); if (*start < maxCachedPrime) { // When the stop number <= maxCachedPrime // primesieve::iterator uses the primes // cache instead of sieving and does not // even initialize Erat::init() *stop = maxCachedPrime; *dist = *stop - *start; } else { *dist = getNextDist(*start, *dist); *stop = checkedAdd(*start, *dist); if (useStopHint(*start, stopHint)) *stop = checkedAdd(stopHint, maxPrimeGap(stopHint)); } } void IteratorHelper::prev(uint64_t* start, uint64_t* stop, uint64_t stopHint, uint64_t* dist) { *stop = checkedSub(*start, 1); *dist = getPrevDist(*stop, *dist); *start = checkedSub(*stop, *dist); if (useStopHint(*start, *stop, stopHint)) *start = checkedSub(stopHint, maxPrimeGap(stopHint)); } } // namespace <commit_msg>Remove unused header<commit_after>/// /// @file IteratorHelper.cpp /// Functions used to calculate the next start and stop /// numbers for primesieve::iterator. /// /// Copyright (C) 2019 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primesieve/config.hpp> #include <primesieve/IteratorHelper.hpp> #include <primesieve/PrimeGenerator.hpp> #include <primesieve/pmath.hpp> #include <stdint.h> #include <algorithm> #include <cmath> using namespace std; using namespace primesieve; namespace { uint64_t getNextDist(uint64_t n, uint64_t dist) { double x = (double) n; uint64_t tinyDist = PrimeGenerator::maxCachedPrime() * 4; uint64_t minDist = (uint64_t) sqrt(x); uint64_t maxDist = 1ull << 60; dist *= 4; dist = max(dist, tinyDist); dist = max(dist, minDist); dist = min(dist, maxDist); return dist; } uint64_t getPrevDist(uint64_t n, uint64_t dist) { double x = (double) n; x = max(x, 10.0); double logx = ceil(log(x)); uint64_t minDist = config::MIN_CACHE_ITERATOR; uint64_t maxDist = config::MAX_CACHE_ITERATOR; minDist /= sizeof(uint64_t); maxDist /= sizeof(uint64_t); minDist *= (uint64_t) logx; maxDist *= (uint64_t) logx; uint64_t tinyDist = PrimeGenerator::maxCachedPrime() * 4; uint64_t defaultDist = (uint64_t) (sqrt(x) * 2); dist *= 4; dist = max(dist, tinyDist); dist = min(dist, minDist); dist = max(dist, defaultDist); dist = min(dist, maxDist); return dist; } bool useStopHint(uint64_t start, uint64_t stopHint) { return stopHint >= start && stopHint < numeric_limits<uint64_t>::max(); } bool useStopHint(uint64_t start, uint64_t stop, uint64_t stopHint) { return stopHint >= start && stopHint <= stop; } } // namespace namespace primesieve { void IteratorHelper::next(uint64_t* start, uint64_t* stop, uint64_t stopHint, uint64_t* dist) { *start = checkedAdd(*stop, 1); uint64_t maxCachedPrime = PrimeGenerator::maxCachedPrime(); if (*start < maxCachedPrime) { // When the stop number <= maxCachedPrime // primesieve::iterator uses the primes // cache instead of sieving and does not // even initialize Erat::init() *stop = maxCachedPrime; *dist = *stop - *start; } else { *dist = getNextDist(*start, *dist); *stop = checkedAdd(*start, *dist); if (useStopHint(*start, stopHint)) *stop = checkedAdd(stopHint, maxPrimeGap(stopHint)); } } void IteratorHelper::prev(uint64_t* start, uint64_t* stop, uint64_t stopHint, uint64_t* dist) { *stop = checkedSub(*start, 1); *dist = getPrevDist(*stop, *dist); *start = checkedSub(*stop, *dist); if (useStopHint(*start, *stop, stopHint)) *start = checkedSub(stopHint, maxPrimeGap(stopHint)); } } // namespace <|endoftext|>
<commit_before> #include <unistd.h> #include <sstream> #include "tclap/CmdLine.h" #include "beanstalk.hpp" #include "alpr.h" #include "openalpr/simpleini/simpleini.h" #include "openalpr/cjson.h" #include "support/tinythread.h" #include "videobuffer.h" #include "uuid.h" #include <curl/curl.h> // prototypes void streamRecognitionThread(void* arg); bool writeToQueue(std::string jsonResult); bool uploadPost(std::string url, std::string data); void dataUploadThread(void* arg); // Constants const std::string DEFAULT_LOG_FILE_PATH="/var/log/openalpr.log"; const std::string WTS_CONFIG_FILE_PATH="/etc/openalpr/wts.conf"; const std::string BEANSTALK_QUEUE_HOST="127.0.0.1"; const int BEANSTALK_PORT=11300; const std::string BEANSTALK_TUBE_NAME="alpr"; struct CaptureThreadData { std::string stream_url; std::string site_id; int camera_id; std::string config_file; std::string country_code; std::string output_image_folder; }; struct UploadThreadData { std::string upload_url; }; bool daemon_active; int main( int argc, const char** argv ) { daemon_active = true; bool noDaemon = false; std::string logFile; int topn; std::string configFile; std::string country; TCLAP::CmdLine cmd("OpenAlpr Daemon", ' ', Alpr::getVersion()); TCLAP::ValueArg<std::string> countryCodeArg("c","country","Country code to identify (either us for USA or eu for Europe). Default=us",false, "us" ,"country_code"); TCLAP::ValueArg<std::string> configFileArg("","config","Path to the openalpr.conf file.",false, "" ,"config_file"); TCLAP::ValueArg<int> topNArg("n","topn","Max number of possible plate numbers to return. Default=10",false, 10 ,"topN"); TCLAP::ValueArg<std::string> logFileArg("l","log","Log file to write to. Default=" + DEFAULT_LOG_FILE_PATH,false, DEFAULT_LOG_FILE_PATH ,"topN"); TCLAP::SwitchArg daemonOffSwitch("f","foreground","Set this flag for debugging. Disables forking the process as a daemon and runs in the foreground. Default=off", cmd, false); try { cmd.add( topNArg ); cmd.add( configFileArg ); cmd.add( logFileArg ); if (cmd.parse( argc, argv ) == false) { // Error occured while parsing. Exit now. return 1; } country = countryCodeArg.getValue(); configFile = configFileArg.getValue(); logFile = logFileArg.getValue(); topn = topNArg.getValue(); noDaemon = daemonOffSwitch.getValue(); } catch (TCLAP::ArgException &e) // catch any exceptions { std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; return 1; } if (noDaemon == false) { // Fork off into a separate daemon daemon(0, 0); // Redirect std out to log file std::ofstream out(logFile.c_str()); std::cout.rdbuf(out.rdbuf()); std::cerr.rdbuf(out.rdbuf()); std::cout << "Running OpenALPR daemon in daemon mode." << std::endl; } else { std::cout << "Running OpenALPR daemon in the foreground" << std::endl; } CSimpleIniA ini; ini.SetMultiKey(); ini.LoadFile(WTS_CONFIG_FILE_PATH.c_str()); std::vector<std::string> stream_urls; CSimpleIniA::TNamesDepend values; ini.GetAllValues("daemon", "stream", values); // sort the values into the original load order values.sort(CSimpleIniA::Entry::LoadOrder()); // output all of the items CSimpleIniA::TNamesDepend::const_iterator i; for (i = values.begin(); i != values.end(); ++i) { stream_urls.push_back(i->pItem); } if (stream_urls.size() == 0) { std::cout << "No video streams defined in the configuration" << std::endl; return 1; } std::string imageFolder = ini.GetValue("daemon", "image_folder", "/tmp/"); std::string upload_url = ini.GetValue("daemon", "upload_address", ""); std::string site_id = ini.GetValue("daemon", "site_id", ""); std::cout << "Using: " << imageFolder << " for storing valid plate images" << std::endl; for (int i = 0; i < stream_urls.size(); i++) { CaptureThreadData* tdata = new CaptureThreadData(); tdata->stream_url = stream_urls[i]; tdata->camera_id = i + 1; tdata->config_file = configFile; tdata->output_image_folder = imageFolder; tdata->country_code = country; tdata->site_id = site_id; tthread::thread* t = new tthread::thread(streamRecognitionThread, (void*) tdata); } // Kick off the data upload thread UploadThreadData* udata = new UploadThreadData(); udata->upload_url = upload_url; tthread::thread* t = new tthread::thread(dataUploadThread, (void*) udata ); while (daemon_active) { usleep(30000); } } void streamRecognitionThread(void* arg) { CaptureThreadData* tdata = (CaptureThreadData*) arg; std::cout << "country: " << tdata->country_code << " -- config file: " << tdata->config_file << std::endl; std::cout << "Stream " << tdata->camera_id << ": " << tdata->stream_url << std::endl; Alpr alpr(tdata->country_code, tdata->config_file); std::cout << "asdf" << std::endl; int framenum = 0; VideoBuffer videoBuffer; videoBuffer.connect(tdata->stream_url, 5); cv::Mat latestFrame; std::vector<uchar> buffer; std::cout << "Daemon active: " << daemon_active << std::endl; while (daemon_active) { int response = videoBuffer.getLatestFrame(&latestFrame); if (response != -1) { cv::imencode(".bmp", latestFrame, buffer ); std::vector<AlprResult> results = alpr.recognize(buffer); if (results.size() > 0) { // Create a UUID for the image std::string uuid = newUUID(); // Save the image to disk (using the UUID) std::stringstream ss; ss << tdata->output_image_folder << "/" << uuid << ".jpg"; cv::imwrite(ss.str(), latestFrame); // Update the JSON content to include UUID and camera ID cJSON *root; root=cJSON_CreateObject(); std::string json = alpr.toJson(results); cJSON *array = cJSON_Parse(json.c_str()); cJSON_AddStringToObject(root, "uuid", uuid.c_str()); cJSON_AddNumberToObject(root, "camera_id", tdata->camera_id); cJSON_AddStringToObject(root, "site-id", tdata->site_id.c_str()); cJSON_AddItemToObject(root, "results", array); char *out; out=cJSON_PrintUnformatted(root); cJSON_Delete(root); std::string response(out); free(out); // Push the results to the Beanstalk queue writeToQueue(response); } } usleep(10000); } videoBuffer.disconnect(); std::cout << "Video processing ended" << std::endl; delete tdata; } bool writeToQueue(std::string jsonResult) { Beanstalk::Client client(BEANSTALK_QUEUE_HOST, BEANSTALK_PORT); client.use(BEANSTALK_TUBE_NAME); int id = client.put(jsonResult); if (id <= 0) return false; std::cout << "put job id: " << id << std::endl; return true; } void dataUploadThread(void* arg) { UploadThreadData* udata = (UploadThreadData*) arg; Beanstalk::Client client(BEANSTALK_QUEUE_HOST, BEANSTALK_PORT); client.watch(BEANSTALK_TUBE_NAME); while(daemon_active) { Beanstalk::Job job; client.reserve(job); if (job.id() > 0) { if (uploadPost(udata->upload_url, job.body())) { client.del(job.id()); std::cout << "Job: " << job.id() << " successfully uploaded" << std::endl; } else { client.release(job); std::cout << "Job: " << job.id() << " failed to upload. Will retry." << std::endl; } } usleep(10000); } } bool uploadPost(std::string url, std::string data) { bool success = true; CURL *curl; CURLcode res; /* In windows, this will init the winsock stuff */ curl_global_init(CURL_GLOBAL_ALL); /* get a curl handle */ curl = curl_easy_init(); if(curl) { /* First set the URL that is about to receive our POST. This URL can just as well be a https:// URL if that is what should receive the data. */ curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); /* Now specify the POST data */ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str()); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); /* Check for errors */ if(res != CURLE_OK) { success = false; } /* always cleanup */ curl_easy_cleanup(curl); } curl_global_cleanup(); return success; }<commit_msg>Updated POSTS to work with web server<commit_after> #include <unistd.h> #include <sstream> #include "tclap/CmdLine.h" #include "beanstalk.hpp" #include "alpr.h" #include "openalpr/simpleini/simpleini.h" #include "openalpr/cjson.h" #include "support/tinythread.h" #include "videobuffer.h" #include "uuid.h" #include <curl/curl.h> // prototypes void streamRecognitionThread(void* arg); bool writeToQueue(std::string jsonResult); bool uploadPost(std::string url, std::string data); void dataUploadThread(void* arg); // Constants const std::string DEFAULT_LOG_FILE_PATH="/var/log/openalpr.log"; const std::string WTS_CONFIG_FILE_PATH="/etc/openalpr/wts.conf"; const std::string BEANSTALK_QUEUE_HOST="127.0.0.1"; const int BEANSTALK_PORT=11300; const std::string BEANSTALK_TUBE_NAME="alpr"; struct CaptureThreadData { std::string stream_url; std::string site_id; int camera_id; std::string config_file; std::string country_code; std::string output_image_folder; }; struct UploadThreadData { std::string upload_url; }; bool daemon_active; int main( int argc, const char** argv ) { daemon_active = true; bool noDaemon = false; std::string logFile; int topn; std::string configFile; std::string country; TCLAP::CmdLine cmd("OpenAlpr Daemon", ' ', Alpr::getVersion()); TCLAP::ValueArg<std::string> countryCodeArg("c","country","Country code to identify (either us for USA or eu for Europe). Default=us",false, "us" ,"country_code"); TCLAP::ValueArg<std::string> configFileArg("","config","Path to the openalpr.conf file.",false, "" ,"config_file"); TCLAP::ValueArg<int> topNArg("n","topn","Max number of possible plate numbers to return. Default=10",false, 10 ,"topN"); TCLAP::ValueArg<std::string> logFileArg("l","log","Log file to write to. Default=" + DEFAULT_LOG_FILE_PATH,false, DEFAULT_LOG_FILE_PATH ,"topN"); TCLAP::SwitchArg daemonOffSwitch("f","foreground","Set this flag for debugging. Disables forking the process as a daemon and runs in the foreground. Default=off", cmd, false); try { cmd.add( topNArg ); cmd.add( configFileArg ); cmd.add( logFileArg ); if (cmd.parse( argc, argv ) == false) { // Error occured while parsing. Exit now. return 1; } country = countryCodeArg.getValue(); configFile = configFileArg.getValue(); logFile = logFileArg.getValue(); topn = topNArg.getValue(); noDaemon = daemonOffSwitch.getValue(); } catch (TCLAP::ArgException &e) // catch any exceptions { std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; return 1; } if (noDaemon == false) { // Fork off into a separate daemon daemon(0, 0); // Redirect std out to log file std::ofstream out(logFile.c_str()); std::cout.rdbuf(out.rdbuf()); std::cerr.rdbuf(out.rdbuf()); std::cout << "Running OpenALPR daemon in daemon mode." << std::endl; } else { std::cout << "Running OpenALPR daemon in the foreground" << std::endl; } CSimpleIniA ini; ini.SetMultiKey(); ini.LoadFile(WTS_CONFIG_FILE_PATH.c_str()); std::vector<std::string> stream_urls; CSimpleIniA::TNamesDepend values; ini.GetAllValues("daemon", "stream", values); // sort the values into the original load order values.sort(CSimpleIniA::Entry::LoadOrder()); // output all of the items CSimpleIniA::TNamesDepend::const_iterator i; for (i = values.begin(); i != values.end(); ++i) { stream_urls.push_back(i->pItem); } if (stream_urls.size() == 0) { std::cout << "No video streams defined in the configuration" << std::endl; return 1; } std::string imageFolder = ini.GetValue("daemon", "image_folder", "/tmp/"); std::string upload_url = ini.GetValue("daemon", "upload_address", ""); std::string site_id = ini.GetValue("daemon", "site_id", ""); std::cout << "Using: " << imageFolder << " for storing valid plate images" << std::endl; for (int i = 0; i < stream_urls.size(); i++) { CaptureThreadData* tdata = new CaptureThreadData(); tdata->stream_url = stream_urls[i]; tdata->camera_id = i + 1; tdata->config_file = configFile; tdata->output_image_folder = imageFolder; tdata->country_code = country; tdata->site_id = site_id; tthread::thread* t = new tthread::thread(streamRecognitionThread, (void*) tdata); } // Kick off the data upload thread UploadThreadData* udata = new UploadThreadData(); udata->upload_url = upload_url; tthread::thread* t = new tthread::thread(dataUploadThread, (void*) udata ); while (daemon_active) { usleep(30000); } } void streamRecognitionThread(void* arg) { CaptureThreadData* tdata = (CaptureThreadData*) arg; std::cout << "country: " << tdata->country_code << " -- config file: " << tdata->config_file << std::endl; std::cout << "Stream " << tdata->camera_id << ": " << tdata->stream_url << std::endl; Alpr alpr(tdata->country_code, tdata->config_file); std::cout << "asdf" << std::endl; int framenum = 0; VideoBuffer videoBuffer; videoBuffer.connect(tdata->stream_url, 5); cv::Mat latestFrame; std::vector<uchar> buffer; std::cout << "Daemon active: " << daemon_active << std::endl; while (daemon_active) { int response = videoBuffer.getLatestFrame(&latestFrame); if (response != -1) { cv::imencode(".bmp", latestFrame, buffer ); std::vector<AlprResult> results = alpr.recognize(buffer); if (results.size() > 0) { // Create a UUID for the image std::string uuid = newUUID(); // Save the image to disk (using the UUID) std::stringstream ss; ss << tdata->output_image_folder << "/" << uuid << ".jpg"; cv::imwrite(ss.str(), latestFrame); // Update the JSON content to include UUID and camera ID cJSON *root; root=cJSON_CreateObject(); std::string json = alpr.toJson(results); cJSON *array = cJSON_Parse(json.c_str()); cJSON_AddStringToObject(root, "uuid", uuid.c_str()); cJSON_AddNumberToObject(root, "camera_id", tdata->camera_id); cJSON_AddStringToObject(root, "site-id", tdata->site_id.c_str()); cJSON_AddItemToObject(root, "results", array); char *out; out=cJSON_PrintUnformatted(root); cJSON_Delete(root); std::string response(out); free(out); // Push the results to the Beanstalk queue writeToQueue(response); } } usleep(10000); } videoBuffer.disconnect(); std::cout << "Video processing ended" << std::endl; delete tdata; } bool writeToQueue(std::string jsonResult) { Beanstalk::Client client(BEANSTALK_QUEUE_HOST, BEANSTALK_PORT); client.use(BEANSTALK_TUBE_NAME); int id = client.put(jsonResult); if (id <= 0) return false; std::cout << "put job id: " << id << std::endl; return true; } void dataUploadThread(void* arg) { /* In windows, this will init the winsock stuff */ curl_global_init(CURL_GLOBAL_ALL); UploadThreadData* udata = (UploadThreadData*) arg; Beanstalk::Client client(BEANSTALK_QUEUE_HOST, BEANSTALK_PORT); client.watch(BEANSTALK_TUBE_NAME); while(daemon_active) { Beanstalk::Job job; client.reserve(job); if (job.id() > 0) { if (uploadPost(udata->upload_url, job.body())) { client.del(job.id()); std::cout << "Job: " << job.id() << " successfully uploaded" << std::endl; } else { client.release(job); std::cout << "Job: " << job.id() << " failed to upload. Will retry." << std::endl; } } usleep(10000); } curl_global_cleanup(); } bool uploadPost(std::string url, std::string data) { bool success = true; CURL *curl; CURLcode res; /* get a curl handle */ curl = curl_easy_init(); if(curl) { /* First set the URL that is about to receive our POST. This URL can just as well be a https:// URL if that is what should receive the data. */ curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); /* Now specify the POST data */ //char* escaped_data = curl_easy_escape(curl, data.c_str(), data.length()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str()); //curl_free(escaped_data); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); /* Check for errors */ if(res != CURLE_OK) { success = false; } /* always cleanup */ curl_easy_cleanup(curl); } return success; }<|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: liFilterConsole2D.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <liFilterConsole2D.h> #include <FL/fl_file_chooser.H> /************************************ * * Constructor * ***********************************/ liFilterConsole2D ::liFilterConsole2D() { m_InputViewer = InputImageViewerType::New(); m_Viewer_H1x = ImageViewerType::New(); m_Viewer_H1y = ImageViewerType::New(); m_Viewer_H2x = ImageViewerType::New(); m_Viewer_H2y = ImageViewerType::New(); m_Viewer_Laplacian = ImageViewerType::New(); m_Viewer_Smoothed = ImageViewerType::New(); m_Viewer_Gradient_Modulus = ImageViewerType::New(); m_InputViewer->SetLabel( "Input Image" ); m_Viewer_H1x->SetLabel( "Gradient X" ); m_Viewer_H1y->SetLabel( "Gradient Y" ); m_Viewer_H2x->SetLabel( "Second Derivative X" ); m_Viewer_H2y->SetLabel( "Second Derivative Y" ); m_Viewer_Laplacian->SetLabel( "Laplacian" ); m_Viewer_Smoothed->SetLabel( "Smoothed" ); m_Viewer_Gradient_Modulus->SetLabel( "Gradient Modulus" ); progressSlider->Observe( m_Hx.GetPointer() ); progressSlider->Observe( m_Hy.GetPointer() ); progressSlider->Observe( m_H1x.GetPointer() ); progressSlider->Observe( m_H1y.GetPointer() ); progressSlider->Observe( m_H2x.GetPointer() ); progressSlider->Observe( m_H2y.GetPointer() ); progressSlider->Observe( m_Laplacian.GetPointer() ); progressSlider->Observe( m_Smoothed.GetPointer() ); progressSlider->Observe( m_Modulus.GetPointer() ); progressSlider->Observe( m_IntensityScaleSmoothed.GetPointer() ); progressSlider->Observe( m_IntensityScaleLaplacian.GetPointer() ); progressSlider->Observe( m_IntensityScaleModulus.GetPointer() ); progressSlider->Observe( m_WriterSmoothed.GetPointer() ); progressSlider->Observe( m_WriterLaplacian.GetPointer() ); progressSlider->Observe( m_WriterModulus.GetPointer() ); loadButton->Observe( m_Reader.GetPointer() ); inputButton->Observe( m_Reader.GetPointer() ); HxButton->Observe( m_Hx.GetPointer() ); HyButton->Observe( m_Hy.GetPointer() ); H1xButton->Observe( m_H1x.GetPointer() ); H1yButton->Observe( m_H1y.GetPointer() ); H2xButton->Observe( m_H2x.GetPointer() ); H2yButton->Observe( m_H2y.GetPointer() ); laplacianButton->Observe( m_Laplacian.GetPointer() ); smoothedButton->Observe( m_Smoothed.GetPointer() ); modulusButton->Observe( m_Modulus.GetPointer() ); m_Reader->AddObserver( itk::ModifiedEvent(), HxButton->GetRedrawCommand().GetPointer() ); m_Reader->AddObserver( itk::ModifiedEvent(), HyButton->GetRedrawCommand().GetPointer() ); m_Reader->AddObserver( itk::ModifiedEvent(), H1xButton->GetRedrawCommand().GetPointer() ); m_Reader->AddObserver( itk::ModifiedEvent(), H1yButton->GetRedrawCommand().GetPointer() ); m_Reader->AddObserver( itk::ModifiedEvent(), H2xButton->GetRedrawCommand().GetPointer() ); m_Reader->AddObserver( itk::ModifiedEvent(), H2yButton->GetRedrawCommand().GetPointer() ); m_Reader->AddObserver( itk::ModifiedEvent(), laplacianButton->GetRedrawCommand().GetPointer() ); m_Reader->AddObserver( itk::ModifiedEvent(), smoothedButton->GetRedrawCommand().GetPointer() ); m_Reader->AddObserver( itk::ModifiedEvent(), modulusButton->GetRedrawCommand().GetPointer() ); m_IntensityScaleModulus->SetScale( 0.2 ); m_IntensityScaleSmoothed->SetScale( 0.2 ); m_IntensityScaleLaplacian->SetScale( 0.2 ); m_IntensityScaleModulus->SetShift( 1000 ); m_IntensityScaleSmoothed->SetScale( 1000 ); m_IntensityScaleLaplacian->SetScale( 1000 ); this->ShowStatus("Let's start by loading an image..."); } /************************************ * * Destructor * ***********************************/ liFilterConsole2D ::~liFilterConsole2D() { } /************************************ * * Load * ***********************************/ void liFilterConsole2D ::Load( void ) { const char * filename = fl_file_chooser("Image filename","*.png",""); if( !filename ) { return; } this->ShowStatus("Loading image file..."); try { liFilterConsole2DBase::Load( filename ); } catch( ... ) { this->ShowStatus("Problems reading file format"); controlsGroup->deactivate(); return; } this->ShowStatus("File Loaded"); controlsGroup->activate(); } /************************************ * * Show * ***********************************/ void liFilterConsole2D ::Show( void ) { consoleWindow->show(); } /************************************ * * Hide * ***********************************/ void liFilterConsole2D ::Hide( void ) { consoleWindow->hide(); m_Viewer_H1x->Hide(); m_Viewer_H1y->Hide(); m_Viewer_H2x->Hide(); m_Viewer_H2y->Hide(); m_InputViewer->Hide(); m_Viewer_Laplacian->Hide(); m_Viewer_Smoothed->Hide(); m_Viewer_Gradient_Modulus->Hide(); } /************************************ * * Quit * ***********************************/ void liFilterConsole2D ::Quit( void ) { Hide(); } /************************************ * * Show Status * ***********************************/ void liFilterConsole2D ::ShowStatus( const char * message ) { liFilterConsole2DBase::ShowStatus( message ); statusTextOutput->value( message ); Fl::check(); } /************************************ * * Show Input Image * ***********************************/ void liFilterConsole2D ::ShowInput( void ) { if( ! (m_ImageLoaded) ) { this->ShowStatus("Please load an image first"); return; } m_InputViewer->SetImage( m_Reader->GetOutput() ); m_InputViewer->Show(); } /************************************ * * Show Filtered Image * ***********************************/ void liFilterConsole2D ::ShowFilteredX( void ) { m_H1x->Update(); m_Viewer_H1x->SetImage( m_H1x->GetOutput() ); m_Viewer_H1x->Show(); } /************************************ * * Show Filtered Image * ***********************************/ void liFilterConsole2D ::ShowFilteredY( void ) { m_H1y->Update(); m_Viewer_H1y->SetImage( m_H1y->GetOutput() ); m_Viewer_H1y->Show(); } /************************************ * * Show Second Derivative X * ***********************************/ void liFilterConsole2D ::ShowSecondDerivativeX( void ) { m_H2x->Update(); m_Viewer_H2x->SetImage( m_H2x->GetOutput() ); m_Viewer_H2x->Show(); } /************************************ * * Show Second Derivative Y * ***********************************/ void liFilterConsole2D ::ShowSecondDerivativeY( void ) { m_H2y->Update(); m_Viewer_H2y->SetImage( m_H2y->GetOutput() ); m_Viewer_H2y->Show(); } /************************************ * * Show Smoothed * ***********************************/ void liFilterConsole2D ::ShowSmoothed( void ) { m_Smoothed->Update(); m_Viewer_Smoothed->SetImage( m_Smoothed->GetOutput() ); m_Viewer_Smoothed->Show(); } /************************************ * * Show Laplacian * ***********************************/ void liFilterConsole2D ::ShowLaplacian( void ) { m_Laplacian->Update(); m_Viewer_Laplacian->SetImage( m_Laplacian->GetOutput() ); m_Viewer_Laplacian->Show(); } /************************************ * * Show Gradient Modulus * ***********************************/ void liFilterConsole2D ::ShowGradientModulus( void ) { m_Modulus->Update(); m_Viewer_Gradient_Modulus->SetImage( m_Modulus->GetOutput() ); m_Viewer_Gradient_Modulus->Show(); } /************************************ * * Execute * ***********************************/ void liFilterConsole2D ::Execute( void ) { if( ! (m_ImageLoaded) ) { this->ShowStatus("Please load an image first"); return; } this->ShowStatus("Filtering Image with a Gaussian..."); liFilterConsole2DBase::Execute(); this->ShowStatus("Filtering done "); } /************************************ * * SaveLaplacian * ***********************************/ void liFilterConsole2D ::SaveLaplacian( void ) { const char * filename = fl_file_chooser("Image filename","*.png",""); if( !filename ) { return; } this->ShowStatus("Saving image file..."); try { liFilterConsole2DBase::SaveLaplacian( filename ); } catch( ... ) { this->ShowStatus("Problems writing file format"); return; } this->ShowStatus("File Saved"); } /************************************ * * SaveModulus * ***********************************/ void liFilterConsole2D ::SaveModulus( void ) { const char * filename = fl_file_chooser("Image filename","*.png",""); if( !filename ) { return; } this->ShowStatus("Saving image file..."); try { liFilterConsole2DBase::SaveModulus( filename ); } catch( ... ) { this->ShowStatus("Problems writing file format"); return; } this->ShowStatus("File Saved"); } /************************************ * * SaveSmoothed * ***********************************/ void liFilterConsole2D ::SaveSmoothed( void ) { const char * filename = fl_file_chooser("Image filename","*.png",""); if( !filename ) { return; } this->ShowStatus("Saving image file..."); try { liFilterConsole2DBase::SaveSmoothed( filename ); } catch( ... ) { this->ShowStatus("Problems writing file format"); return; } this->ShowStatus("File Saved"); } <commit_msg>ENH: The GaussianFilter is better scaled now, so the ShiftFilter is set to 1.0.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: liFilterConsole2D.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <liFilterConsole2D.h> #include <FL/fl_file_chooser.H> /************************************ * * Constructor * ***********************************/ liFilterConsole2D ::liFilterConsole2D() { m_InputViewer = InputImageViewerType::New(); m_Viewer_H1x = ImageViewerType::New(); m_Viewer_H1y = ImageViewerType::New(); m_Viewer_H2x = ImageViewerType::New(); m_Viewer_H2y = ImageViewerType::New(); m_Viewer_Laplacian = ImageViewerType::New(); m_Viewer_Smoothed = ImageViewerType::New(); m_Viewer_Gradient_Modulus = ImageViewerType::New(); m_InputViewer->SetLabel( "Input Image" ); m_Viewer_H1x->SetLabel( "Gradient X" ); m_Viewer_H1y->SetLabel( "Gradient Y" ); m_Viewer_H2x->SetLabel( "Second Derivative X" ); m_Viewer_H2y->SetLabel( "Second Derivative Y" ); m_Viewer_Laplacian->SetLabel( "Laplacian" ); m_Viewer_Smoothed->SetLabel( "Smoothed" ); m_Viewer_Gradient_Modulus->SetLabel( "Gradient Modulus" ); progressSlider->Observe( m_Hx.GetPointer() ); progressSlider->Observe( m_Hy.GetPointer() ); progressSlider->Observe( m_H1x.GetPointer() ); progressSlider->Observe( m_H1y.GetPointer() ); progressSlider->Observe( m_H2x.GetPointer() ); progressSlider->Observe( m_H2y.GetPointer() ); progressSlider->Observe( m_Laplacian.GetPointer() ); progressSlider->Observe( m_Smoothed.GetPointer() ); progressSlider->Observe( m_Modulus.GetPointer() ); progressSlider->Observe( m_IntensityScaleSmoothed.GetPointer() ); progressSlider->Observe( m_IntensityScaleLaplacian.GetPointer() ); progressSlider->Observe( m_IntensityScaleModulus.GetPointer() ); progressSlider->Observe( m_WriterSmoothed.GetPointer() ); progressSlider->Observe( m_WriterLaplacian.GetPointer() ); progressSlider->Observe( m_WriterModulus.GetPointer() ); loadButton->Observe( m_Reader.GetPointer() ); inputButton->Observe( m_Reader.GetPointer() ); HxButton->Observe( m_Hx.GetPointer() ); HyButton->Observe( m_Hy.GetPointer() ); H1xButton->Observe( m_H1x.GetPointer() ); H1yButton->Observe( m_H1y.GetPointer() ); H2xButton->Observe( m_H2x.GetPointer() ); H2yButton->Observe( m_H2y.GetPointer() ); laplacianButton->Observe( m_Laplacian.GetPointer() ); smoothedButton->Observe( m_Smoothed.GetPointer() ); modulusButton->Observe( m_Modulus.GetPointer() ); m_Reader->AddObserver( itk::ModifiedEvent(), HxButton->GetRedrawCommand().GetPointer() ); m_Reader->AddObserver( itk::ModifiedEvent(), HyButton->GetRedrawCommand().GetPointer() ); m_Reader->AddObserver( itk::ModifiedEvent(), H1xButton->GetRedrawCommand().GetPointer() ); m_Reader->AddObserver( itk::ModifiedEvent(), H1yButton->GetRedrawCommand().GetPointer() ); m_Reader->AddObserver( itk::ModifiedEvent(), H2xButton->GetRedrawCommand().GetPointer() ); m_Reader->AddObserver( itk::ModifiedEvent(), H2yButton->GetRedrawCommand().GetPointer() ); m_Reader->AddObserver( itk::ModifiedEvent(), laplacianButton->GetRedrawCommand().GetPointer() ); m_Reader->AddObserver( itk::ModifiedEvent(), smoothedButton->GetRedrawCommand().GetPointer() ); m_Reader->AddObserver( itk::ModifiedEvent(), modulusButton->GetRedrawCommand().GetPointer() ); m_IntensityScaleModulus->SetScale( 1.0 ); m_IntensityScaleSmoothed->SetScale( 1.0 ); m_IntensityScaleLaplacian->SetScale( 1.0 ); m_IntensityScaleModulus->SetShift( 1000 ); m_IntensityScaleSmoothed->SetScale( 1000 ); m_IntensityScaleLaplacian->SetScale( 1000 ); this->ShowStatus("Let's start by loading an image..."); } /************************************ * * Destructor * ***********************************/ liFilterConsole2D ::~liFilterConsole2D() { } /************************************ * * Load * ***********************************/ void liFilterConsole2D ::Load( void ) { const char * filename = fl_file_chooser("Image filename","*.png",""); if( !filename ) { return; } this->ShowStatus("Loading image file..."); try { liFilterConsole2DBase::Load( filename ); } catch( ... ) { this->ShowStatus("Problems reading file format"); controlsGroup->deactivate(); return; } this->ShowStatus("File Loaded"); controlsGroup->activate(); } /************************************ * * Show * ***********************************/ void liFilterConsole2D ::Show( void ) { consoleWindow->show(); } /************************************ * * Hide * ***********************************/ void liFilterConsole2D ::Hide( void ) { consoleWindow->hide(); m_Viewer_H1x->Hide(); m_Viewer_H1y->Hide(); m_Viewer_H2x->Hide(); m_Viewer_H2y->Hide(); m_InputViewer->Hide(); m_Viewer_Laplacian->Hide(); m_Viewer_Smoothed->Hide(); m_Viewer_Gradient_Modulus->Hide(); } /************************************ * * Quit * ***********************************/ void liFilterConsole2D ::Quit( void ) { Hide(); } /************************************ * * Show Status * ***********************************/ void liFilterConsole2D ::ShowStatus( const char * message ) { liFilterConsole2DBase::ShowStatus( message ); statusTextOutput->value( message ); Fl::check(); } /************************************ * * Show Input Image * ***********************************/ void liFilterConsole2D ::ShowInput( void ) { if( ! (m_ImageLoaded) ) { this->ShowStatus("Please load an image first"); return; } m_InputViewer->SetImage( m_Reader->GetOutput() ); m_InputViewer->Show(); } /************************************ * * Show Filtered Image * ***********************************/ void liFilterConsole2D ::ShowFilteredX( void ) { m_H1x->Update(); m_Viewer_H1x->SetImage( m_H1x->GetOutput() ); m_Viewer_H1x->Show(); } /************************************ * * Show Filtered Image * ***********************************/ void liFilterConsole2D ::ShowFilteredY( void ) { m_H1y->Update(); m_Viewer_H1y->SetImage( m_H1y->GetOutput() ); m_Viewer_H1y->Show(); } /************************************ * * Show Second Derivative X * ***********************************/ void liFilterConsole2D ::ShowSecondDerivativeX( void ) { m_H2x->Update(); m_Viewer_H2x->SetImage( m_H2x->GetOutput() ); m_Viewer_H2x->Show(); } /************************************ * * Show Second Derivative Y * ***********************************/ void liFilterConsole2D ::ShowSecondDerivativeY( void ) { m_H2y->Update(); m_Viewer_H2y->SetImage( m_H2y->GetOutput() ); m_Viewer_H2y->Show(); } /************************************ * * Show Smoothed * ***********************************/ void liFilterConsole2D ::ShowSmoothed( void ) { m_Smoothed->Update(); m_Viewer_Smoothed->SetImage( m_Smoothed->GetOutput() ); m_Viewer_Smoothed->Show(); } /************************************ * * Show Laplacian * ***********************************/ void liFilterConsole2D ::ShowLaplacian( void ) { m_Laplacian->Update(); m_Viewer_Laplacian->SetImage( m_Laplacian->GetOutput() ); m_Viewer_Laplacian->Show(); } /************************************ * * Show Gradient Modulus * ***********************************/ void liFilterConsole2D ::ShowGradientModulus( void ) { m_Modulus->Update(); m_Viewer_Gradient_Modulus->SetImage( m_Modulus->GetOutput() ); m_Viewer_Gradient_Modulus->Show(); } /************************************ * * Execute * ***********************************/ void liFilterConsole2D ::Execute( void ) { if( ! (m_ImageLoaded) ) { this->ShowStatus("Please load an image first"); return; } this->ShowStatus("Filtering Image with a Gaussian..."); liFilterConsole2DBase::Execute(); this->ShowStatus("Filtering done "); } /************************************ * * SaveLaplacian * ***********************************/ void liFilterConsole2D ::SaveLaplacian( void ) { const char * filename = fl_file_chooser("Image filename","*.png",""); if( !filename ) { return; } this->ShowStatus("Saving image file..."); try { liFilterConsole2DBase::SaveLaplacian( filename ); } catch( ... ) { this->ShowStatus("Problems writing file format"); return; } this->ShowStatus("File Saved"); } /************************************ * * SaveModulus * ***********************************/ void liFilterConsole2D ::SaveModulus( void ) { const char * filename = fl_file_chooser("Image filename","*.png",""); if( !filename ) { return; } this->ShowStatus("Saving image file..."); try { liFilterConsole2DBase::SaveModulus( filename ); } catch( ... ) { this->ShowStatus("Problems writing file format"); return; } this->ShowStatus("File Saved"); } /************************************ * * SaveSmoothed * ***********************************/ void liFilterConsole2D ::SaveSmoothed( void ) { const char * filename = fl_file_chooser("Image filename","*.png",""); if( !filename ) { return; } this->ShowStatus("Saving image file..."); try { liFilterConsole2DBase::SaveSmoothed( filename ); } catch( ... ) { this->ShowStatus("Problems writing file format"); return; } this->ShowStatus("File Saved"); } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <dart/dynamics/dynamics.h> #include <dart/common/StlHelpers.h> #include <aikido/constraint/dart.hpp> #include <aikido/statespace/dart/RealVectorJointStateSpace.hpp> #include <aikido/statespace/dart/SO2JointStateSpace.hpp> using Vector0d = Eigen::Matrix<double, 0, 1>; using Vector1d = Eigen::Matrix<double, 1, 1>; using dart::common::make_unique; using dart::dynamics::BodyNode; using dart::dynamics::Joint; using dart::dynamics::RevoluteJoint; using dart::dynamics::Skeleton; using dart::dynamics::SkeletonPtr; using aikido::constraint::SampleGenerator; using aikido::statespace::RealVectorJointStateSpace; using aikido::statespace::SO2JointStateSpace; using aikido::util::RNGWrapper; using aikido::constraint::createDifferentiableBoundsFor; using aikido::constraint::createProjectableBoundsFor; using aikido::constraint::createTestableBoundsFor; using aikido::constraint::createSampleableBoundsFor; static Vector1d make_vector(double _x) { Vector1d matrix; matrix(0, 0) = _x; return matrix; } //============================================================================= class RealVectorJointStateSpaceHelpersTests : public ::testing::Test { protected: static constexpr int NUM_SAMPLES { 1000 }; void SetUp() override { mSkeleton = Skeleton::create(); mJoint = mSkeleton->createJointAndBodyNodePair< RevoluteJoint, BodyNode>().first; mJoint->setPositionLowerLimit(0, -1.); mJoint->setPositionUpperLimit(0, 2.); mStateSpace = std::make_shared<RealVectorJointStateSpace>(mJoint); } SkeletonPtr mSkeleton; RevoluteJoint* mJoint; std::shared_ptr<RealVectorJointStateSpace> mStateSpace; }; //============================================================================= TEST_F(RealVectorJointStateSpaceHelpersTests, createTestableBoundsFor) { auto constraint = createTestableBoundsFor<RealVectorJointStateSpace>( mStateSpace); auto state = mStateSpace->createState(); EXPECT_EQ(mStateSpace, constraint->getStateSpace()); mJoint->setPosition(0, -0.9); mStateSpace->getState(state); EXPECT_TRUE(constraint->isSatisfied(state)); mJoint->setPosition(0, 1.9); mStateSpace->getState(state); EXPECT_TRUE(constraint->isSatisfied(state)); mJoint->setPosition(0, -1.1); mStateSpace->getState(state); EXPECT_FALSE(constraint->isSatisfied(state)); mJoint->setPosition(0, 2.1); mStateSpace->getState(state); EXPECT_FALSE(constraint->isSatisfied(state)); } //============================================================================= TEST_F(RealVectorJointStateSpaceHelpersTests, createProjectableBounds) { auto testableConstraint = createTestableBoundsFor<RealVectorJointStateSpace>(mStateSpace); auto projectableConstraint = createProjectableBoundsFor<RealVectorJointStateSpace>(mStateSpace); auto inState = mStateSpace->createState(); auto outState = mStateSpace->createState(); EXPECT_EQ(mStateSpace, projectableConstraint->getStateSpace()); // Doesn't change the value if the constraint is satisfied. mJoint->setPosition(0, -0.9); mStateSpace->getState(inState); EXPECT_TRUE(projectableConstraint->project(inState, outState)); EXPECT_TRUE(inState.getValue().isApprox(outState.getValue())); mJoint->setPosition(0, 1.9); mStateSpace->getState(inState); EXPECT_TRUE(projectableConstraint->project(inState, outState)); EXPECT_TRUE(inState.getValue().isApprox(outState.getValue())); // Output is feasible if the constriant is not satisfied. mJoint->setPosition(0, -1.1); mStateSpace->getState(inState); EXPECT_TRUE(projectableConstraint->project(inState, outState)); EXPECT_TRUE(testableConstraint->isSatisfied(outState)); mJoint->setPosition(0, 2.1); mStateSpace->getState(inState); EXPECT_TRUE(projectableConstraint->project(inState, outState)); EXPECT_TRUE(testableConstraint->isSatisfied(outState)); } //============================================================================= TEST_F(RealVectorJointStateSpaceHelpersTests, createDifferentiableBounds) { const auto differentiableConstraint = createDifferentiableBoundsFor<RealVectorJointStateSpace>(mStateSpace); EXPECT_EQ(mStateSpace, differentiableConstraint->getStateSpace()); auto state = mStateSpace->createState(); // Value is zero when the constraint is satisfied. mJoint->setPosition(0, -0.9); mStateSpace->getState(state); auto constraintValue = differentiableConstraint->getValue(state); EXPECT_TRUE(Vector1d::Zero().isApprox(constraintValue)); mJoint->setPosition(0, 1.9); mStateSpace->getState(state); constraintValue = differentiableConstraint->getValue(state); EXPECT_TRUE(Vector1d::Zero().isApprox(constraintValue)); // Value is non-zero when the constraint is not satisfied. mJoint->setPosition(0, -1.1); mStateSpace->getState(state); constraintValue = differentiableConstraint->getValue(state); EXPECT_FALSE(Vector1d::Zero().isApprox(constraintValue)); mJoint->setPosition(0, 2.1); mStateSpace->getState(state); constraintValue = differentiableConstraint->getValue(state); EXPECT_FALSE(Vector1d::Zero().isApprox(constraintValue)); } //============================================================================= TEST_F(RealVectorJointStateSpaceHelpersTests, createSampleableBounds) { auto rng = make_unique<RNGWrapper<std::default_random_engine>>(0); const auto testableConstraint = createTestableBoundsFor<RealVectorJointStateSpace>(mStateSpace); const auto sampleableConstraint = createSampleableBoundsFor<RealVectorJointStateSpace>( mStateSpace, std::move(rng)); ASSERT_TRUE(!!sampleableConstraint); EXPECT_EQ(mStateSpace, sampleableConstraint->getStateSpace()); const auto generator = sampleableConstraint->createSampleGenerator(); ASSERT_TRUE(!!generator); EXPECT_EQ(mStateSpace, generator->getStateSpace()); auto state = mStateSpace->createState(); for (size_t isample = 0; isample < NUM_SAMPLES; ++isample) { ASSERT_TRUE(generator->canSample()); ASSERT_EQ(SampleGenerator::NO_LIMIT, generator->getNumSamples()); ASSERT_TRUE(generator->sample(state)); ASSERT_TRUE(testableConstraint->isSatisfied(state)); } } //============================================================================= class SO2JointStateSpaceHelpersTests : public ::testing::Test { protected: static constexpr int NUM_SAMPLES { 1000 }; void SetUp() override { mSkeleton = Skeleton::create(); mJoint = mSkeleton->createJointAndBodyNodePair< RevoluteJoint, BodyNode>().first; // Don't set any limits. mStateSpace = std::make_shared<SO2JointStateSpace>(mJoint); } SkeletonPtr mSkeleton; RevoluteJoint* mJoint; std::shared_ptr<SO2JointStateSpace> mStateSpace; }; //============================================================================= TEST_F(SO2JointStateSpaceHelpersTests, createTestableBoundsFor) { auto constraint = createTestableBoundsFor<SO2JointStateSpace>( mStateSpace); auto state = mStateSpace->createState(); EXPECT_EQ(mStateSpace, constraint->getStateSpace()); mJoint->setPosition(0, -0.9); mStateSpace->getState(state); EXPECT_TRUE(constraint->isSatisfied(state)); } //============================================================================= TEST_F(SO2JointStateSpaceHelpersTests, createProjectableBounds) { auto testableConstraint = createTestableBoundsFor<SO2JointStateSpace>(mStateSpace); auto projectableConstraint = createProjectableBoundsFor<SO2JointStateSpace>(mStateSpace); auto inState = mStateSpace->createState(); auto outState = mStateSpace->createState(); EXPECT_EQ(mStateSpace, projectableConstraint->getStateSpace()); // Doesn't change the value if the constraint is satisfied. mJoint->setPosition(0, -0.9); mStateSpace->getState(inState); EXPECT_TRUE(projectableConstraint->project(inState, outState)); EXPECT_DOUBLE_EQ(inState.getAngle(), outState.getAngle()); } //============================================================================= TEST_F(SO2JointStateSpaceHelpersTests, createDifferentiableBounds) { const auto differentiableConstraint = createDifferentiableBoundsFor<SO2JointStateSpace>(mStateSpace); EXPECT_EQ(mStateSpace, differentiableConstraint->getStateSpace()); auto state = mStateSpace->createState(); mJoint->setPosition(0, -0.9); mStateSpace->getState(state); auto constraintValue = differentiableConstraint->getValue(state); EXPECT_TRUE(Vector0d::Zero().isApprox(constraintValue)); } //============================================================================= TEST_F(SO2JointStateSpaceHelpersTests, createSampleableBounds) { auto rng = make_unique<RNGWrapper<std::default_random_engine>>(0); const auto sampleableConstraint = createSampleableBoundsFor<SO2JointStateSpace>( mStateSpace, std::move(rng)); ASSERT_TRUE(!!sampleableConstraint); EXPECT_EQ(mStateSpace, sampleableConstraint->getStateSpace()); const auto generator = sampleableConstraint->createSampleGenerator(); ASSERT_TRUE(!!generator); EXPECT_EQ(mStateSpace, generator->getStateSpace()); auto state = mStateSpace->createState(); for (size_t isample = 0; isample < NUM_SAMPLES; ++isample) { ASSERT_TRUE(generator->canSample()); ASSERT_EQ(SampleGenerator::NO_LIMIT, generator->getNumSamples()); ASSERT_TRUE(generator->sample(state)); // There is nothing to test here. } } <commit_msg>Simplified some SO2 bound tests.<commit_after>#include <gtest/gtest.h> #include <dart/dynamics/dynamics.h> #include <dart/common/StlHelpers.h> #include <aikido/constraint/dart.hpp> #include <aikido/constraint/SatisfiedConstraint.hpp> #include <aikido/statespace/dart/RealVectorJointStateSpace.hpp> #include <aikido/statespace/dart/SO2JointStateSpace.hpp> using Vector0d = Eigen::Matrix<double, 0, 1>; using Vector1d = Eigen::Matrix<double, 1, 1>; using dart::common::make_unique; using dart::dynamics::BodyNode; using dart::dynamics::Joint; using dart::dynamics::RevoluteJoint; using dart::dynamics::Skeleton; using dart::dynamics::SkeletonPtr; using aikido::constraint::SampleGenerator; using aikido::constraint::SatisfiedConstraint; using aikido::statespace::RealVectorJointStateSpace; using aikido::statespace::SO2JointStateSpace; using aikido::util::RNGWrapper; using aikido::constraint::createDifferentiableBoundsFor; using aikido::constraint::createProjectableBoundsFor; using aikido::constraint::createTestableBoundsFor; using aikido::constraint::createSampleableBoundsFor; static Vector1d make_vector(double _x) { Vector1d matrix; matrix(0, 0) = _x; return matrix; } //============================================================================= class RealVectorJointStateSpaceHelpersTests : public ::testing::Test { protected: static constexpr int NUM_SAMPLES { 1000 }; void SetUp() override { mSkeleton = Skeleton::create(); mJoint = mSkeleton->createJointAndBodyNodePair< RevoluteJoint, BodyNode>().first; mJoint->setPositionLowerLimit(0, -1.); mJoint->setPositionUpperLimit(0, 2.); mStateSpace = std::make_shared<RealVectorJointStateSpace>(mJoint); } SkeletonPtr mSkeleton; RevoluteJoint* mJoint; std::shared_ptr<RealVectorJointStateSpace> mStateSpace; }; //============================================================================= TEST_F(RealVectorJointStateSpaceHelpersTests, createTestableBoundsFor) { auto constraint = createTestableBoundsFor<RealVectorJointStateSpace>( mStateSpace); auto state = mStateSpace->createState(); EXPECT_EQ(mStateSpace, constraint->getStateSpace()); mJoint->setPosition(0, -0.9); mStateSpace->getState(state); EXPECT_TRUE(constraint->isSatisfied(state)); mJoint->setPosition(0, 1.9); mStateSpace->getState(state); EXPECT_TRUE(constraint->isSatisfied(state)); mJoint->setPosition(0, -1.1); mStateSpace->getState(state); EXPECT_FALSE(constraint->isSatisfied(state)); mJoint->setPosition(0, 2.1); mStateSpace->getState(state); EXPECT_FALSE(constraint->isSatisfied(state)); } //============================================================================= TEST_F(RealVectorJointStateSpaceHelpersTests, createProjectableBounds) { auto testableConstraint = createTestableBoundsFor<RealVectorJointStateSpace>(mStateSpace); auto projectableConstraint = createProjectableBoundsFor<RealVectorJointStateSpace>(mStateSpace); auto inState = mStateSpace->createState(); auto outState = mStateSpace->createState(); EXPECT_EQ(mStateSpace, projectableConstraint->getStateSpace()); // Doesn't change the value if the constraint is satisfied. mJoint->setPosition(0, -0.9); mStateSpace->getState(inState); EXPECT_TRUE(projectableConstraint->project(inState, outState)); EXPECT_TRUE(inState.getValue().isApprox(outState.getValue())); mJoint->setPosition(0, 1.9); mStateSpace->getState(inState); EXPECT_TRUE(projectableConstraint->project(inState, outState)); EXPECT_TRUE(inState.getValue().isApprox(outState.getValue())); // Output is feasible if the constriant is not satisfied. mJoint->setPosition(0, -1.1); mStateSpace->getState(inState); EXPECT_TRUE(projectableConstraint->project(inState, outState)); EXPECT_TRUE(testableConstraint->isSatisfied(outState)); mJoint->setPosition(0, 2.1); mStateSpace->getState(inState); EXPECT_TRUE(projectableConstraint->project(inState, outState)); EXPECT_TRUE(testableConstraint->isSatisfied(outState)); } //============================================================================= TEST_F(RealVectorJointStateSpaceHelpersTests, createDifferentiableBounds) { const auto differentiableConstraint = createDifferentiableBoundsFor<RealVectorJointStateSpace>(mStateSpace); EXPECT_EQ(mStateSpace, differentiableConstraint->getStateSpace()); auto state = mStateSpace->createState(); // Value is zero when the constraint is satisfied. mJoint->setPosition(0, -0.9); mStateSpace->getState(state); auto constraintValue = differentiableConstraint->getValue(state); EXPECT_TRUE(Vector1d::Zero().isApprox(constraintValue)); mJoint->setPosition(0, 1.9); mStateSpace->getState(state); constraintValue = differentiableConstraint->getValue(state); EXPECT_TRUE(Vector1d::Zero().isApprox(constraintValue)); // Value is non-zero when the constraint is not satisfied. mJoint->setPosition(0, -1.1); mStateSpace->getState(state); constraintValue = differentiableConstraint->getValue(state); EXPECT_FALSE(Vector1d::Zero().isApprox(constraintValue)); mJoint->setPosition(0, 2.1); mStateSpace->getState(state); constraintValue = differentiableConstraint->getValue(state); EXPECT_FALSE(Vector1d::Zero().isApprox(constraintValue)); } //============================================================================= TEST_F(RealVectorJointStateSpaceHelpersTests, createSampleableBounds) { auto rng = make_unique<RNGWrapper<std::default_random_engine>>(0); const auto testableConstraint = createTestableBoundsFor<RealVectorJointStateSpace>(mStateSpace); const auto sampleableConstraint = createSampleableBoundsFor<RealVectorJointStateSpace>( mStateSpace, std::move(rng)); ASSERT_TRUE(!!sampleableConstraint); EXPECT_EQ(mStateSpace, sampleableConstraint->getStateSpace()); const auto generator = sampleableConstraint->createSampleGenerator(); ASSERT_TRUE(!!generator); EXPECT_EQ(mStateSpace, generator->getStateSpace()); auto state = mStateSpace->createState(); for (size_t isample = 0; isample < NUM_SAMPLES; ++isample) { ASSERT_TRUE(generator->canSample()); ASSERT_EQ(SampleGenerator::NO_LIMIT, generator->getNumSamples()); ASSERT_TRUE(generator->sample(state)); ASSERT_TRUE(testableConstraint->isSatisfied(state)); } } //============================================================================= class SO2JointStateSpaceHelpersTests : public ::testing::Test { protected: static constexpr int NUM_SAMPLES { 1000 }; void SetUp() override { mSkeleton = Skeleton::create(); mJoint = mSkeleton->createJointAndBodyNodePair< RevoluteJoint, BodyNode>().first; // Don't set any limits. mStateSpace = std::make_shared<SO2JointStateSpace>(mJoint); } SkeletonPtr mSkeleton; RevoluteJoint* mJoint; std::shared_ptr<SO2JointStateSpace> mStateSpace; }; //============================================================================= TEST_F(SO2JointStateSpaceHelpersTests, createTestableBoundsFor) { const auto constraint = createTestableBoundsFor<SO2JointStateSpace>(mStateSpace); EXPECT_TRUE(!!dynamic_cast<SatisfiedConstraint*>(constraint.get())); EXPECT_EQ(mStateSpace, constraint->getStateSpace()); } //============================================================================= TEST_F(SO2JointStateSpaceHelpersTests, createProjectableBounds) { const auto constraint = createProjectableBoundsFor<SO2JointStateSpace>(mStateSpace); EXPECT_TRUE(!!dynamic_cast<SatisfiedConstraint*>(constraint.get())); EXPECT_EQ(mStateSpace, constraint->getStateSpace()); } //============================================================================= TEST_F(SO2JointStateSpaceHelpersTests, createDifferentiableBounds) { const auto constraint = createDifferentiableBoundsFor<SO2JointStateSpace>(mStateSpace); EXPECT_TRUE(!!dynamic_cast<SatisfiedConstraint*>(constraint.get())); EXPECT_EQ(mStateSpace, constraint->getStateSpace()); } //============================================================================= TEST_F(SO2JointStateSpaceHelpersTests, createSampleableBounds) { const auto sampleableConstraint = createSampleableBoundsFor<SO2JointStateSpace>(mStateSpace, make_unique<RNGWrapper<std::default_random_engine>>(0)); ASSERT_TRUE(!!sampleableConstraint); EXPECT_EQ(mStateSpace, sampleableConstraint->getStateSpace()); const auto generator = sampleableConstraint->createSampleGenerator(); ASSERT_TRUE(!!generator); EXPECT_EQ(mStateSpace, generator->getStateSpace()); auto state = mStateSpace->createState(); for (size_t isample = 0; isample < NUM_SAMPLES; ++isample) { ASSERT_TRUE(generator->canSample()); ASSERT_EQ(SampleGenerator::NO_LIMIT, generator->getNumSamples()); ASSERT_TRUE(generator->sample(state)); // There is nothing to test here. } } <|endoftext|>
<commit_before>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #include <seastar/core/reactor.hh> #include <seastar/core/app-template.hh> #include <seastar/core/print.hh> #include <seastar/core/shared_ptr.hh> using namespace seastar; const char* de_type_desc(directory_entry_type t) { switch (t) { case directory_entry_type::unknown: return "unknown"; case directory_entry_type::block_device: return "block_device"; case directory_entry_type::char_device: return "char_device"; case directory_entry_type::directory: return "directory"; case directory_entry_type::fifo: return "fifo"; case directory_entry_type::link: return "link"; case directory_entry_type::regular: return "regular"; case directory_entry_type::socket: return "socket"; } assert(0 && "should not get here"); return nullptr; } int main(int ac, char** av) { class lister { file _f; subscription<directory_entry> _listing; public: lister(file f) : _f(std::move(f)) , _listing(_f.list_directory([this] (directory_entry de) { return report(de); })) { } future<> done() { return _listing.done(); } private: future<> report(directory_entry de) { return file_stat(de.name, follow_symlink::no).then([de = std::move(de)] (stat_data sd) { if (de.type) { assert(*de.type == sd.type); } else { assert(sd.type == directory_entry_type::unknown); } fmt::print("{} (type={})\n", de.name, de_type_desc(sd.type)); return make_ready_future<>(); }); } }; return app_template().run_deprecated(ac, av, [] { return engine().open_directory(".").then([] (file f) { auto l = make_lw_shared<lister>(std::move(f)); return l->done().then([l] { // ugly thing to keep *l alive engine().exit(0); }); }); }); } <commit_msg>directory_test: Update to use run instead of run_deprecated<commit_after>/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #include <seastar/core/reactor.hh> #include <seastar/core/app-template.hh> #include <seastar/core/print.hh> #include <seastar/core/shared_ptr.hh> using namespace seastar; const char* de_type_desc(directory_entry_type t) { switch (t) { case directory_entry_type::unknown: return "unknown"; case directory_entry_type::block_device: return "block_device"; case directory_entry_type::char_device: return "char_device"; case directory_entry_type::directory: return "directory"; case directory_entry_type::fifo: return "fifo"; case directory_entry_type::link: return "link"; case directory_entry_type::regular: return "regular"; case directory_entry_type::socket: return "socket"; } assert(0 && "should not get here"); return nullptr; } int main(int ac, char** av) { class lister { file _f; subscription<directory_entry> _listing; public: lister(file f) : _f(std::move(f)) , _listing(_f.list_directory([this] (directory_entry de) { return report(de); })) { } future<> done() { return _listing.done(); } private: future<> report(directory_entry de) { return file_stat(de.name, follow_symlink::no).then([de = std::move(de)] (stat_data sd) { if (de.type) { assert(*de.type == sd.type); } else { assert(sd.type == directory_entry_type::unknown); } fmt::print("{} (type={})\n", de.name, de_type_desc(sd.type)); return make_ready_future<>(); }); } }; return app_template().run(ac, av, [] { return engine().open_directory(".").then([] (file f) { return do_with(lister(std::move(f)), [] (lister& l) { return l.done().then([] { return 0; }); }); }); }); } <|endoftext|>
<commit_before>#include "clustering/administration/namespace_interface_repository.hpp" #include "errors.hpp" #include <boost/bind.hpp> #include <boost/ptr_container/ptr_map.hpp> #include "concurrency/cross_thread_signal.hpp" #include "concurrency/cross_thread_watchable.hpp" #define NAMESPACE_INTERFACE_EXPIRATION_MS (60 * 1000) template <class protocol_t> struct namespace_repo_t<protocol_t>::namespace_cache_t { public: boost::ptr_map<namespace_id_t, namespace_cache_entry_t> entries; auto_drainer_t drainer; }; template <class protocol_t> namespace_repo_t<protocol_t>::namespace_repo_t(mailbox_manager_t *_mailbox_manager, clone_ptr_t<watchable_t<std::map<peer_id_t, namespaces_directory_metadata_t<protocol_t> > > > _namespaces_directory_metadata, typename protocol_t::context_t *_ctx) : mailbox_manager(_mailbox_manager), namespaces_directory_metadata(_namespaces_directory_metadata), ctx(_ctx) { } template <class protocol_t> namespace_repo_t<protocol_t>::~namespace_repo_t() { } template <class protocol_t> std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > get_reactor_business_cards( const std::map<peer_id_t, namespaces_directory_metadata_t<protocol_t> > &ns_directory_metadata, namespace_id_t n_id) { std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > res; for (typename std::map<peer_id_t, namespaces_directory_metadata_t<protocol_t> >::const_iterator it = ns_directory_metadata.begin(); it != ns_directory_metadata.end(); it++) { typename namespaces_directory_metadata_t<protocol_t>::reactor_bcards_map_t::const_iterator jt = it->second.reactor_bcards.find(n_id); if (jt != it->second.reactor_bcards.end()) { res[it->first] = jt->second.internal; } else { res[it->first] = cow_ptr_t<reactor_business_card_t<protocol_t> >(); } } return res; } template <class protocol_t> namespace_repo_t<protocol_t>::access_t::access_t() : cache_entry(NULL), thread(INVALID_THREAD) { } template<class protocol_t> namespace_repo_t<protocol_t>::access_t::access_t(namespace_repo_t *parent, namespace_id_t namespace_id, signal_t *interruptor) : thread(get_thread_id()) { { ASSERT_FINITE_CORO_WAITING; namespace_cache_t *cache = parent->namespace_caches.get(); if (cache->entries.find(namespace_id) == cache->entries.end()) { cache_entry = new namespace_cache_entry_t; cache_entry->ref_count = 0; cache_entry->pulse_when_ref_count_becomes_zero = NULL; cache_entry->pulse_when_ref_count_becomes_nonzero = NULL; ref_handler.init(cache_entry); cache->entries.insert(namespace_id, cache_entry); coro_t::spawn_sometime(boost::bind( &namespace_repo_t<protocol_t>::create_and_destroy_namespace_interface, parent, cache, namespace_id, auto_drainer_t::lock_t(&cache->drainer))); } else { cache_entry = &cache->entries[namespace_id]; ref_handler.init(cache_entry); } } wait_interruptible(cache_entry->namespace_if.get_ready_signal(), interruptor); } template <class protocol_t> namespace_repo_t<protocol_t>::access_t::access_t(const access_t& access) : cache_entry(access.cache_entry), thread(access.thread) { if (cache_entry) { rassert_unreviewed(get_thread_id() == thread); ref_handler.init(cache_entry); } } template <class protocol_t> typename namespace_repo_t<protocol_t>::access_t &namespace_repo_t<protocol_t>::access_t::operator=(const access_t &access) { if (this != &access) { cache_entry = access.cache_entry; ref_handler.reset(); if (access.cache_entry) { ref_handler.init(access.cache_entry); } thread = access.thread; } return *this; } template <class protocol_t> namespace_interface_t<protocol_t> *namespace_repo_t<protocol_t>::access_t::get_namespace_if() { rassert_unreviewed(thread == get_thread_id()); return cache_entry->namespace_if.get_value(); } template <class protocol_t> namespace_repo_t<protocol_t>::access_t::ref_handler_t::ref_handler_t() : ref_target(NULL) { } template <class protocol_t> namespace_repo_t<protocol_t>::access_t::ref_handler_t::~ref_handler_t() { reset(); } template <class protocol_t> void namespace_repo_t<protocol_t>::access_t::ref_handler_t::init(namespace_cache_entry_t *_ref_target) { ASSERT_NO_CORO_WAITING; rassert_unreviewed(ref_target == NULL); ref_target = _ref_target; ref_target->ref_count++; if (ref_target->ref_count == 1) { if (ref_target->pulse_when_ref_count_becomes_nonzero) { ref_target->pulse_when_ref_count_becomes_nonzero->pulse_if_not_already_pulsed(); } } } template <class protocol_t> void namespace_repo_t<protocol_t>::access_t::ref_handler_t::reset() { ASSERT_NO_CORO_WAITING; if (ref_target != NULL) { ref_target->ref_count--; if (ref_target->ref_count == 0) { if (ref_target->pulse_when_ref_count_becomes_zero) { ref_target->pulse_when_ref_count_becomes_zero->pulse_if_not_already_pulsed(); } } } } template <class protocol_t> void namespace_repo_t<protocol_t>::create_and_destroy_namespace_interface( namespace_cache_t *cache, namespace_id_t namespace_id, auto_drainer_t::lock_t keepalive) THROWS_NOTHING{ keepalive.assert_is_holding(&cache->drainer); int thread = get_thread_id(); namespace_cache_entry_t *cache_entry = cache->entries.find(namespace_id)->second; rassert_unreviewed(!cache_entry->namespace_if.get_ready_signal()->is_pulsed()); /* We need to switch to `home_thread()` to construct `cross_thread_watchable`, then switch back. In destruction we need to do the reverse. Fortunately RAII works really nicely here. */ on_thread_t switch_to_home_thread(home_thread()); clone_ptr_t<watchable_t<std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > > > subview = namespaces_directory_metadata->subview(boost::bind(&get_reactor_business_cards<protocol_t>, _1, namespace_id)); cross_thread_watchable_variable_t<std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > > cross_thread_watchable(subview, thread); on_thread_t switch_back(thread); cluster_namespace_interface_t<protocol_t> namespace_interface( mailbox_manager, cross_thread_watchable.get_watchable(), ctx); try { wait_interruptible(namespace_interface.get_initial_ready_signal(), keepalive.get_drain_signal()); /* Notify `access_t`s that the namespace is available now */ cache_entry->namespace_if.pulse(&namespace_interface); /* Wait until it's time to shut down */ while (true) { while (cache_entry->ref_count != 0) { cond_t ref_count_is_zero; assignment_sentry_t<cond_t *> notify_if_ref_count_becomes_zero( &cache_entry->pulse_when_ref_count_becomes_zero, &ref_count_is_zero); wait_interruptible(&ref_count_is_zero, keepalive.get_drain_signal()); } signal_timer_t expiration_timer(NAMESPACE_INTERFACE_EXPIRATION_MS); cond_t ref_count_is_nonzero; assignment_sentry_t<cond_t *> notify_if_ref_count_becomes_nonzero( &cache_entry->pulse_when_ref_count_becomes_nonzero, &ref_count_is_nonzero); wait_any_t waiter(&expiration_timer, &ref_count_is_nonzero); wait_interruptible(&waiter, keepalive.get_drain_signal()); if (!ref_count_is_nonzero.is_pulsed()) { rassert_unreviewed(cache_entry->ref_count == 0); /* We waited a whole `NAMESPACE_INTERFACE_EXPIRATION_MS` and nothing used us. So let's destroy ourselves. */ break; } } } catch (interrupted_exc_t) { /* We got here because we were interrupted in the startup process. That means the `namespace_repo_t` destructor was called, which means there mustn't exist any `access_t` objects. So ref_count must be 0. */ rassert_unreviewed(cache_entry->ref_count == 0); } ASSERT_NO_CORO_WAITING; cache->entries.erase(namespace_id); } #include "mock/dummy_protocol.hpp" #include "memcached/protocol.hpp" #include "rdb_protocol/protocol.hpp" template class namespace_repo_t<mock::dummy_protocol_t>; template class namespace_repo_t<memcached_protocol_t>; template class namespace_repo_t<rdb_protocol_t>; <commit_msg>Reviewed assertions in namespace_interface_repository.cc.<commit_after>#include "clustering/administration/namespace_interface_repository.hpp" #include "errors.hpp" #include <boost/bind.hpp> #include <boost/ptr_container/ptr_map.hpp> #include "concurrency/cross_thread_signal.hpp" #include "concurrency/cross_thread_watchable.hpp" #define NAMESPACE_INTERFACE_EXPIRATION_MS (60 * 1000) template <class protocol_t> struct namespace_repo_t<protocol_t>::namespace_cache_t { public: boost::ptr_map<namespace_id_t, namespace_cache_entry_t> entries; auto_drainer_t drainer; }; template <class protocol_t> namespace_repo_t<protocol_t>::namespace_repo_t(mailbox_manager_t *_mailbox_manager, clone_ptr_t<watchable_t<std::map<peer_id_t, namespaces_directory_metadata_t<protocol_t> > > > _namespaces_directory_metadata, typename protocol_t::context_t *_ctx) : mailbox_manager(_mailbox_manager), namespaces_directory_metadata(_namespaces_directory_metadata), ctx(_ctx) { } template <class protocol_t> namespace_repo_t<protocol_t>::~namespace_repo_t() { } template <class protocol_t> std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > get_reactor_business_cards( const std::map<peer_id_t, namespaces_directory_metadata_t<protocol_t> > &ns_directory_metadata, namespace_id_t n_id) { std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > res; for (typename std::map<peer_id_t, namespaces_directory_metadata_t<protocol_t> >::const_iterator it = ns_directory_metadata.begin(); it != ns_directory_metadata.end(); it++) { typename namespaces_directory_metadata_t<protocol_t>::reactor_bcards_map_t::const_iterator jt = it->second.reactor_bcards.find(n_id); if (jt != it->second.reactor_bcards.end()) { res[it->first] = jt->second.internal; } else { res[it->first] = cow_ptr_t<reactor_business_card_t<protocol_t> >(); } } return res; } template <class protocol_t> namespace_repo_t<protocol_t>::access_t::access_t() : cache_entry(NULL), thread(INVALID_THREAD) { } template<class protocol_t> namespace_repo_t<protocol_t>::access_t::access_t(namespace_repo_t *parent, namespace_id_t namespace_id, signal_t *interruptor) : thread(get_thread_id()) { { ASSERT_FINITE_CORO_WAITING; namespace_cache_t *cache = parent->namespace_caches.get(); if (cache->entries.find(namespace_id) == cache->entries.end()) { cache_entry = new namespace_cache_entry_t; cache_entry->ref_count = 0; cache_entry->pulse_when_ref_count_becomes_zero = NULL; cache_entry->pulse_when_ref_count_becomes_nonzero = NULL; ref_handler.init(cache_entry); cache->entries.insert(namespace_id, cache_entry); coro_t::spawn_sometime(boost::bind( &namespace_repo_t<protocol_t>::create_and_destroy_namespace_interface, parent, cache, namespace_id, auto_drainer_t::lock_t(&cache->drainer))); } else { cache_entry = &cache->entries[namespace_id]; ref_handler.init(cache_entry); } } wait_interruptible(cache_entry->namespace_if.get_ready_signal(), interruptor); } template <class protocol_t> namespace_repo_t<protocol_t>::access_t::access_t(const access_t& access) : cache_entry(access.cache_entry), thread(access.thread) { if (cache_entry) { rassert_reviewed(get_thread_id() == thread); ref_handler.init(cache_entry); } } template <class protocol_t> typename namespace_repo_t<protocol_t>::access_t &namespace_repo_t<protocol_t>::access_t::operator=(const access_t &access) { if (this != &access) { cache_entry = access.cache_entry; ref_handler.reset(); if (access.cache_entry) { ref_handler.init(access.cache_entry); } thread = access.thread; } return *this; } template <class protocol_t> namespace_interface_t<protocol_t> *namespace_repo_t<protocol_t>::access_t::get_namespace_if() { rassert_reviewed(thread == get_thread_id()); return cache_entry->namespace_if.get_value(); } template <class protocol_t> namespace_repo_t<protocol_t>::access_t::ref_handler_t::ref_handler_t() : ref_target(NULL) { } template <class protocol_t> namespace_repo_t<protocol_t>::access_t::ref_handler_t::~ref_handler_t() { reset(); } template <class protocol_t> void namespace_repo_t<protocol_t>::access_t::ref_handler_t::init(namespace_cache_entry_t *_ref_target) { ASSERT_NO_CORO_WAITING; guarantee_reviewed(ref_target == NULL); ref_target = _ref_target; ref_target->ref_count++; if (ref_target->ref_count == 1) { if (ref_target->pulse_when_ref_count_becomes_nonzero) { ref_target->pulse_when_ref_count_becomes_nonzero->pulse_if_not_already_pulsed(); } } } template <class protocol_t> void namespace_repo_t<protocol_t>::access_t::ref_handler_t::reset() { ASSERT_NO_CORO_WAITING; if (ref_target != NULL) { ref_target->ref_count--; if (ref_target->ref_count == 0) { if (ref_target->pulse_when_ref_count_becomes_zero) { ref_target->pulse_when_ref_count_becomes_zero->pulse_if_not_already_pulsed(); } } } } template <class protocol_t> void namespace_repo_t<protocol_t>::create_and_destroy_namespace_interface( namespace_cache_t *cache, namespace_id_t namespace_id, auto_drainer_t::lock_t keepalive) THROWS_NOTHING{ keepalive.assert_is_holding(&cache->drainer); int thread = get_thread_id(); namespace_cache_entry_t *cache_entry = cache->entries.find(namespace_id)->second; guarantee_reviewed(!cache_entry->namespace_if.get_ready_signal()->is_pulsed()); /* We need to switch to `home_thread()` to construct `cross_thread_watchable`, then switch back. In destruction we need to do the reverse. Fortunately RAII works really nicely here. */ on_thread_t switch_to_home_thread(home_thread()); clone_ptr_t<watchable_t<std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > > > subview = namespaces_directory_metadata->subview(boost::bind(&get_reactor_business_cards<protocol_t>, _1, namespace_id)); cross_thread_watchable_variable_t<std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > > cross_thread_watchable(subview, thread); on_thread_t switch_back(thread); cluster_namespace_interface_t<protocol_t> namespace_interface( mailbox_manager, cross_thread_watchable.get_watchable(), ctx); try { wait_interruptible(namespace_interface.get_initial_ready_signal(), keepalive.get_drain_signal()); /* Notify `access_t`s that the namespace is available now */ cache_entry->namespace_if.pulse(&namespace_interface); /* Wait until it's time to shut down */ while (true) { while (cache_entry->ref_count != 0) { cond_t ref_count_is_zero; assignment_sentry_t<cond_t *> notify_if_ref_count_becomes_zero( &cache_entry->pulse_when_ref_count_becomes_zero, &ref_count_is_zero); wait_interruptible(&ref_count_is_zero, keepalive.get_drain_signal()); } signal_timer_t expiration_timer(NAMESPACE_INTERFACE_EXPIRATION_MS); cond_t ref_count_is_nonzero; assignment_sentry_t<cond_t *> notify_if_ref_count_becomes_nonzero( &cache_entry->pulse_when_ref_count_becomes_nonzero, &ref_count_is_nonzero); wait_any_t waiter(&expiration_timer, &ref_count_is_nonzero); wait_interruptible(&waiter, keepalive.get_drain_signal()); if (!ref_count_is_nonzero.is_pulsed()) { guarantee_reviewed(cache_entry->ref_count == 0); /* We waited a whole `NAMESPACE_INTERFACE_EXPIRATION_MS` and nothing used us. So let's destroy ourselves. */ break; } } } catch (interrupted_exc_t) { /* We got here because we were interrupted in the startup process. That means the `namespace_repo_t` destructor was called, which means there mustn't exist any `access_t` objects. So ref_count must be 0. */ guarantee_reviewed(cache_entry->ref_count == 0); } ASSERT_NO_CORO_WAITING; cache->entries.erase(namespace_id); } #include "mock/dummy_protocol.hpp" #include "memcached/protocol.hpp" #include "rdb_protocol/protocol.hpp" template class namespace_repo_t<mock::dummy_protocol_t>; template class namespace_repo_t<memcached_protocol_t>; template class namespace_repo_t<rdb_protocol_t>; <|endoftext|>
<commit_before> #ifndef FIXED_FIXED_HPP_INCLUDED #define FIXED_FIXED_HPP_INCLUDED // Copyright Joel Riendeau 2008 // Jean-Philippe Gravel 2008 // Jean-Olivier Racine 2008 // // Distributed under the New BSD License. // (See accompanying file NewBSDLicense.txt or copy at // http://www.opensource.org/licenses/bsd-license.php) #include "integer_types.hpp" #include "boost\mpl\if.hpp" template <sint8_t Magnitude, uint8_t Fractional> class Q { public: Q() : m_Comp(0) {} Q(const Q& val) : m_Comp(val.m_Comp) {} template <typename T> Q(T val) : m_Magn(static_cast<InternalType>(val)), m_Frac(0) {} Q(float val) { m_Comp = static_cast<InternalType>(val * (1 << Fractional)); } Q(double val) { m_Comp = static_cast<InternalType>(val * (1 << Fractional)); } template <typename T> inline operator T() const { return static_cast<T>(m_Magn); } inline operator float() const { if (0 == m_Comp) return 0.0f; float result = static_cast<float>(m_Comp); ((FloatFormat*)&result)->exponent -= Fractional; return result; } inline bool operator==(const Q& val) const {return m_Comp == val.m_Comp;} inline bool operator!=(const Q& val) const {return m_Comp != val.m_Comp;} inline bool operator< (const Q& val) const {return m_Comp < val.m_Comp;} inline bool operator<=(const Q& val) const {return m_Comp <= val.m_Comp;} inline bool operator> (const Q& val) const {return m_Comp > val.m_Comp;} inline bool operator>=(const Q& val) const {return m_Comp >= val.m_Comp;} inline Q operator+ (const Q& val) const {Q res; res.m_Comp = m_Comp + val.m_Comp; return res;} inline Q operator+=(const Q& val) {m_Comp += val.m_Comp; return *this;} inline Q operator- (const Q& val) const {Q res; res.m_Comp = m_Comp - val.m_Comp; return res;} inline Q operator-=(const Q& val) {m_Comp -= val.m_Comp; return *this;} inline Q operator* (const Q& val) const { Q res; res.m_Comp = (static_cast<MultiplyType>(m_Comp) * static_cast<MultiplyType>(val.m_Comp)) >> Fractional; return res; } inline Q operator*=(const Q& val) { m_Comp = (static_cast<MultiplyType>(m_Comp) * static_cast<MultiplyType>(val.m_Comp)) >> Fractional; return *this; } inline Q operator/(const Q& val) const { Q res; if (val.m_Comp == 0) res.m_Comp = ~val.m_Comp; res.m_Comp = ((static_cast<MultiplyType>(m_Comp) << Fractional) / val.m_Comp) >> Fractional; return res; } inline Q operator/=(const Q& val) { if (val.m_Comp == 0) m_Comp = ~val.m_Comp; else m_Comp = ((static_cast<MultiplyType>(m_Comp) << Fractional) / val.m_Comp) >> Fractional; return *this; } // A template to select the smallest integer type for a given amount of bits template <uint8_t Bits, bool Signed> struct FixedInteger { typedef typename boost::mpl::if_c<(Bits <= 8 && Signed), sint8_t , typename boost::mpl::if_c<(Bits <= 8 && !Signed), uint8_t , typename boost::mpl::if_c<(Bits <= 16 && Signed), sint16_t , typename boost::mpl::if_c<(Bits <= 16 && !Signed), uint16_t , typename boost::mpl::if_c<(Bits <= 32 && Signed), sint32_t , typename boost::mpl::if_c<(Bits <= 32 && !Signed), uint32_t , typename boost::mpl::if_c<(Bits <= 64 && Signed), sint64_t , typename boost::mpl::if_c<(Bits <= 64 && !Signed), uint64_t , void>::type >::type >::type >::type >::type >::type >::type >::type type; }; enum { NBits = (Magnitude < 0 ? -Magnitude : Magnitude) + Fractional, NBits_Magn = (Magnitude < 0 ? -Magnitude : Magnitude), NBits_Frac = Fractional }; typedef typename FixedInteger<NBits, (Magnitude < 0)>::type InternalType; typedef typename FixedInteger<NBits*2, (Magnitude < 0)>::type MultiplyType; typedef typename FixedInteger<(NBits > sizeof(float) ? NBits : sizeof(float)), false>::type FloatCastType; inline InternalType Frac() {return m_Frac;} union { struct { InternalType m_Frac : NBits_Frac; InternalType m_Magn : NBits_Magn; }; InternalType m_Comp; }; private: typedef union FloatFormat { struct { uint32_t mantissa : 23; uint32_t exponent : 8; uint32_t sign : 1; }; uint32_t full; } FloatFormat; }; template <sint8_t Magnitude, uint8_t Fractional> inline Q<Magnitude, Fractional> sqrt(const Q<Magnitude, Fractional>& val) { //if (Magnitude < 0) // return MAX_VAL Q<Magnitude, Fractional>::MultiplyType temp = val.m_Comp << Fractional; Q<Magnitude, Fractional>::InternalType root = 0, test; for (Sint8 i = Q<Magnitude, Fractional>::NBits - 1; i >= 0; i--) { test = root + (1 << i); if (temp >= test << i) { temp -= test << i; root |= 2 << i; } } return root >> 1; } template <sint8_t Magnitude, uint8_t Fractional> inline Q<Magnitude, Fractional> floor(const Q<Magnitude, Fractional>& val) { Q<Magnitude, Fractional> ret = val; ret.m_Frac = 0; return ret; } template <sint8_t Magnitude, uint8_t Fractional> inline Q<Magnitude, Fractional> ceil(const Q<Magnitude, Fractional>& val) { Q<Magnitude, Fractional> ret = val; if (0 != ret.m_Frac) ++ret.m_Magn; ret.m_Frac = 0; return ret; } /* fixed pow(fixed fixedPower); fixed log10(void); fixed log(void); fixed exp(void); fixed cos(void); fixed sin(void); fixed tan(void);*/ #endif<commit_msg>-Removed inlines -Set arithmetic operator arguments to receive const references -Added a templated constructor for other Q types -Started working on comparison operators -Forced m_Frac to an unsigned type, and renamed the types used for m_Magn and m_Frac<commit_after> #ifndef FIXED_FIXED_HPP_INCLUDED #define FIXED_FIXED_HPP_INCLUDED // Copyright Joel Riendeau 2008 // Jean-Philippe Gravel 2008 // Jean-Olivier Racine 2008 // // Distributed under the New BSD License. // (See accompanying file NewBSDLicense.txt or copy at // http://www.opensource.org/licenses/bsd-license.php) #include "integer_types.hpp" #include "boost\mpl\if.hpp" template <sint8_t Magnitude, uint8_t Fractional> class Q { public: Q() : m_Comp(0) {} template <sint8_t M, uint8_t F> explicit Q(const Q<M,F>& val) { m_Comp = (Fractional > F) ? static_cast<MagnType>(val.m_Comp << (Fractional - F)) : static_cast<MagnType>(val.m_Comp >> (F - Fractional)) ; } template <typename T> Q(T val) : m_Magn(static_cast<MagnType>(val)), m_Frac(0) {} Q(float val) { m_Comp = static_cast<MagnType>(val * (1 << Fractional)); } Q(double val) { m_Comp = static_cast<MagnType>(val * (1 << Fractional)); } template <typename T> operator T() const { return static_cast<T>(m_Magn); } operator float() const { float result = static_cast<float>(m_Comp); ((FloatFormat*)&result)->exponent -= Fractional; return (0 == m_Comp) ? 0.0f : result; } template <sint8_t M, uint8_t F> bool operator==(const Q<M,F>& val) const { return (m_Magn == val.m_Magn) && (m_Frac == val.m_Frac); } bool operator!=(const Q& val) const {return m_Comp != val.m_Comp;} bool operator< (const Q& val) const {return m_Comp < val.m_Comp;} bool operator<=(const Q& val) const {return m_Comp <= val.m_Comp;} bool operator> (const Q& val) const {return m_Comp > val.m_Comp;} bool operator>=(const Q& val) const {return m_Comp >= val.m_Comp;} Q operator+ (const Q& val) const {Q res; res.m_Comp = m_Comp + val.m_Comp; return res;} Q operator+=(const Q& val) {m_Comp += val.m_Comp; return *this;} Q operator- (const Q& val) const {Q res; res.m_Comp = m_Comp - val.m_Comp; return res;} Q operator-=(const Q& val) {m_Comp -= val.m_Comp; return *this;} Q operator* (const Q& val) const { Q res; res.m_Comp = (static_cast<MultiplyType>(m_Comp) * static_cast<MultiplyType>(val.m_Comp)) >> Fractional; return res; } Q operator*=(const Q& val) { m_Comp = (static_cast<MultiplyType>(m_Comp) * static_cast<MultiplyType>(val.m_Comp)) >> Fractional; return *this; } Q operator/(const Q& val) const { Q res; if (val.m_Comp == 0) res.m_Comp = ~val.m_Comp; res.m_Comp = ((static_cast<MultiplyType>(m_Comp) << Fractional) / val.m_Comp) >> Fractional; return res; } Q operator/=(const Q& val) { if (val.m_Comp == 0) m_Comp = ~val.m_Comp; else m_Comp = ((static_cast<MultiplyType>(m_Comp) << Fractional) / val.m_Comp) >> Fractional; return *this; } // A template to select the smallest integer type for a given amount of bits template <uint8_t Bits, bool Signed> struct FixedInteger { typedef typename boost::mpl::if_c<(Bits <= 8 && Signed), sint8_t , typename boost::mpl::if_c<(Bits <= 8 && !Signed), uint8_t , typename boost::mpl::if_c<(Bits <= 16 && Signed), sint16_t , typename boost::mpl::if_c<(Bits <= 16 && !Signed), uint16_t , typename boost::mpl::if_c<(Bits <= 32 && Signed), sint32_t , typename boost::mpl::if_c<(Bits <= 32 && !Signed), uint32_t , typename boost::mpl::if_c<(Bits <= 64 && Signed), sint64_t , typename boost::mpl::if_c<(Bits <= 64 && !Signed), uint64_t , void>::type >::type >::type >::type >::type >::type >::type >::type type; }; enum { NBits = (Magnitude < 0 ? -Magnitude : Magnitude) + Fractional, NBits_Magn = (Magnitude < 0 ? -Magnitude : Magnitude), NBits_Frac = Fractional }; typedef typename FixedInteger<NBits, (Magnitude < 0)>::type MagnType; typedef typename FixedInteger<NBits, false>::type FracType; typedef typename FixedInteger<NBits*2, (Magnitude < 0)>::type MultiplyType; typedef typename FixedInteger<(NBits > sizeof(float) ? NBits : sizeof(float)), false>::type FloatCastType; FracType Frac() {return m_Frac;} union { struct { FracType m_Frac : NBits_Frac; MagnType m_Magn : NBits_Magn; }; MagnType m_Comp; }; private: typedef union FloatFormat { struct { uint32_t mantissa : 23; uint32_t exponent : 8; uint32_t sign : 1; }; uint32_t full; } FloatFormat; }; template <sint8_t Magnitude, uint8_t Fractional> Q<Magnitude, Fractional> sqrt(const Q<Magnitude, Fractional>& val) { //if (Magnitude < 0) // return MAX_VAL Q<Magnitude, Fractional>::MultiplyType temp = val.m_Comp << Fractional; Q<Magnitude, Fractional>::InternalType root = 0, test; for (Sint8 i = Q<Magnitude, Fractional>::NBits - 1; i >= 0; i--) { test = root + (1 << i); if (temp >= test << i) { temp -= test << i; root |= 2 << i; } } return root >> 1; } template <sint8_t Magnitude, uint8_t Fractional> Q<Magnitude, Fractional> floor(const Q<Magnitude, Fractional>& val) { Q<Magnitude, Fractional> ret = val; ret.m_Frac = 0; return ret; } template <sint8_t Magnitude, uint8_t Fractional> Q<Magnitude, Fractional> ceil(const Q<Magnitude, Fractional>& val) { Q<Magnitude, Fractional> ret = val; if (0 != ret.m_Frac) ++ret.m_Magn; ret.m_Frac = 0; return ret; } /* fixed pow(fixed fixedPower); fixed log10(void); fixed log(void); fixed exp(void); fixed cos(void); fixed sin(void); fixed tan(void);*/ #endif<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: flbytes.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2006-06-19 21:19:58 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _FLBYTES_HXX #include <flbytes.hxx> #endif #ifndef _SVSTDARR_ULONGS_DECL #define _SVSTDARR_ULONGS #include <svstdarr.hxx> #undef _SVSTDARR_ULONGS #endif namespace unnamed_svtools_flbytes {} using namespace unnamed_svtools_flbytes; // unnamed namespaces don't work well yet //============================================================================ namespace unnamed_svtools_flbytes { inline ULONG MyMin( long a, long b ) { return Max( long( Min( a , b ) ), 0L ); } } //============================================================================ // // SvFillLockBytes // //============================================================================ TYPEINIT1(SvFillLockBytes, SvLockBytes); //============================================================================ SvFillLockBytes::SvFillLockBytes( SvLockBytes* pLockBytes ) : xLockBytes( pLockBytes ), nFilledSize( 0 ), bTerminated( FALSE ) { } //============================================================================ ErrCode SvFillLockBytes::ReadAt( ULONG nPos, void* pBuffer, ULONG nCount, ULONG *pRead ) const { if( bTerminated ) return xLockBytes->ReadAt( nPos, pBuffer, nCount, pRead ); else { ULONG nWanted = nPos + nCount; if( IsSynchronMode() ) { while( nWanted > nFilledSize && !bTerminated ) Application::Yield(); return xLockBytes->ReadAt( nPos, pBuffer, nCount, pRead ); } else { ULONG nRead = MyMin( nCount, long( nFilledSize ) - nPos ); ULONG nErr = xLockBytes->ReadAt( nPos, pBuffer, nRead, pRead ); return ( !nCount || nRead == nCount || nErr ) ? nErr : ERRCODE_IO_PENDING; } } } //============================================================================ ErrCode SvFillLockBytes::WriteAt( ULONG nPos, const void* pBuffer, ULONG nCount, ULONG *pWritten ) { if( bTerminated ) return xLockBytes->WriteAt( nPos, pBuffer, nCount, pWritten ); else { ULONG nWanted = nPos + nCount; if( IsSynchronMode() ) { while( nWanted > nFilledSize && !bTerminated ) Application::Yield(); return xLockBytes->WriteAt( nPos, pBuffer, nCount, pWritten ); } else { ULONG nRead = MyMin( nCount, long( nFilledSize ) - nPos ); ULONG nErr = xLockBytes->WriteAt( nPos, pBuffer, nRead, pWritten ); return ( !nCount || nRead == nCount || nErr ) ? nErr : ERRCODE_IO_PENDING; } } } //============================================================================ ErrCode SvFillLockBytes::Flush() const { return xLockBytes->Flush( ); } //============================================================================ ErrCode SvFillLockBytes::SetSize( ULONG nSize ) { return xLockBytes->SetSize( nSize ); } //============================================================================ ErrCode SvFillLockBytes::LockRegion( ULONG nPos, ULONG nCount, LockType eType) { return xLockBytes->LockRegion( nPos, nCount, eType ); } //============================================================================ ErrCode SvFillLockBytes::UnlockRegion( ULONG nPos, ULONG nCount, LockType eType) { return xLockBytes->UnlockRegion( nPos, nCount, eType ); } //============================================================================ ErrCode SvFillLockBytes::Stat( SvLockBytesStat* pStat, SvLockBytesStatFlag eFlag) const { return xLockBytes->Stat( pStat, eFlag ); } //============================================================================ ErrCode SvFillLockBytes::FillAppend( const void* pBuffer, ULONG nCount, ULONG *pWritten ) { ErrCode nRet = xLockBytes->WriteAt( nFilledSize, pBuffer, nCount, pWritten ); nFilledSize += *pWritten; return nRet; } //============================================================================ void SvFillLockBytes::Terminate() { bTerminated = TRUE; } //============================================================================ SV_DECL_IMPL_REF_LIST( SvLockBytes, SvLockBytes* ) //============================================================================ // // SvSyncLockBytes // //============================================================================ TYPEINIT1(SvSyncLockBytes, SvOpenLockBytes); //============================================================================ // virtual ErrCode SvSyncLockBytes::ReadAt(ULONG nPos, void * pBuffer, ULONG nCount, ULONG * pRead) const { for (ULONG nReadTotal = 0;;) { ULONG nReadCount = 0; ErrCode nError = m_xAsyncLockBytes->ReadAt(nPos, pBuffer, nCount, &nReadCount); nReadTotal += nReadCount; if (nError != ERRCODE_IO_PENDING || !IsSynchronMode()) { if (pRead) *pRead = nReadTotal; return nError; } nPos += nReadCount; pBuffer = static_cast< sal_Char * >(pBuffer) + nReadCount; nCount -= nReadCount; Application::Yield(); } } //============================================================================ // virtual ErrCode SvSyncLockBytes::WriteAt(ULONG nPos, const void * pBuffer, ULONG nCount, ULONG * pWritten) { for (ULONG nWrittenTotal = 0;;) { ULONG nWrittenCount = 0; ErrCode nError = m_xAsyncLockBytes->WriteAt(nPos, pBuffer, nCount, &nWrittenCount); nWrittenTotal += nWrittenCount; if (nError != ERRCODE_IO_PENDING || !IsSynchronMode()) { if (pWritten) *pWritten = nWrittenTotal; return nError; } nPos += nWrittenCount; pBuffer = static_cast< sal_Char const * >(pBuffer) + nWrittenCount; nCount -= nWrittenCount; Application::Yield(); } } //============================================================================ // // SvCompositeLockBytes // //============================================================================ struct SvCompositeLockBytes_Impl { SvLockBytesMemberList aLockBytes; SvULongs aPositions; SvULongs aOffsets; BOOL bPending; ULONG RelativeOffset( ULONG nPos ) const; ErrCode ReadWrite_Impl( ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pProcessed, BOOL bRead ); SvCompositeLockBytes_Impl() : bPending( FALSE ){} }; //============================================================================ ULONG SvCompositeLockBytes_Impl::RelativeOffset( ULONG nPos ) const { const SvULongs& rPositions = aPositions; const SvULongs& rOffsets = aOffsets; USHORT nMinPos = 0; USHORT nListCount = rPositions.Count(); // Erster Lockbytes, der bearbeitet werden muss while( nMinPos + 1 < nListCount && rPositions[ nMinPos + 1 ] <= nPos ) nMinPos ++; ULONG nSectionStart = rPositions[ nMinPos ]; if( nSectionStart > nPos ) return ULONG_MAX; return rOffsets[ nMinPos ] + nPos - nSectionStart; } //============================================================================ ErrCode SvCompositeLockBytes_Impl::ReadWrite_Impl( ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pProcessed, BOOL bRead ) { ErrCode nErr = ERRCODE_NONE; SvULongs& rPositions = aPositions; SvULongs& rOffsets = aOffsets; SvLockBytesMemberList& rLockBytes = aLockBytes; ULONG nBytes = nCount; USHORT nListCount = rPositions.Count(); USHORT nMinPos = 0; // Erster Lockbytes, der bearbeitet werden muss while( nMinPos + 1 < nListCount && rPositions[ nMinPos + 1 ] <= nPos ) nMinPos ++; ULONG nSectionStart = rPositions[ nMinPos ]; if( nSectionStart > nPos ) { // Es wird aus fuehrendem Leerbereich gearbeitet *pProcessed = 0; return ERRCODE_IO_CANTREAD; } ULONG nDone; while( nMinPos < nListCount ) { ULONG nToProcess; ULONG nSectionStop; if( nMinPos + 1 < nListCount ) { nSectionStop = rPositions[ nMinPos + 1 ]; nToProcess = MyMin( long( nSectionStop ) - nPos, nBytes ); } else { nToProcess = nBytes; nSectionStop = 0; } ULONG nAbsPos = nPos - nSectionStart + rOffsets[ nMinPos ]; SvLockBytes* pLB = rLockBytes.GetObject( nMinPos ); if( bRead ) nErr = pLB->ReadAt( nAbsPos, pBuffer, nToProcess, &nDone ); else nErr = pLB->WriteAt( nAbsPos, pBuffer, nToProcess, &nDone ); nBytes -= nDone; if( nErr || nDone < nToProcess || !nBytes ) { *pProcessed = nCount - nBytes; // Wenn aus dem letzten LockBytes nichts mehr gelesen wurde und // bPending gesetzt ist, Pending zurueck if( !nDone && nMinPos == nListCount - 1 ) return bPending ? ERRCODE_IO_PENDING : nErr; else return nErr; } pBuffer = static_cast< sal_Char * >(pBuffer) + nDone; nPos += nDone; nSectionStart = nSectionStop; nMinPos++; } return nErr; } //============================================================================ TYPEINIT1(SvCompositeLockBytes, SvLockBytes); //============================================================================ SvCompositeLockBytes::SvCompositeLockBytes() : pImpl( new SvCompositeLockBytes_Impl ) { } //============================================================================ SvCompositeLockBytes::~SvCompositeLockBytes() { delete pImpl; } //============================================================================ void SvCompositeLockBytes::SetIsPending( BOOL bSet ) { pImpl->bPending = bSet; } //============================================================================ ULONG SvCompositeLockBytes::RelativeOffset( ULONG nPos ) const { return pImpl->RelativeOffset( nPos ); } //============================================================================ ErrCode SvCompositeLockBytes::ReadAt( ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pRead ) const { return pImpl->ReadWrite_Impl( nPos, pBuffer, nCount, pRead, TRUE ); } //============================================================================ ErrCode SvCompositeLockBytes::WriteAt( ULONG nPos, const void* pBuffer, ULONG nCount, ULONG* pWritten ) { return pImpl->ReadWrite_Impl( nPos, const_cast< void * >(pBuffer), nCount, pWritten, FALSE ); } //============================================================================ ErrCode SvCompositeLockBytes::Flush() const { SvLockBytesMemberList& rLockBytes = pImpl->aLockBytes; ErrCode nErr = ERRCODE_NONE; for( USHORT nCount = (USHORT)rLockBytes.Count(); !nErr && nCount--; ) nErr = rLockBytes.GetObject( nCount )->Flush(); return nErr; } //============================================================================ ErrCode SvCompositeLockBytes::SetSize( ULONG ) { DBG_ERROR( "not implemented" ); return ERRCODE_IO_NOTSUPPORTED; } //============================================================================ ErrCode SvCompositeLockBytes::LockRegion( ULONG, ULONG, LockType ) { DBG_ERROR( "not implemented" ); return ERRCODE_IO_NOTSUPPORTED; } //============================================================================ ErrCode SvCompositeLockBytes::UnlockRegion( ULONG, ULONG, LockType ) { DBG_ERROR( "not implemented" ); return ERRCODE_IO_NOTSUPPORTED; } //============================================================================ ErrCode SvCompositeLockBytes::Stat( SvLockBytesStat* pStat, SvLockBytesStatFlag eFlag) const { USHORT nMax = pImpl->aPositions.Count() - 1; SvLockBytesStat aStat; ErrCode nErr = pImpl->aLockBytes.GetObject( nMax )->Stat( &aStat, eFlag ); pStat->nSize = pImpl->aPositions[ nMax ] + aStat.nSize; return nErr; } //============================================================================ void SvCompositeLockBytes::Append( SvLockBytes* pLockBytes, ULONG nPos, ULONG nOffset ) { USHORT nCount = pImpl->aOffsets.Count(); pImpl->aLockBytes.Insert( pLockBytes, nCount ); pImpl->aPositions.Insert( nPos, nCount ); pImpl->aOffsets.Insert( nOffset, nCount ); } //============================================================================ SvLockBytes* SvCompositeLockBytes::GetLastLockBytes() const { return pImpl->aLockBytes.Count() ? pImpl->aLockBytes.GetObject( pImpl->aLockBytes.Count() - 1 ) : 0; } <commit_msg>INTEGRATION: CWS pchfix02 (1.3.92); FILE MERGED 2006/09/01 17:43:19 kaib 1.3.92.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: flbytes.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-17 15:10:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _FLBYTES_HXX #include <flbytes.hxx> #endif #ifndef _SVSTDARR_ULONGS_DECL #define _SVSTDARR_ULONGS #include <svstdarr.hxx> #undef _SVSTDARR_ULONGS #endif namespace unnamed_svtools_flbytes {} using namespace unnamed_svtools_flbytes; // unnamed namespaces don't work well yet //============================================================================ namespace unnamed_svtools_flbytes { inline ULONG MyMin( long a, long b ) { return Max( long( Min( a , b ) ), 0L ); } } //============================================================================ // // SvFillLockBytes // //============================================================================ TYPEINIT1(SvFillLockBytes, SvLockBytes); //============================================================================ SvFillLockBytes::SvFillLockBytes( SvLockBytes* pLockBytes ) : xLockBytes( pLockBytes ), nFilledSize( 0 ), bTerminated( FALSE ) { } //============================================================================ ErrCode SvFillLockBytes::ReadAt( ULONG nPos, void* pBuffer, ULONG nCount, ULONG *pRead ) const { if( bTerminated ) return xLockBytes->ReadAt( nPos, pBuffer, nCount, pRead ); else { ULONG nWanted = nPos + nCount; if( IsSynchronMode() ) { while( nWanted > nFilledSize && !bTerminated ) Application::Yield(); return xLockBytes->ReadAt( nPos, pBuffer, nCount, pRead ); } else { ULONG nRead = MyMin( nCount, long( nFilledSize ) - nPos ); ULONG nErr = xLockBytes->ReadAt( nPos, pBuffer, nRead, pRead ); return ( !nCount || nRead == nCount || nErr ) ? nErr : ERRCODE_IO_PENDING; } } } //============================================================================ ErrCode SvFillLockBytes::WriteAt( ULONG nPos, const void* pBuffer, ULONG nCount, ULONG *pWritten ) { if( bTerminated ) return xLockBytes->WriteAt( nPos, pBuffer, nCount, pWritten ); else { ULONG nWanted = nPos + nCount; if( IsSynchronMode() ) { while( nWanted > nFilledSize && !bTerminated ) Application::Yield(); return xLockBytes->WriteAt( nPos, pBuffer, nCount, pWritten ); } else { ULONG nRead = MyMin( nCount, long( nFilledSize ) - nPos ); ULONG nErr = xLockBytes->WriteAt( nPos, pBuffer, nRead, pWritten ); return ( !nCount || nRead == nCount || nErr ) ? nErr : ERRCODE_IO_PENDING; } } } //============================================================================ ErrCode SvFillLockBytes::Flush() const { return xLockBytes->Flush( ); } //============================================================================ ErrCode SvFillLockBytes::SetSize( ULONG nSize ) { return xLockBytes->SetSize( nSize ); } //============================================================================ ErrCode SvFillLockBytes::LockRegion( ULONG nPos, ULONG nCount, LockType eType) { return xLockBytes->LockRegion( nPos, nCount, eType ); } //============================================================================ ErrCode SvFillLockBytes::UnlockRegion( ULONG nPos, ULONG nCount, LockType eType) { return xLockBytes->UnlockRegion( nPos, nCount, eType ); } //============================================================================ ErrCode SvFillLockBytes::Stat( SvLockBytesStat* pStat, SvLockBytesStatFlag eFlag) const { return xLockBytes->Stat( pStat, eFlag ); } //============================================================================ ErrCode SvFillLockBytes::FillAppend( const void* pBuffer, ULONG nCount, ULONG *pWritten ) { ErrCode nRet = xLockBytes->WriteAt( nFilledSize, pBuffer, nCount, pWritten ); nFilledSize += *pWritten; return nRet; } //============================================================================ void SvFillLockBytes::Terminate() { bTerminated = TRUE; } //============================================================================ SV_DECL_IMPL_REF_LIST( SvLockBytes, SvLockBytes* ) //============================================================================ // // SvSyncLockBytes // //============================================================================ TYPEINIT1(SvSyncLockBytes, SvOpenLockBytes); //============================================================================ // virtual ErrCode SvSyncLockBytes::ReadAt(ULONG nPos, void * pBuffer, ULONG nCount, ULONG * pRead) const { for (ULONG nReadTotal = 0;;) { ULONG nReadCount = 0; ErrCode nError = m_xAsyncLockBytes->ReadAt(nPos, pBuffer, nCount, &nReadCount); nReadTotal += nReadCount; if (nError != ERRCODE_IO_PENDING || !IsSynchronMode()) { if (pRead) *pRead = nReadTotal; return nError; } nPos += nReadCount; pBuffer = static_cast< sal_Char * >(pBuffer) + nReadCount; nCount -= nReadCount; Application::Yield(); } } //============================================================================ // virtual ErrCode SvSyncLockBytes::WriteAt(ULONG nPos, const void * pBuffer, ULONG nCount, ULONG * pWritten) { for (ULONG nWrittenTotal = 0;;) { ULONG nWrittenCount = 0; ErrCode nError = m_xAsyncLockBytes->WriteAt(nPos, pBuffer, nCount, &nWrittenCount); nWrittenTotal += nWrittenCount; if (nError != ERRCODE_IO_PENDING || !IsSynchronMode()) { if (pWritten) *pWritten = nWrittenTotal; return nError; } nPos += nWrittenCount; pBuffer = static_cast< sal_Char const * >(pBuffer) + nWrittenCount; nCount -= nWrittenCount; Application::Yield(); } } //============================================================================ // // SvCompositeLockBytes // //============================================================================ struct SvCompositeLockBytes_Impl { SvLockBytesMemberList aLockBytes; SvULongs aPositions; SvULongs aOffsets; BOOL bPending; ULONG RelativeOffset( ULONG nPos ) const; ErrCode ReadWrite_Impl( ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pProcessed, BOOL bRead ); SvCompositeLockBytes_Impl() : bPending( FALSE ){} }; //============================================================================ ULONG SvCompositeLockBytes_Impl::RelativeOffset( ULONG nPos ) const { const SvULongs& rPositions = aPositions; const SvULongs& rOffsets = aOffsets; USHORT nMinPos = 0; USHORT nListCount = rPositions.Count(); // Erster Lockbytes, der bearbeitet werden muss while( nMinPos + 1 < nListCount && rPositions[ nMinPos + 1 ] <= nPos ) nMinPos ++; ULONG nSectionStart = rPositions[ nMinPos ]; if( nSectionStart > nPos ) return ULONG_MAX; return rOffsets[ nMinPos ] + nPos - nSectionStart; } //============================================================================ ErrCode SvCompositeLockBytes_Impl::ReadWrite_Impl( ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pProcessed, BOOL bRead ) { ErrCode nErr = ERRCODE_NONE; SvULongs& rPositions = aPositions; SvULongs& rOffsets = aOffsets; SvLockBytesMemberList& rLockBytes = aLockBytes; ULONG nBytes = nCount; USHORT nListCount = rPositions.Count(); USHORT nMinPos = 0; // Erster Lockbytes, der bearbeitet werden muss while( nMinPos + 1 < nListCount && rPositions[ nMinPos + 1 ] <= nPos ) nMinPos ++; ULONG nSectionStart = rPositions[ nMinPos ]; if( nSectionStart > nPos ) { // Es wird aus fuehrendem Leerbereich gearbeitet *pProcessed = 0; return ERRCODE_IO_CANTREAD; } ULONG nDone; while( nMinPos < nListCount ) { ULONG nToProcess; ULONG nSectionStop; if( nMinPos + 1 < nListCount ) { nSectionStop = rPositions[ nMinPos + 1 ]; nToProcess = MyMin( long( nSectionStop ) - nPos, nBytes ); } else { nToProcess = nBytes; nSectionStop = 0; } ULONG nAbsPos = nPos - nSectionStart + rOffsets[ nMinPos ]; SvLockBytes* pLB = rLockBytes.GetObject( nMinPos ); if( bRead ) nErr = pLB->ReadAt( nAbsPos, pBuffer, nToProcess, &nDone ); else nErr = pLB->WriteAt( nAbsPos, pBuffer, nToProcess, &nDone ); nBytes -= nDone; if( nErr || nDone < nToProcess || !nBytes ) { *pProcessed = nCount - nBytes; // Wenn aus dem letzten LockBytes nichts mehr gelesen wurde und // bPending gesetzt ist, Pending zurueck if( !nDone && nMinPos == nListCount - 1 ) return bPending ? ERRCODE_IO_PENDING : nErr; else return nErr; } pBuffer = static_cast< sal_Char * >(pBuffer) + nDone; nPos += nDone; nSectionStart = nSectionStop; nMinPos++; } return nErr; } //============================================================================ TYPEINIT1(SvCompositeLockBytes, SvLockBytes); //============================================================================ SvCompositeLockBytes::SvCompositeLockBytes() : pImpl( new SvCompositeLockBytes_Impl ) { } //============================================================================ SvCompositeLockBytes::~SvCompositeLockBytes() { delete pImpl; } //============================================================================ void SvCompositeLockBytes::SetIsPending( BOOL bSet ) { pImpl->bPending = bSet; } //============================================================================ ULONG SvCompositeLockBytes::RelativeOffset( ULONG nPos ) const { return pImpl->RelativeOffset( nPos ); } //============================================================================ ErrCode SvCompositeLockBytes::ReadAt( ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pRead ) const { return pImpl->ReadWrite_Impl( nPos, pBuffer, nCount, pRead, TRUE ); } //============================================================================ ErrCode SvCompositeLockBytes::WriteAt( ULONG nPos, const void* pBuffer, ULONG nCount, ULONG* pWritten ) { return pImpl->ReadWrite_Impl( nPos, const_cast< void * >(pBuffer), nCount, pWritten, FALSE ); } //============================================================================ ErrCode SvCompositeLockBytes::Flush() const { SvLockBytesMemberList& rLockBytes = pImpl->aLockBytes; ErrCode nErr = ERRCODE_NONE; for( USHORT nCount = (USHORT)rLockBytes.Count(); !nErr && nCount--; ) nErr = rLockBytes.GetObject( nCount )->Flush(); return nErr; } //============================================================================ ErrCode SvCompositeLockBytes::SetSize( ULONG ) { DBG_ERROR( "not implemented" ); return ERRCODE_IO_NOTSUPPORTED; } //============================================================================ ErrCode SvCompositeLockBytes::LockRegion( ULONG, ULONG, LockType ) { DBG_ERROR( "not implemented" ); return ERRCODE_IO_NOTSUPPORTED; } //============================================================================ ErrCode SvCompositeLockBytes::UnlockRegion( ULONG, ULONG, LockType ) { DBG_ERROR( "not implemented" ); return ERRCODE_IO_NOTSUPPORTED; } //============================================================================ ErrCode SvCompositeLockBytes::Stat( SvLockBytesStat* pStat, SvLockBytesStatFlag eFlag) const { USHORT nMax = pImpl->aPositions.Count() - 1; SvLockBytesStat aStat; ErrCode nErr = pImpl->aLockBytes.GetObject( nMax )->Stat( &aStat, eFlag ); pStat->nSize = pImpl->aPositions[ nMax ] + aStat.nSize; return nErr; } //============================================================================ void SvCompositeLockBytes::Append( SvLockBytes* pLockBytes, ULONG nPos, ULONG nOffset ) { USHORT nCount = pImpl->aOffsets.Count(); pImpl->aLockBytes.Insert( pLockBytes, nCount ); pImpl->aPositions.Insert( nPos, nCount ); pImpl->aOffsets.Insert( nOffset, nCount ); } //============================================================================ SvLockBytes* SvCompositeLockBytes::GetLastLockBytes() const { return pImpl->aLockBytes.Count() ? pImpl->aLockBytes.GetObject( pImpl->aLockBytes.Count() - 1 ) : 0; } <|endoftext|>
<commit_before>// // ex7_13.cpp // Exercise 7.13 // // Created by pezy on 11/9/14. // #include "ex7_12.h" int main() { Sales_data total(std::cin); if (!total.isbn().empty()) { std::istream &is = std::cin; while (is) { Sales_data trans(is); if (total.isbn() == trans.isbn()) total.combine(trans); else { print(std::cout, total) << std::endl; total = trans; } } print(std::cout, total) << std::endl; } else { std::cerr << "No data?!" << std::endl; return -1; } return 0; } <commit_msg>Fixed #658<commit_after>// // ex7_13.cpp // Exercise 7.13 // // Created by pezy on 11/9/14. // #include "ex7_12.h" int main() { Sales_data total(std::cin); if (!total.isbn().empty()) { std::istream &is = std::cin; while (is) { Sales_data trans(is); if (!is) break; if (total.isbn() == trans.isbn()) total.combine(trans); else { print(std::cout, total) << std::endl; total = trans; } } print(std::cout, total) << std::endl; } else { std::cerr << "No data?!" << std::endl; return -1; } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: editobj2.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-08 22:28:19 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _EDITOBJ2_HXX #define _EDITOBJ2_HXX #include <editobj.hxx> #include <editdoc.hxx> #include <vcl/fontcvt.hxx> class SfxStyleSheetPool; class XEditAttribute { friend class ContentInfo; // fuer DTOR friend class BinTextObject; // fuer DTOR private: const SfxPoolItem* pItem; USHORT nStart; USHORT nEnd; XEditAttribute(); XEditAttribute( const XEditAttribute& rCopyFrom ); ~XEditAttribute(); public: XEditAttribute( const SfxPoolItem& rAttr ); XEditAttribute( const SfxPoolItem& rAttr, USHORT nStart, USHORT nEnd ); const SfxPoolItem* GetItem() const { return pItem; } USHORT& GetStart() { return nStart; } USHORT& GetEnd() { return nEnd; } USHORT GetStart() const { return nStart; } USHORT GetEnd() const { return nEnd; } USHORT GetLen() const { return nEnd-nStart; } inline BOOL IsFeature(); }; inline BOOL XEditAttribute::IsFeature() { USHORT nWhich = pItem->Which(); return ( ( nWhich >= EE_FEATURE_START ) && ( nWhich <= EE_FEATURE_END ) ); } typedef XEditAttribute* XEditAttributePtr; SV_DECL_PTRARR( XEditAttributeListImpl, XEditAttributePtr, 0, 4 ); class XEditAttributeList : public XEditAttributeListImpl { public: XEditAttribute* FindAttrib( USHORT nWhich, USHORT nChar ) const; }; struct XParaPortion { long nHeight; USHORT nFirstLineOffset; EditLineList aLines; TextPortionList aTextPortions; }; typedef XParaPortion* XParaPortionPtr; SV_DECL_PTRARR( XBaseParaPortionList, XParaPortionPtr, 0, 4 ); class XParaPortionList : public XBaseParaPortionList { ULONG nRefDevPtr; OutDevType eRefDevType; MapMode aRefMapMode; ULONG nPaperWidth; public: XParaPortionList( OutputDevice* pRefDev, ULONG nPW ) : aRefMapMode( pRefDev->GetMapMode() ) { nRefDevPtr = (ULONG)pRefDev; nPaperWidth = nPW; eRefDevType = pRefDev->GetOutDevType(); } ULONG GetRefDevPtr() const { return nRefDevPtr; } ULONG GetPaperWidth() const { return nPaperWidth; } OutDevType GetRefDevType() const { return eRefDevType; } const MapMode& GetRefMapMode() const { return aRefMapMode; } }; struct LoadStoreTempInfos { ByteString aOrgString_Load; FontToSubsFontConverter hOldSymbolConv_Store; BOOL bSymbolParagraph_Store; LoadStoreTempInfos() { bSymbolParagraph_Store = FALSE; hOldSymbolConv_Store = NULL; } }; class ContentInfo { friend class BinTextObject; private: String aText; String aStyle; XEditAttributeList aAttribs; SfxStyleFamily eFamily; SfxItemSet aParaAttribs; WrongList* pWrongs; LoadStoreTempInfos* pTempLoadStoreInfos; ContentInfo( SfxItemPool& rPool ); ContentInfo( const ContentInfo& rCopyFrom, SfxItemPool& rPoolToUse ); public: ~ContentInfo(); const String& GetText() const { return aText; } const String& GetStyle() const { return aStyle; } const XEditAttributeList& GetAttribs() const { return aAttribs; } const SfxItemSet& GetParaAttribs() const { return aParaAttribs; } SfxStyleFamily GetFamily() const { return eFamily; } String& GetText() { return aText; } String& GetStyle() { return aStyle; } XEditAttributeList& GetAttribs() { return aAttribs; } SfxItemSet& GetParaAttribs() { return aParaAttribs; } SfxStyleFamily& GetFamily() { return eFamily; } WrongList* GetWrongList() const { return pWrongs; } void SetWrongList( WrongList* p ) { pWrongs = p; } LoadStoreTempInfos* GetLoadStoreTempInfos() const { return pTempLoadStoreInfos; } void CreateLoadStoreTempInfos(); void DestroyLoadStoreTempInfos(); }; typedef ContentInfo* ContentInfoPtr; SV_DECL_PTRARR( ContentInfoList, ContentInfoPtr, 1, 4 ); // MT 05/00: Sollte mal direkt EditTextObjekt werden => keine virtuellen Methoden mehr. class BinTextObject : public EditTextObject { private: ContentInfoList aContents; SfxItemPool* pPool; BOOL bOwnerOfPool; XParaPortionList* pPortionInfo; ULONG nObjSettings; USHORT nMetric; USHORT nVersion; USHORT nUserType; USHORT nScriptType; BOOL bVertical; BOOL bStoreUnicodeStrings; protected: void DeleteContents(); virtual void StoreData( SvStream& rOStream ) const; virtual void CreateData( SvStream& rIStream ); BOOL ImpChangeStyleSheets( const String& rOldName, SfxStyleFamily eOldFamily, const String& rNewName, SfxStyleFamily eNewFamily ); public: BinTextObject( SfxItemPool* pPool ); BinTextObject( const BinTextObject& ); virtual ~BinTextObject(); virtual EditTextObject* Clone() const; USHORT GetUserType() const; void SetUserType( USHORT n ); ULONG GetObjectSettings() const; void SetObjectSettings( ULONG n ); BOOL IsVertical() const; void SetVertical( BOOL b ); USHORT GetScriptType() const; void SetScriptType( USHORT nType ); USHORT GetVersion() const; // Solange der Outliner keine Recordlaenge speichert void SetLRSpaceItemFlags( BOOL bOutlineMode ); void AdjustImportedLRSpaceItems( BOOL bTurnOfBullets ); ContentInfo* CreateAndInsertContent(); XEditAttribute* CreateAttrib( const SfxPoolItem& rItem, USHORT nStart, USHORT nEnd ); void DestroyAttrib( XEditAttribute* pAttr ); ContentInfoList& GetContents() { return aContents; } const ContentInfoList& GetContents() const { return aContents; } SfxItemPool* GetPool() const { return pPool; } XParaPortionList* GetPortionInfo() const { return pPortionInfo; } void SetPortionInfo( XParaPortionList* pP ) { pPortionInfo = pP; } virtual USHORT GetParagraphCount() const; virtual String GetText( USHORT nParagraph ) const; virtual void Insert( const EditTextObject& rObj, USHORT nPara ); virtual EditTextObject* CreateTextObject( USHORT nPara, USHORT nParas = 1 ) const; virtual void RemoveParagraph( USHORT nPara ); virtual BOOL HasPortionInfo() const; virtual void ClearPortionInfo(); virtual BOOL HasOnlineSpellErrors() const; virtual BOOL HasCharAttribs( USHORT nWhich = 0 ) const; virtual void GetCharAttribs( USHORT nPara, EECharAttribArray& rLst ) const; virtual BOOL RemoveCharAttribs( USHORT nWhich = 0 ); virtual BOOL RemoveParaAttribs( USHORT nWhich = 0 ); virtual void MergeParaAttribs( const SfxItemSet& rAttribs, USHORT nStart, USHORT nEnd ); virtual BOOL IsFieldObject() const; virtual const SvxFieldItem* GetField() const; virtual BOOL HasField( TypeId Type = NULL ) const; SfxItemSet GetParaAttribs( USHORT nPara ) const; void SetParaAttribs( USHORT nPara, const SfxItemSet& rAttribs ); virtual BOOL HasStyleSheet( const XubString& rName, SfxStyleFamily eFamily ) const; virtual void GetStyleSheet( USHORT nPara, XubString& rName, SfxStyleFamily& eFamily ) const; virtual void SetStyleSheet( USHORT nPara, const XubString& rName, const SfxStyleFamily& eFamily ); virtual BOOL ChangeStyleSheets( const XubString& rOldName, SfxStyleFamily eOldFamily, const String& rNewName, SfxStyleFamily eNewFamily ); virtual void ChangeStyleSheetName( SfxStyleFamily eFamily, const XubString& rOldName, const XubString& rNewName ); void CreateData300( SvStream& rIStream ); BOOL HasMetric() const { return nMetric != 0xFFFF; } USHORT GetMetric() const { return nMetric; } void SetMetric( USHORT n ) { nMetric = n; } BOOL IsOwnerOfPool() const { return bOwnerOfPool; } void StoreUnicodeStrings( BOOL b ) { bStoreUnicodeStrings = b; } void PrepareStore( SfxStyleSheetPool* pStyleSheetPool ); void FinishStore(); void FinishLoad( SfxStyleSheetPool* pStyleSheetPool ); }; #endif // _EDITOBJ2_HXX <commit_msg>INTEGRATION: CWS impresspresobjs (1.6.140); FILE MERGED 2005/12/09 15:05:20 cl 1.6.140.1: #i58649# added operator== for undo in impress outline view<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: editobj2.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2006-01-10 14:47:14 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _EDITOBJ2_HXX #define _EDITOBJ2_HXX #include <editobj.hxx> #include <editdoc.hxx> #include <vcl/fontcvt.hxx> class SfxStyleSheetPool; class XEditAttribute { friend class ContentInfo; // fuer DTOR friend class BinTextObject; // fuer DTOR private: const SfxPoolItem* pItem; USHORT nStart; USHORT nEnd; XEditAttribute(); XEditAttribute( const XEditAttribute& rCopyFrom ); ~XEditAttribute(); public: XEditAttribute( const SfxPoolItem& rAttr ); XEditAttribute( const SfxPoolItem& rAttr, USHORT nStart, USHORT nEnd ); const SfxPoolItem* GetItem() const { return pItem; } USHORT& GetStart() { return nStart; } USHORT& GetEnd() { return nEnd; } USHORT GetStart() const { return nStart; } USHORT GetEnd() const { return nEnd; } USHORT GetLen() const { return nEnd-nStart; } inline BOOL IsFeature(); inline bool operator==( const XEditAttribute& rCompare ); }; inline bool XEditAttribute::operator==( const XEditAttribute& rCompare ) { return (nStart == rCompare.nStart) && (nEnd == rCompare.nEnd) && ( (pItem == rCompare.pItem) || (*pItem == *rCompare.pItem)); } inline BOOL XEditAttribute::IsFeature() { USHORT nWhich = pItem->Which(); return ( ( nWhich >= EE_FEATURE_START ) && ( nWhich <= EE_FEATURE_END ) ); } typedef XEditAttribute* XEditAttributePtr; SV_DECL_PTRARR( XEditAttributeListImpl, XEditAttributePtr, 0, 4 ); class XEditAttributeList : public XEditAttributeListImpl { public: XEditAttribute* FindAttrib( USHORT nWhich, USHORT nChar ) const; }; struct XParaPortion { long nHeight; USHORT nFirstLineOffset; EditLineList aLines; TextPortionList aTextPortions; }; typedef XParaPortion* XParaPortionPtr; SV_DECL_PTRARR( XBaseParaPortionList, XParaPortionPtr, 0, 4 ); class XParaPortionList : public XBaseParaPortionList { ULONG nRefDevPtr; OutDevType eRefDevType; MapMode aRefMapMode; ULONG nPaperWidth; public: XParaPortionList( OutputDevice* pRefDev, ULONG nPW ) : aRefMapMode( pRefDev->GetMapMode() ) { nRefDevPtr = (ULONG)pRefDev; nPaperWidth = nPW; eRefDevType = pRefDev->GetOutDevType(); } ULONG GetRefDevPtr() const { return nRefDevPtr; } ULONG GetPaperWidth() const { return nPaperWidth; } OutDevType GetRefDevType() const { return eRefDevType; } const MapMode& GetRefMapMode() const { return aRefMapMode; } }; struct LoadStoreTempInfos { ByteString aOrgString_Load; FontToSubsFontConverter hOldSymbolConv_Store; BOOL bSymbolParagraph_Store; LoadStoreTempInfos() { bSymbolParagraph_Store = FALSE; hOldSymbolConv_Store = NULL; } }; class ContentInfo { friend class BinTextObject; private: String aText; String aStyle; XEditAttributeList aAttribs; SfxStyleFamily eFamily; SfxItemSet aParaAttribs; WrongList* pWrongs; LoadStoreTempInfos* pTempLoadStoreInfos; ContentInfo( SfxItemPool& rPool ); ContentInfo( const ContentInfo& rCopyFrom, SfxItemPool& rPoolToUse ); public: ~ContentInfo(); const String& GetText() const { return aText; } const String& GetStyle() const { return aStyle; } const XEditAttributeList& GetAttribs() const { return aAttribs; } const SfxItemSet& GetParaAttribs() const { return aParaAttribs; } SfxStyleFamily GetFamily() const { return eFamily; } String& GetText() { return aText; } String& GetStyle() { return aStyle; } XEditAttributeList& GetAttribs() { return aAttribs; } SfxItemSet& GetParaAttribs() { return aParaAttribs; } SfxStyleFamily& GetFamily() { return eFamily; } WrongList* GetWrongList() const { return pWrongs; } void SetWrongList( WrongList* p ) { pWrongs = p; } LoadStoreTempInfos* GetLoadStoreTempInfos() const { return pTempLoadStoreInfos; } void CreateLoadStoreTempInfos(); void DestroyLoadStoreTempInfos(); bool operator==( const ContentInfo& rCompare ) const; }; typedef ContentInfo* ContentInfoPtr; SV_DECL_PTRARR( ContentInfoList, ContentInfoPtr, 1, 4 ); // MT 05/00: Sollte mal direkt EditTextObjekt werden => keine virtuellen Methoden mehr. class BinTextObject : public EditTextObject { private: ContentInfoList aContents; SfxItemPool* pPool; BOOL bOwnerOfPool; XParaPortionList* pPortionInfo; ULONG nObjSettings; USHORT nMetric; USHORT nVersion; USHORT nUserType; USHORT nScriptType; BOOL bVertical; BOOL bStoreUnicodeStrings; protected: void DeleteContents(); virtual void StoreData( SvStream& rOStream ) const; virtual void CreateData( SvStream& rIStream ); BOOL ImpChangeStyleSheets( const String& rOldName, SfxStyleFamily eOldFamily, const String& rNewName, SfxStyleFamily eNewFamily ); public: BinTextObject( SfxItemPool* pPool ); BinTextObject( const BinTextObject& ); virtual ~BinTextObject(); virtual EditTextObject* Clone() const; USHORT GetUserType() const; void SetUserType( USHORT n ); ULONG GetObjectSettings() const; void SetObjectSettings( ULONG n ); BOOL IsVertical() const; void SetVertical( BOOL b ); USHORT GetScriptType() const; void SetScriptType( USHORT nType ); USHORT GetVersion() const; // Solange der Outliner keine Recordlaenge speichert void SetLRSpaceItemFlags( BOOL bOutlineMode ); void AdjustImportedLRSpaceItems( BOOL bTurnOfBullets ); ContentInfo* CreateAndInsertContent(); XEditAttribute* CreateAttrib( const SfxPoolItem& rItem, USHORT nStart, USHORT nEnd ); void DestroyAttrib( XEditAttribute* pAttr ); ContentInfoList& GetContents() { return aContents; } const ContentInfoList& GetContents() const { return aContents; } SfxItemPool* GetPool() const { return pPool; } XParaPortionList* GetPortionInfo() const { return pPortionInfo; } void SetPortionInfo( XParaPortionList* pP ) { pPortionInfo = pP; } virtual USHORT GetParagraphCount() const; virtual String GetText( USHORT nParagraph ) const; virtual void Insert( const EditTextObject& rObj, USHORT nPara ); virtual EditTextObject* CreateTextObject( USHORT nPara, USHORT nParas = 1 ) const; virtual void RemoveParagraph( USHORT nPara ); virtual BOOL HasPortionInfo() const; virtual void ClearPortionInfo(); virtual BOOL HasOnlineSpellErrors() const; virtual BOOL HasCharAttribs( USHORT nWhich = 0 ) const; virtual void GetCharAttribs( USHORT nPara, EECharAttribArray& rLst ) const; virtual BOOL RemoveCharAttribs( USHORT nWhich = 0 ); virtual BOOL RemoveParaAttribs( USHORT nWhich = 0 ); virtual void MergeParaAttribs( const SfxItemSet& rAttribs, USHORT nStart, USHORT nEnd ); virtual BOOL IsFieldObject() const; virtual const SvxFieldItem* GetField() const; virtual BOOL HasField( TypeId Type = NULL ) const; SfxItemSet GetParaAttribs( USHORT nPara ) const; void SetParaAttribs( USHORT nPara, const SfxItemSet& rAttribs ); virtual BOOL HasStyleSheet( const XubString& rName, SfxStyleFamily eFamily ) const; virtual void GetStyleSheet( USHORT nPara, XubString& rName, SfxStyleFamily& eFamily ) const; virtual void SetStyleSheet( USHORT nPara, const XubString& rName, const SfxStyleFamily& eFamily ); virtual BOOL ChangeStyleSheets( const XubString& rOldName, SfxStyleFamily eOldFamily, const String& rNewName, SfxStyleFamily eNewFamily ); virtual void ChangeStyleSheetName( SfxStyleFamily eFamily, const XubString& rOldName, const XubString& rNewName ); void CreateData300( SvStream& rIStream ); BOOL HasMetric() const { return nMetric != 0xFFFF; } USHORT GetMetric() const { return nMetric; } void SetMetric( USHORT n ) { nMetric = n; } BOOL IsOwnerOfPool() const { return bOwnerOfPool; } void StoreUnicodeStrings( BOOL b ) { bStoreUnicodeStrings = b; } void PrepareStore( SfxStyleSheetPool* pStyleSheetPool ); void FinishStore(); void FinishLoad( SfxStyleSheetPool* pStyleSheetPool ); bool operator==( const BinTextObject& rCompare ) const; }; #endif // _EDITOBJ2_HXX <|endoftext|>
<commit_before>/*############################################################################################ Garden System Wireless controller for watering electropumps Author: Daniele Colanardi License: BSD, see LICENSE file ############################################################################################*/ #include <Wire.h> #include "input.h" LightMPR121 touch; void init_buttons() { Wire.begin(); touch.begin(); } bool update_buttons() { touch.update(); } bool is_pressed(uint8_t i) { return touch.touched(i); } bool released(uint8_t i) { return true; } <commit_msg>Add basic retriggering to input<commit_after>/*############################################################################################ Garden System Wireless controller for watering electropumps Author: Daniele Colanardi License: BSD, see LICENSE file ############################################################################################*/ #include <Wire.h> #include "input.h" LightMPR121 touch; int last_status; long repeat_timer; bool changed; void init_buttons() { Wire.begin(); touch.begin(); } bool update_buttons() { int new_status = touch.update(); changed = new_status != last_status; last_status = new_status; if (changed || millis() - repeat_timer > 150) { repeat_timer = millis(); if(!changed) changed = true; } } bool is_pressed(uint8_t i) { return touch.touched(i) && changed; } bool released(uint8_t i) { return true; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: caption.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: os $ $Date: 2002-12-05 13:00:20 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PRECOMPILED #include "ui_pch.hxx" #endif #pragma hdrstop #ifndef _TOOLS_DEBUG_HXX //autogen #include <tools/debug.hxx> #endif #include "numrule.hxx" #include "caption.hxx" #define VERSION_01 1 #define CAPTION_VERSION VERSION_01 /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ InsCaptionOpt::InsCaptionOpt(const SwCapObjType eType, const SvGlobalName* pOleId) : bUseCaption(FALSE), eObjType(eType), nNumType(SVX_NUM_ARABIC), nPos(1), nLevel(0), cSeparator('.'), bIgnoreSeqOpts(FALSE), bCopyAttributes(FALSE) { if (pOleId) aOleId = *pOleId; } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ InsCaptionOpt::InsCaptionOpt(const InsCaptionOpt& rOpt) { *this = rOpt; } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ InsCaptionOpt::~InsCaptionOpt() { } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ InsCaptionOpt& InsCaptionOpt::operator=( const InsCaptionOpt& rOpt ) { bUseCaption = rOpt.bUseCaption; eObjType = rOpt.eObjType; aOleId = rOpt.aOleId; sCategory = rOpt.sCategory; nNumType = rOpt.nNumType; sCaption = rOpt.sCaption; nPos = rOpt.nPos; nLevel = rOpt.nLevel; cSeparator = rOpt.cSeparator; bIgnoreSeqOpts = rOpt.bIgnoreSeqOpts; bCopyAttributes = rOpt.bCopyAttributes; return *this; } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ BOOL InsCaptionOpt::operator==( const InsCaptionOpt& rOpt ) const { return (eObjType == rOpt.eObjType && aOleId == rOpt.aOleId); // Damit gleiche Ole-IDs nicht mehrfach eingefuegt // werden koennen, auf nichts weiteres vergleichen /* && sCategory == rOpt.sCategory && nNumType == rOpt.nNumType && sCaption == rOpt.sCaption && nPos == rOpt.nPos && nLevel == rOpt.nLevel && cSeparator == rOpt.cSeparator);*/ } /************************************************************************* |* |* InsCaptionOpt::operator>>() |* |* Beschreibung Stream-Leseoperator |* *************************************************************************/ SvStream& operator>>( SvStream& rIStream, InsCaptionOpt& rCapOpt ) { rtl_TextEncoding eEncoding = gsl_getSystemTextEncoding(); UINT16 nVal; BYTE cVal; BYTE nVersion; rIStream >> nVersion; rIStream >> cVal; rCapOpt.UseCaption() = cVal != 0; rIStream >> nVal; rCapOpt.eObjType = (SwCapObjType)nVal; rIStream >> rCapOpt.aOleId; rIStream.ReadByteString( rCapOpt.sCategory, eEncoding ); rIStream >> nVal; rCapOpt.nNumType = nVal; rIStream.ReadByteString( rCapOpt.sCaption, eEncoding ); rIStream >> nVal; rCapOpt.nPos = nVal; rIStream >> nVal; rCapOpt.nLevel = nVal; rIStream >> cVal; rCapOpt.cSeparator = UniString( ByteString(cVal) , eEncoding).GetChar(0); return rIStream; } /************************************************************************* |* |* InsCaptionOpt::operator<<() |* |* Beschreibung Stream-Schreiboperator |* *************************************************************************/ SvStream& operator<<( SvStream& rOStream, const InsCaptionOpt& rCapOpt ) { rtl_TextEncoding eEncoding = gsl_getSystemTextEncoding(); rOStream << (BYTE)CAPTION_VERSION << (BYTE)rCapOpt.UseCaption() << (UINT16)rCapOpt.eObjType << rCapOpt.aOleId; rOStream.WriteByteString( rCapOpt.sCategory, eEncoding ); rOStream << (UINT16)rCapOpt.nNumType; rOStream.WriteByteString( rCapOpt.sCaption, eEncoding ); BYTE cSep = ByteString(UniString(rCapOpt.cSeparator), eEncoding).GetChar(0); rOStream << (UINT16)rCapOpt.nPos << (UINT16)rCapOpt.nLevel << cSep; return rOStream; } <commit_msg>INTEGRATION: CWS os8 (1.2.138); FILE MERGED 2003/04/03 07:13:43 os 1.2.138.1: #108583# precompiled headers removed<commit_after>/************************************************************************* * * $RCSfile: caption.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2003-04-17 15:17:00 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _TOOLS_DEBUG_HXX //autogen #include <tools/debug.hxx> #endif #include "numrule.hxx" #include "caption.hxx" #define VERSION_01 1 #define CAPTION_VERSION VERSION_01 /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ InsCaptionOpt::InsCaptionOpt(const SwCapObjType eType, const SvGlobalName* pOleId) : bUseCaption(FALSE), eObjType(eType), nNumType(SVX_NUM_ARABIC), nPos(1), nLevel(0), cSeparator('.'), bIgnoreSeqOpts(FALSE), bCopyAttributes(FALSE) { if (pOleId) aOleId = *pOleId; } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ InsCaptionOpt::InsCaptionOpt(const InsCaptionOpt& rOpt) { *this = rOpt; } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ InsCaptionOpt::~InsCaptionOpt() { } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ InsCaptionOpt& InsCaptionOpt::operator=( const InsCaptionOpt& rOpt ) { bUseCaption = rOpt.bUseCaption; eObjType = rOpt.eObjType; aOleId = rOpt.aOleId; sCategory = rOpt.sCategory; nNumType = rOpt.nNumType; sCaption = rOpt.sCaption; nPos = rOpt.nPos; nLevel = rOpt.nLevel; cSeparator = rOpt.cSeparator; bIgnoreSeqOpts = rOpt.bIgnoreSeqOpts; bCopyAttributes = rOpt.bCopyAttributes; return *this; } /*-------------------------------------------------------------------- Beschreibung: --------------------------------------------------------------------*/ BOOL InsCaptionOpt::operator==( const InsCaptionOpt& rOpt ) const { return (eObjType == rOpt.eObjType && aOleId == rOpt.aOleId); // Damit gleiche Ole-IDs nicht mehrfach eingefuegt // werden koennen, auf nichts weiteres vergleichen /* && sCategory == rOpt.sCategory && nNumType == rOpt.nNumType && sCaption == rOpt.sCaption && nPos == rOpt.nPos && nLevel == rOpt.nLevel && cSeparator == rOpt.cSeparator);*/ } /************************************************************************* |* |* InsCaptionOpt::operator>>() |* |* Beschreibung Stream-Leseoperator |* *************************************************************************/ SvStream& operator>>( SvStream& rIStream, InsCaptionOpt& rCapOpt ) { rtl_TextEncoding eEncoding = gsl_getSystemTextEncoding(); UINT16 nVal; BYTE cVal; BYTE nVersion; rIStream >> nVersion; rIStream >> cVal; rCapOpt.UseCaption() = cVal != 0; rIStream >> nVal; rCapOpt.eObjType = (SwCapObjType)nVal; rIStream >> rCapOpt.aOleId; rIStream.ReadByteString( rCapOpt.sCategory, eEncoding ); rIStream >> nVal; rCapOpt.nNumType = nVal; rIStream.ReadByteString( rCapOpt.sCaption, eEncoding ); rIStream >> nVal; rCapOpt.nPos = nVal; rIStream >> nVal; rCapOpt.nLevel = nVal; rIStream >> cVal; rCapOpt.cSeparator = UniString( ByteString(cVal) , eEncoding).GetChar(0); return rIStream; } /************************************************************************* |* |* InsCaptionOpt::operator<<() |* |* Beschreibung Stream-Schreiboperator |* *************************************************************************/ SvStream& operator<<( SvStream& rOStream, const InsCaptionOpt& rCapOpt ) { rtl_TextEncoding eEncoding = gsl_getSystemTextEncoding(); rOStream << (BYTE)CAPTION_VERSION << (BYTE)rCapOpt.UseCaption() << (UINT16)rCapOpt.eObjType << rCapOpt.aOleId; rOStream.WriteByteString( rCapOpt.sCategory, eEncoding ); rOStream << (UINT16)rCapOpt.nNumType; rOStream.WriteByteString( rCapOpt.sCaption, eEncoding ); BYTE cSep = ByteString(UniString(rCapOpt.cSeparator), eEncoding).GetChar(0); rOStream << (UINT16)rCapOpt.nPos << (UINT16)rCapOpt.nLevel << cSep; return rOStream; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: grfshex.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hjs $ $Date: 2003-08-19 12:00:03 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _DOCARY_HXX #include <docary.hxx> #endif #ifndef _GRFSH_HXX #include <grfsh.hxx> #endif #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _VIEW_HXX #include <view.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _DOCARY_HXX #include <docary.hxx> #endif #ifndef _TEXTSH_HXX #include <textsh.hxx> #endif #ifndef _VIEWOPT_HXX #include <viewopt.hxx> #endif #ifndef _SWUNDO_HXX #include <swundo.hxx> #endif #ifndef _SHELLS_HRC #include <shells.hrc> #endif #ifndef _CAPTION_HXX #include <caption.hxx> #endif #define _SVSTDARR_STRINGSSORTDTOR #include <svtools/svstdarr.hxx> #ifndef _FILTER_HXX #include <svtools/filter.hxx> #endif #ifndef _SVX_IMPGRF_HXX #include <svx/impgrf.hxx> #endif #ifndef _SVX_HTMLMODE_HXX //autogen #include <svx/htmlmode.hxx> #endif #ifndef _DOCSH_HXX #include <docsh.hxx> #endif #ifndef _FRMFMT_HXX #include <frmfmt.hxx> #endif #ifndef _FRMMGR_HXX #include <frmmgr.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _SWSTYLENAMEMAPPER_HXX #include <SwStyleNameMapper.hxx> #endif #ifndef _FILEDLGHELPER_HXX #include <sfx2/filedlghelper.hxx> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_ #include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_ #include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_ #include <com/sun/star/ui/dialogs/ListboxControlActions.hpp> #endif #ifndef _POOLFMT_HRC #include <poolfmt.hrc> #endif #include <sfx2/request.hxx> #include <svtools/stritem.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::ui::dialogs; using namespace ::sfx2; using namespace ::rtl; BOOL SwTextShell::InsertGraphicDlg( SfxRequest& rReq ) { #ifndef ENABLE_PROP_WITHOUTLINK #define ENABLE_PROP_WITHOUTLINK 0x08 #endif BOOL bReturn = FALSE; SwView &rVw = GetView(); SwDocShell* pDocShell = rVw.GetDocShell(); USHORT nHtmlMode = ::GetHtmlMode(pDocShell); // im HTML-Mode nur verknuepft einfuegen FileDialogHelper* pFileDlg = new FileDialogHelper( SFXWB_GRAPHIC | SFXWB_SHOWSTYLES ); pFileDlg->SetTitle(SW_RESSTR(STR_INSERT_GRAPHIC )); pFileDlg->SetContext( FileDialogHelper::SW_INSERT_GRAPHIC ); Reference < XFilePicker > xFP = pFileDlg->GetFilePicker(); Reference < XFilePickerControlAccess > xCtrlAcc(xFP, UNO_QUERY); if(nHtmlMode & HTMLMODE_ON) { sal_Bool bTrue = sal_True; Any aVal(&bTrue, ::getBooleanCppuType()); xCtrlAcc->setValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0, aVal); xCtrlAcc->enableControl( ExtendedFilePickerElementIds::CHECKBOX_LINK, sal_False); } SvStringsSortDtor aFormats; SwDoc* pDoc = pDocShell->GetDoc(); const USHORT nArrLen = pDoc->GetFrmFmts()->Count(); USHORT i; for( i = 0; i < nArrLen; i++ ) { SwFrmFmt* pFmt = (*pDoc->GetFrmFmts())[ i ]; if(pFmt->IsDefault() || pFmt->IsAuto()) continue; String *pFormat = new String(pFmt->GetName()); aFormats.Insert(pFormat); } // pool formats // const SvStringsDtor& rFrmPoolArr = SwStyleNameMapper::GetFrmFmtUINameArray(); for( i = 0; i < rFrmPoolArr.Count(); i++ ) { String *pFormat = new String(*rFrmPoolArr[i]); if (!aFormats.Insert(pFormat)) delete pFormat; } Sequence<OUString> aListBoxEntries(aFormats.Count()); OUString* pEntries = aListBoxEntries.getArray(); sal_Int16 nSelect = 0; String sGraphicFormat = SW_RESSTR(STR_POOLFRM_GRAPHIC); for(i = 0; i < aFormats.Count(); ++i) { pEntries[i] = *aFormats[i]; if(pEntries[i].equals(sGraphicFormat)) nSelect = i; } try { Any aTemplates(&aListBoxEntries, ::getCppuType(&aListBoxEntries)); xCtrlAcc->setValue( ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE, ListboxControlActions::ADD_ITEMS , aTemplates ); Any aSelectPos(&nSelect, ::getCppuType(&nSelect)); xCtrlAcc->setValue( ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE, ListboxControlActions::SET_SELECT_ITEM, aSelectPos ); } catch(Exception& ) { DBG_ERROR("control acces failed") } SFX_REQUEST_ARG( rReq, pName, SfxStringItem, SID_INSERT_GRAPHIC , sal_False ); BOOL bShowError = !pName; if( pName || ERRCODE_NONE == pFileDlg->Execute() ) { String aFileName, aFilterName; if ( pName ) { aFileName = pName->GetValue(); SFX_REQUEST_ARG( rReq, pFilter, SfxStringItem, FN_PARAM_FILTER , sal_False ); if ( pFilter ) aFilterName = pFilter->GetValue(); } else { aFileName = pFileDlg->GetPath(); aFilterName = pFileDlg->GetCurrentFilter(); rReq.AppendItem( SfxStringItem( SID_INSERT_GRAPHIC, aFileName ) ); rReq.AppendItem( SfxStringItem( FN_PARAM_FILTER, aFilterName ) ); sal_Bool bAsLink; if(nHtmlMode & HTMLMODE_ON) bAsLink = sal_True; else { try { Any aVal = xCtrlAcc->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0); DBG_ASSERT(aVal.hasValue(), "Value CBX_INSERT_AS_LINK not found") bAsLink = aVal.hasValue() ? *(sal_Bool*) aVal.getValue() : sal_True; Any aTemplateValue = xCtrlAcc->getValue( ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE, ListboxControlActions::GET_SELECTED_ITEM ); OUString sTmpl; aTemplateValue >>= sTmpl; rReq.AppendItem( SfxStringItem( FN_PARAM_2, sTmpl) ); } catch(Exception& ) { DBG_ERROR("control acces failed") } } rReq.AppendItem( SfxBoolItem( FN_PARAM_1, bAsLink ) ); } SFX_REQUEST_ARG( rReq, pAsLink, SfxBoolItem, FN_PARAM_1 , sal_False ); SFX_REQUEST_ARG( rReq, pStyle, SfxStringItem, FN_PARAM_2 , sal_False ); sal_Bool bAsLink; if( nHtmlMode & HTMLMODE_ON ) bAsLink = sal_True; else { if ( rReq.GetArgs() ) { if ( pAsLink ) bAsLink = pAsLink->GetValue(); if ( pStyle ) sGraphicFormat = pStyle->GetValue(); } else { Any aVal = xCtrlAcc->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0); DBG_ASSERT(aVal.hasValue(), "Value CBX_INSERT_AS_LINK not found") bAsLink = aVal.hasValue() ? *(sal_Bool*) aVal.getValue() : sal_True; Any aTemplateValue = xCtrlAcc->getValue( ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE, ListboxControlActions::GET_SELECTED_ITEM ); OUString sTmpl; aTemplateValue >>= sTmpl; sGraphicFormat = sTmpl; if ( sGraphicFormat.Len() ) rReq.AppendItem( SfxStringItem( FN_PARAM_2, sGraphicFormat ) ); rReq.AppendItem( SfxBoolItem( FN_PARAM_1, bAsLink ) ); } } SwWrtShell& rSh = GetShell(); rSh.StartAction(); rSh.StartUndo(UNDO_INSERT); USHORT nError = InsertGraphic( aFileName, aFilterName, bAsLink, ::GetGrfFilter() ); // Format ist ungleich Current Filter, jetzt mit auto. detection if( nError == GRFILTER_FORMATERROR ) nError = InsertGraphic( aFileName, aEmptyStr, bAsLink, ::GetGrfFilter() ); if ( rSh.IsFrmSelected() ) { SwFrmFmt* pFmt = pDoc->FindFrmFmtByName( sGraphicFormat ); if(!pFmt) pFmt = pDoc->MakeFrmFmt(sGraphicFormat, 0); rSh.SetFrmFmt( pFmt ); } RESOURCE_TYPE nResId = 0; switch( nError ) { case GRFILTER_OPENERROR: nResId = STR_GRFILTER_OPENERROR; break; case GRFILTER_IOERROR: nResId = STR_GRFILTER_IOERROR; break; case GRFILTER_FORMATERROR: nResId = STR_GRFILTER_FORMATERROR; break; case GRFILTER_VERSIONERROR: nResId = STR_GRFILTER_VERSIONERROR; break; case GRFILTER_FILTERERROR: nResId = STR_GRFILTER_FILTERERROR; break; case GRFILTER_TOOBIG: nResId = STR_GRFILTER_TOOBIG; break; } rSh.EndAction(); if( nResId ) { if( bShowError ) { InfoBox aInfoBox( rVw.GetWindow(), SW_RESSTR( nResId )); aInfoBox.Execute(); } rReq.Ignore(); } else { // set the specific graphic attrbutes to the graphic bReturn = TRUE; rVw.AutoCaption( GRAPHIC_CAP ); rReq.Done(); } rSh.EndUndo(UNDO_INSERT); // wegen moegl. Shellwechsel } DELETEZ( pFrmMgr ); delete pFileDlg; return bReturn; } <commit_msg>INTEGRATION: CWS swundo01 (1.8.126); FILE MERGED 2003/09/23 13:28:52 hbrinkm 1.8.126.2: RESYNC: (1.8-1.9); FILE MERGED 2003/09/23 12:38:11 hbrinkm 1.8.126.1: #111827#<commit_after>/************************************************************************* * * $RCSfile: grfshex.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: kz $ $Date: 2004-05-18 14:12:31 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _DOCARY_HXX #include <docary.hxx> #endif #ifndef _GRFSH_HXX #include <grfsh.hxx> #endif #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _VIEW_HXX #include <view.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _DOCARY_HXX #include <docary.hxx> #endif #ifndef _TEXTSH_HXX #include <textsh.hxx> #endif #ifndef _VIEWOPT_HXX #include <viewopt.hxx> #endif #ifndef _SWUNDO_HXX #include <swundo.hxx> #endif #ifndef _SHELLS_HRC #include <shells.hrc> #endif #ifndef _CAPTION_HXX #include <caption.hxx> #endif #define _SVSTDARR_STRINGSSORTDTOR #include <svtools/svstdarr.hxx> #ifndef _FILTER_HXX #include <svtools/filter.hxx> #endif #ifndef _SVX_IMPGRF_HXX #include <svx/impgrf.hxx> #endif #ifndef _SVX_HTMLMODE_HXX //autogen #include <svx/htmlmode.hxx> #endif #ifndef _DOCSH_HXX #include <docsh.hxx> #endif #ifndef _FRMFMT_HXX #include <frmfmt.hxx> #endif #ifndef _FRMMGR_HXX #include <frmmgr.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _SWSTYLENAMEMAPPER_HXX #include <SwStyleNameMapper.hxx> #endif #ifndef _FILEDLGHELPER_HXX #include <sfx2/filedlghelper.hxx> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_ #include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_ #include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_ #include <com/sun/star/ui/dialogs/ListboxControlActions.hpp> #endif #ifndef _POOLFMT_HRC #include <poolfmt.hrc> #endif #include <sfx2/request.hxx> #include <svtools/stritem.hxx> // -> #111827# #include <SwRewriter.hxx> #include <undobj.hxx> #include <comcore.hrc> // <- #111827# using namespace ::com::sun::star::uno; using namespace ::com::sun::star::ui::dialogs; using namespace ::sfx2; using namespace ::rtl; BOOL SwTextShell::InsertGraphicDlg( SfxRequest& rReq ) { #ifndef ENABLE_PROP_WITHOUTLINK #define ENABLE_PROP_WITHOUTLINK 0x08 #endif BOOL bReturn = FALSE; SwView &rVw = GetView(); SwDocShell* pDocShell = rVw.GetDocShell(); USHORT nHtmlMode = ::GetHtmlMode(pDocShell); // im HTML-Mode nur verknuepft einfuegen FileDialogHelper* pFileDlg = new FileDialogHelper( SFXWB_GRAPHIC | SFXWB_SHOWSTYLES ); pFileDlg->SetTitle(SW_RESSTR(STR_INSERT_GRAPHIC )); pFileDlg->SetContext( FileDialogHelper::SW_INSERT_GRAPHIC ); Reference < XFilePicker > xFP = pFileDlg->GetFilePicker(); Reference < XFilePickerControlAccess > xCtrlAcc(xFP, UNO_QUERY); if(nHtmlMode & HTMLMODE_ON) { sal_Bool bTrue = sal_True; Any aVal(&bTrue, ::getBooleanCppuType()); xCtrlAcc->setValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0, aVal); xCtrlAcc->enableControl( ExtendedFilePickerElementIds::CHECKBOX_LINK, sal_False); } SvStringsSortDtor aFormats; SwDoc* pDoc = pDocShell->GetDoc(); const USHORT nArrLen = pDoc->GetFrmFmts()->Count(); USHORT i; for( i = 0; i < nArrLen; i++ ) { SwFrmFmt* pFmt = (*pDoc->GetFrmFmts())[ i ]; if(pFmt->IsDefault() || pFmt->IsAuto()) continue; String *pFormat = new String(pFmt->GetName()); aFormats.Insert(pFormat); } // pool formats // const SvStringsDtor& rFrmPoolArr = SwStyleNameMapper::GetFrmFmtUINameArray(); for( i = 0; i < rFrmPoolArr.Count(); i++ ) { String *pFormat = new String(*rFrmPoolArr[i]); if (!aFormats.Insert(pFormat)) delete pFormat; } Sequence<OUString> aListBoxEntries(aFormats.Count()); OUString* pEntries = aListBoxEntries.getArray(); sal_Int16 nSelect = 0; String sGraphicFormat = SW_RESSTR(STR_POOLFRM_GRAPHIC); for(i = 0; i < aFormats.Count(); ++i) { pEntries[i] = *aFormats[i]; if(pEntries[i].equals(sGraphicFormat)) nSelect = i; } try { Any aTemplates(&aListBoxEntries, ::getCppuType(&aListBoxEntries)); xCtrlAcc->setValue( ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE, ListboxControlActions::ADD_ITEMS , aTemplates ); Any aSelectPos(&nSelect, ::getCppuType(&nSelect)); xCtrlAcc->setValue( ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE, ListboxControlActions::SET_SELECT_ITEM, aSelectPos ); } catch(Exception& ) { DBG_ERROR("control acces failed") } SFX_REQUEST_ARG( rReq, pName, SfxStringItem, SID_INSERT_GRAPHIC , sal_False ); BOOL bShowError = !pName; if( pName || ERRCODE_NONE == pFileDlg->Execute() ) { String aFileName, aFilterName; if ( pName ) { aFileName = pName->GetValue(); SFX_REQUEST_ARG( rReq, pFilter, SfxStringItem, FN_PARAM_FILTER , sal_False ); if ( pFilter ) aFilterName = pFilter->GetValue(); } else { aFileName = pFileDlg->GetPath(); aFilterName = pFileDlg->GetCurrentFilter(); rReq.AppendItem( SfxStringItem( SID_INSERT_GRAPHIC, aFileName ) ); rReq.AppendItem( SfxStringItem( FN_PARAM_FILTER, aFilterName ) ); sal_Bool bAsLink; if(nHtmlMode & HTMLMODE_ON) bAsLink = sal_True; else { try { Any aVal = xCtrlAcc->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0); DBG_ASSERT(aVal.hasValue(), "Value CBX_INSERT_AS_LINK not found") bAsLink = aVal.hasValue() ? *(sal_Bool*) aVal.getValue() : sal_True; Any aTemplateValue = xCtrlAcc->getValue( ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE, ListboxControlActions::GET_SELECTED_ITEM ); OUString sTmpl; aTemplateValue >>= sTmpl; rReq.AppendItem( SfxStringItem( FN_PARAM_2, sTmpl) ); } catch(Exception& ) { DBG_ERROR("control acces failed") } } rReq.AppendItem( SfxBoolItem( FN_PARAM_1, bAsLink ) ); } SFX_REQUEST_ARG( rReq, pAsLink, SfxBoolItem, FN_PARAM_1 , sal_False ); SFX_REQUEST_ARG( rReq, pStyle, SfxStringItem, FN_PARAM_2 , sal_False ); sal_Bool bAsLink; if( nHtmlMode & HTMLMODE_ON ) bAsLink = sal_True; else { if ( rReq.GetArgs() ) { if ( pAsLink ) bAsLink = pAsLink->GetValue(); if ( pStyle ) sGraphicFormat = pStyle->GetValue(); } else { Any aVal = xCtrlAcc->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0); DBG_ASSERT(aVal.hasValue(), "Value CBX_INSERT_AS_LINK not found") bAsLink = aVal.hasValue() ? *(sal_Bool*) aVal.getValue() : sal_True; Any aTemplateValue = xCtrlAcc->getValue( ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE, ListboxControlActions::GET_SELECTED_ITEM ); OUString sTmpl; aTemplateValue >>= sTmpl; sGraphicFormat = sTmpl; if ( sGraphicFormat.Len() ) rReq.AppendItem( SfxStringItem( FN_PARAM_2, sGraphicFormat ) ); rReq.AppendItem( SfxBoolItem( FN_PARAM_1, bAsLink ) ); } } SwWrtShell& rSh = GetShell(); rSh.StartAction(); /// #111827# SwRewriter aRewriter; aRewriter.AddRule(UNDO_ARG1, String(SW_RES(STR_GRAPHIC_DEFNAME))); rSh.StartUndo(UNDO_INSERT, &aRewriter); USHORT nError = InsertGraphic( aFileName, aFilterName, bAsLink, ::GetGrfFilter() ); // Format ist ungleich Current Filter, jetzt mit auto. detection if( nError == GRFILTER_FORMATERROR ) nError = InsertGraphic( aFileName, aEmptyStr, bAsLink, ::GetGrfFilter() ); if ( rSh.IsFrmSelected() ) { SwFrmFmt* pFmt = pDoc->FindFrmFmtByName( sGraphicFormat ); if(!pFmt) pFmt = pDoc->MakeFrmFmt(sGraphicFormat, 0); rSh.SetFrmFmt( pFmt ); } RESOURCE_TYPE nResId = 0; switch( nError ) { case GRFILTER_OPENERROR: nResId = STR_GRFILTER_OPENERROR; break; case GRFILTER_IOERROR: nResId = STR_GRFILTER_IOERROR; break; case GRFILTER_FORMATERROR: nResId = STR_GRFILTER_FORMATERROR; break; case GRFILTER_VERSIONERROR: nResId = STR_GRFILTER_VERSIONERROR; break; case GRFILTER_FILTERERROR: nResId = STR_GRFILTER_FILTERERROR; break; case GRFILTER_TOOBIG: nResId = STR_GRFILTER_TOOBIG; break; } rSh.EndAction(); if( nResId ) { if( bShowError ) { InfoBox aInfoBox( rVw.GetWindow(), SW_RESSTR( nResId )); aInfoBox.Execute(); } rReq.Ignore(); } else { // set the specific graphic attrbutes to the graphic bReturn = TRUE; rVw.AutoCaption( GRAPHIC_CAP ); rReq.Done(); } rSh.EndUndo(UNDO_INSERT); // wegen moegl. Shellwechsel } DELETEZ( pFrmMgr ); delete pFileDlg; return bReturn; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: textdrw.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2003-03-27 15:44:22 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PRECOMPILED #include "ui_pch.hxx" #endif #pragma hdrstop #ifndef _SVDVIEW_HXX //autogen #include <svx/svdview.hxx> #endif #ifndef _URLOBJ_HXX //autogen #include <tools/urlobj.hxx> #endif #ifndef _SVX_FMGLOB_HXX #include <svx/fmglob.hxx> #endif #ifndef _SVDOUNO_HXX //autogen #include <svx/svdouno.hxx> #endif #ifndef _COM_SUN_STAR_FORM_FORMBUTTONTYPE_HPP_ #include <com/sun/star/form/FormButtonType.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _VIEW_HXX #include <view.hxx> #endif #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _EDTWIN_HXX #include <edtwin.hxx> #endif #ifndef _SWUNDO_HXX #include <swundo.hxx> #endif #ifndef _BASESH_HXX #include <basesh.hxx> #endif #ifndef _POOLFMT_HRC #include <poolfmt.hrc> #endif #ifndef _SV_SOUND_HXX #include <vcl/sound.hxx> #endif #define C2U(cChar) rtl::OUString::createFromAscii(cChar) using namespace ::com::sun::star; using namespace ::rtl; /*--------------------------------------------------------------------------- Beschreibung: ----------------------------------------------------------------------------*/ void SwBaseShell::InsertURLButton(const String& rURL, const String& rTarget, const String& rTxt) { SwWrtShell& rSh = GetShell(); if (!rSh.HasDrawView()) rSh.MakeDrawView(); SdrView *pSdrView = rSh.GetDrawView(); // OBJ_FM_BUTTON pSdrView->SetDesignMode(TRUE); pSdrView->SetCurrentObj(OBJ_FM_BUTTON); pSdrView->SetEditMode(sal_False); Point aStartPos(rSh.GetCharRect().Pos() + Point(0, 1)); rSh.StartAction(); rSh.StartUndo( UIUNDO_INSERT_URLBTN ); if (rSh.BeginCreate(OBJ_FM_BUTTON, FmFormInventor, aStartPos)) { pSdrView->SetOrtho(sal_False); Size aSz(GetView().GetEditWin().PixelToLogic(Size(140, 20))); Point aEndPos(aSz.Width(), aSz.Height()); rSh.MoveCreate(aStartPos + aEndPos); rSh.EndCreate(SDRCREATE_FORCEEND); const SdrMarkList& rMarkList = pSdrView->GetMarkList(); if (rMarkList.GetMark(0)) { SdrUnoObj* pUnoCtrl = PTR_CAST(SdrUnoObj, rMarkList.GetMark(0)->GetObj()); uno::Reference< awt::XControlModel > xControlModel = pUnoCtrl->GetUnoControlModel(); ASSERT( xControlModel.is(), "UNO-Control ohne Model" ); if( !xControlModel.is() ) return; uno::Reference< beans::XPropertySet > xPropSet(xControlModel, uno::UNO_QUERY); uno::Any aTmp; aTmp <<= OUString(rTxt); xPropSet->setPropertyValue( C2U("Label"), aTmp ); aTmp <<= OUString(INetURLObject::RelToAbs(rURL)); xPropSet->setPropertyValue( C2U("TargetURL"), aTmp ); if( rTarget.Len() ) { aTmp <<= OUString(rTarget); xPropSet->setPropertyValue( C2U("TargetFrame"), aTmp ); } form::FormButtonType eButtonType = form::FormButtonType_URL; aTmp.setValue( &eButtonType, ::getCppuType((const form::FormButtonType*)0)); xPropSet->setPropertyValue( C2U("ButtonType"), aTmp ); if ( Sound::IsSoundFile( rURL ) ) { // #105638# OJ aTmp <<= sal_True; xPropSet->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DispatchURLInternal" )), aTmp ); } } if (rSh.IsObjSelected()) { // rSh.ChgAnchor(FLY_AT_CNTNT); rSh.UnSelectFrm(); } } rSh.EndUndo( UIUNDO_INSERT_URLBTN ); rSh.EndAction(); } <commit_msg>INTEGRATION: CWS os8 (1.4.2.1.86); FILE MERGED 2003/04/03 07:15:06 os 1.4.2.1.86.1: #108583# precompiled headers removed<commit_after>/************************************************************************* * * $RCSfile: textdrw.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2003-04-17 15:43:30 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _SVDVIEW_HXX //autogen #include <svx/svdview.hxx> #endif #ifndef _URLOBJ_HXX //autogen #include <tools/urlobj.hxx> #endif #ifndef _SVX_FMGLOB_HXX #include <svx/fmglob.hxx> #endif #ifndef _SVDOUNO_HXX //autogen #include <svx/svdouno.hxx> #endif #ifndef _COM_SUN_STAR_FORM_FORMBUTTONTYPE_HPP_ #include <com/sun/star/form/FormButtonType.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _VIEW_HXX #include <view.hxx> #endif #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _EDTWIN_HXX #include <edtwin.hxx> #endif #ifndef _SWUNDO_HXX #include <swundo.hxx> #endif #ifndef _BASESH_HXX #include <basesh.hxx> #endif #ifndef _POOLFMT_HRC #include <poolfmt.hrc> #endif #ifndef _SV_SOUND_HXX #include <vcl/sound.hxx> #endif #define C2U(cChar) rtl::OUString::createFromAscii(cChar) using namespace ::com::sun::star; using namespace ::rtl; /*--------------------------------------------------------------------------- Beschreibung: ----------------------------------------------------------------------------*/ void SwBaseShell::InsertURLButton(const String& rURL, const String& rTarget, const String& rTxt) { SwWrtShell& rSh = GetShell(); if (!rSh.HasDrawView()) rSh.MakeDrawView(); SdrView *pSdrView = rSh.GetDrawView(); // OBJ_FM_BUTTON pSdrView->SetDesignMode(TRUE); pSdrView->SetCurrentObj(OBJ_FM_BUTTON); pSdrView->SetEditMode(sal_False); Point aStartPos(rSh.GetCharRect().Pos() + Point(0, 1)); rSh.StartAction(); rSh.StartUndo( UIUNDO_INSERT_URLBTN ); if (rSh.BeginCreate(OBJ_FM_BUTTON, FmFormInventor, aStartPos)) { pSdrView->SetOrtho(sal_False); Size aSz(GetView().GetEditWin().PixelToLogic(Size(140, 20))); Point aEndPos(aSz.Width(), aSz.Height()); rSh.MoveCreate(aStartPos + aEndPos); rSh.EndCreate(SDRCREATE_FORCEEND); const SdrMarkList& rMarkList = pSdrView->GetMarkList(); if (rMarkList.GetMark(0)) { SdrUnoObj* pUnoCtrl = PTR_CAST(SdrUnoObj, rMarkList.GetMark(0)->GetObj()); uno::Reference< awt::XControlModel > xControlModel = pUnoCtrl->GetUnoControlModel(); ASSERT( xControlModel.is(), "UNO-Control ohne Model" ); if( !xControlModel.is() ) return; uno::Reference< beans::XPropertySet > xPropSet(xControlModel, uno::UNO_QUERY); uno::Any aTmp; aTmp <<= OUString(rTxt); xPropSet->setPropertyValue( C2U("Label"), aTmp ); aTmp <<= OUString(INetURLObject::RelToAbs(rURL)); xPropSet->setPropertyValue( C2U("TargetURL"), aTmp ); if( rTarget.Len() ) { aTmp <<= OUString(rTarget); xPropSet->setPropertyValue( C2U("TargetFrame"), aTmp ); } form::FormButtonType eButtonType = form::FormButtonType_URL; aTmp.setValue( &eButtonType, ::getCppuType((const form::FormButtonType*)0)); xPropSet->setPropertyValue( C2U("ButtonType"), aTmp ); if ( Sound::IsSoundFile( rURL ) ) { // #105638# OJ aTmp <<= sal_True; xPropSet->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DispatchURLInternal" )), aTmp ); } } if (rSh.IsObjSelected()) { // rSh.ChgAnchor(FLY_AT_CNTNT); rSh.UnSelectFrm(); } } rSh.EndUndo( UIUNDO_INSERT_URLBTN ); rSh.EndAction(); } <|endoftext|>
<commit_before>// // Created by Mingkai Chen on 2017-03-10. // #include "util_test.h" #include "fuzz.h" #ifdef UTIL_TEST_H bool tensorshape_equal ( const tensorshape& ts1, const tensorshape& ts2) { std::vector<size_t> vs = ts1.as_list(); std::vector<size_t> vs2 = ts2.as_list(); if (vs.size() != vs2.size()) return false; return std::equal(vs.begin(), vs.end(), vs2.begin()); } bool tensorshape_equal ( const tensorshape& ts1, std::vector<size_t>& ts2) { std::vector<size_t> vs = ts1.as_list(); if (vs.size() != ts2.size()) return false; return std::equal(vs.begin(), vs.end(), ts2.begin()); } void print (std::vector<double> raw) { for (double r : raw) { std::cout << r << " "; } std::cout << "\n"; } tensorshape make_partial (std::vector<size_t> shapelist) { size_t nzeros = 1; if (shapelist.size() > 2) { nzeros = FUZZ::getInt(1, "nzeros", {1, shapelist.size()-1})[0]; } else if (shapelist.size() == 1) { shapelist.push_back(0); return shapelist; } std::vector<size_t> zeros = FUZZ::getInt(nzeros, "zeros", {0, shapelist.size()-1}); for (size_t zidx : zeros) { shapelist[zidx] = 0; } return tensorshape(shapelist); } tensorshape make_incompatible (std::vector<size_t> shapelist) { for (size_t i = 0; i < shapelist.size(); i++) { shapelist[i]++; } return tensorshape(shapelist); } // make partial full, but incompatible to comp tensorshape make_full_incomp (std::vector<size_t> partial, std::vector<size_t> complete) { assert(partial.size() == complete.size()); for (size_t i = 0, n = partial.size(); i < n; i++) { if (partial[i] == 0) { partial[i] = complete[i]+1; } } return partial; } tensorshape padd(std::vector<size_t> shapelist, size_t nfront, size_t nback) { std::vector<size_t> out(nfront, 1); out.insert(out.end(), shapelist.begin(), shapelist.end()); out.insert(out.end(), nback, 1); return tensorshape(out); } std::vector<std::vector<double> > doubleDArr(std::vector<double> v, std::vector<size_t> dimensions) { assert(dimensions.size() == 2); size_t cols = dimensions[0]; size_t rows = dimensions[1]; std::vector<std::vector<double> > mat(rows); auto it = v.begin(); for (size_t i = 0; i < rows; i++) { mat[i].insert(mat[i].end(), it, it+cols); it+=cols; } return mat; } tensorshape random_shape (void) { size_t scalar = FUZZ::getInt(1, "scalar", {2, 10})[0]; std::vector<size_t> shape = FUZZ::getInt(scalar, "shape", {0, 21}); return tensorshape(shape); } tensorshape random_def_shape (int lowerrank, int upperrank, size_t minn, size_t maxn) { size_t rank; if (lowerrank == upperrank) { rank = lowerrank; } else { rank = FUZZ::getInt(1, "rank", {lowerrank, upperrank})[0]; } size_t maxvalue = 0; size_t minvalue = 0; for (size_t i = maxn; maxn > 0; maxn /= rank) { maxvalue++; } for (size_t i = minn; minn > 0; minn /= rank) { minvalue++; } // we don't care if minvalue overapproximates size_t realmaxn = std::pow((double)maxvalue, (double)rank); size_t error = realmaxn > maxn ? realmaxn - maxn : maxn - realmaxn; size_t ncorrection = 0; for (; error > 0; error /= maxvalue) { ncorrection++; } std::vector<size_t> shape = FUZZ::getInt(rank, "shape", {minvalue, maxvalue}); for (size_t i = 0; i < ncorrection && i < rank; i++) { size_t shapeidx = rank-i-1; if (shape[shapeidx] > 1) { shape[shapeidx]++; } else { ncorrection++; } } return tensorshape(shape); } #endif <commit_msg>generated def shape is guaranteed to never exceed 10000 given param<commit_after>// // Created by Mingkai Chen on 2017-03-10. // #include "util_test.h" #include "fuzz.h" #ifdef UTIL_TEST_H bool tensorshape_equal ( const tensorshape& ts1, const tensorshape& ts2) { std::vector<size_t> vs = ts1.as_list(); std::vector<size_t> vs2 = ts2.as_list(); if (vs.size() != vs2.size()) return false; return std::equal(vs.begin(), vs.end(), vs2.begin()); } bool tensorshape_equal ( const tensorshape& ts1, std::vector<size_t>& ts2) { std::vector<size_t> vs = ts1.as_list(); if (vs.size() != ts2.size()) return false; return std::equal(vs.begin(), vs.end(), ts2.begin()); } void print (std::vector<double> raw) { for (double r : raw) { std::cout << r << " "; } std::cout << "\n"; } tensorshape make_partial (std::vector<size_t> shapelist) { size_t nzeros = 1; if (shapelist.size() > 2) { nzeros = FUZZ::getInt(1, "nzeros", {1, shapelist.size()-1})[0]; } else if (shapelist.size() == 1) { shapelist.push_back(0); return shapelist; } std::vector<size_t> zeros = FUZZ::getInt(nzeros, "zeros", {0, shapelist.size()-1}); for (size_t zidx : zeros) { shapelist[zidx] = 0; } return tensorshape(shapelist); } tensorshape make_incompatible (std::vector<size_t> shapelist) { for (size_t i = 0; i < shapelist.size(); i++) { shapelist[i]++; } return tensorshape(shapelist); } // make partial full, but incompatible to comp tensorshape make_full_incomp (std::vector<size_t> partial, std::vector<size_t> complete) { assert(partial.size() == complete.size()); for (size_t i = 0, n = partial.size(); i < n; i++) { if (partial[i] == 0) { partial[i] = complete[i]+1; } } return partial; } tensorshape padd(std::vector<size_t> shapelist, size_t nfront, size_t nback) { std::vector<size_t> out(nfront, 1); out.insert(out.end(), shapelist.begin(), shapelist.end()); out.insert(out.end(), nback, 1); return tensorshape(out); } std::vector<std::vector<double> > doubleDArr(std::vector<double> v, std::vector<size_t> dimensions) { assert(dimensions.size() == 2); size_t cols = dimensions[0]; size_t rows = dimensions[1]; std::vector<std::vector<double> > mat(rows); auto it = v.begin(); for (size_t i = 0; i < rows; i++) { mat[i].insert(mat[i].end(), it, it+cols); it+=cols; } return mat; } tensorshape random_shape (void) { size_t scalar = FUZZ::getInt(1, "scalar", {2, 10})[0]; std::vector<size_t> shape = FUZZ::getInt(scalar, "shape", {0, 21}); return tensorshape(shape); } tensorshape random_def_shape (int lowerrank, int upperrank, size_t minn, size_t maxn) { size_t rank = lowerrank; if (lowerrank != upperrank) { rank = FUZZ::getInt(1, "rank", {lowerrank, upperrank})[0]; } assert(rank > 0); if (rank < 2) { return FUZZ::getInt(1, "shape", {minn, maxn}); } // invariant: rank > 1 size_t maxvalue = 0; size_t minvalue = 0; size_t lowercut = 0; if (rank > 5) lowercut = 1; for (size_t i = maxn; i > lowercut; i /= rank) { maxvalue++; } for (size_t i = minn; i > lowercut; i /= rank) { minvalue++; } // we don't care if minvalue overapproximates size_t ncorrection = 0; size_t realmaxn = std::pow((double)maxvalue, (double)rank); if (realmaxn > maxn) { size_t error = realmaxn - maxn; for (; error > 0; error /= maxvalue) { ncorrection++; } } std::vector<size_t> shape; if (ncorrection == rank) { for (size_t i = 0; i < rank; i++) { std::stringstream ss; ss << "shape i=" << i; size_t shapei = maxvalue; if (minvalue != maxvalue) { shapei = FUZZ::getInt(1, ss.str(), {minvalue, maxvalue})[0]; } shape.push_back(shapei); maxn /= shapei; if (maxn < maxvalue) { break; // stop early } } } else { std::vector<size_t> shape2; if (rank-ncorrection) { shape = FUZZ::getInt(rank-ncorrection, "shapepart1", {minvalue, maxvalue}); } if (ncorrection) { shape2 = FUZZ::getInt(ncorrection, "shapepart2", {minvalue, maxvalue-1}); } shape.insert(shape.end(), shape2.begin(), shape2.end()); } tensorshape outshape(shape); if (outshape.n_elems() > 10000) { // warn } return outshape; } #endif <|endoftext|>
<commit_before>#ifndef _SDD_MEM_PTR_HH_ #define _SDD_MEM_PTR_HH_ #include <cassert> #include <functional> // hash, function #include <type_traits> // remove_const #include "sdd/mem/unique_table.hh" namespace sdd { namespace mem { /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief Define the type of a deletion handler. /// /// A deletion handler is called by ptr whenever a data is no longer referenced. template <typename Unique> using handler_type = std::function<void (const Unique&)>; /// @internal /// @brief Get the deletion handler for a given Unique type. template <typename Unique> handler_type<Unique>& deletion_handler() { static handler_type<Unique> handler = [](const Unique&){assert(false && "Unset handler");}; return handler; } /// @internal /// @brief Get the deletion handler for a given Unique type. template <typename Unique> void reset_deletion_handler() { deletion_handler<Unique>() = [](const Unique&){assert(false && "Reset handler");}; } /// @internal /// @brief Set the deletion handler for a given Unique type. template <typename Unique> void set_deletion_handler(const handler_type<Unique>& h) { deletion_handler<Unique>() = h; } /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief A smart pointer to manage unified ressources. /// @tparam Unique the type of the unified ressource. /// /// Unified ressources are ref_counted elements constructed with an unique_table. template <typename Unique> class ptr { // Can't default construct a ptr. ptr() = delete; private: /// @brief Pointer to the managed ressource, a unified data. const Unique* x_; public: /// @brief Constructor with a unified data. explicit ptr(const Unique& p) noexcept : x_(&p) { x_->increment_reference_counter(); } /// @brief Copy constructor. ptr(const ptr& other) noexcept : x_(other.x_) { x_->increment_reference_counter(); } /// @brief Copy operator. ptr& operator=(const ptr& other) noexcept { other.x_->increment_reference_counter(); x_->decrement_reference_counter(); erase_if_necessary(x_); x_ = other.x_; return *this; } /// @brief Destructor. ~ptr() { x_->decrement_reference_counter(); erase_if_necessary(x_); } /// @brief Get a reference to the unified data. const Unique& operator*() const noexcept { return *x_; } /// @brief Get a pointer to the unified data. const Unique* operator->() const noexcept { return x_; } /// @brief Swap. friend void swap(ptr& lhs, ptr& rhs) noexcept { using std::swap; swap(lhs.x_, rhs.x_); } private: /// @brief If the managed data is no longer referenced, erase it. static void erase_if_necessary(const Unique* x) noexcept { static void* table[2] = {&&noop, &&erase}; goto *table[x->is_not_referenced()]; erase: deletion_handler<Unique>()(*x); noop:; } }; /*------------------------------------------------------------------------------------------------*/ /// @internal /// @related ptr /// /// O(1). template <typename Unique> inline bool operator==(const ptr<Unique>& lhs, const ptr<Unique>& rhs) noexcept { return lhs.operator->() == rhs.operator->(); } /// @internal /// @related ptr /// /// O(1). template <typename Unique> inline bool operator<(const ptr<Unique>& lhs, const ptr<Unique>& rhs) noexcept { return lhs.operator->() < rhs.operator->(); } /*------------------------------------------------------------------------------------------------*/ }} // namespace sdd::mem namespace std { /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief Hash specialization for sdd::mem::ptr template <typename Unique> struct hash<sdd::mem::ptr<Unique>> { std::size_t operator()(const sdd::mem::ptr<Unique>& x) const noexcept { return std::hash<decltype(x.operator->())>()(x.operator->()); } }; /*------------------------------------------------------------------------------------------------*/ } // namespace std #endif // _SDD_MEM_PTR_HH_ <commit_msg>Documentation.<commit_after>#ifndef _SDD_MEM_PTR_HH_ #define _SDD_MEM_PTR_HH_ #include <cassert> #include <functional> // hash, function #include <type_traits> // remove_const #include "sdd/mem/unique_table.hh" namespace sdd { namespace mem { /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief Define the type of a deletion handler. /// /// A deletion handler is called by ptr whenever a data is no longer referenced. template <typename Unique> using handler_type = std::function<void (const Unique&)>; /// @internal /// @brief Get the deletion handler for a given Unique type. template <typename Unique> handler_type<Unique>& deletion_handler() { static handler_type<Unique> handler = [](const Unique&){assert(false && "Unset handler");}; return handler; } /// @internal /// @brief Reset the deletion handler for a given Unique type. template <typename Unique> void reset_deletion_handler() { deletion_handler<Unique>() = [](const Unique&){assert(false && "Reset handler");}; } /// @internal /// @brief Set the deletion handler for a given Unique type. template <typename Unique> void set_deletion_handler(const handler_type<Unique>& h) { deletion_handler<Unique>() = h; } /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief A smart pointer to manage unified ressources. /// @tparam Unique the type of the unified ressource. /// /// Unified ressources are ref_counted elements constructed with an unique_table. template <typename Unique> class ptr { // Can't default construct a ptr. ptr() = delete; private: /// @brief Pointer to the managed ressource, a unified data. const Unique* x_; public: /// @brief Constructor with a unified data. explicit ptr(const Unique& p) noexcept : x_(&p) { x_->increment_reference_counter(); } /// @brief Copy constructor. ptr(const ptr& other) noexcept : x_(other.x_) { x_->increment_reference_counter(); } /// @brief Copy operator. ptr& operator=(const ptr& other) noexcept { other.x_->increment_reference_counter(); x_->decrement_reference_counter(); erase_if_necessary(x_); x_ = other.x_; return *this; } /// @brief Destructor. ~ptr() { x_->decrement_reference_counter(); erase_if_necessary(x_); } /// @brief Get a reference to the unified data. const Unique& operator*() const noexcept { return *x_; } /// @brief Get a pointer to the unified data. const Unique* operator->() const noexcept { return x_; } /// @brief Swap. friend void swap(ptr& lhs, ptr& rhs) noexcept { using std::swap; swap(lhs.x_, rhs.x_); } private: /// @brief If the managed data is no longer referenced, erase it. static void erase_if_necessary(const Unique* x) noexcept { static void* table[2] = {&&noop, &&erase}; goto *table[x->is_not_referenced()]; erase: deletion_handler<Unique>()(*x); noop:; } }; /*------------------------------------------------------------------------------------------------*/ /// @internal /// @related ptr /// /// O(1). template <typename Unique> inline bool operator==(const ptr<Unique>& lhs, const ptr<Unique>& rhs) noexcept { return lhs.operator->() == rhs.operator->(); } /// @internal /// @related ptr /// /// O(1). template <typename Unique> inline bool operator<(const ptr<Unique>& lhs, const ptr<Unique>& rhs) noexcept { return lhs.operator->() < rhs.operator->(); } /*------------------------------------------------------------------------------------------------*/ }} // namespace sdd::mem namespace std { /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief Hash specialization for sdd::mem::ptr template <typename Unique> struct hash<sdd::mem::ptr<Unique>> { std::size_t operator()(const sdd::mem::ptr<Unique>& x) const noexcept { return std::hash<decltype(x.operator->())>()(x.operator->()); } }; /*------------------------------------------------------------------------------------------------*/ } // namespace std #endif // _SDD_MEM_PTR_HH_ <|endoftext|>
<commit_before>#include "GeoCoordinate.hpp" #include "entities/Element.hpp" #include "entities/Node.hpp" #include "entities/Way.hpp" #include "entities/Area.hpp" #include "entities/Relation.hpp" #include "index/ElementStore.hpp" #include "mapcss/StyleProvider.hpp" #include "test_utils/ElementUtils.hpp" #include "test_utils/MapCssUtils.hpp" #include <boost/test/unit_test.hpp> #include <functional> #include <initializer_list> #include <utility> using namespace utymap::entities; using namespace utymap::index; using namespace utymap::mapcss; typedef std::function<void(const Element&, const utymap::QuadKey&)> StoreCallback; class TestElementStore : public ElementStore { public: int times; TestElementStore(const StyleProvider& styleProvider, StringTable& stringTable, StoreCallback function) : ElementStore(styleProvider, stringTable), function_(function), times(0) { } protected: void storeImpl(const Element& element, const utymap::QuadKey& quadKey) { times++; function_(element, quadKey); } private: StoreCallback function_; }; struct Index_ElementStoreFixture { Index_ElementStoreFixture() : stringTablePtr(new StringTable("")), styleProviderPtr(nullptr), elementStorePtr() { BOOST_TEST_MESSAGE("setup fixture"); } ~Index_ElementStoreFixture() { BOOST_TEST_MESSAGE("teardown fixture"); BOOST_TEST_CHECK(elementStorePtr->times > 0); delete elementStorePtr; delete styleProviderPtr; delete stringTablePtr; std::remove("string.idx"); std::remove("string.dat"); } void createElementStore(std::string stylesheet, const StoreCallback callback) { styleProviderPtr = MapCssUtils::createStyleProviderFromString(*stringTablePtr, stylesheet); elementStorePtr = new TestElementStore(*styleProviderPtr, *stringTablePtr, callback); } StringTable* stringTablePtr; StyleProvider* styleProviderPtr; TestElementStore* elementStorePtr; }; bool checkQuadKey(const utymap::QuadKey& quadKey, int lod, int tileX, int tileY) { return quadKey.levelOfDetail == lod && quadKey.tileX == tileX && quadKey.tileY == tileY; } template<typename T> void checkGeometry(const T& t, std::initializer_list<std::pair<double, double>> geometry) { BOOST_CHECK_EQUAL(t.coordinates.size(), geometry.size()); int i = 0; for (const auto& pair : geometry) { BOOST_CHECK_EQUAL(pair.first, t.coordinates[i].latitude); BOOST_CHECK_EQUAL(pair.second, t.coordinates[i].longitude); i++; } } BOOST_FIXTURE_TEST_SUITE(Index_ElementStore, Index_ElementStoreFixture) BOOST_AUTO_TEST_CASE(GivenWayIntersectsTwoTilesOnce_WhenStore_GeometryIsClipped) { Way way = ElementUtils::createElement<Way>(*stringTablePtr, { { "test", "Foo" } }, { { 10, 10 }, { 10, -10 }}); createElementStore("way|z1[test=Foo] { key:val; clip: true;}", [&](const Element& element, const utymap::QuadKey& quadKey) { if (checkQuadKey(quadKey, 1, 0, 0)) { checkGeometry<Way>(reinterpret_cast<const Way&>(element), { { 10, -10 }, { 10, 0 } }); } else if (checkQuadKey(quadKey, 1, 1, 0)) { checkGeometry<Way>(reinterpret_cast<const Way&>(element), { { 10, 0 }, { 10, 10 } }); } else { BOOST_TEST_FAIL("Unexpected quadKey!"); } }); elementStorePtr->store(way, LodRange(1,1)); BOOST_CHECK_EQUAL(elementStorePtr->times, 2); } BOOST_AUTO_TEST_CASE(GivenWayIntersectsTwoTilesTwice_WhenStore_GeometryIsClipped) { Way way = ElementUtils::createElement<Way>(*stringTablePtr, { { "test", "Foo" } }, { { 10, 10 }, { 10, -10 }, { 20, -10 }, {20, 10} }); createElementStore("way|z1[test=Foo] { key:val; clip: true;}", [&](const Element& element, const utymap::QuadKey& quadKey) { if (checkQuadKey(quadKey, 1, 0, 0)) { checkGeometry<Way>(reinterpret_cast<const Way&>(element), { { 20, 0 }, { 20, -10 }, { 10, -10 }, {10, 0} }); } else if (checkQuadKey(quadKey, 1, 1, 0)) { const Relation& relation = reinterpret_cast<const Relation&>(element); BOOST_CHECK_EQUAL(relation.elements.size(), 2); checkGeometry<Way>(reinterpret_cast<const Way&>(*relation.elements[0]), { { 20, 10 }, { 20, 0 } }); checkGeometry<Way>(reinterpret_cast<const Way&>(*relation.elements[1]), { { 10, 0 }, { 10, 10 } }); } else { BOOST_TEST_FAIL("Unexpected quadKey!"); } }); elementStorePtr->store(way, LodRange(1, 1)); BOOST_CHECK_EQUAL(elementStorePtr->times, 2); } BOOST_AUTO_TEST_CASE(GivenAreaIntersectsTwoTilesOnce_WhenStore_GeometryIsClipped) { Area way = ElementUtils::createElement<Area>(*stringTablePtr, { { "test", "Foo" } }, { { 10, 10 }, { 20, 10 }, { 20, -10 }, { 10, -10 } }); createElementStore("area|z1[test=Foo] { key:val; clip: true;}", [&](const Element& element, const utymap::QuadKey& quadKey) { if (checkQuadKey(quadKey, 1, 0, 0)) { checkGeometry<Area>(reinterpret_cast<const Area&>(element), { { 20, 0 }, { 20, -10 }, {10, -10}, {10, 0} }); } else if (checkQuadKey(quadKey, 1, 1, 0)) { checkGeometry<Area>(reinterpret_cast<const Area&>(element), { { 20, 10 }, { 20, 0 }, { 10, 0 }, { 10, 10 } }); } else { BOOST_TEST_FAIL("Unexpected quadKey!"); } }); elementStorePtr->store(way, LodRange(1, 1)); BOOST_CHECK_EQUAL(elementStorePtr->times, 2); } BOOST_AUTO_TEST_CASE(GivenAreaIntersectsTwoTilesTwice_WhenStore_GeometryIsClipped) { Area way = ElementUtils::createElement<Area>(*stringTablePtr, { { "test", "Foo" } }, { { 20, 10 }, { 20, -10 }, { 5, -10 }, { 5, 10 }, { 10, 10 }, { 10, -5 }, { 15, -5 }, { 15, 10 } }); createElementStore("area|z1[test=Foo] { key:val; clip: true;}", [&](const Element& element, const utymap::QuadKey& quadKey) { if (checkQuadKey(quadKey, 1, 0, 0)) { checkGeometry<Area>(reinterpret_cast<const Area&>(element), { { 10, 0 }, { 10, -5 }, { 15, -5 }, { 15, 0 }, { 20, 0 }, { 20, -10 }, { 5, -10 }, { 5, 0 } }); } else if (checkQuadKey(quadKey, 1, 1, 0)) { const Relation& relation = reinterpret_cast<const Relation&>(element); BOOST_CHECK_EQUAL(relation.elements.size(), 2); checkGeometry<Area>(reinterpret_cast<const Area&>(*relation.elements[0]), { { 15, 10 }, { 20, 10 }, { 20, 0 }, {15, 0} }); checkGeometry<Area>(reinterpret_cast<const Area&>(*relation.elements[1]), { { 10, 10 }, { 10, 0 }, { 5, 0 }, { 5, 10 } }); } else { BOOST_TEST_FAIL("Unexpected quadKey!"); } }); elementStorePtr->store(way, LodRange(1, 1)); BOOST_CHECK_EQUAL(elementStorePtr->times, 2); } BOOST_AUTO_TEST_CASE(GivenAreaBiggerThanTile_WhenStore_GeometryIsEmpty) { Area way = ElementUtils::createElement<Area>(*stringTablePtr, { { "test", "Foo" } }, { { -10, -10 }, { -10, 181 }, { 91, 181 }, { 91, -10 } }); createElementStore("area|z1[test=Foo] { key:val; clip: true;}", [&](const Element& element, const utymap::QuadKey& quadKey) { if (checkQuadKey(quadKey, 1, 1, 0)) { BOOST_CHECK_EQUAL(reinterpret_cast<const Area&>(element).coordinates.size(), 0); } }); elementStorePtr->store(way, LodRange(1, 1)); BOOST_CHECK_EQUAL(elementStorePtr->times, 4); } BOOST_AUTO_TEST_CASE(GivenRelationOfPolygonWithHole_WhenStore_AreaIsReturnedWithClippedGeometry) { Area outer = ElementUtils::createElement<Area>(*stringTablePtr, {}, { { 5, 10 }, { 20, 10 }, { 20, -10 }, {5, -10} }); Area inner = ElementUtils::createElement<Area>(*stringTablePtr, {}, { { 10, 5 }, { 15, 5 }, { 15, -5 }, { 10, -5 } }); Relation relation; relation.tags = std::vector<Tag>{ ElementUtils::createTag(*stringTablePtr, "test", "Foo") }; relation.elements.push_back(std::shared_ptr<Area>(new Area(inner))); relation.elements.push_back(std::shared_ptr<Area>(new Area(outer))); createElementStore("relation|z1[test=Foo] { key:val; clip: true;}", [&](const Element& element, const utymap::QuadKey& quadKey) { if (checkQuadKey(quadKey, 1, 1, 0)) { checkGeometry<Area>(reinterpret_cast<const Area&>(element), { { 20, 10 }, { 20, 0 }, { 15, 0 }, { 15, 5 }, { 10, 5 }, { 10, 0 }, { 5, 0 }, {5, 10} }); } else if(checkQuadKey(quadKey, 1, 0, 0)) { checkGeometry<Area>(reinterpret_cast<const Area&>(element), { { 10, 0 }, { 10, -5 }, { 15, -5 }, { 15, 0 }, { 20, 0 }, { 20, -10 }, { 5, -10 }, { 5, 0 } }); } else { BOOST_TEST_FAIL("Unexpected quadKey!"); } }); elementStorePtr->store(relation, LodRange(1, 1)); BOOST_CHECK_EQUAL(elementStorePtr->times, 2); } BOOST_AUTO_TEST_CASE(GivenRelationOfPolygonWithHole_WhenStore_RelationIsReturnedWithClippedGeometry) { Area outer = ElementUtils::createElement<Area>(*stringTablePtr, {}, { { 5, 10 }, { 20, 10 }, { 20, -10 }, { 5, -10 } }); Area inner = ElementUtils::createElement<Area>(*stringTablePtr, {}, { { 10, 8 }, { 15, 8 }, { 15, 2 }, { 10, 2 } }); Relation relation; relation.tags = std::vector<Tag>{ ElementUtils::createTag(*stringTablePtr, "test", "Foo") }; relation.elements.push_back(std::shared_ptr<Area>(new Area(inner))); relation.elements.push_back(std::shared_ptr<Area>(new Area(outer))); createElementStore("relation|z1[test=Foo] { key:val; clip: true;}", [&](const Element& element, const utymap::QuadKey& quadKey) { if (checkQuadKey(quadKey, 1, 1, 0)) { const Relation& relation = reinterpret_cast<const Relation&>(element); BOOST_CHECK_EQUAL(relation.elements.size(), 2); checkGeometry<Area>(reinterpret_cast<const Area&>(*relation.elements[0]), { { 20, 10 }, { 20, 0 }, { 5, 0 }, { 5, 10 } }); checkGeometry<Area>(reinterpret_cast<const Area&>(*relation.elements[1]), { { 10, 2 }, { 15, 2 }, { 15, 8 }, { 10, 8 } }); } else if (checkQuadKey(quadKey, 1, 0, 0)) { checkGeometry<Area>(reinterpret_cast<const Area&>(element), { { 20, 0 }, { 20, -10 }, { 5, -10 }, { 5, 0 } }); } else { BOOST_TEST_FAIL("Unexpected quadKey!"); } }); elementStorePtr->store(relation, LodRange(1, 1)); BOOST_CHECK_EQUAL(elementStorePtr->times, 2); } BOOST_AUTO_TEST_SUITE_END()<commit_msg>index: add unit test for way outside tile<commit_after>#include "GeoCoordinate.hpp" #include "entities/Element.hpp" #include "entities/Node.hpp" #include "entities/Way.hpp" #include "entities/Area.hpp" #include "entities/Relation.hpp" #include "index/ElementStore.hpp" #include "mapcss/StyleProvider.hpp" #include "test_utils/ElementUtils.hpp" #include "test_utils/MapCssUtils.hpp" #include <boost/test/unit_test.hpp> #include <functional> #include <initializer_list> #include <utility> using namespace utymap::entities; using namespace utymap::index; using namespace utymap::mapcss; typedef std::function<void(const Element&, const utymap::QuadKey&)> StoreCallback; class TestElementStore : public ElementStore { public: int times; TestElementStore(const StyleProvider& styleProvider, StringTable& stringTable, StoreCallback function) : ElementStore(styleProvider, stringTable), function_(function), times(0) { } protected: void storeImpl(const Element& element, const utymap::QuadKey& quadKey) { times++; function_(element, quadKey); } private: StoreCallback function_; }; struct Index_ElementStoreFixture { Index_ElementStoreFixture() : stringTablePtr(new StringTable("")), styleProviderPtr(nullptr), elementStorePtr() { BOOST_TEST_MESSAGE("setup fixture"); } ~Index_ElementStoreFixture() { BOOST_TEST_MESSAGE("teardown fixture"); BOOST_TEST_CHECK(elementStorePtr->times > 0); delete elementStorePtr; delete styleProviderPtr; delete stringTablePtr; std::remove("string.idx"); std::remove("string.dat"); } void createElementStore(std::string stylesheet, const StoreCallback callback) { styleProviderPtr = MapCssUtils::createStyleProviderFromString(*stringTablePtr, stylesheet); elementStorePtr = new TestElementStore(*styleProviderPtr, *stringTablePtr, callback); } StringTable* stringTablePtr; StyleProvider* styleProviderPtr; TestElementStore* elementStorePtr; }; bool checkQuadKey(const utymap::QuadKey& quadKey, int lod, int tileX, int tileY) { return quadKey.levelOfDetail == lod && quadKey.tileX == tileX && quadKey.tileY == tileY; } template<typename T> void checkGeometry(const T& t, std::initializer_list<std::pair<double, double>> geometry) { BOOST_CHECK_EQUAL(t.coordinates.size(), geometry.size()); int i = 0; for (const auto& pair : geometry) { BOOST_CHECK_EQUAL(pair.first, t.coordinates[i].latitude); BOOST_CHECK_EQUAL(pair.second, t.coordinates[i].longitude); i++; } } BOOST_FIXTURE_TEST_SUITE(Index_ElementStore, Index_ElementStoreFixture) BOOST_AUTO_TEST_CASE(GivenWayIntersectsTwoTilesOnce_WhenStore_GeometryIsClipped) { Way way = ElementUtils::createElement<Way>(*stringTablePtr, { { "test", "Foo" } }, { { 10, 10 }, { 10, -10 }}); createElementStore("way|z1[test=Foo] { key:val; clip: true;}", [&](const Element& element, const utymap::QuadKey& quadKey) { if (checkQuadKey(quadKey, 1, 0, 0)) { checkGeometry<Way>(reinterpret_cast<const Way&>(element), { { 10, -10 }, { 10, 0 } }); } else if (checkQuadKey(quadKey, 1, 1, 0)) { checkGeometry<Way>(reinterpret_cast<const Way&>(element), { { 10, 0 }, { 10, 10 } }); } else { BOOST_TEST_FAIL("Unexpected quadKey!"); } }); elementStorePtr->store(way, LodRange(1,1)); BOOST_CHECK_EQUAL(elementStorePtr->times, 2); } BOOST_AUTO_TEST_CASE(GivenWayIntersectsTwoTilesTwice_WhenStore_GeometryIsClipped) { Way way = ElementUtils::createElement<Way>(*stringTablePtr, { { "test", "Foo" } }, { { 10, 10 }, { 10, -10 }, { 20, -10 }, {20, 10} }); createElementStore("way|z1[test=Foo] { key:val; clip: true;}", [&](const Element& element, const utymap::QuadKey& quadKey) { if (checkQuadKey(quadKey, 1, 0, 0)) { checkGeometry<Way>(reinterpret_cast<const Way&>(element), { { 20, 0 }, { 20, -10 }, { 10, -10 }, {10, 0} }); } else if (checkQuadKey(quadKey, 1, 1, 0)) { const Relation& relation = reinterpret_cast<const Relation&>(element); BOOST_CHECK_EQUAL(relation.elements.size(), 2); checkGeometry<Way>(reinterpret_cast<const Way&>(*relation.elements[0]), { { 20, 10 }, { 20, 0 } }); checkGeometry<Way>(reinterpret_cast<const Way&>(*relation.elements[1]), { { 10, 0 }, { 10, 10 } }); } else { BOOST_TEST_FAIL("Unexpected quadKey!"); } }); elementStorePtr->store(way, LodRange(1, 1)); BOOST_CHECK_EQUAL(elementStorePtr->times, 2); } BOOST_AUTO_TEST_CASE(GivenWayOutsideTileWithBoundingBoxIntersectingTile_WhenStore_IsSkipped) { Way way = ElementUtils::createElement<Way>(*stringTablePtr, { { "test", "Foo" } }, { { -10, 20 }, { -5, -10 }, { 10, -10 } }); createElementStore("way|z1[test=Foo] { key:val; clip: true;}", [&](const Element& element, const utymap::QuadKey& quadKey) { if (checkQuadKey(quadKey, 1, 1, 1) || checkQuadKey(quadKey, 1, 0, 0) || checkQuadKey(quadKey, 1, 0, 1)) { BOOST_CHECK(reinterpret_cast<const Way&>(element).coordinates.size() > 0); } else if (checkQuadKey(quadKey, 1, 1, 0)) { BOOST_TEST_FAIL("This quadkey should be skipped!!"); } else { BOOST_TEST_FAIL("Unexpected quadKey!"); } }); elementStorePtr->store(way, LodRange(1, 1)); BOOST_CHECK_EQUAL(elementStorePtr->times, 3); } BOOST_AUTO_TEST_CASE(GivenAreaIntersectsTwoTilesOnce_WhenStore_GeometryIsClipped) { Area way = ElementUtils::createElement<Area>(*stringTablePtr, { { "test", "Foo" } }, { { 10, 10 }, { 20, 10 }, { 20, -10 }, { 10, -10 } }); createElementStore("area|z1[test=Foo] { key:val; clip: true;}", [&](const Element& element, const utymap::QuadKey& quadKey) { if (checkQuadKey(quadKey, 1, 0, 0)) { checkGeometry<Area>(reinterpret_cast<const Area&>(element), { { 20, 0 }, { 20, -10 }, {10, -10}, {10, 0} }); } else if (checkQuadKey(quadKey, 1, 1, 0)) { checkGeometry<Area>(reinterpret_cast<const Area&>(element), { { 20, 10 }, { 20, 0 }, { 10, 0 }, { 10, 10 } }); } else { BOOST_TEST_FAIL("Unexpected quadKey!"); } }); elementStorePtr->store(way, LodRange(1, 1)); BOOST_CHECK_EQUAL(elementStorePtr->times, 2); } BOOST_AUTO_TEST_CASE(GivenAreaIntersectsTwoTilesTwice_WhenStore_GeometryIsClipped) { Area way = ElementUtils::createElement<Area>(*stringTablePtr, { { "test", "Foo" } }, { { 20, 10 }, { 20, -10 }, { 5, -10 }, { 5, 10 }, { 10, 10 }, { 10, -5 }, { 15, -5 }, { 15, 10 } }); createElementStore("area|z1[test=Foo] { key:val; clip: true;}", [&](const Element& element, const utymap::QuadKey& quadKey) { if (checkQuadKey(quadKey, 1, 0, 0)) { checkGeometry<Area>(reinterpret_cast<const Area&>(element), { { 10, 0 }, { 10, -5 }, { 15, -5 }, { 15, 0 }, { 20, 0 }, { 20, -10 }, { 5, -10 }, { 5, 0 } }); } else if (checkQuadKey(quadKey, 1, 1, 0)) { const Relation& relation = reinterpret_cast<const Relation&>(element); BOOST_CHECK_EQUAL(relation.elements.size(), 2); checkGeometry<Area>(reinterpret_cast<const Area&>(*relation.elements[0]), { { 15, 10 }, { 20, 10 }, { 20, 0 }, {15, 0} }); checkGeometry<Area>(reinterpret_cast<const Area&>(*relation.elements[1]), { { 10, 10 }, { 10, 0 }, { 5, 0 }, { 5, 10 } }); } else { BOOST_TEST_FAIL("Unexpected quadKey!"); } }); elementStorePtr->store(way, LodRange(1, 1)); BOOST_CHECK_EQUAL(elementStorePtr->times, 2); } BOOST_AUTO_TEST_CASE(GivenAreaBiggerThanTile_WhenStore_GeometryIsEmpty) { Area way = ElementUtils::createElement<Area>(*stringTablePtr, { { "test", "Foo" } }, { { -10, -10 }, { -10, 181 }, { 91, 181 }, { 91, -10 } }); createElementStore("area|z1[test=Foo] { key:val; clip: true;}", [&](const Element& element, const utymap::QuadKey& quadKey) { if (checkQuadKey(quadKey, 1, 1, 0)) { BOOST_CHECK_EQUAL(reinterpret_cast<const Area&>(element).coordinates.size(), 0); } }); elementStorePtr->store(way, LodRange(1, 1)); BOOST_CHECK_EQUAL(elementStorePtr->times, 4); } BOOST_AUTO_TEST_CASE(GivenRelationOfPolygonWithHole_WhenStore_AreaIsReturnedWithClippedGeometry) { Area outer = ElementUtils::createElement<Area>(*stringTablePtr, {}, { { 5, 10 }, { 20, 10 }, { 20, -10 }, {5, -10} }); Area inner = ElementUtils::createElement<Area>(*stringTablePtr, {}, { { 10, 5 }, { 15, 5 }, { 15, -5 }, { 10, -5 } }); Relation relation; relation.tags = std::vector<Tag>{ ElementUtils::createTag(*stringTablePtr, "test", "Foo") }; relation.elements.push_back(std::shared_ptr<Area>(new Area(inner))); relation.elements.push_back(std::shared_ptr<Area>(new Area(outer))); createElementStore("relation|z1[test=Foo] { key:val; clip: true;}", [&](const Element& element, const utymap::QuadKey& quadKey) { if (checkQuadKey(quadKey, 1, 1, 0)) { checkGeometry<Area>(reinterpret_cast<const Area&>(element), { { 20, 10 }, { 20, 0 }, { 15, 0 }, { 15, 5 }, { 10, 5 }, { 10, 0 }, { 5, 0 }, {5, 10} }); } else if(checkQuadKey(quadKey, 1, 0, 0)) { checkGeometry<Area>(reinterpret_cast<const Area&>(element), { { 10, 0 }, { 10, -5 }, { 15, -5 }, { 15, 0 }, { 20, 0 }, { 20, -10 }, { 5, -10 }, { 5, 0 } }); } else { BOOST_TEST_FAIL("Unexpected quadKey!"); } }); elementStorePtr->store(relation, LodRange(1, 1)); BOOST_CHECK_EQUAL(elementStorePtr->times, 2); } BOOST_AUTO_TEST_CASE(GivenRelationOfPolygonWithHole_WhenStore_RelationIsReturnedWithClippedGeometry) { Area outer = ElementUtils::createElement<Area>(*stringTablePtr, {}, { { 5, 10 }, { 20, 10 }, { 20, -10 }, { 5, -10 } }); Area inner = ElementUtils::createElement<Area>(*stringTablePtr, {}, { { 10, 8 }, { 15, 8 }, { 15, 2 }, { 10, 2 } }); Relation relation; relation.tags = std::vector<Tag>{ ElementUtils::createTag(*stringTablePtr, "test", "Foo") }; relation.elements.push_back(std::shared_ptr<Area>(new Area(inner))); relation.elements.push_back(std::shared_ptr<Area>(new Area(outer))); createElementStore("relation|z1[test=Foo] { key:val; clip: true;}", [&](const Element& element, const utymap::QuadKey& quadKey) { if (checkQuadKey(quadKey, 1, 1, 0)) { const Relation& relation = reinterpret_cast<const Relation&>(element); BOOST_CHECK_EQUAL(relation.elements.size(), 2); checkGeometry<Area>(reinterpret_cast<const Area&>(*relation.elements[0]), { { 20, 10 }, { 20, 0 }, { 5, 0 }, { 5, 10 } }); checkGeometry<Area>(reinterpret_cast<const Area&>(*relation.elements[1]), { { 10, 2 }, { 15, 2 }, { 15, 8 }, { 10, 8 } }); } else if (checkQuadKey(quadKey, 1, 0, 0)) { checkGeometry<Area>(reinterpret_cast<const Area&>(element), { { 20, 0 }, { 20, -10 }, { 5, -10 }, { 5, 0 } }); } else { BOOST_TEST_FAIL("Unexpected quadKey!"); } }); elementStorePtr->store(relation, LodRange(1, 1)); BOOST_CHECK_EQUAL(elementStorePtr->times, 2); } BOOST_AUTO_TEST_SUITE_END()<|endoftext|>
<commit_before>#include "test-helpers.h" #include <sstream> #include "text-buffer.h" #include "text-slice.h" using std::move; using std::string; using std::stringstream; TEST_CASE("TextBuffer::build - can build a TextBuffer from a UTF8 stream") { string input = "abγdefg\nhijklmnop"; stringstream stream(input, std::ios_base::in); vector<size_t> progress_reports; TextBuffer buffer = TextBuffer::build(stream, input.size(), "UTF8", 3, [&](size_t percent_done) { progress_reports.push_back(percent_done); }); auto text = buffer.text(); REQUIRE(buffer.text() == Text {u"abγdefg\nhijklmnop"}); REQUIRE(progress_reports == vector<size_t>({3, 5, 8, 11, 14, 17, 18})); } TEST_CASE("TextBuffer::set_text_in_range - basic") { TextBuffer buffer {u"abc\ndef\nghi"}; buffer.set_text_in_range(Range {{0, 2}, {2, 1}}, Text {u"jkl\nmno"}); REQUIRE(buffer.text() == Text {u"abjkl\nmnohi"}); REQUIRE(buffer.text_in_range(Range {{0, 1}, {1, 4}}) == Text {u"bjkl\nmnoh"}); } TEST_CASE("TextBuffer::line_length_for_row - basic") { TextBuffer buffer {u"a\n\nb\r\rc\r\n\r\n"}; REQUIRE(buffer.line_length_for_row(0) == 1); REQUIRE(buffer.line_length_for_row(1) == 0); } TEST_CASE("TextBuffer::set_text_in_range - random edits") { auto t = time(nullptr); for (uint i = 0; i < 100; i++) { auto seed = t + i; srand(seed); printf("Seed: %ld\n", seed); TextBuffer buffer {get_random_string()}; for (uint j = 0; j < 10; j++) { Text original_text = buffer.text(); Range deleted_range = get_random_range(buffer); Text inserted_text = get_random_text(); buffer.set_text_in_range(deleted_range, TextSlice {inserted_text}); original_text.splice(deleted_range.start, deleted_range.extent(), TextSlice {inserted_text}); REQUIRE(buffer.extent() == original_text.extent()); REQUIRE(buffer.text() == original_text); for (uint32_t row = 0; row < original_text.extent().row; row++) { REQUIRE( Point(row, buffer.line_length_for_row(row)) == Point(row, original_text.line_length_for_row(row)) ); } } } } <commit_msg>Ensure seeds aren't repeated in random set_text_in_range test<commit_after>#include "test-helpers.h" #include <sstream> #include "text-buffer.h" #include "text-slice.h" using std::move; using std::string; using std::stringstream; TEST_CASE("TextBuffer::build - can build a TextBuffer from a UTF8 stream") { string input = "abγdefg\nhijklmnop"; stringstream stream(input, std::ios_base::in); vector<size_t> progress_reports; TextBuffer buffer = TextBuffer::build(stream, input.size(), "UTF8", 3, [&](size_t percent_done) { progress_reports.push_back(percent_done); }); auto text = buffer.text(); REQUIRE(buffer.text() == Text {u"abγdefg\nhijklmnop"}); REQUIRE(progress_reports == vector<size_t>({3, 5, 8, 11, 14, 17, 18})); } TEST_CASE("TextBuffer::set_text_in_range - basic") { TextBuffer buffer {u"abc\ndef\nghi"}; buffer.set_text_in_range(Range {{0, 2}, {2, 1}}, Text {u"jkl\nmno"}); REQUIRE(buffer.text() == Text {u"abjkl\nmnohi"}); REQUIRE(buffer.text_in_range(Range {{0, 1}, {1, 4}}) == Text {u"bjkl\nmnoh"}); } TEST_CASE("TextBuffer::line_length_for_row - basic") { TextBuffer buffer {u"a\n\nb\r\rc\r\n\r\n"}; REQUIRE(buffer.line_length_for_row(0) == 1); REQUIRE(buffer.line_length_for_row(1) == 0); } TEST_CASE("TextBuffer::set_text_in_range - random edits") { auto t = time(nullptr); for (uint i = 0; i < 1000; i++) { auto seed = t * 1000 + i; srand(seed); printf("Seed: %ld\n", seed); TextBuffer buffer {get_random_string()}; for (uint j = 0; j < 10; j++) { // printf("j: %u\n", j); Text original_text = buffer.text(); Range deleted_range = get_random_range(buffer); Text inserted_text = get_random_text(); buffer.set_text_in_range(deleted_range, TextSlice {inserted_text}); original_text.splice(deleted_range.start, deleted_range.extent(), TextSlice {inserted_text}); REQUIRE(buffer.extent() == original_text.extent()); REQUIRE(buffer.text() == original_text); for (uint32_t row = 0; row < original_text.extent().row; row++) { REQUIRE( Point(row, buffer.line_length_for_row(row)) == Point(row, original_text.line_length_for_row(row)) ); } } } } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // Peloton // // typelimit_sql_test.cpp // // Identification: test/sql/typelimit_sql_test.cpp // // Copyright (c) 2015-17, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include "catalog/catalog.h" #include "common/harness.h" #include "concurrency/transaction_manager_factory.h" #include "sql/testing_sql_util.h" namespace peloton { namespace test { class TypeLimitSQLTests : public PelotonTest {}; const std::vector<type::TypeId> typeLimitSQLTestTypes = { type::TypeId::BOOLEAN, type::TypeId::TINYINT, type::TypeId::SMALLINT, type::TypeId::INTEGER, // FIXME type::TypeId::BIGINT, // FIXME type::TypeId::DECIMAL, // FIXME type::TypeId::TIMESTAMP, // FIXME type::TypeId::DATE }; void CreateAndLoadTable(std::string table_name, type::TypeId col_type) { std::string sql = StringUtil::Format("CREATE TABLE %s(id INT PRIMARY KEY, b %s);", table_name.c_str(), TypeIdToString(col_type).c_str()); LOG_TRACE("SQL: %s", sql.c_str()); TestingSQLUtil::ExecuteSQLQuery(sql); } /** * Check whether we can INSERT values that we have reserved for our NULL indicators * The DBMS should throw an error to prevent you from doing that */ TEST_F(TypeLimitSQLTests, InsertInvalidMinValue) { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); auto txn = txn_manager.BeginTransaction(); catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn); txn_manager.CommitTransaction(txn); for (auto col_type : typeLimitSQLTestTypes) { // CREATE TABLE that contains a column for each type std::string table_name = "tbl" + TypeIdToString(col_type); CreateAndLoadTable(table_name, col_type); // Then try to insert the min value std::ostringstream os; os << "INSERT INTO " << table_name << " VALUES (1, "; switch (col_type) { case type::TypeId::BOOLEAN: os << (int32_t)type::PELOTON_BOOLEAN_NULL; break; case type::TypeId::TINYINT: os << (int32_t)type::PELOTON_INT8_NULL; break; case type::TypeId::SMALLINT: os << type::PELOTON_INT16_NULL; break; case type::TypeId::INTEGER: os << type::PELOTON_INT32_NULL; break; case type::TypeId::BIGINT: os << type::PELOTON_INT64_NULL; break; case type::TypeId::DECIMAL: os << type::PELOTON_DECIMAL_NULL; break; case type::TypeId::TIMESTAMP: os << type::PELOTON_TIMESTAMP_NULL; break; case type::TypeId::DATE: os << type::PELOTON_DATE_NULL; break; default: { // Nothing to do! } } // SWITCH os << ");"; // This should throw an error because the query // is trying to insert a value that is not in a valid range for the type auto result = TestingSQLUtil::ExecuteSQLQuery(os.str()); LOG_DEBUG("%s => %s", TypeIdToString(col_type).c_str(), os.str().c_str()); EXPECT_EQ(ResultType::FAILURE, result); } // free the database just created txn = txn_manager.BeginTransaction(); catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn); txn_manager.CommitTransaction(txn); } } // namespace test } // namespace peloton<commit_msg>Added TIMESTAMP to TypeLimitSQLTests::InsertInvalidMinValue<commit_after>//===----------------------------------------------------------------------===// // // Peloton // // typelimit_sql_test.cpp // // Identification: test/sql/typelimit_sql_test.cpp // // Copyright (c) 2015-17, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <memory> #include "catalog/catalog.h" #include "common/harness.h" #include "concurrency/transaction_manager_factory.h" #include "sql/testing_sql_util.h" namespace peloton { namespace test { class TypeLimitSQLTests : public PelotonTest {}; const std::vector<type::TypeId> typeLimitSQLTestTypes = { type::TypeId::BOOLEAN, type::TypeId::TINYINT, type::TypeId::SMALLINT, type::TypeId::INTEGER, type::TypeId::TIMESTAMP, // FIXME type::TypeId::BIGINT, // FIXME type::TypeId::DECIMAL, // FIXME type::TypeId::DATE }; void CreateAndLoadTable(std::string table_name, type::TypeId col_type) { std::string sql = StringUtil::Format("CREATE TABLE %s(id INT PRIMARY KEY, b %s);", table_name.c_str(), TypeIdToString(col_type).c_str()); LOG_TRACE("SQL: %s", sql.c_str()); TestingSQLUtil::ExecuteSQLQuery(sql); } /** * Check whether we can INSERT values that we have reserved for our NULL indicators * The DBMS should throw an error to prevent you from doing that */ TEST_F(TypeLimitSQLTests, InsertInvalidMinValue) { auto &txn_manager = concurrency::TransactionManagerFactory::GetInstance(); auto txn = txn_manager.BeginTransaction(); catalog::Catalog::GetInstance()->CreateDatabase(DEFAULT_DB_NAME, txn); txn_manager.CommitTransaction(txn); for (auto col_type : typeLimitSQLTestTypes) { // CREATE TABLE that contains a column for each type std::string table_name = "tbl" + TypeIdToString(col_type); CreateAndLoadTable(table_name, col_type); // Then try to insert the min value std::ostringstream os; os << "INSERT INTO " << table_name << " VALUES (1, "; switch (col_type) { case type::TypeId::BOOLEAN: os << (int32_t)type::PELOTON_BOOLEAN_NULL; break; case type::TypeId::TINYINT: os << (int32_t)type::PELOTON_INT8_NULL; break; case type::TypeId::SMALLINT: os << type::PELOTON_INT16_NULL; break; case type::TypeId::INTEGER: os << type::PELOTON_INT32_NULL; break; case type::TypeId::BIGINT: os << type::PELOTON_INT64_NULL; break; case type::TypeId::DECIMAL: os << type::PELOTON_DECIMAL_NULL; break; case type::TypeId::TIMESTAMP: os << type::PELOTON_TIMESTAMP_NULL; break; case type::TypeId::DATE: os << type::PELOTON_DATE_NULL; break; default: { // Nothing to do! } } // SWITCH os << ");"; // This should throw an error because the query // is trying to insert a value that is not in a valid range for the type auto result = TestingSQLUtil::ExecuteSQLQuery(os.str()); LOG_TRACE("%s => %s", TypeIdToString(col_type).c_str(), os.str().c_str()); EXPECT_EQ(ResultType::FAILURE, result); } // free the database just created txn = txn_manager.BeginTransaction(); catalog::Catalog::GetInstance()->DropDatabaseWithName(DEFAULT_DB_NAME, txn); txn_manager.CommitTransaction(txn); } } // namespace test } // namespace peloton<|endoftext|>
<commit_before>// Copyright 2018 The gVisor 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 <errno.h> #include <signal.h> #include <sys/resource.h> #include <sys/stat.h> #include <sys/vfs.h> #include <time.h> #include <unistd.h> #include <iostream> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "test/syscalls/linux/file_base.h" #include "test/util/capability_util.h" #include "test/util/cleanup.h" #include "test/util/file_descriptor.h" #include "test/util/temp_path.h" #include "test/util/test_util.h" namespace gvisor { namespace testing { namespace { class FixtureTruncateTest : public FileTest { void SetUp() override { FileTest::SetUp(); } }; TEST_F(FixtureTruncateTest, Truncate) { // Get the current rlimit and restore after test run. struct rlimit initial_lim; ASSERT_THAT(getrlimit(RLIMIT_FSIZE, &initial_lim), SyscallSucceeds()); auto cleanup = Cleanup([&initial_lim] { EXPECT_THAT(setrlimit(RLIMIT_FSIZE, &initial_lim), SyscallSucceeds()); }); // Check that it starts at size zero. struct stat buf; ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds()); EXPECT_EQ(buf.st_size, 0); // Stay at size zero. EXPECT_THAT(truncate(test_file_name_.c_str(), 0), SyscallSucceeds()); ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds()); EXPECT_EQ(buf.st_size, 0); // Grow to ten bytes. EXPECT_THAT(truncate(test_file_name_.c_str(), 10), SyscallSucceeds()); ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds()); EXPECT_EQ(buf.st_size, 10); // Can't be truncated to a negative number. EXPECT_THAT(truncate(test_file_name_.c_str(), -1), SyscallFailsWithErrno(EINVAL)); // Try growing past the file size limit. sigset_t new_mask; sigemptyset(&new_mask); sigaddset(&new_mask, SIGXFSZ); sigprocmask(SIG_BLOCK, &new_mask, nullptr); struct timespec timelimit; timelimit.tv_sec = 10; timelimit.tv_nsec = 0; struct rlimit setlim; setlim.rlim_cur = 1024; setlim.rlim_max = RLIM_INFINITY; ASSERT_THAT(setrlimit(RLIMIT_FSIZE, &setlim), SyscallSucceeds()); EXPECT_THAT(truncate(test_file_name_.c_str(), 1025), SyscallFailsWithErrno(EFBIG)); EXPECT_EQ(sigtimedwait(&new_mask, nullptr, &timelimit), SIGXFSZ); ASSERT_THAT(sigprocmask(SIG_UNBLOCK, &new_mask, nullptr), SyscallSucceeds()); // Shrink back down to zero. EXPECT_THAT(truncate(test_file_name_.c_str(), 0), SyscallSucceeds()); ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds()); EXPECT_EQ(buf.st_size, 0); } TEST_F(FixtureTruncateTest, Ftruncate) { // Get the current rlimit and restore after test run. struct rlimit initial_lim; ASSERT_THAT(getrlimit(RLIMIT_FSIZE, &initial_lim), SyscallSucceeds()); auto cleanup = Cleanup([&initial_lim] { EXPECT_THAT(setrlimit(RLIMIT_FSIZE, &initial_lim), SyscallSucceeds()); }); // Check that it starts at size zero. struct stat buf; ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds()); EXPECT_EQ(buf.st_size, 0); // Stay at size zero. EXPECT_THAT(ftruncate(test_file_fd_.get(), 0), SyscallSucceeds()); ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds()); EXPECT_EQ(buf.st_size, 0); // Grow to ten bytes. EXPECT_THAT(ftruncate(test_file_fd_.get(), 10), SyscallSucceeds()); ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds()); EXPECT_EQ(buf.st_size, 10); // Can't be truncated to a negative number. EXPECT_THAT(ftruncate(test_file_fd_.get(), -1), SyscallFailsWithErrno(EINVAL)); // Try growing past the file size limit. sigset_t new_mask; sigemptyset(&new_mask); sigaddset(&new_mask, SIGXFSZ); sigprocmask(SIG_BLOCK, &new_mask, nullptr); struct timespec timelimit; timelimit.tv_sec = 10; timelimit.tv_nsec = 0; struct rlimit setlim; setlim.rlim_cur = 1024; setlim.rlim_max = RLIM_INFINITY; ASSERT_THAT(setrlimit(RLIMIT_FSIZE, &setlim), SyscallSucceeds()); EXPECT_THAT(ftruncate(test_file_fd_.get(), 1025), SyscallFailsWithErrno(EFBIG)); EXPECT_EQ(sigtimedwait(&new_mask, nullptr, &timelimit), SIGXFSZ); ASSERT_THAT(sigprocmask(SIG_UNBLOCK, &new_mask, nullptr), SyscallSucceeds()); // Shrink back down to zero. EXPECT_THAT(ftruncate(test_file_fd_.get(), 0), SyscallSucceeds()); ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds()); EXPECT_EQ(buf.st_size, 0); } // Truncating a file down clears that portion of the file. TEST_F(FixtureTruncateTest, FtruncateShrinkGrow) { std::vector<char> buf(10, 'a'); EXPECT_THAT(WriteFd(test_file_fd_.get(), buf.data(), buf.size()), SyscallSucceedsWithValue(buf.size())); // Shrink then regrow the file. This should clear the second half of the file. EXPECT_THAT(ftruncate(test_file_fd_.get(), 5), SyscallSucceeds()); EXPECT_THAT(ftruncate(test_file_fd_.get(), 10), SyscallSucceeds()); EXPECT_THAT(lseek(test_file_fd_.get(), 0, SEEK_SET), SyscallSucceeds()); std::vector<char> buf2(10); EXPECT_THAT(ReadFd(test_file_fd_.get(), buf2.data(), buf2.size()), SyscallSucceedsWithValue(buf2.size())); std::vector<char> expect = {'a', 'a', 'a', 'a', 'a', '\0', '\0', '\0', '\0', '\0'}; EXPECT_EQ(expect, buf2); } TEST(TruncateTest, TruncateDir) { auto temp_dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir()); EXPECT_THAT(truncate(temp_dir.path().c_str(), 0), SyscallFailsWithErrno(EISDIR)); } TEST(TruncateTest, FtruncateDir) { auto temp_dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir()); const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(temp_dir.path(), O_DIRECTORY | O_RDONLY)); EXPECT_THAT(ftruncate(fd.get(), 0), SyscallFailsWithErrno(EINVAL)); } TEST(TruncateTest, TruncateNonWriteable) { // Make sure we don't have CAP_DAC_OVERRIDE, since that allows the user to // always override write permissions. ASSERT_NO_ERRNO(SetCapability(CAP_DAC_OVERRIDE, false)); auto temp_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith( GetAbsoluteTestTmpdir(), absl::string_view(), 0555 /* mode */)); EXPECT_THAT(truncate(temp_file.path().c_str(), 0), SyscallFailsWithErrno(EACCES)); } TEST(TruncateTest, FtruncateNonWriteable) { auto temp_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith( GetAbsoluteTestTmpdir(), absl::string_view(), 0555 /* mode */)); const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(temp_file.path(), O_RDONLY)); EXPECT_THAT(ftruncate(fd.get(), 0), SyscallFailsWithErrno(EINVAL)); } TEST(TruncateTest, TruncateNonExist) { EXPECT_THAT(truncate("/foo/bar", 0), SyscallFailsWithErrno(ENOENT)); } TEST(TruncateTest, FtruncateVirtualTmp_NoRandomSave) { auto temp_file = NewTempAbsPathInDir("/dev/shm"); const DisableSave ds; // Incompatible permissions. const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(temp_file, O_RDWR | O_CREAT | O_EXCL, 0)); EXPECT_THAT(ftruncate(fd.get(), 100), SyscallSucceeds()); } // NOTE: There are additional truncate(2)/ftruncate(2) tests in mknod.cc // which are there to avoid running the tests on a number of different // filesystems which may not support mknod. } // namespace } // namespace testing } // namespace gvisor <commit_msg>Add ftruncate test for writeable fd but no write permissions.<commit_after>// Copyright 2018 The gVisor 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 <errno.h> #include <signal.h> #include <sys/resource.h> #include <sys/stat.h> #include <sys/vfs.h> #include <time.h> #include <unistd.h> #include <iostream> #include <string> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/string_view.h" #include "test/syscalls/linux/file_base.h" #include "test/util/capability_util.h" #include "test/util/cleanup.h" #include "test/util/file_descriptor.h" #include "test/util/temp_path.h" #include "test/util/test_util.h" namespace gvisor { namespace testing { namespace { class FixtureTruncateTest : public FileTest { void SetUp() override { FileTest::SetUp(); } }; TEST_F(FixtureTruncateTest, Truncate) { // Get the current rlimit and restore after test run. struct rlimit initial_lim; ASSERT_THAT(getrlimit(RLIMIT_FSIZE, &initial_lim), SyscallSucceeds()); auto cleanup = Cleanup([&initial_lim] { EXPECT_THAT(setrlimit(RLIMIT_FSIZE, &initial_lim), SyscallSucceeds()); }); // Check that it starts at size zero. struct stat buf; ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds()); EXPECT_EQ(buf.st_size, 0); // Stay at size zero. EXPECT_THAT(truncate(test_file_name_.c_str(), 0), SyscallSucceeds()); ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds()); EXPECT_EQ(buf.st_size, 0); // Grow to ten bytes. EXPECT_THAT(truncate(test_file_name_.c_str(), 10), SyscallSucceeds()); ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds()); EXPECT_EQ(buf.st_size, 10); // Can't be truncated to a negative number. EXPECT_THAT(truncate(test_file_name_.c_str(), -1), SyscallFailsWithErrno(EINVAL)); // Try growing past the file size limit. sigset_t new_mask; sigemptyset(&new_mask); sigaddset(&new_mask, SIGXFSZ); sigprocmask(SIG_BLOCK, &new_mask, nullptr); struct timespec timelimit; timelimit.tv_sec = 10; timelimit.tv_nsec = 0; struct rlimit setlim; setlim.rlim_cur = 1024; setlim.rlim_max = RLIM_INFINITY; ASSERT_THAT(setrlimit(RLIMIT_FSIZE, &setlim), SyscallSucceeds()); EXPECT_THAT(truncate(test_file_name_.c_str(), 1025), SyscallFailsWithErrno(EFBIG)); EXPECT_EQ(sigtimedwait(&new_mask, nullptr, &timelimit), SIGXFSZ); ASSERT_THAT(sigprocmask(SIG_UNBLOCK, &new_mask, nullptr), SyscallSucceeds()); // Shrink back down to zero. EXPECT_THAT(truncate(test_file_name_.c_str(), 0), SyscallSucceeds()); ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds()); EXPECT_EQ(buf.st_size, 0); } TEST_F(FixtureTruncateTest, Ftruncate) { // Get the current rlimit and restore after test run. struct rlimit initial_lim; ASSERT_THAT(getrlimit(RLIMIT_FSIZE, &initial_lim), SyscallSucceeds()); auto cleanup = Cleanup([&initial_lim] { EXPECT_THAT(setrlimit(RLIMIT_FSIZE, &initial_lim), SyscallSucceeds()); }); // Check that it starts at size zero. struct stat buf; ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds()); EXPECT_EQ(buf.st_size, 0); // Stay at size zero. EXPECT_THAT(ftruncate(test_file_fd_.get(), 0), SyscallSucceeds()); ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds()); EXPECT_EQ(buf.st_size, 0); // Grow to ten bytes. EXPECT_THAT(ftruncate(test_file_fd_.get(), 10), SyscallSucceeds()); ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds()); EXPECT_EQ(buf.st_size, 10); // Can't be truncated to a negative number. EXPECT_THAT(ftruncate(test_file_fd_.get(), -1), SyscallFailsWithErrno(EINVAL)); // Try growing past the file size limit. sigset_t new_mask; sigemptyset(&new_mask); sigaddset(&new_mask, SIGXFSZ); sigprocmask(SIG_BLOCK, &new_mask, nullptr); struct timespec timelimit; timelimit.tv_sec = 10; timelimit.tv_nsec = 0; struct rlimit setlim; setlim.rlim_cur = 1024; setlim.rlim_max = RLIM_INFINITY; ASSERT_THAT(setrlimit(RLIMIT_FSIZE, &setlim), SyscallSucceeds()); EXPECT_THAT(ftruncate(test_file_fd_.get(), 1025), SyscallFailsWithErrno(EFBIG)); EXPECT_EQ(sigtimedwait(&new_mask, nullptr, &timelimit), SIGXFSZ); ASSERT_THAT(sigprocmask(SIG_UNBLOCK, &new_mask, nullptr), SyscallSucceeds()); // Shrink back down to zero. EXPECT_THAT(ftruncate(test_file_fd_.get(), 0), SyscallSucceeds()); ASSERT_THAT(fstat(test_file_fd_.get(), &buf), SyscallSucceeds()); EXPECT_EQ(buf.st_size, 0); } // Truncating a file down clears that portion of the file. TEST_F(FixtureTruncateTest, FtruncateShrinkGrow) { std::vector<char> buf(10, 'a'); EXPECT_THAT(WriteFd(test_file_fd_.get(), buf.data(), buf.size()), SyscallSucceedsWithValue(buf.size())); // Shrink then regrow the file. This should clear the second half of the file. EXPECT_THAT(ftruncate(test_file_fd_.get(), 5), SyscallSucceeds()); EXPECT_THAT(ftruncate(test_file_fd_.get(), 10), SyscallSucceeds()); EXPECT_THAT(lseek(test_file_fd_.get(), 0, SEEK_SET), SyscallSucceeds()); std::vector<char> buf2(10); EXPECT_THAT(ReadFd(test_file_fd_.get(), buf2.data(), buf2.size()), SyscallSucceedsWithValue(buf2.size())); std::vector<char> expect = {'a', 'a', 'a', 'a', 'a', '\0', '\0', '\0', '\0', '\0'}; EXPECT_EQ(expect, buf2); } TEST(TruncateTest, TruncateDir) { auto temp_dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir()); EXPECT_THAT(truncate(temp_dir.path().c_str(), 0), SyscallFailsWithErrno(EISDIR)); } TEST(TruncateTest, FtruncateDir) { auto temp_dir = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateDir()); const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(temp_dir.path(), O_DIRECTORY | O_RDONLY)); EXPECT_THAT(ftruncate(fd.get(), 0), SyscallFailsWithErrno(EINVAL)); } TEST(TruncateTest, TruncateNonWriteable) { // Make sure we don't have CAP_DAC_OVERRIDE, since that allows the user to // always override write permissions. ASSERT_NO_ERRNO(SetCapability(CAP_DAC_OVERRIDE, false)); auto temp_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith( GetAbsoluteTestTmpdir(), absl::string_view(), 0555 /* mode */)); EXPECT_THAT(truncate(temp_file.path().c_str(), 0), SyscallFailsWithErrno(EACCES)); } TEST(TruncateTest, FtruncateNonWriteable) { auto temp_file = ASSERT_NO_ERRNO_AND_VALUE(TempPath::CreateFileWith( GetAbsoluteTestTmpdir(), absl::string_view(), 0555 /* mode */)); const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(temp_file.path(), O_RDONLY)); EXPECT_THAT(ftruncate(fd.get(), 0), SyscallFailsWithErrno(EINVAL)); } // ftruncate(2) should succeed as long as the file descriptor is writeable, // regardless of whether the file permissions allow writing. TEST(TruncateTest, FtruncateWithoutWritePermission_NoRandomSave) { // Drop capabilities that allow us to override file permissions. ASSERT_NO_ERRNO(SetCapability(CAP_DAC_OVERRIDE, false)); // The only time we can open a file with flags forbidden by its permissions // is when we are creating the file. We cannot re-open with the same flags, // so we cannot restore an fd obtained from such an operation. const DisableSave ds; auto path = NewTempAbsPath(); const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(path, O_RDWR | O_CREAT, 0444)); // In goferfs, ftruncate may be converted to a remote truncate operation that // unavoidably requires write permission. SKIP_IF(IsRunningOnGvisor() && !ASSERT_NO_ERRNO_AND_VALUE(IsTmpfs(path))); ASSERT_THAT(ftruncate(fd.get(), 100), SyscallSucceeds()); } TEST(TruncateTest, TruncateNonExist) { EXPECT_THAT(truncate("/foo/bar", 0), SyscallFailsWithErrno(ENOENT)); } TEST(TruncateTest, FtruncateVirtualTmp_NoRandomSave) { auto temp_file = NewTempAbsPathInDir("/dev/shm"); const DisableSave ds; // Incompatible permissions. const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(Open(temp_file, O_RDWR | O_CREAT | O_EXCL, 0)); EXPECT_THAT(ftruncate(fd.get(), 100), SyscallSucceeds()); } // NOTE: There are additional truncate(2)/ftruncate(2) tests in mknod.cc // which are there to avoid running the tests on a number of different // filesystems which may not support mknod. } // namespace } // namespace testing } // namespace gvisor <|endoftext|>
<commit_before>/*************************************************** Lighting Controller Richard Huish 2016 ESP8266 based with local home-assistant.io GUI, 433Mhz transmitter for lighting control and DHT22 temperature-humidity sensor ---------- Key Libraries: ESP8266WiFi.h> https://github.com/esp8266/Arduino RCSwitch.h https://github.com/sui77/rc-switch DHT.h https://github.com/adafruit/DHT-sensor-library Adafruit_Sensor.g https://github.com/adafruit/Adafruit_Sensor required for DHT.h ---------- GUI: Locally hosted home assistant MQTT: Locally hosted broker https://mosquitto.org/ ---------- The circuit: NodeMCU Amica (ESP8266) Inputs: DHT22 temperature-humidity sensor - GPIO pin 5 (NodeMCU Pin D1) Outputs: 433Mhz Transmitter - GPIO pin 2 (NODEMCU Pin D4) LED_NODEMCU - pin 16 (NodeMCU Pin D0) LED_ESP - GPIO pin 2 (NodeMCU Pin D4) (Shared with 433Mhz TX) ---------- Notes: NodeMCU lED lights to show MQTT conenction. ESP lED lights to show WIFI conenction. ****************************************************/ // Note: Libaries are inluced in "Project Dependencies" file platformio.ini #include <ESP8266WiFi.h> // ESP8266 core for Arduino https://github.com/esp8266/Arduino #include <PubSubClient.h> // Arduino Client for MQTT https://github.com/knolleary/pubsubclient #include <RCSwitch.h> // https://github.com/sui77/rc-switch #include <DHT.h> // https://github.com/adafruit/DHT-sensor-library #include <Adafruit_Sensor.h> // have to add for the DHT to work https://github.com/adafruit/Adafruit_Sensor #include <secretes.h> // Passwords etc not for github // DHT sensor parameters #define DHTPIN 5 // GPIO pin 5 (NodeMCU Pin D1) #define DHTTYPE DHT22 // DHT sensor instance DHT dht(DHTPIN, DHTTYPE, 15); // WiFi parameters const char* wifi_ssid = secrete_wifi_ssid; // Wifi access point SSID const char* wifi_password = secrete_wifi_password; // Wifi access point password // 433Mhz transmitter parameters const int tx433Mhz_pin = 2; // GPIO pin 2 (NODEMCU Pin D4) const int setPulseLength = 305; // 433MHZ TX instance RCSwitch mySwitch = RCSwitch(); // MQTT Settings const char* mqtt_server = secrete_mqtt_server; // E.G. 192.168.1.xx const char* clientName = secrete_clientName; // Client to report to MQTT const char* mqtt_username = secrete_mqtt_username; // MQTT Username const char* mqtt_password = secrete_mqtt_password; // MQTT Password boolean willRetain = true; // MQTT Last Will and Testament const char* willMessage = "offline"; // MQTT Last Will and Testament Message // Subscribe const char* subscribeLightingGatewayTopic = secrete_subscribeLightingGatewayTopic; // E.G. Home/LightingGateway/transmit // Publish const char* publishTemperatureTopic = secrete_publishTemperatureTopic; // E.G. Home/Room/temperature const char* publishHumidityTopic = secrete_publishHumidityTopic; // E.G. Home/Room/humidity const char* publishLastWillTopic = secrete_publishLastWillTopic; // E.G. Home/LightingGateway/status" const char* publishClientName = secrete_publishClientName; // E.G. Home/LightingGateway/status" const char* publishIpAddress = secrete_publishIpAddress; // E.G. Home/LightingGateway/status" const char* publishSignalStrength = secrete_publishSignalStrength; // E.G. Home/LightingGateway/status" const char* publishHostName = secrete_publishHostName; // E.G. Home/LightingGateway/status" // MQTT instance WiFiClient espClient; PubSubClient mqttClient(espClient); char message_buff[100]; long lastReconnectAttempt = 0; // Reconnecting MQTT - non-blocking https://github.com/knolleary/pubsubclient/blob/master/examples/mqtt_reconnect_nonblocking/mqtt_reconnect_nonblocking.ino // MQTT publish frequency unsigned long previousMillis = 0; const long publishInterval = 60000; // Publish requency in milliseconds 60000 = 1 min // LED output parameters const int DIGITAL_PIN_LED_ESP = 2; // Define LED on ESP8266 sub-modual const int DIGITAL_PIN_LED_NODEMCU = 16; // Define LED on NodeMCU board - Lights on pin LOW // Setp the connection to WIFI and the MQTT Broker. Normally called only once from setup void setup_wifi() { /* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default, would try to act as both a client and an access-point and could cause network-issues with your other WiFi-devices on your WiFi-network. */ WiFi.mode(WIFI_STA); // Connect to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.print(wifi_ssid); WiFi.begin(wifi_ssid, wifi_password); while (WiFi.status() != WL_CONNECTED) { delay(250); Serial.print("."); } Serial.print(""); Serial.println("WiFi connected"); Serial.printf("RSSI: %d dBm\n", WiFi.RSSI()); Serial.print("Connected, IP address: "); Serial.println(WiFi.localIP()); Serial.printf("Hostname: %s\n", WiFi.hostname().c_str()); digitalWrite(DIGITAL_PIN_LED_NODEMCU, LOW); // Lights on LOW. Light the NodeMCU LED to show wifi connection. } // 433Mhz Gatway void transmit433Msg(int msgToSend) { // Acknowledgements // thisoldgeek/ESP8266-RCSwitch // https://github.com/thisoldgeek/ESP8266-RCSwitch // Find the codes for your RC Switch using https://github.com/ninjablocks/433Utils (RF_Sniffer.ino) // sui77/rc-switch // https://github.com/sui77/rc-switch/tree/c5645170be8cb3044f4a8ca8565bfd2d221ba182 mySwitch.send(msgToSend, 24); Serial.println(F("433Mhz TX command sent!")); } // MQTT payload to transmit via out gateway void mqttcallback(char* topic, byte* payload, unsigned int length) { //If you want to publish a message from within the message callback function, it is necessary to make a copy of the topic and payload values as the client uses the same internal buffer for inbound and outbound messages: //http://www.hivemq.com/blog/mqtt-client-library-encyclopedia-arduino-pubsubclient/ Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); // create character buffer with ending null terminator (string) int i = 0; for (i = 0; i < length; i++) { message_buff[i] = payload[i]; } message_buff[i] = '\0'; // Check the value of the message String msgString = String(message_buff); Serial.println(msgString); // Check the message topic String srtTopic = topic; if (srtTopic.equals(subscribeLightingGatewayTopic)) { int msgSend = msgString.toInt(); //do the transmittt transmit433Msg(msgSend); delay(500); } } /* Non-Blocking mqtt reconnect. Called from checkMqttConnection. */ boolean mqttReconnect() { // Call on the background functions to allow them to do their thing yield(); // Attempt to connect if (mqttClient.connect(clientName, mqtt_username, mqtt_password, publishLastWillTopic, 0, willRetain, willMessage)) { Serial.print("Attempting MQTT connection..."); // Once connected, update status to online, retained = true - last will Message will drop in if we go offline ... mqttClient.publish(publishLastWillTopic, "online", true); // Publish device name, retained = true mqttClient.publish(publishClientName, clientName, true); // Publish device IP Address, retained = true char buf[16]; sprintf(buf, "%d.%d.%d.%d", WiFi.localIP()[0], WiFi.localIP()[1], WiFi.localIP()[2], WiFi.localIP()[3] ); mqttClient.publish(publishIpAddress, buf, true); // Publish the Wi-Fi signal quality (RSSI), retained = true String tempVar = String(WiFi.RSSI()); mqttClient.publish(publishSignalStrength, tempVar.c_str(), true); // Publish the device DHCP hostname, retained = true mqttClient.publish(publishHostName, WiFi.hostname().c_str(), true); // Resubscribe to feeds mqttClient.subscribe(subscribeLightingGatewayTopic); Serial.println("connected"); } else { Serial.print("Failed MQTT connection, rc="); Serial.print(mqttClient.state()); Serial.println(" try in 1.5 seconds"); } return mqttClient.connected(); } /* Checks if connection to the MQTT server is ok. Client connected using a non-blocking reconnect function. If the client loses its connection, it attempts to reconnect every 5 seconds without blocking the main loop. Called from main loop. */ void checkMqttConnection() { if (!mqttClient.connected()) { // We are not connected. Turn off the wifi LED digitalWrite(DIGITAL_PIN_LED_ESP, HIGH); // Lights on LOW long now = millis(); if (now - lastReconnectAttempt > 5000) { lastReconnectAttempt = now; // Attempt to reconnect if (mqttReconnect()) { lastReconnectAttempt = 0; } } } else { // We are connected. digitalWrite(DIGITAL_PIN_LED_ESP, LOW); // Lights on LOW //call on the background functions to allow them to do their thing. yield(); // Client connected: MQTT client loop processing mqttClient.loop(); } } void mtqqPublish() { // Only run when publishInterval in milliseonds exspires unsigned long currentMillis = millis(); // CODE TO MOVE TO functions if (currentMillis - previousMillis >= publishInterval) { // save the last time this ran previousMillis = currentMillis; if (mqttClient.connected()) { // Publish data // Publish the Wi-Fi signal quality (RSSI) String tempVar = String(WiFi.RSSI()); mqttClient.publish(publishSignalStrength, tempVar.c_str()); Serial.printf("RSSI: %d dBm\n", WiFi.RSSI()); // Grab the current state of the sensor String strTemp = String(dht.readTemperature()); //Could use String(dht.readTemperature()).c_str()) to do it all in one line if (!mqttClient.publish(publishTemperatureTopic, String(dht.readTemperature()).c_str())) // Convert dht.readTemperature() to string object, then to char array. Serial.print(F("Failed to published to [")), Serial.print(publishTemperatureTopic), Serial.print("] "); else Serial.print(F("Temperature published to [")), Serial.print(publishTemperatureTopic), Serial.println("] "); String strHumi = String(dht.readHumidity()); if (!mqttClient.publish(publishHumidityTopic, strHumi.c_str())) Serial.print(F("Failed to humidity to [")), Serial.print(publishHumidityTopic), Serial.print("] "); else Serial.print(F("Humidity published to [")), Serial.print(publishHumidityTopic), Serial.println("] "); } } } void setup() { // Initialize pins pinMode(DIGITAL_PIN_LED_NODEMCU, OUTPUT); pinMode(DIGITAL_PIN_LED_ESP, OUTPUT); // Initialize pin start values digitalWrite(DIGITAL_PIN_LED_NODEMCU, LOW); // Lights on HIGH digitalWrite(DIGITAL_PIN_LED_ESP, HIGH); // Lights on LOW // set serial speed Serial.begin(115200); Serial.println("Setup Starting"); // Setup 433Mhz Transmitter pinMode(tx433Mhz_pin, OUTPUT); // Set 433Mhz pin to output mySwitch.enableTransmit(tx433Mhz_pin); // Set pulse length. mySwitch.setPulseLength(setPulseLength); // Optional set protocol (default is 1, will work for most outlets) mySwitch.setProtocol(1); // Call on the background functions to allow them to do their thing yield(); // Setup wifi setup_wifi(); // Call on the background functions to allow them to do their thing yield(); // Set MQTT settings mqttClient.setServer(mqtt_server, 1883); mqttClient.setCallback(mqttcallback); // Call on the background functions to allow them to do their thing yield(); Serial.println("Setup Complete"); } /// Main working loop void loop() { yield(); // call on the background functions to allow them to do their thing. // First check if we are connected to the MQTT broker checkMqttConnection(); yield(); // call on the background functions to allow them to do their thing. // Publish MQTT mtqqPublish(); } <commit_msg>Added extra publish topics<commit_after>/*************************************************** Lighting Controller Richard Huish 2016 ESP8266 based with local home-assistant.io GUI, 433Mhz transmitter for lighting control and DHT22 temperature-humidity sensor ---------- Key Libraries: ESP8266WiFi.h> https://github.com/esp8266/Arduino RCSwitch.h https://github.com/sui77/rc-switch DHT.h https://github.com/adafruit/DHT-sensor-library Adafruit_Sensor.g https://github.com/adafruit/Adafruit_Sensor required for DHT.h ---------- GUI: Locally hosted home assistant MQTT: Locally hosted broker https://mosquitto.org/ ---------- The circuit: NodeMCU Amica (ESP8266) Inputs: DHT22 temperature-humidity sensor - GPIO pin 5 (NodeMCU Pin D1) Outputs: 433Mhz Transmitter - GPIO pin 2 (NODEMCU Pin D4) LED_NODEMCU - pin 16 (NodeMCU Pin D0) LED_ESP - GPIO pin 2 (NodeMCU Pin D4) (Shared with 433Mhz TX) ---------- Notes: NodeMCU lED lights to show MQTT conenction. ESP lED lights to show WIFI conenction. ****************************************************/ // Note: Libaries are inluced in "Project Dependencies" file platformio.ini #include <ESP8266WiFi.h> // ESP8266 core for Arduino https://github.com/esp8266/Arduino #include <PubSubClient.h> // Arduino Client for MQTT https://github.com/knolleary/pubsubclient #include <RCSwitch.h> // https://github.com/sui77/rc-switch #include <DHT.h> // https://github.com/adafruit/DHT-sensor-library #include <Adafruit_Sensor.h> // have to add for the DHT to work https://github.com/adafruit/Adafruit_Sensor #include <secretes.h> // Passwords etc not for github // DHT sensor parameters #define DHTPIN 5 // GPIO pin 5 (NodeMCU Pin D1) #define DHTTYPE DHT22 // DHT sensor instance DHT dht(DHTPIN, DHTTYPE, 15); // WiFi parameters const char* wifi_ssid = secrete_wifi_ssid; // Wifi access point SSID const char* wifi_password = secrete_wifi_password; // Wifi access point password // 433Mhz transmitter parameters const int tx433Mhz_pin = 2; // GPIO pin 2 (NODEMCU Pin D4) const int setPulseLength = 305; // 433MHZ TX instance RCSwitch mySwitch = RCSwitch(); // MQTT Settings const char* mqtt_server = secrete_mqtt_server; // E.G. 192.168.1.xx const char* clientName = secrete_clientName; // Client to report to MQTT const char* mqtt_username = secrete_mqtt_username; // MQTT Username const char* mqtt_password = secrete_mqtt_password; // MQTT Password boolean willRetain = true; // MQTT Last Will and Testament const char* willMessage = "offline"; // MQTT Last Will and Testament Message // Subscribe const char* subscribeLightingGatewayTopic = secrete_subscribeLightingGatewayTopic; // E.G. Home/LightingGateway/transmit // Publish const char* publishTemperatureTopic = secrete_publishTemperatureTopic; // E.G. Home/Room/temperature const char* publishHumidityTopic = secrete_publishHumidityTopic; // E.G. Home/Room/humidity const char* publishLastWillTopic = secrete_publishLastWillTopic; // E.G. Home/LightingGateway/status" const char* publishClientName = secrete_publishClientName; // E.G. Home/LightingGateway/clientName" const char* publishIpAddress = secrete_publishIpAddress; // E.G. Home/LightingGateway/IpAddress" const char* publishSignalStrength = secrete_publishSignalStrength; // E.G. Home/LightingGateway/SignalStrength" const char* publishHostName = secrete_publishHostName; // E.G. Home/LightingGateway/HostName" const char* publishSSID = secrete_publishSSID; // E.G. Home/LightingGateway/SSID" // MQTT instance WiFiClient espClient; PubSubClient mqttClient(espClient); char message_buff[100]; long lastReconnectAttempt = 0; // Reconnecting MQTT - non-blocking https://github.com/knolleary/pubsubclient/blob/master/examples/mqtt_reconnect_nonblocking/mqtt_reconnect_nonblocking.ino // MQTT publish frequency unsigned long previousMillis = 0; const long publishInterval = 60000; // Publish requency in milliseconds 60000 = 1 min // LED output parameters const int DIGITAL_PIN_LED_ESP = 2; // Define LED on ESP8266 sub-modual const int DIGITAL_PIN_LED_NODEMCU = 16; // Define LED on NodeMCU board - Lights on pin LOW // Setp the connection to WIFI and the MQTT Broker. Normally called only once from setup void setup_wifi() { /* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default, would try to act as both a client and an access-point and could cause network-issues with your other WiFi-devices on your WiFi-network. */ WiFi.mode(WIFI_STA); // Connect to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.print(wifi_ssid); WiFi.begin(wifi_ssid, wifi_password); while (WiFi.status() != WL_CONNECTED) { delay(250); Serial.print("."); } Serial.print(""); Serial.println("WiFi connected"); Serial.printf("RSSI: %d dBm\n", WiFi.RSSI()); Serial.print("Connected, IP address: "); Serial.println(WiFi.localIP()); Serial.printf("Hostname: %s\n", WiFi.hostname().c_str()); digitalWrite(DIGITAL_PIN_LED_NODEMCU, LOW); // Lights on LOW. Light the NodeMCU LED to show wifi connection. } // 433Mhz Gatway void transmit433Msg(int msgToSend) { // Acknowledgements // thisoldgeek/ESP8266-RCSwitch // https://github.com/thisoldgeek/ESP8266-RCSwitch // Find the codes for your RC Switch using https://github.com/ninjablocks/433Utils (RF_Sniffer.ino) // sui77/rc-switch // https://github.com/sui77/rc-switch/tree/c5645170be8cb3044f4a8ca8565bfd2d221ba182 mySwitch.send(msgToSend, 24); Serial.println(F("433Mhz TX command sent!")); } // MQTT payload to transmit via out gateway void mqttcallback(char* topic, byte* payload, unsigned int length) { //If you want to publish a message from within the message callback function, it is necessary to make a copy of the topic and payload values as the client uses the same internal buffer for inbound and outbound messages: //http://www.hivemq.com/blog/mqtt-client-library-encyclopedia-arduino-pubsubclient/ Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); // create character buffer with ending null terminator (string) int i = 0; for (i = 0; i < length; i++) { message_buff[i] = payload[i]; } message_buff[i] = '\0'; // Check the value of the message String msgString = String(message_buff); Serial.println(msgString); // Check the message topic String srtTopic = topic; if (srtTopic.equals(subscribeLightingGatewayTopic)) { int msgSend = msgString.toInt(); //do the transmittt transmit433Msg(msgSend); delay(500); } } /* Non-Blocking mqtt reconnect. Called from checkMqttConnection. Based on example from 5ace47b Sep 7, 2015 https://github.com/knolleary/pubsubclient/blob/master/examples/mqtt_reconnect_nonblocking/mqtt_reconnect_nonblocking.ino */ boolean mqttReconnect() { // Call on the background functions to allow them to do their thing yield(); // Attempt to connect if (mqttClient.connect(clientName, mqtt_username, mqtt_password, publishLastWillTopic, 0, willRetain, willMessage)) { Serial.print("Attempting MQTT connection..."); // Once connected, update status to online, retained = true - last will Message will drop in if we go offline ... mqttClient.publish(publishLastWillTopic, "online", true); // Publish device name, retained = true mqttClient.publish(publishClientName, clientName, true); // Publish device IP Address, retained = true char buf[16]; sprintf(buf, "%d.%d.%d.%d", WiFi.localIP()[0], WiFi.localIP()[1], WiFi.localIP()[2], WiFi.localIP()[3] ); mqttClient.publish(publishIpAddress, buf, true); // Publish the Wi-Fi signal quality (RSSI), retained = true String tempVar = String(WiFi.RSSI()); mqttClient.publish(publishSignalStrength, tempVar.c_str(), true); // Publish the device DHCP hostname, retained = true mqttClient.publish(publishHostName, WiFi.hostname().c_str(), true); // Publish the WiFi SSID, retained = true mqttClient.publish(publishSSID, WiFi.SSID().c_str(), true); // Resubscribe to feeds mqttClient.subscribe(subscribeLightingGatewayTopic); Serial.println("connected"); } else { Serial.print("Failed MQTT connection, rc="); Serial.print(mqttClient.state()); Serial.println(" try in 1.5 seconds"); } return mqttClient.connected(); } /* Checks if connection to the MQTT server is ok. Client connected using a non-blocking reconnect function. If the client loses its connection, it attempts to reconnect every 5 seconds without blocking the main loop. Called from main loop. */ void checkMqttConnection() { if (!mqttClient.connected()) { // We are not connected. Turn off the wifi LED digitalWrite(DIGITAL_PIN_LED_ESP, HIGH); // Lights on LOW long now = millis(); if (now - lastReconnectAttempt > 5000) { lastReconnectAttempt = now; // Attempt to reconnect if (mqttReconnect()) { lastReconnectAttempt = 0; } } } else { // We are connected. digitalWrite(DIGITAL_PIN_LED_ESP, LOW); // Lights on LOW //call on the background functions to allow them to do their thing. yield(); // Client connected: MQTT client loop processing mqttClient.loop(); } } void mtqqPublish() { // Only run when publishInterval in milliseonds exspires unsigned long currentMillis = millis(); // CODE TO MOVE TO functions if (currentMillis - previousMillis >= publishInterval) { // save the last time this ran previousMillis = currentMillis; if (mqttClient.connected()) { // Publish data // Publish the Wi-Fi signal quality (RSSI) String tempVar = String(WiFi.RSSI()); mqttClient.publish(publishSignalStrength, tempVar.c_str()); Serial.printf("RSSI: %d dBm\n", WiFi.RSSI()); // Grab the current state of the sensor String strTemp = String(dht.readTemperature()); //Could use String(dht.readTemperature()).c_str()) to do it all in one line if (!mqttClient.publish(publishTemperatureTopic, String(dht.readTemperature()).c_str())) // Convert dht.readTemperature() to string object, then to char array. Serial.print(F("Failed to published to [")), Serial.print(publishTemperatureTopic), Serial.print("] "); else Serial.print(F("Temperature published to [")), Serial.print(publishTemperatureTopic), Serial.println("] "); String strHumi = String(dht.readHumidity()); if (!mqttClient.publish(publishHumidityTopic, strHumi.c_str())) Serial.print(F("Failed to humidity to [")), Serial.print(publishHumidityTopic), Serial.print("] "); else Serial.print(F("Humidity published to [")), Serial.print(publishHumidityTopic), Serial.println("] "); } } } void setup() { // Initialize pins pinMode(DIGITAL_PIN_LED_NODEMCU, OUTPUT); pinMode(DIGITAL_PIN_LED_ESP, OUTPUT); // Initialize pin start values digitalWrite(DIGITAL_PIN_LED_NODEMCU, LOW); // Lights on HIGH digitalWrite(DIGITAL_PIN_LED_ESP, HIGH); // Lights on LOW // set serial speed Serial.begin(115200); Serial.println("Setup Starting"); // Setup 433Mhz Transmitter pinMode(tx433Mhz_pin, OUTPUT); // Set 433Mhz pin to output mySwitch.enableTransmit(tx433Mhz_pin); // Set pulse length. mySwitch.setPulseLength(setPulseLength); // Optional set protocol (default is 1, will work for most outlets) mySwitch.setProtocol(1); // Call on the background functions to allow them to do their thing yield(); // Setup wifi setup_wifi(); // Call on the background functions to allow them to do their thing yield(); // Set MQTT settings mqttClient.setServer(mqtt_server, 1883); mqttClient.setCallback(mqttcallback); // Call on the background functions to allow them to do their thing yield(); Serial.println("Setup Complete"); } /// Main working loop void loop() { yield(); // call on the background functions to allow them to do their thing. // First check if we are connected to the MQTT broker checkMqttConnection(); yield(); // call on the background functions to allow them to do their thing. // Publish MQTT mtqqPublish(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestPolarAxes.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .SECTION Thanks // This test was written by Philippe Pbay, Kitware SAS 2011 #include "vtkBYUReader.h" #include "vtkCamera.h" #include "vtkPolarAxesActor.h" #include "vtkLight.h" #include "vtkLODActor.h" #include "vtkNew.h" #include "vtkOutlineFilter.h" #include "vtkPolyDataMapper.h" #include "vtkPolyDataNormals.h" #include "vtkProperty.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkSmartPointer.h" #include "vtkTestUtilities.h" #include "vtkTextProperty.h" //---------------------------------------------------------------------------- int TestPolarAxes( int argc, char * argv [] ) { vtkNew<vtkBYUReader> reader; char* fname = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/teapot.g" ); reader->SetGeometryFileName( fname ); delete [] fname; vtkNew<vtkPolyDataNormals> normals; normals->SetInputConnection( reader->GetOutputPort() ); vtkNew<vtkPolyDataMapper> readerMapper; readerMapper->SetInputConnection( normals->GetOutputPort() ); vtkNew<vtkLODActor> readerActor; readerActor->SetMapper( readerMapper.GetPointer() ); readerActor->GetProperty()->SetDiffuseColor( .5, .8, .3 ); vtkNew<vtkOutlineFilter> outline; outline->SetInputConnection(normals->GetOutputPort() ); vtkNew<vtkPolyDataMapper> mapOutline; mapOutline->SetInputConnection(outline->GetOutputPort() ); vtkNew<vtkActor> outlineActor; outlineActor->SetMapper( mapOutline.GetPointer() ); outlineActor->GetProperty()->SetColor( 0.0, 0.0, 0.0 ); vtkNew<vtkCamera> camera; camera->SetClippingRange( 1.0, 100.0 ); camera->SetFocalPoint( 0.9, 1.0, 0.0 ); camera->SetPosition( 2., 6., 13. ); vtkNew<vtkLight> light; light->SetFocalPoint( 0.21406, 1.5, 0.0 ); light->SetPosition( 7., 7., 4. ); vtkNew<vtkRenderer> renderer; renderer->SetActiveCamera( camera.GetPointer() ); renderer->AddLight( light.GetPointer() ); // Update normals in order to get correct bounds for polar axes normals->Update(); vtkNew<vtkPolarAxesActor> polaxes; polaxes->SetBounds( normals->GetOutput()->GetBounds() ); polaxes->SetPole( 0., 1., 3. ); polaxes->SetAutoScaleRadius( false ); polaxes->SetMaximumRadius( 3. ); polaxes->SetMaximumAngle( 180. ); polaxes->SetNumberOfRadialAxes( 7 ); polaxes->SetCamera( renderer->GetActiveCamera() ); polaxes->SetRadialLabelFormat( "%6.1f" ); polaxes->GetRadialAxesProperty()->SetColor( .0, .0, .9 ); polaxes->SetScreenSize( 12.0 ); polaxes->GetPolarAxisTitleTextProperty()->SetColor( .9, 0., 0. ); polaxes->GetPolarAxisLabelTextProperty()->SetColor( .9, 0., 0. ); vtkNew<vtkRenderWindow> renWin; renWin->SetMultiSamples( 0 ); renWin->AddRenderer( renderer.GetPointer() ); renWin->SetWindowName( "VTK - Polar Axes custom range" ); renWin->SetSize( 600, 600 ); vtkNew<vtkRenderWindowInteractor> iren; iren->SetRenderWindow( renWin.GetPointer() ); renderer->SetBackground( 1., 1., 1. ); renderer->AddViewProp( readerActor.GetPointer() ); renderer->AddViewProp( outlineActor.GetPointer() ); renderer->AddViewProp( polaxes.GetPointer() ); renWin->Render(); int retVal = vtkRegressionTestImage( renWin.GetPointer() ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } return !retVal; } <commit_msg>Nicer background to test polar axes<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestPolarAxes.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .SECTION Thanks // This test was written by Philippe Pbay, Kitware SAS 2011 #include "vtkBYUReader.h" #include "vtkCamera.h" #include "vtkPolarAxesActor.h" #include "vtkLight.h" #include "vtkLODActor.h" #include "vtkNew.h" #include "vtkOutlineFilter.h" #include "vtkPolyDataMapper.h" #include "vtkPolyDataNormals.h" #include "vtkProperty.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkSmartPointer.h" #include "vtkTestUtilities.h" #include "vtkTextProperty.h" //---------------------------------------------------------------------------- int TestPolarAxes( int argc, char * argv [] ) { vtkNew<vtkBYUReader> reader; char* fname = vtkTestUtilities::ExpandDataFileName( argc, argv, "Data/teapot.g" ); reader->SetGeometryFileName( fname ); delete [] fname; vtkNew<vtkPolyDataNormals> normals; normals->SetInputConnection( reader->GetOutputPort() ); vtkNew<vtkPolyDataMapper> readerMapper; readerMapper->SetInputConnection( normals->GetOutputPort() ); vtkNew<vtkLODActor> readerActor; readerActor->SetMapper( readerMapper.GetPointer() ); readerActor->GetProperty()->SetDiffuseColor( .5, .8, .3 ); vtkNew<vtkOutlineFilter> outline; outline->SetInputConnection(normals->GetOutputPort() ); vtkNew<vtkPolyDataMapper> mapOutline; mapOutline->SetInputConnection(outline->GetOutputPort() ); vtkNew<vtkActor> outlineActor; outlineActor->SetMapper( mapOutline.GetPointer() ); outlineActor->GetProperty()->SetColor( 0.0, 0.0, 0.0 ); vtkNew<vtkCamera> camera; camera->SetClippingRange( 1.0, 100.0 ); camera->SetFocalPoint( 0.9, 1.0, 0.0 ); camera->SetPosition( 2., 6., 13. ); vtkNew<vtkLight> light; light->SetFocalPoint( 0.21406, 1.5, 0.0 ); light->SetPosition( 7., 7., 4. ); vtkNew<vtkRenderer> renderer; renderer->SetActiveCamera( camera.GetPointer() ); renderer->AddLight( light.GetPointer() ); // Update normals in order to get correct bounds for polar axes normals->Update(); vtkNew<vtkPolarAxesActor> polaxes; polaxes->SetBounds( normals->GetOutput()->GetBounds() ); polaxes->SetPole( 0., 1., 3. ); polaxes->SetAutoScaleRadius( false ); polaxes->SetMaximumRadius( 3. ); polaxes->SetMaximumAngle( 180. ); polaxes->SetNumberOfRadialAxes( 7 ); polaxes->SetCamera( renderer->GetActiveCamera() ); polaxes->SetRadialLabelFormat( "%6.1f" ); polaxes->GetRadialAxesProperty()->SetColor( .0, .0, .9 ); polaxes->SetScreenSize( 12.0 ); polaxes->GetPolarAxisTitleTextProperty()->SetColor( .9, 0., 0. ); polaxes->GetPolarAxisLabelTextProperty()->SetColor( .9, 0., 0. ); vtkNew<vtkRenderWindow> renWin; renWin->SetMultiSamples( 0 ); renWin->AddRenderer( renderer.GetPointer() ); renWin->SetWindowName( "VTK - Polar Axes custom range" ); renWin->SetSize( 600, 600 ); vtkNew<vtkRenderWindowInteractor> iren; iren->SetRenderWindow( renWin.GetPointer() ); renderer->SetBackground( .7, .7, .7 ); renderer->AddViewProp( readerActor.GetPointer() ); renderer->AddViewProp( outlineActor.GetPointer() ); renderer->AddViewProp( polaxes.GetPointer() ); renWin->Render(); int retVal = vtkRegressionTestImage( renWin.GetPointer() ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } return !retVal; } <|endoftext|>
<commit_before>//===--- SILExtract.cpp - SIL function extraction utility -----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// /// \file /// /// This utility is meant to help simplify the extraction of test cases from sil /// files by removing (currently only) functions that do not match a list of /// string. It also allows for the inverse to be selected. Eventually this /// should have additional capabilities like stripping globals, vtables, etc. /// //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-func-extractor" #include "swift/Strings.h" #include "swift/Basic/Demangle.h" #include "swift/Basic/LLVM.h" #include "swift/Basic/LLVMInitialize.h" #include "swift/Frontend/DiagnosticVerifier.h" #include "swift/Frontend/Frontend.h" #include "swift/Frontend/PrintingDiagnosticConsumer.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILUndef.h" #include "swift/SILOptimizer/Analysis/Analysis.h" #include "swift/SILOptimizer/PassManager/PassManager.h" #include "swift/SILOptimizer/PassManager/Passes.h" #include "swift/Serialization/SerializedModuleLoader.h" #include "swift/Serialization/SerializationOptions.h" #include "swift/Serialization/SerializedSILLoader.h" #include "swift/Subsystems.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/Signals.h" #include <cstdio> using namespace swift; static llvm::cl::opt<std::string> InputFilename(llvm::cl::desc("input file"), llvm::cl::init("-"), llvm::cl::Positional); static llvm::cl::opt<std::string> OutputFilename("o", llvm::cl::desc("output filename"), llvm::cl::init("-")); static llvm::cl::opt<bool> EmitVerboseSIL("emit-verbose-sil", llvm::cl::desc("Emit locations during sil emission.")); static llvm::cl::list<std::string> FunctionNames("func", llvm::cl::desc("Function names to extract.")); static llvm::cl::opt<bool> EmitSIB("emit-sib", llvm::cl::desc("Emit a sib file as output instead of a sil file")); static llvm::cl::opt<bool> InvertMatch( "invert", llvm::cl::desc("Match functions whose name do not " "match the names of the functions to be extracted")); static llvm::cl::list<std::string> ImportPaths("I", llvm::cl::desc("add a directory to the import search path")); static llvm::cl::opt<std::string> ModuleName("module-name", llvm::cl::desc("The name of the module if processing" " a module. Necessary for processing " "stdin.")); static llvm::cl::opt<std::string> ModuleCachePath("module-cache-path", llvm::cl::desc("Clang module cache path")); static llvm::cl::opt<std::string> ResourceDir( "resource-dir", llvm::cl::desc("The directory that holds the compiler resource files")); static llvm::cl::opt<std::string> SDKPath("sdk", llvm::cl::desc("The path to the SDK for use with the clang " "importer."), llvm::cl::init("")); static llvm::cl::opt<std::string> Triple("target", llvm::cl::desc("target triple")); static llvm::cl::opt<bool> EnableSILSortOutput("emit-sorted-sil", llvm::cl::Hidden, llvm::cl::init(false), llvm::cl::desc("Sort Functions, VTables, Globals, " "WitnessTables by name to ease diffing.")); static llvm::cl::opt<bool> DisableASTDump("sil-disable-ast-dump", llvm::cl::Hidden, llvm::cl::init(false), llvm::cl::desc("Do not dump AST.")); static llvm::cl::opt<bool> AssumeUnqualifiedOwnershipWhenParsing( "assume-parsing-unqualified-ownership-sil", llvm::cl::Hidden, llvm::cl::init(false), llvm::cl::desc("Assume all parsed functions have unqualified ownership")); // This function isn't referenced outside its translation unit, but it // can't use the "static" keyword because its address is used for // getMainExecutable (since some platforms don't support taking the // address of main, and some platforms can't implement getMainExecutable // without being given the address of a function in the main executable). void anchorForGetMainExecutable() {} template <typename Cmp> static bool stringInSortedArray(StringRef str, ArrayRef<std::string> list, Cmp &&cmp) { if (list.empty()) return false; auto iter = std::lower_bound(list.begin(), list.end(), str, cmp); // If we didn't find str, return false. if (list.end() == iter) return false; return !cmp(str, *iter); } void removeUnwantedFunctions(SILModule *M, ArrayRef<std::string> MangledNames, ArrayRef<std::string> DemangledNames) { assert((!MangledNames.empty() || !DemangledNames.empty()) && "Expected names of function we want to retain!"); assert(M && "Expected a SIL module to extract from."); std::vector<SILFunction *> DeadFunctions; for (auto &F : M->getFunctionList()) { StringRef MangledName = F.getName(); std::string DemangledName = swift::Demangle::demangleSymbolAsString(MangledName); DemangledName = DemangledName.substr(0, DemangledName.find(' ')); DEBUG(llvm::dbgs() << "Visiting New Func:\n" << " Mangled: " << MangledName << "\n Demangled: " << DemangledName << "\n"); bool FoundMangledName = stringInSortedArray(MangledName, MangledNames, std::less<std::string>()); bool FoundDemangledName = stringInSortedArray( DemangledName, DemangledNames, [](const std::string &str1, const std::string &str2) -> bool { return str1.substr(0, str1.find(' ')) < str2.substr(0, str2.find(' ')); }); if ((FoundMangledName || FoundDemangledName) ^ InvertMatch) { DEBUG(llvm::dbgs() << " Not removing!\n"); continue; } DEBUG(llvm::dbgs() << " Removing!\n"); // If F has no body, there is nothing further to do. if (!F.size()) continue; SILBasicBlock &BB = F.front(); SILLocation Loc = BB.back().getLoc(); BB.split(BB.begin()); // Make terminator unreachable. SILBuilder(&BB).createUnreachable(Loc); DeadFunctions.push_back(&F); } // After running this pass all of the functions we will remove // should consist only of one basic block terminated by // UnreachableInst. performSILDiagnoseUnreachable(M); // Now mark all of these functions as public and remove their bodies. for (auto &F : DeadFunctions) { F->setLinkage(SILLinkage::PublicExternal); F->getBlocks().clear(); } // Remove dead functions. SILPassManager PM(M); PM.addDeadFunctionElimination(); PM.run(); } int main(int argc, char **argv) { INITIALIZE_LLVM(argc, argv); llvm::cl::ParseCommandLineOptions(argc, argv, "Swift SIL Extractor\n"); CompilerInvocation Invocation; Invocation.setMainExecutablePath(llvm::sys::fs::getMainExecutable( argv[0], reinterpret_cast<void *>(&anchorForGetMainExecutable))); // Give the context the list of search paths to use for modules. Invocation.setImportSearchPaths(ImportPaths); // Set the SDK path and target if given. if (SDKPath.getNumOccurrences() == 0) { const char *SDKROOT = getenv("SDKROOT"); if (SDKROOT) SDKPath = SDKROOT; } if (!SDKPath.empty()) Invocation.setSDKPath(SDKPath); if (!Triple.empty()) Invocation.setTargetTriple(Triple); if (!ResourceDir.empty()) Invocation.setRuntimeResourcePath(ResourceDir); Invocation.getClangImporterOptions().ModuleCachePath = ModuleCachePath; Invocation.setParseStdlib(); Invocation.getLangOptions().DisableAvailabilityChecking = true; Invocation.getLangOptions().EnableAccessControl = false; Invocation.getLangOptions().EnableObjCAttrRequiresFoundation = false; // Load the input file. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr = llvm::MemoryBuffer::getFileOrSTDIN(InputFilename); if (!FileBufOrErr) { fprintf(stderr, "Error! Failed to open file: %s\n", InputFilename.c_str()); exit(-1); } // If it looks like we have an AST, set the source file kind to SIL and the // name of the module to the file's name. Invocation.addInputBuffer(FileBufOrErr.get().get()); serialization::ExtendedValidationInfo extendedInfo; auto result = serialization::validateSerializedAST( FileBufOrErr.get()->getBuffer(), &extendedInfo); bool HasSerializedAST = result.status == serialization::Status::Valid; if (HasSerializedAST) { const StringRef Stem = ModuleName.size() ? StringRef(ModuleName) : llvm::sys::path::stem(InputFilename); Invocation.setModuleName(Stem); Invocation.setInputKind(InputFileKind::IFK_Swift_Library); } else { Invocation.setModuleName("main"); Invocation.setInputKind(InputFileKind::IFK_SIL); } SILOptions &SILOpts = Invocation.getSILOptions(); SILOpts.AssumeUnqualifiedOwnershipWhenParsing = AssumeUnqualifiedOwnershipWhenParsing; CompilerInstance CI; PrintingDiagnosticConsumer PrintDiags; CI.addDiagnosticConsumer(&PrintDiags); if (CI.setup(Invocation)) return 1; CI.performSema(); // If parsing produced an error, don't run any passes. if (CI.getASTContext().hadError()) return 1; // Load the SIL if we have a module. We have to do this after SILParse // creating the unfortunate double if statement. if (HasSerializedAST) { assert(!CI.hasSILModule() && "performSema() should not create a SILModule."); CI.setSILModule( SILModule::createEmptyModule(CI.getMainModule(), CI.getSILOptions())); std::unique_ptr<SerializedSILLoader> SL = SerializedSILLoader::create( CI.getASTContext(), CI.getSILModule(), nullptr); if (extendedInfo.isSIB()) SL->getAllForModule(CI.getMainModule()->getName(), nullptr); else SL->getAll(); } if (!FunctionNames.empty()) { // For efficient usage, we separate our names into two separate sorted // lists, one of managled names, and one of unmangled names. std::vector<std::string> Names; std::copy(FunctionNames.begin(), FunctionNames.end(), std::back_inserter(Names)); // First partition our function names into mangled/demangled arrays. auto FirstDemangledName = std::partition( Names.begin(), Names.end(), [](const std::string &Name) -> bool { return StringRef(Name).startswith("_T"); }); // Then grab offsets to avoid any issues with iterator invalidation when we // sort. unsigned NumMangled = std::distance(Names.begin(), FirstDemangledName); unsigned NumNames = Names.size(); // Then sort the two partitioned arrays. std::sort(Names.begin(), FirstDemangledName); std::sort(FirstDemangledName, Names.end()); // Finally construct our ArrayRefs into the sorted std::vector for our // mangled and demangled names. ArrayRef<std::string> MangledNames(&*Names.begin(), NumMangled); ArrayRef<std::string> DemangledNames(&*std::next(Names.begin(), NumMangled), NumNames - NumMangled); DEBUG(llvm::errs() << "MangledNames to keep:\n"; std::for_each(MangledNames.begin(), MangledNames.end(), [](const std::string &str) { llvm::errs() << " " << str << '\n'; })); DEBUG(llvm::errs() << "DemangledNames to keep:\n"; std::for_each(DemangledNames.begin(), DemangledNames.end(), [](const std::string &str) { llvm::errs() << " " << str << '\n'; })); removeUnwantedFunctions(CI.getSILModule(), MangledNames, DemangledNames); } if (EmitSIB) { llvm::SmallString<128> OutputFile; if (OutputFilename.size()) { OutputFile = OutputFilename; } else if (ModuleName.size()) { OutputFile = ModuleName; llvm::sys::path::replace_extension(OutputFile, SIB_EXTENSION); } else { OutputFile = CI.getMainModule()->getName().str(); llvm::sys::path::replace_extension(OutputFile, SIB_EXTENSION); } SerializationOptions serializationOpts; serializationOpts.OutputPath = OutputFile.c_str(); serializationOpts.SerializeAllSIL = true; serializationOpts.IsSIB = true; serialize(CI.getMainModule(), serializationOpts, CI.getSILModule()); } else { const StringRef OutputFile = OutputFilename.size() ? StringRef(OutputFilename) : "-"; if (OutputFile == "-") { CI.getSILModule()->print(llvm::outs(), EmitVerboseSIL, CI.getMainModule(), EnableSILSortOutput, !DisableASTDump); } else { std::error_code EC; llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_None); if (EC) { llvm::errs() << "while opening '" << OutputFile << "': " << EC.message() << '\n'; return 1; } CI.getSILModule()->print(OS, EmitVerboseSIL, CI.getMainModule(), EnableSILSortOutput, !DisableASTDump); } } return CI.getASTContext().hadError(); } <commit_msg>[gardening] Remove unnecessary template arg.<commit_after>//===--- SILExtract.cpp - SIL function extraction utility -----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// /// \file /// /// This utility is meant to help simplify the extraction of test cases from sil /// files by removing (currently only) functions that do not match a list of /// string. It also allows for the inverse to be selected. Eventually this /// should have additional capabilities like stripping globals, vtables, etc. /// //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-func-extractor" #include "swift/Strings.h" #include "swift/Basic/Demangle.h" #include "swift/Basic/LLVM.h" #include "swift/Basic/LLVMInitialize.h" #include "swift/Frontend/DiagnosticVerifier.h" #include "swift/Frontend/Frontend.h" #include "swift/Frontend/PrintingDiagnosticConsumer.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILUndef.h" #include "swift/SILOptimizer/Analysis/Analysis.h" #include "swift/SILOptimizer/PassManager/PassManager.h" #include "swift/SILOptimizer/PassManager/Passes.h" #include "swift/Serialization/SerializedModuleLoader.h" #include "swift/Serialization/SerializationOptions.h" #include "swift/Serialization/SerializedSILLoader.h" #include "swift/Subsystems.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/Signals.h" #include <cstdio> using namespace swift; static llvm::cl::opt<std::string> InputFilename(llvm::cl::desc("input file"), llvm::cl::init("-"), llvm::cl::Positional); static llvm::cl::opt<std::string> OutputFilename("o", llvm::cl::desc("output filename"), llvm::cl::init("-")); static llvm::cl::opt<bool> EmitVerboseSIL("emit-verbose-sil", llvm::cl::desc("Emit locations during sil emission.")); static llvm::cl::list<std::string> FunctionNames("func", llvm::cl::desc("Function names to extract.")); static llvm::cl::opt<bool> EmitSIB("emit-sib", llvm::cl::desc("Emit a sib file as output instead of a sil file")); static llvm::cl::opt<bool> InvertMatch( "invert", llvm::cl::desc("Match functions whose name do not " "match the names of the functions to be extracted")); static llvm::cl::list<std::string> ImportPaths("I", llvm::cl::desc("add a directory to the import search path")); static llvm::cl::opt<std::string> ModuleName("module-name", llvm::cl::desc("The name of the module if processing" " a module. Necessary for processing " "stdin.")); static llvm::cl::opt<std::string> ModuleCachePath("module-cache-path", llvm::cl::desc("Clang module cache path")); static llvm::cl::opt<std::string> ResourceDir( "resource-dir", llvm::cl::desc("The directory that holds the compiler resource files")); static llvm::cl::opt<std::string> SDKPath("sdk", llvm::cl::desc("The path to the SDK for use with the clang " "importer."), llvm::cl::init("")); static llvm::cl::opt<std::string> Triple("target", llvm::cl::desc("target triple")); static llvm::cl::opt<bool> EnableSILSortOutput("emit-sorted-sil", llvm::cl::Hidden, llvm::cl::init(false), llvm::cl::desc("Sort Functions, VTables, Globals, " "WitnessTables by name to ease diffing.")); static llvm::cl::opt<bool> DisableASTDump("sil-disable-ast-dump", llvm::cl::Hidden, llvm::cl::init(false), llvm::cl::desc("Do not dump AST.")); static llvm::cl::opt<bool> AssumeUnqualifiedOwnershipWhenParsing( "assume-parsing-unqualified-ownership-sil", llvm::cl::Hidden, llvm::cl::init(false), llvm::cl::desc("Assume all parsed functions have unqualified ownership")); // This function isn't referenced outside its translation unit, but it // can't use the "static" keyword because its address is used for // getMainExecutable (since some platforms don't support taking the // address of main, and some platforms can't implement getMainExecutable // without being given the address of a function in the main executable). void anchorForGetMainExecutable() {} static bool stringInSortedArray( StringRef str, ArrayRef<std::string> list, llvm::function_ref<bool(const std::string &, const std::string &)> &&cmp) { if (list.empty()) return false; auto iter = std::lower_bound(list.begin(), list.end(), str, cmp); // If we didn't find str, return false. if (list.end() == iter) return false; return !cmp(str, *iter); } void removeUnwantedFunctions(SILModule *M, ArrayRef<std::string> MangledNames, ArrayRef<std::string> DemangledNames) { assert((!MangledNames.empty() || !DemangledNames.empty()) && "Expected names of function we want to retain!"); assert(M && "Expected a SIL module to extract from."); std::vector<SILFunction *> DeadFunctions; for (auto &F : M->getFunctionList()) { StringRef MangledName = F.getName(); std::string DemangledName = swift::Demangle::demangleSymbolAsString(MangledName); DemangledName = DemangledName.substr(0, DemangledName.find(' ')); DEBUG(llvm::dbgs() << "Visiting New Func:\n" << " Mangled: " << MangledName << "\n Demangled: " << DemangledName << "\n"); bool FoundMangledName = stringInSortedArray(MangledName, MangledNames, std::less<std::string>()); bool FoundDemangledName = stringInSortedArray( DemangledName, DemangledNames, [](const std::string &str1, const std::string &str2) -> bool { return str1.substr(0, str1.find(' ')) < str2.substr(0, str2.find(' ')); }); if ((FoundMangledName || FoundDemangledName) ^ InvertMatch) { DEBUG(llvm::dbgs() << " Not removing!\n"); continue; } DEBUG(llvm::dbgs() << " Removing!\n"); // If F has no body, there is nothing further to do. if (!F.size()) continue; SILBasicBlock &BB = F.front(); SILLocation Loc = BB.back().getLoc(); BB.split(BB.begin()); // Make terminator unreachable. SILBuilder(&BB).createUnreachable(Loc); DeadFunctions.push_back(&F); } // After running this pass all of the functions we will remove // should consist only of one basic block terminated by // UnreachableInst. performSILDiagnoseUnreachable(M); // Now mark all of these functions as public and remove their bodies. for (auto &F : DeadFunctions) { F->setLinkage(SILLinkage::PublicExternal); F->getBlocks().clear(); } // Remove dead functions. SILPassManager PM(M); PM.addDeadFunctionElimination(); PM.run(); } int main(int argc, char **argv) { INITIALIZE_LLVM(argc, argv); llvm::cl::ParseCommandLineOptions(argc, argv, "Swift SIL Extractor\n"); CompilerInvocation Invocation; Invocation.setMainExecutablePath(llvm::sys::fs::getMainExecutable( argv[0], reinterpret_cast<void *>(&anchorForGetMainExecutable))); // Give the context the list of search paths to use for modules. Invocation.setImportSearchPaths(ImportPaths); // Set the SDK path and target if given. if (SDKPath.getNumOccurrences() == 0) { const char *SDKROOT = getenv("SDKROOT"); if (SDKROOT) SDKPath = SDKROOT; } if (!SDKPath.empty()) Invocation.setSDKPath(SDKPath); if (!Triple.empty()) Invocation.setTargetTriple(Triple); if (!ResourceDir.empty()) Invocation.setRuntimeResourcePath(ResourceDir); Invocation.getClangImporterOptions().ModuleCachePath = ModuleCachePath; Invocation.setParseStdlib(); Invocation.getLangOptions().DisableAvailabilityChecking = true; Invocation.getLangOptions().EnableAccessControl = false; Invocation.getLangOptions().EnableObjCAttrRequiresFoundation = false; // Load the input file. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr = llvm::MemoryBuffer::getFileOrSTDIN(InputFilename); if (!FileBufOrErr) { fprintf(stderr, "Error! Failed to open file: %s\n", InputFilename.c_str()); exit(-1); } // If it looks like we have an AST, set the source file kind to SIL and the // name of the module to the file's name. Invocation.addInputBuffer(FileBufOrErr.get().get()); serialization::ExtendedValidationInfo extendedInfo; auto result = serialization::validateSerializedAST( FileBufOrErr.get()->getBuffer(), &extendedInfo); bool HasSerializedAST = result.status == serialization::Status::Valid; if (HasSerializedAST) { const StringRef Stem = ModuleName.size() ? StringRef(ModuleName) : llvm::sys::path::stem(InputFilename); Invocation.setModuleName(Stem); Invocation.setInputKind(InputFileKind::IFK_Swift_Library); } else { Invocation.setModuleName("main"); Invocation.setInputKind(InputFileKind::IFK_SIL); } SILOptions &SILOpts = Invocation.getSILOptions(); SILOpts.AssumeUnqualifiedOwnershipWhenParsing = AssumeUnqualifiedOwnershipWhenParsing; CompilerInstance CI; PrintingDiagnosticConsumer PrintDiags; CI.addDiagnosticConsumer(&PrintDiags); if (CI.setup(Invocation)) return 1; CI.performSema(); // If parsing produced an error, don't run any passes. if (CI.getASTContext().hadError()) return 1; // Load the SIL if we have a module. We have to do this after SILParse // creating the unfortunate double if statement. if (HasSerializedAST) { assert(!CI.hasSILModule() && "performSema() should not create a SILModule."); CI.setSILModule( SILModule::createEmptyModule(CI.getMainModule(), CI.getSILOptions())); std::unique_ptr<SerializedSILLoader> SL = SerializedSILLoader::create( CI.getASTContext(), CI.getSILModule(), nullptr); if (extendedInfo.isSIB()) SL->getAllForModule(CI.getMainModule()->getName(), nullptr); else SL->getAll(); } if (!FunctionNames.empty()) { // For efficient usage, we separate our names into two separate sorted // lists, one of managled names, and one of unmangled names. std::vector<std::string> Names; std::copy(FunctionNames.begin(), FunctionNames.end(), std::back_inserter(Names)); // First partition our function names into mangled/demangled arrays. auto FirstDemangledName = std::partition( Names.begin(), Names.end(), [](const std::string &Name) -> bool { return StringRef(Name).startswith("_T"); }); // Then grab offsets to avoid any issues with iterator invalidation when we // sort. unsigned NumMangled = std::distance(Names.begin(), FirstDemangledName); unsigned NumNames = Names.size(); // Then sort the two partitioned arrays. std::sort(Names.begin(), FirstDemangledName); std::sort(FirstDemangledName, Names.end()); // Finally construct our ArrayRefs into the sorted std::vector for our // mangled and demangled names. ArrayRef<std::string> MangledNames(&*Names.begin(), NumMangled); ArrayRef<std::string> DemangledNames(&*std::next(Names.begin(), NumMangled), NumNames - NumMangled); DEBUG(llvm::errs() << "MangledNames to keep:\n"; std::for_each(MangledNames.begin(), MangledNames.end(), [](const std::string &str) { llvm::errs() << " " << str << '\n'; })); DEBUG(llvm::errs() << "DemangledNames to keep:\n"; std::for_each(DemangledNames.begin(), DemangledNames.end(), [](const std::string &str) { llvm::errs() << " " << str << '\n'; })); removeUnwantedFunctions(CI.getSILModule(), MangledNames, DemangledNames); } if (EmitSIB) { llvm::SmallString<128> OutputFile; if (OutputFilename.size()) { OutputFile = OutputFilename; } else if (ModuleName.size()) { OutputFile = ModuleName; llvm::sys::path::replace_extension(OutputFile, SIB_EXTENSION); } else { OutputFile = CI.getMainModule()->getName().str(); llvm::sys::path::replace_extension(OutputFile, SIB_EXTENSION); } SerializationOptions serializationOpts; serializationOpts.OutputPath = OutputFile.c_str(); serializationOpts.SerializeAllSIL = true; serializationOpts.IsSIB = true; serialize(CI.getMainModule(), serializationOpts, CI.getSILModule()); } else { const StringRef OutputFile = OutputFilename.size() ? StringRef(OutputFilename) : "-"; if (OutputFile == "-") { CI.getSILModule()->print(llvm::outs(), EmitVerboseSIL, CI.getMainModule(), EnableSILSortOutput, !DisableASTDump); } else { std::error_code EC; llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_None); if (EC) { llvm::errs() << "while opening '" << OutputFile << "': " << EC.message() << '\n'; return 1; } CI.getSILModule()->print(OS, EmitVerboseSIL, CI.getMainModule(), EnableSILSortOutput, !DisableASTDump); } } return CI.getASTContext().hadError(); } <|endoftext|>
<commit_before>#include <ROOT/RDataFrame.hxx> #include <ROOT/RTrivialDS.hxx> #include <TChain.h> #include <TSystem.h> #include <TTree.h> #include <gtest/gtest.h> #include <atomic> #include <memory> #include <thread> // std::thread::hardware_concurrency // fixture for all tests in this file struct DefinePerSample : ::testing::TestWithParam<bool> { unsigned int NSLOTS; unsigned int NENTRIES = std::max(10u, std::thread::hardware_concurrency() * 2); DefinePerSample() : NSLOTS(GetParam() ? std::min(4u, std::thread::hardware_concurrency()) : 1u) { if (GetParam()) ROOT::EnableImplicitMT(); } ~DefinePerSample() { if (GetParam()) ROOT::DisableImplicitMT(); } }; // A RAII object that ensures existence of nFiles root files named prefix0.root, prefix1.root, ... // Each file contains a TTree called "t" with one `int` branch called "x" with sequentially increasing values (0,1,2...) struct InputFilesRAII { unsigned int fNFiles = 0; std::string fPrefix; InputFilesRAII(unsigned int nFiles, std::string prefix) : fNFiles(nFiles), fPrefix(std::move(prefix)) { for (auto i = 0u; i < fNFiles; ++i) { TFile f((fPrefix + std::to_string(i) + ".root").c_str(), "recreate"); TTree t("t", "t"); t.Branch("x", &i); t.Fill(); t.Write(); } } ~InputFilesRAII() { for (auto i = 0u; i < fNFiles; ++i) gSystem->Unlink((fPrefix + std::to_string(i) + ".root").c_str()); } }; TEST_P(DefinePerSample, NoJitting) { std::atomic_int counter{0}; auto df = ROOT::RDataFrame(NENTRIES).DefinePerSample("x", [&counter](unsigned int, const ROOT::RDF::RSampleInfo &) { ++counter; return 42; }); auto xmin = df.Min<int>("x"); auto xmax = df.Max<int>("x"); EXPECT_EQ(*xmin, 42); EXPECT_EQ(*xmax, 42); // RDF with empty sources tries to produce 2 tasks per slot when MT is enabled const auto expected = ROOT::IsImplicitMTEnabled() ? std::min(NENTRIES, df.GetNSlots() * 2u) : 1u; EXPECT_EQ(counter, expected); } int AtomicIntValueFromInterpreter(std::string_view varName) { return int(*reinterpret_cast<std::atomic_int *>(gInterpreter->Calc(varName.data()))); } TEST(DefinePerSample, Jitted) { gInterpreter->Declare("std::atomic_int rdftestcounter1{0};"); auto df = ROOT::RDataFrame(3).DefinePerSample("x", "rdftestcounter1++; return 42;"); auto xmin = df.Min<int>("x"); auto xmax = df.Max<int>("x"); EXPECT_EQ(*xmin, 42); EXPECT_EQ(*xmax, 42); // RDF with empty sources tries to produce 2 tasks per slot when MT is enabled const auto expected = ROOT::IsImplicitMTEnabled() ? std::min(3u, df.GetNSlots() * 2u) : 1u; EXPECT_EQ(AtomicIntValueFromInterpreter("rdftestcounter1"), expected); } TEST_P(DefinePerSample, Tree) { const std::string prefix = "rdfdatablockcallback_ttree"; InputFilesRAII file(1u, prefix); ROOT::RDataFrame df("t", prefix + "*"); std::atomic_int counter{0}; auto df2 = df.DefinePerSample("y", [&counter](unsigned int, const ROOT::RDF::RSampleInfo &db) { EXPECT_EQ(db.EntryRange(), std::make_pair(0ull, 1ull)); ++counter; return 42; }); auto xmin = df2.Min<int>("y"); auto xmax = df2.Max<int>("y"); EXPECT_EQ(*xmin, 42); EXPECT_EQ(*xmax, 42); const auto expected = 1u; // as the TTree only contains one cluster, we only have one "data-block" EXPECT_EQ(counter, expected); } TEST_P(DefinePerSample, TChain) { const std::string prefix = "rdfdatablockcallback_tchain"; InputFilesRAII file(5u, prefix); ROOT::RDataFrame df("t", prefix + "*"); std::atomic_int counter{0}; auto df2 = df.DefinePerSample("y", [&counter](unsigned int, const ROOT::RDF::RSampleInfo &db) { EXPECT_EQ(db.EntryRange(), std::make_pair(0ull, 1ull)); ++counter; return 42; }); auto xmin = df2.Min<int>("y"); auto xmax = df2.Max<int>("y"); EXPECT_EQ(*xmin, 42); EXPECT_EQ(*xmax, 42); const auto expected = 5u; // one "data-block" per tree (because each tree only has one cluster) EXPECT_EQ(counter, expected); } TEST(DefinePerSampleMore, ThrowOnRedefinition) { auto df = ROOT::RDataFrame(1) .Define("x", [] { return 42; }); EXPECT_THROW(df.DefinePerSample("x", [](unsigned, const ROOT::RDF::RSampleInfo &) { return 42; }), std::runtime_error); } TEST(DefinePerSampleMore, GetColumnType) { auto df = ROOT::RDataFrame(1).DefinePerSample("x", [](unsigned, const ROOT::RDF::RSampleInfo &) { return 42; }); EXPECT_EQ(df.GetColumnType("x"), "int"); } TEST(DefinePerSampleMore, GetColumnNames) { auto df = ROOT::RDataFrame(1).DefinePerSample("x", [](unsigned, const ROOT::RDF::RSampleInfo &) { return 42; }); EXPECT_EQ(df.GetColumnNames(), std::vector<std::string>{"x"}); } TEST(DefinePerSampleMore, GetDefinedColumnNames) { auto df = ROOT::RDataFrame(1).DefinePerSample("x", [](unsigned, const ROOT::RDF::RSampleInfo &) { return 42; }); EXPECT_EQ(df.GetDefinedColumnNames(), std::vector<std::string>{"x"}); } /* TODO // Not supported yet TEST(DefinePerSample, DataSource) { ROOT::RDataFrame df(std::make_unique<ROOT::RDF::RTrivialDS>(1)); auto r = df.DefinePerSample("col0", [] { return 42; }).Max<int>("col0"); EXPECT_EQ(*r, 42); } */ // instantiate single-thread tests INSTANTIATE_TEST_SUITE_P(Seq, DefinePerSample, ::testing::Values(false)); #ifdef R__USE_IMT // instantiate multi-thread tests INSTANTIATE_TEST_SUITE_P(MT, DefinePerSample, ::testing::Values(true)); #endif <commit_msg>[DF] Use different file names in different tests<commit_after>#include <ROOT/RDataFrame.hxx> #include <ROOT/RTrivialDS.hxx> #include <TChain.h> #include <TSystem.h> #include <TTree.h> #include <gtest/gtest.h> #include <atomic> #include <memory> #include <thread> // std::thread::hardware_concurrency // fixture for all tests in this file struct DefinePerSample : ::testing::TestWithParam<bool> { unsigned int NSLOTS; unsigned int NENTRIES = std::max(10u, std::thread::hardware_concurrency() * 2); DefinePerSample() : NSLOTS(GetParam() ? std::min(4u, std::thread::hardware_concurrency()) : 1u) { if (GetParam()) ROOT::EnableImplicitMT(); } ~DefinePerSample() { if (GetParam()) ROOT::DisableImplicitMT(); } }; // A RAII object that ensures existence of nFiles root files named prefix0.root, prefix1.root, ... // Each file contains a TTree called "t" with one `int` branch called "x" with sequentially increasing values (0,1,2...) struct InputFilesRAII { unsigned int fNFiles = 0; std::string fPrefix; InputFilesRAII(unsigned int nFiles, std::string prefix) : fNFiles(nFiles), fPrefix(std::move(prefix)) { for (auto i = 0u; i < fNFiles; ++i) { TFile f((fPrefix + std::to_string(i) + ".root").c_str(), "recreate"); TTree t("t", "t"); t.Branch("x", &i); t.Fill(); t.Write(); } } ~InputFilesRAII() { for (auto i = 0u; i < fNFiles; ++i) gSystem->Unlink((fPrefix + std::to_string(i) + ".root").c_str()); } }; TEST_P(DefinePerSample, NoJitting) { std::atomic_int counter{0}; auto df = ROOT::RDataFrame(NENTRIES).DefinePerSample("x", [&counter](unsigned int, const ROOT::RDF::RSampleInfo &) { ++counter; return 42; }); auto xmin = df.Min<int>("x"); auto xmax = df.Max<int>("x"); EXPECT_EQ(*xmin, 42); EXPECT_EQ(*xmax, 42); // RDF with empty sources tries to produce 2 tasks per slot when MT is enabled const auto expected = ROOT::IsImplicitMTEnabled() ? std::min(NENTRIES, df.GetNSlots() * 2u) : 1u; EXPECT_EQ(counter, expected); } int AtomicIntValueFromInterpreter(std::string_view varName) { return int(*reinterpret_cast<std::atomic_int *>(gInterpreter->Calc(varName.data()))); } TEST(DefinePerSample, Jitted) { gInterpreter->Declare("std::atomic_int rdftestcounter1{0};"); auto df = ROOT::RDataFrame(3).DefinePerSample("x", "rdftestcounter1++; return 42;"); auto xmin = df.Min<int>("x"); auto xmax = df.Max<int>("x"); EXPECT_EQ(*xmin, 42); EXPECT_EQ(*xmax, 42); // RDF with empty sources tries to produce 2 tasks per slot when MT is enabled const auto expected = ROOT::IsImplicitMTEnabled() ? std::min(3u, df.GetNSlots() * 2u) : 1u; EXPECT_EQ(AtomicIntValueFromInterpreter("rdftestcounter1"), expected); } TEST_P(DefinePerSample, Tree) { const std::string prefix = "rdfdefinepersample_tree"; InputFilesRAII file(1u, prefix); ROOT::RDataFrame df("t", prefix + "*"); std::atomic_int counter{0}; auto df2 = df.DefinePerSample("y", [&counter](unsigned int, const ROOT::RDF::RSampleInfo &db) { EXPECT_EQ(db.EntryRange(), std::make_pair(0ull, 1ull)); ++counter; return 42; }); auto xmin = df2.Min<int>("y"); auto xmax = df2.Max<int>("y"); EXPECT_EQ(*xmin, 42); EXPECT_EQ(*xmax, 42); const auto expected = 1u; // as the TTree only contains one cluster, we only have one "data-block" EXPECT_EQ(counter, expected); } TEST_P(DefinePerSample, TChain) { const std::string prefix = "rdfdefinepersample_chain"; InputFilesRAII file(5u, prefix); ROOT::RDataFrame df("t", prefix + "*"); std::atomic_int counter{0}; auto df2 = df.DefinePerSample("y", [&counter](unsigned int, const ROOT::RDF::RSampleInfo &db) { EXPECT_EQ(db.EntryRange(), std::make_pair(0ull, 1ull)); ++counter; return 42; }); auto xmin = df2.Min<int>("y"); auto xmax = df2.Max<int>("y"); EXPECT_EQ(*xmin, 42); EXPECT_EQ(*xmax, 42); const auto expected = 5u; // one "data-block" per tree (because each tree only has one cluster) EXPECT_EQ(counter, expected); } TEST(DefinePerSampleMore, ThrowOnRedefinition) { auto df = ROOT::RDataFrame(1) .Define("x", [] { return 42; }); EXPECT_THROW(df.DefinePerSample("x", [](unsigned, const ROOT::RDF::RSampleInfo &) { return 42; }), std::runtime_error); } TEST(DefinePerSampleMore, GetColumnType) { auto df = ROOT::RDataFrame(1).DefinePerSample("x", [](unsigned, const ROOT::RDF::RSampleInfo &) { return 42; }); EXPECT_EQ(df.GetColumnType("x"), "int"); } TEST(DefinePerSampleMore, GetColumnNames) { auto df = ROOT::RDataFrame(1).DefinePerSample("x", [](unsigned, const ROOT::RDF::RSampleInfo &) { return 42; }); EXPECT_EQ(df.GetColumnNames(), std::vector<std::string>{"x"}); } TEST(DefinePerSampleMore, GetDefinedColumnNames) { auto df = ROOT::RDataFrame(1).DefinePerSample("x", [](unsigned, const ROOT::RDF::RSampleInfo &) { return 42; }); EXPECT_EQ(df.GetDefinedColumnNames(), std::vector<std::string>{"x"}); } /* TODO // Not supported yet TEST(DefinePerSample, DataSource) { ROOT::RDataFrame df(std::make_unique<ROOT::RDF::RTrivialDS>(1)); auto r = df.DefinePerSample("col0", [] { return 42; }).Max<int>("col0"); EXPECT_EQ(*r, 42); } */ // instantiate single-thread tests INSTANTIATE_TEST_SUITE_P(Seq, DefinePerSample, ::testing::Values(false)); #ifdef R__USE_IMT // instantiate multi-thread tests INSTANTIATE_TEST_SUITE_P(MT, DefinePerSample, ::testing::Values(true)); #endif <|endoftext|>
<commit_before>/* -*- 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 <sfx2/sidebar/ResourceDefinitions.hrc> #include <sfx2/sidebar/Theme.hxx> #include <sfx2/sidebar/ControlFactory.hxx> #include <com/sun/star/chart/ChartAxisLabelPosition.hpp> #include "ChartErrorBarPanel.hxx" #include "ChartController.hxx" #include <sfx2/bindings.hxx> #include <sfx2/dispatch.hxx> #include <sfx2/imagemgr.hxx> #include <vcl/fixed.hxx> #include <vcl/lstbox.hxx> #include <vcl/field.hxx> #include <vcl/toolbox.hxx> #include <svl/intitem.hxx> #include <svl/stritem.hxx> #include <comphelper/processfactory.hxx> using namespace css; using namespace css::uno; using ::sfx2::sidebar::Theme; namespace chart { namespace sidebar { namespace { css::uno::Reference<css::beans::XPropertySet> getErrorBarPropSet( css::uno::Reference<css::frame::XModel> xModel, const OUString& rCID) { return ObjectIdentifier::getObjectPropertySet(rCID, xModel); } bool showPositiveError(css::uno::Reference<css::frame::XModel> xModel, const OUString& rCID) { css::uno::Reference<css::beans::XPropertySet> xPropSet = getErrorBarPropSet(xModel, rCID); if (!xPropSet.is()) return false; css::uno::Any aAny = xPropSet->getPropertyValue("ShowPositiveError"); if (!aAny.hasValue()) return false; bool bShow = false; aAny >>= bShow; return bShow; } bool showNegativeError(css::uno::Reference<css::frame::XModel> xModel, const OUString& rCID) { css::uno::Reference<css::beans::XPropertySet> xPropSet = getErrorBarPropSet(xModel, rCID); if (!xPropSet.is()) return false; css::uno::Any aAny = xPropSet->getPropertyValue("ShowNegativeError"); if (!aAny.hasValue()) return false; bool bShow = false; aAny >>= bShow; return bShow; } void setShowPositiveError(css::uno::Reference<css::frame::XModel> xModel, const OUString& rCID, bool bShow) { css::uno::Reference<css::beans::XPropertySet> xPropSet = getErrorBarPropSet(xModel, rCID); if (!xPropSet.is()) return; xPropSet->setPropertyValue("ShowPositiveError", css::uno::makeAny(bShow)); } void setShowNegativeError(css::uno::Reference<css::frame::XModel> xModel, const OUString& rCID, bool bShow) { css::uno::Reference<css::beans::XPropertySet> xPropSet = getErrorBarPropSet(xModel, rCID); if (!xPropSet.is()) return; xPropSet->setPropertyValue("ShowNegativeError", css::uno::makeAny(bShow)); } OUString getCID(css::uno::Reference<css::frame::XModel> xModel) { css::uno::Reference<css::frame::XController> xController(xModel->getCurrentController()); css::uno::Reference<css::view::XSelectionSupplier> xSelectionSupplier(xController, css::uno::UNO_QUERY); if (!xSelectionSupplier.is()) return OUString(); uno::Any aAny = xSelectionSupplier->getSelection(); assert(aAny.hasValue()); OUString aCID; aAny >>= aCID; #ifdef DBG_UTIL ObjectType eType = ObjectIdentifier::getObjectType(aCID); assert(eType == OBJECTTYPE_DATA_ERRORS_X || eType == OBJECTTYPE_DATA_ERRORS_Y || eType == OBJECTTYPE_DATA_ERRORS_Z); #endif return aCID; } } ChartErrorBarPanel::ChartErrorBarPanel( vcl::Window* pParent, const css::uno::Reference<css::frame::XFrame>& rxFrame, ChartController* pController) : PanelLayout(pParent, "ChartErrorBarPanel", "modules/schart/ui/sidebarerrorbar.ui", rxFrame), mxFrame(rxFrame), mxModel(pController->getModel()), mxListener(new ChartSidebarModifyListener(this)) { get(mpRBPosAndNeg, "radiobutton_positive_negative"); get(mpRBPos, "radiobutton_positive"); get(mpRBNeg, "radiobutton_negative"); Initialize(); } ChartErrorBarPanel::~ChartErrorBarPanel() { disposeOnce(); } void ChartErrorBarPanel::dispose() { css::uno::Reference<css::util::XModifyBroadcaster> xBroadcaster(mxModel, css::uno::UNO_QUERY_THROW); xBroadcaster->removeModifyListener(mxListener); mpRBPosAndNeg.clear(); mpRBPos.clear(); mpRBNeg.clear(); PanelLayout::dispose(); } void ChartErrorBarPanel::Initialize() { css::uno::Reference<css::util::XModifyBroadcaster> xBroadcaster(mxModel, css::uno::UNO_QUERY_THROW); xBroadcaster->addModifyListener(mxListener); updateData(); Link<> aLink = LINK(this, ChartErrorBarPanel, RadioBtnHdl); mpRBPosAndNeg->SetToggleHdl(aLink); mpRBPos->SetToggleHdl(aLink); mpRBNeg->SetToggleHdl(aLink); } void ChartErrorBarPanel::updateData() { OUString aCID = getCID(mxModel); bool bPos = showPositiveError(mxModel, aCID); bool bNeg = showNegativeError(mxModel, aCID); SolarMutexGuard aGuard; if (bPos && bNeg) mpRBPosAndNeg->Check(true); else if (bPos) mpRBPos->Check(true); else if (bNeg) mpRBNeg->Check(true); } VclPtr<vcl::Window> ChartErrorBarPanel::Create ( vcl::Window* pParent, const css::uno::Reference<css::frame::XFrame>& rxFrame, ChartController* pController) { if (pParent == NULL) throw lang::IllegalArgumentException("no parent Window given to ChartErrorBarPanel::Create", NULL, 0); if ( ! rxFrame.is()) throw lang::IllegalArgumentException("no XFrame given to ChartErrorBarPanel::Create", NULL, 1); return VclPtr<ChartErrorBarPanel>::Create( pParent, rxFrame, pController); } void ChartErrorBarPanel::DataChanged( const DataChangedEvent& ) { updateData(); } void ChartErrorBarPanel::HandleContextChange( const ::sfx2::sidebar::EnumContext& ) { updateData(); } void ChartErrorBarPanel::NotifyItemUpdate( sal_uInt16 /*nSID*/, SfxItemState /*eState*/, const SfxPoolItem* /*pState*/, const bool ) { } void ChartErrorBarPanel::modelInvalid() { } IMPL_LINK_NOARG(ChartErrorBarPanel, RadioBtnHdl) { OUString aCID = getCID(mxModel); bool bPos = mpRBPosAndNeg->IsChecked() || mpRBPos->IsChecked(); bool bNeg = mpRBPosAndNeg->IsChecked() || mpRBNeg->IsChecked(); setShowPositiveError(mxModel, aCID, bPos); setShowNegativeError(mxModel, aCID, bNeg); } }} // end of namespace ::chart::sidebar /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>fix build<commit_after>/* -*- 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 <sfx2/sidebar/ResourceDefinitions.hrc> #include <sfx2/sidebar/Theme.hxx> #include <sfx2/sidebar/ControlFactory.hxx> #include <com/sun/star/chart/ChartAxisLabelPosition.hpp> #include "ChartErrorBarPanel.hxx" #include "ChartController.hxx" #include <sfx2/bindings.hxx> #include <sfx2/dispatch.hxx> #include <sfx2/imagemgr.hxx> #include <vcl/fixed.hxx> #include <vcl/lstbox.hxx> #include <vcl/field.hxx> #include <vcl/toolbox.hxx> #include <svl/intitem.hxx> #include <svl/stritem.hxx> #include <comphelper/processfactory.hxx> using namespace css; using namespace css::uno; using ::sfx2::sidebar::Theme; namespace chart { namespace sidebar { namespace { css::uno::Reference<css::beans::XPropertySet> getErrorBarPropSet( css::uno::Reference<css::frame::XModel> xModel, const OUString& rCID) { return ObjectIdentifier::getObjectPropertySet(rCID, xModel); } bool showPositiveError(css::uno::Reference<css::frame::XModel> xModel, const OUString& rCID) { css::uno::Reference<css::beans::XPropertySet> xPropSet = getErrorBarPropSet(xModel, rCID); if (!xPropSet.is()) return false; css::uno::Any aAny = xPropSet->getPropertyValue("ShowPositiveError"); if (!aAny.hasValue()) return false; bool bShow = false; aAny >>= bShow; return bShow; } bool showNegativeError(css::uno::Reference<css::frame::XModel> xModel, const OUString& rCID) { css::uno::Reference<css::beans::XPropertySet> xPropSet = getErrorBarPropSet(xModel, rCID); if (!xPropSet.is()) return false; css::uno::Any aAny = xPropSet->getPropertyValue("ShowNegativeError"); if (!aAny.hasValue()) return false; bool bShow = false; aAny >>= bShow; return bShow; } void setShowPositiveError(css::uno::Reference<css::frame::XModel> xModel, const OUString& rCID, bool bShow) { css::uno::Reference<css::beans::XPropertySet> xPropSet = getErrorBarPropSet(xModel, rCID); if (!xPropSet.is()) return; xPropSet->setPropertyValue("ShowPositiveError", css::uno::makeAny(bShow)); } void setShowNegativeError(css::uno::Reference<css::frame::XModel> xModel, const OUString& rCID, bool bShow) { css::uno::Reference<css::beans::XPropertySet> xPropSet = getErrorBarPropSet(xModel, rCID); if (!xPropSet.is()) return; xPropSet->setPropertyValue("ShowNegativeError", css::uno::makeAny(bShow)); } OUString getCID(css::uno::Reference<css::frame::XModel> xModel) { css::uno::Reference<css::frame::XController> xController(xModel->getCurrentController()); css::uno::Reference<css::view::XSelectionSupplier> xSelectionSupplier(xController, css::uno::UNO_QUERY); if (!xSelectionSupplier.is()) return OUString(); uno::Any aAny = xSelectionSupplier->getSelection(); assert(aAny.hasValue()); OUString aCID; aAny >>= aCID; #ifdef DBG_UTIL ObjectType eType = ObjectIdentifier::getObjectType(aCID); assert(eType == OBJECTTYPE_DATA_ERRORS_X || eType == OBJECTTYPE_DATA_ERRORS_Y || eType == OBJECTTYPE_DATA_ERRORS_Z); #endif return aCID; } } ChartErrorBarPanel::ChartErrorBarPanel( vcl::Window* pParent, const css::uno::Reference<css::frame::XFrame>& rxFrame, ChartController* pController) : PanelLayout(pParent, "ChartErrorBarPanel", "modules/schart/ui/sidebarerrorbar.ui", rxFrame), mxFrame(rxFrame), mxModel(pController->getModel()), mxListener(new ChartSidebarModifyListener(this)) { get(mpRBPosAndNeg, "radiobutton_positive_negative"); get(mpRBPos, "radiobutton_positive"); get(mpRBNeg, "radiobutton_negative"); Initialize(); } ChartErrorBarPanel::~ChartErrorBarPanel() { disposeOnce(); } void ChartErrorBarPanel::dispose() { css::uno::Reference<css::util::XModifyBroadcaster> xBroadcaster(mxModel, css::uno::UNO_QUERY_THROW); xBroadcaster->removeModifyListener(mxListener); mpRBPosAndNeg.clear(); mpRBPos.clear(); mpRBNeg.clear(); PanelLayout::dispose(); } void ChartErrorBarPanel::Initialize() { css::uno::Reference<css::util::XModifyBroadcaster> xBroadcaster(mxModel, css::uno::UNO_QUERY_THROW); xBroadcaster->addModifyListener(mxListener); updateData(); Link<> aLink = LINK(this, ChartErrorBarPanel, RadioBtnHdl); mpRBPosAndNeg->SetToggleHdl(aLink); mpRBPos->SetToggleHdl(aLink); mpRBNeg->SetToggleHdl(aLink); } void ChartErrorBarPanel::updateData() { OUString aCID = getCID(mxModel); bool bPos = showPositiveError(mxModel, aCID); bool bNeg = showNegativeError(mxModel, aCID); SolarMutexGuard aGuard; if (bPos && bNeg) mpRBPosAndNeg->Check(true); else if (bPos) mpRBPos->Check(true); else if (bNeg) mpRBNeg->Check(true); } VclPtr<vcl::Window> ChartErrorBarPanel::Create ( vcl::Window* pParent, const css::uno::Reference<css::frame::XFrame>& rxFrame, ChartController* pController) { if (pParent == NULL) throw lang::IllegalArgumentException("no parent Window given to ChartErrorBarPanel::Create", NULL, 0); if ( ! rxFrame.is()) throw lang::IllegalArgumentException("no XFrame given to ChartErrorBarPanel::Create", NULL, 1); return VclPtr<ChartErrorBarPanel>::Create( pParent, rxFrame, pController); } void ChartErrorBarPanel::DataChanged( const DataChangedEvent& ) { updateData(); } void ChartErrorBarPanel::HandleContextChange( const ::sfx2::sidebar::EnumContext& ) { updateData(); } void ChartErrorBarPanel::NotifyItemUpdate( sal_uInt16 /*nSID*/, SfxItemState /*eState*/, const SfxPoolItem* /*pState*/, const bool ) { } void ChartErrorBarPanel::modelInvalid() { } IMPL_LINK_NOARG(ChartErrorBarPanel, RadioBtnHdl) { OUString aCID = getCID(mxModel); bool bPos = mpRBPosAndNeg->IsChecked() || mpRBPos->IsChecked(); bool bNeg = mpRBPosAndNeg->IsChecked() || mpRBNeg->IsChecked(); setShowPositiveError(mxModel, aCID, bPos); setShowNegativeError(mxModel, aCID, bNeg); return 0; } }} // end of namespace ::chart::sidebar /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/format_macros.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome/browser/autocomplete/autocomplete.h" #include "chrome/browser/autocomplete/autocomplete_edit.h" #include "chrome/browser/autocomplete/autocomplete_match.h" #include "chrome/browser/autocomplete/autocomplete_popup_model.h" #include "chrome/browser/history/history.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/omnibox/location_bar.h" #include "chrome/browser/ui/omnibox/omnibox_view.h" #include "chrome/common/url_constants.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/notification_type.h" #include "testing/gtest/include/gtest/gtest.h" // Autocomplete test is flaky on ChromeOS. // http://crbug.com/52928 #if defined(OS_CHROMEOS) #define MAYBE_Autocomplete FLAKY_Autocomplete #else #define MAYBE_Autocomplete Autocomplete #endif namespace { string16 AutocompleteResultAsString(const AutocompleteResult& result) { std::string output(base::StringPrintf("{%" PRIuS "} ", result.size())); for (size_t i = 0; i < result.size(); ++i) { AutocompleteMatch match = result.match_at(i); std::string provider_name = match.provider->name(); output.append(base::StringPrintf("[\"%s\" by \"%s\"] ", UTF16ToUTF8(match.contents).c_str(), provider_name.c_str())); } return UTF8ToUTF16(output); } } // namespace class AutocompleteBrowserTest : public InProcessBrowserTest { protected: LocationBar* GetLocationBar() const { return browser()->window()->GetLocationBar(); } AutocompleteController* GetAutocompleteController() const { return GetLocationBar()->location_entry()->model()->popup_model()-> autocomplete_controller(); } }; IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, Basic) { LocationBar* location_bar = GetLocationBar(); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); // TODO(phajdan.jr): check state of IsSelectAll when it's consistent across // platforms. location_bar->FocusLocation(true); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); EXPECT_TRUE(location_bar->location_entry()->IsSelectAll()); location_bar->location_entry()->SetUserText(ASCIIToUTF16("chrome")); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16("chrome"), location_bar->location_entry()->GetText()); EXPECT_FALSE(location_bar->location_entry()->IsSelectAll()); location_bar->location_entry()->RevertAll(); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); EXPECT_FALSE(location_bar->location_entry()->IsSelectAll()); location_bar->location_entry()->SetUserText(ASCIIToUTF16("chrome")); location_bar->Revert(); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); EXPECT_FALSE(location_bar->location_entry()->IsSelectAll()); } IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, MAYBE_Autocomplete) { // The results depend on the history backend being loaded. Make sure it is // loaded so that the autocomplete results are consistent. ui_test_utils::WaitForHistoryToLoad(browser()); LocationBar* location_bar = GetLocationBar(); AutocompleteController* autocomplete_controller = GetAutocompleteController(); { autocomplete_controller->Start( ASCIIToUTF16("chrome"), string16(), true, false, true, AutocompleteInput::SYNCHRONOUS_MATCHES); EXPECT_TRUE(autocomplete_controller->done()); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_TRUE(location_bar->location_entry()->GetText().empty()); EXPECT_TRUE(location_bar->location_entry()->IsSelectAll()); const AutocompleteResult& result = autocomplete_controller->result(); // We get two matches because we have a provider for extension apps and the // Chrome Web Store is a built-in Extension app. For this test, we only care // about the other match existing. ASSERT_GE(result.size(), 1U) << AutocompleteResultAsString(result); AutocompleteMatch match = result.match_at(0); EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type); EXPECT_FALSE(match.deletable); } { location_bar->Revert(); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); EXPECT_FALSE(location_bar->location_entry()->IsSelectAll()); const AutocompleteResult& result = autocomplete_controller->result(); EXPECT_TRUE(result.empty()) << AutocompleteResultAsString(result); } } IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, TabAwayRevertSelect) { // http://code.google.com/p/chromium/issues/detail?id=38385 // Make sure that tabbing away from an empty omnibar causes a revert // and select all. LocationBar* location_bar = GetLocationBar(); EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); location_bar->location_entry()->SetUserText(string16()); browser()->AddSelectedTabWithURL(GURL(chrome::kAboutBlankURL), PageTransition::START_PAGE); ui_test_utils::WaitForNavigation( &browser()->GetSelectedTabContents()->controller()); EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); browser()->CloseTab(); EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); EXPECT_TRUE(location_bar->location_entry()->IsSelectAll()); } IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, FocusSearch) { LocationBar* location_bar = GetLocationBar(); // Focus search when omnibox is blank { EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); location_bar->FocusSearch(); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16("?"), location_bar->location_entry()->GetText()); size_t selection_start, selection_end; location_bar->location_entry()->GetSelectionBounds(&selection_start, &selection_end); EXPECT_EQ(1U, selection_start); EXPECT_EQ(1U, selection_end); } // Focus search when omnibox is _not_ alread in forced query mode. { location_bar->location_entry()->SetUserText(ASCIIToUTF16("foo")); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16("foo"), location_bar->location_entry()->GetText()); location_bar->FocusSearch(); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16("?"), location_bar->location_entry()->GetText()); size_t selection_start, selection_end; location_bar->location_entry()->GetSelectionBounds(&selection_start, &selection_end); EXPECT_EQ(1U, selection_start); EXPECT_EQ(1U, selection_end); } // Focus search when omnibox _is_ already in forced query mode, but no query // has been typed. { location_bar->location_entry()->SetUserText(ASCIIToUTF16("?")); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16("?"), location_bar->location_entry()->GetText()); location_bar->FocusSearch(); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16("?"), location_bar->location_entry()->GetText()); size_t selection_start, selection_end; location_bar->location_entry()->GetSelectionBounds(&selection_start, &selection_end); EXPECT_EQ(1U, selection_start); EXPECT_EQ(1U, selection_end); } // Focus search when omnibox _is_ already in forced query mode, and some query // has been typed. { location_bar->location_entry()->SetUserText(ASCIIToUTF16("?foo")); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16("?foo"), location_bar->location_entry()->GetText()); location_bar->FocusSearch(); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16("?foo"), location_bar->location_entry()->GetText()); size_t selection_start, selection_end; location_bar->location_entry()->GetSelectionBounds(&selection_start, &selection_end); EXPECT_EQ(1U, std::min(selection_start, selection_end)); EXPECT_EQ(4U, std::max(selection_start, selection_end)); } // Focus search when omnibox is in forced query mode with leading whitespace. { location_bar->location_entry()->SetUserText(ASCIIToUTF16(" ?foo")); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16(" ?foo"), location_bar->location_entry()->GetText()); location_bar->FocusSearch(); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16(" ?foo"), location_bar->location_entry()->GetText()); size_t selection_start, selection_end; location_bar->location_entry()->GetSelectionBounds(&selection_start, &selection_end); EXPECT_EQ(4U, std::min(selection_start, selection_end)); EXPECT_EQ(7U, std::max(selection_start, selection_end)); } } <commit_msg><commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/format_macros.h" #include "base/path_service.h" #include "base/stringprintf.h" #include "base/utf_string_conversions.h" #include "chrome/browser/autocomplete/autocomplete.h" #include "chrome/browser/autocomplete/autocomplete_edit.h" #include "chrome/browser/autocomplete/autocomplete_match.h" #include "chrome/browser/autocomplete/autocomplete_popup_model.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/history/history.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/omnibox/location_bar.h" #include "chrome/browser/ui/omnibox/omnibox_view.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/url_constants.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/common/notification_type.h" #include "testing/gtest/include/gtest/gtest.h" // Autocomplete test is flaky on ChromeOS. // http://crbug.com/52928 #if defined(OS_CHROMEOS) #define MAYBE_Autocomplete FLAKY_Autocomplete #else #define MAYBE_Autocomplete Autocomplete #endif namespace { string16 AutocompleteResultAsString(const AutocompleteResult& result) { std::string output(base::StringPrintf("{%" PRIuS "} ", result.size())); for (size_t i = 0; i < result.size(); ++i) { AutocompleteMatch match = result.match_at(i); std::string provider_name = match.provider->name(); output.append(base::StringPrintf("[\"%s\" by \"%s\"] ", UTF16ToUTF8(match.contents).c_str(), provider_name.c_str())); } return UTF8ToUTF16(output); } } // namespace class AutocompleteBrowserTest : public ExtensionBrowserTest { protected: LocationBar* GetLocationBar() const { return browser()->window()->GetLocationBar(); } AutocompleteController* GetAutocompleteController() const { return GetLocationBar()->location_entry()->model()->popup_model()-> autocomplete_controller(); } }; IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, Basic) { LocationBar* location_bar = GetLocationBar(); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); // TODO(phajdan.jr): check state of IsSelectAll when it's consistent across // platforms. location_bar->FocusLocation(true); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); EXPECT_TRUE(location_bar->location_entry()->IsSelectAll()); location_bar->location_entry()->SetUserText(ASCIIToUTF16("chrome")); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16("chrome"), location_bar->location_entry()->GetText()); EXPECT_FALSE(location_bar->location_entry()->IsSelectAll()); location_bar->location_entry()->RevertAll(); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); EXPECT_FALSE(location_bar->location_entry()->IsSelectAll()); location_bar->location_entry()->SetUserText(ASCIIToUTF16("chrome")); location_bar->Revert(); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); EXPECT_FALSE(location_bar->location_entry()->IsSelectAll()); } IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, MAYBE_Autocomplete) { // The results depend on the history backend being loaded. Make sure it is // loaded so that the autocomplete results are consistent. ui_test_utils::WaitForHistoryToLoad(browser()); LocationBar* location_bar = GetLocationBar(); AutocompleteController* autocomplete_controller = GetAutocompleteController(); { autocomplete_controller->Start( ASCIIToUTF16("chrome"), string16(), true, false, true, AutocompleteInput::SYNCHRONOUS_MATCHES); EXPECT_TRUE(autocomplete_controller->done()); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_TRUE(location_bar->location_entry()->GetText().empty()); EXPECT_TRUE(location_bar->location_entry()->IsSelectAll()); const AutocompleteResult& result = autocomplete_controller->result(); // We get two matches because we have a provider for extension apps and the // Chrome Web Store is a built-in Extension app. For this test, we only care // about the other match existing. ASSERT_GE(result.size(), 1U) << AutocompleteResultAsString(result); AutocompleteMatch match = result.match_at(0); EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type); EXPECT_FALSE(match.deletable); } { location_bar->Revert(); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); EXPECT_FALSE(location_bar->location_entry()->IsSelectAll()); const AutocompleteResult& result = autocomplete_controller->result(); EXPECT_TRUE(result.empty()) << AutocompleteResultAsString(result); } } IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, TabAwayRevertSelect) { // http://code.google.com/p/chromium/issues/detail?id=38385 // Make sure that tabbing away from an empty omnibar causes a revert // and select all. LocationBar* location_bar = GetLocationBar(); EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); location_bar->location_entry()->SetUserText(string16()); browser()->AddSelectedTabWithURL(GURL(chrome::kAboutBlankURL), PageTransition::START_PAGE); ui_test_utils::WaitForNavigation( &browser()->GetSelectedTabContents()->controller()); EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); browser()->CloseTab(); EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); EXPECT_TRUE(location_bar->location_entry()->IsSelectAll()); } IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, FocusSearch) { LocationBar* location_bar = GetLocationBar(); // Focus search when omnibox is blank { EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(UTF8ToUTF16(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); location_bar->FocusSearch(); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16("?"), location_bar->location_entry()->GetText()); size_t selection_start, selection_end; location_bar->location_entry()->GetSelectionBounds(&selection_start, &selection_end); EXPECT_EQ(1U, selection_start); EXPECT_EQ(1U, selection_end); } // Focus search when omnibox is _not_ alread in forced query mode. { location_bar->location_entry()->SetUserText(ASCIIToUTF16("foo")); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16("foo"), location_bar->location_entry()->GetText()); location_bar->FocusSearch(); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16("?"), location_bar->location_entry()->GetText()); size_t selection_start, selection_end; location_bar->location_entry()->GetSelectionBounds(&selection_start, &selection_end); EXPECT_EQ(1U, selection_start); EXPECT_EQ(1U, selection_end); } // Focus search when omnibox _is_ already in forced query mode, but no query // has been typed. { location_bar->location_entry()->SetUserText(ASCIIToUTF16("?")); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16("?"), location_bar->location_entry()->GetText()); location_bar->FocusSearch(); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16("?"), location_bar->location_entry()->GetText()); size_t selection_start, selection_end; location_bar->location_entry()->GetSelectionBounds(&selection_start, &selection_end); EXPECT_EQ(1U, selection_start); EXPECT_EQ(1U, selection_end); } // Focus search when omnibox _is_ already in forced query mode, and some query // has been typed. { location_bar->location_entry()->SetUserText(ASCIIToUTF16("?foo")); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16("?foo"), location_bar->location_entry()->GetText()); location_bar->FocusSearch(); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16("?foo"), location_bar->location_entry()->GetText()); size_t selection_start, selection_end; location_bar->location_entry()->GetSelectionBounds(&selection_start, &selection_end); EXPECT_EQ(1U, std::min(selection_start, selection_end)); EXPECT_EQ(4U, std::max(selection_start, selection_end)); } // Focus search when omnibox is in forced query mode with leading whitespace. { location_bar->location_entry()->SetUserText(ASCIIToUTF16(" ?foo")); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16(" ?foo"), location_bar->location_entry()->GetText()); location_bar->FocusSearch(); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_EQ(ASCIIToUTF16(" ?foo"), location_bar->location_entry()->GetText()); size_t selection_start, selection_end; location_bar->location_entry()->GetSelectionBounds(&selection_start, &selection_end); EXPECT_EQ(4U, std::min(selection_start, selection_end)); EXPECT_EQ(7U, std::max(selection_start, selection_end)); } } IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, ExtensionAppProvider) { ExtensionService* service = browser()->profile()->GetExtensionService(); size_t extension_count = service->extensions()->size(); FilePath test_dir; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir)); // Load a packaged app. service->LoadExtension(test_dir.AppendASCII("extensions") .AppendASCII("packaged_app")); WaitForExtensionLoad(); // Load a hosted app. service->LoadExtension(test_dir.AppendASCII("extensions") .AppendASCII("app")); WaitForExtensionLoad(); ASSERT_EQ(extension_count + 2U, service->extensions()->size()); // The results depend on the history backend being loaded. Make sure it is // loaded so that the autocomplete results are consistent. ui_test_utils::WaitForHistoryToLoad(browser()); LocationBar* location_bar = GetLocationBar(); AutocompleteController* autocomplete_controller = GetAutocompleteController(); // Try out the packaged app. { autocomplete_controller->Start( ASCIIToUTF16("Packaged App Test"), string16(), true, false, true, AutocompleteInput::SYNCHRONOUS_MATCHES); EXPECT_TRUE(autocomplete_controller->done()); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_TRUE(location_bar->location_entry()->GetText().empty()); EXPECT_TRUE(location_bar->location_entry()->IsSelectAll()); const AutocompleteResult& result = autocomplete_controller->result(); EXPECT_GT(result.size(), 1U) << AutocompleteResultAsString(result); AutocompleteMatch match = result.match_at(0); EXPECT_EQ(ASCIIToUTF16("Packaged App Test"), match.contents); EXPECT_EQ(AutocompleteMatch::EXTENSION_APP, match.type); EXPECT_FALSE(match.deletable); location_bar->AcceptInput(); } browser()->NewTab(); // Try out the hosted app. { autocomplete_controller->Start( ASCIIToUTF16("App Test"), string16(), true, false, true, AutocompleteInput::SYNCHRONOUS_MATCHES); EXPECT_TRUE(autocomplete_controller->done()); EXPECT_TRUE(location_bar->GetInputString().empty()); EXPECT_TRUE(location_bar->location_entry()->GetText().empty()); EXPECT_TRUE(location_bar->location_entry()->IsSelectAll()); const AutocompleteResult& result = autocomplete_controller->result(); // 'App test' is also a substring of extension 'Packaged App Test'. EXPECT_GT(result.size(), 2U) << AutocompleteResultAsString(result); AutocompleteMatch match = result.match_at(0); EXPECT_EQ(ASCIIToUTF16("App Test"), match.contents); EXPECT_EQ(AutocompleteMatch::EXTENSION_APP, match.type); EXPECT_FALSE(match.deletable); location_bar->AcceptInput(); } } <|endoftext|>
<commit_before>// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "chrome/browser/browser.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/user_script_master.h" #include "chrome/browser/profile.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_details.h" #include "chrome/common/notification_observer.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "net/base/net_util.h" // This file contains high-level startup tests for the extensions system. We've // had many silly bugs where command line flags did not get propagated correctly // into the services, so we didn't start correctly. class ExtensionStartupTestBase : public InProcessBrowserTest { public: ExtensionStartupTestBase() : enable_extensions_(false) { } protected: // InProcessBrowserTest virtual void SetUpCommandLine(CommandLine* command_line) { EnableDOMAutomation(); FilePath profile_dir; PathService::Get(chrome::DIR_USER_DATA, &profile_dir); profile_dir = profile_dir.AppendASCII("Default"); file_util::CreateDirectory(profile_dir); preferences_file_ = profile_dir.AppendASCII("Preferences"); user_scripts_dir_ = profile_dir.AppendASCII("User Scripts"); extensions_dir_ = profile_dir.AppendASCII("Extensions"); if (enable_extensions_) { FilePath src_dir; PathService::Get(chrome::DIR_TEST_DATA, &src_dir); src_dir = src_dir.AppendASCII("extensions").AppendASCII("good"); file_util::CopyFile(src_dir.AppendASCII("Preferences"), preferences_file_); file_util::CopyDirectory(src_dir.AppendASCII("Extensions"), profile_dir, true); // recursive } else { command_line->AppendSwitch(switches::kDisableExtensions); } if (!load_extension_.value().empty()) { command_line->AppendSwitchWithValue(switches::kLoadExtension, load_extension_.ToWStringHack()); } } virtual void TearDown() { EXPECT_TRUE(file_util::Delete(preferences_file_, false)); EXPECT_TRUE(file_util::Delete(user_scripts_dir_, true)); EXPECT_TRUE(file_util::Delete(extensions_dir_, true)); } void WaitForServicesToStart(int num_expected_extensions, bool expect_extensions_enabled) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); if (!service->is_ready()) ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY); ASSERT_TRUE(service->is_ready()); ASSERT_EQ(static_cast<uint32>(num_expected_extensions), service->extensions()->size()); ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled()); UserScriptMaster* master = browser()->profile()->GetUserScriptMaster(); if (!master->ScriptsReady()) { ui_test_utils::WaitForNotification( NotificationType::USER_SCRIPTS_UPDATED); } ASSERT_TRUE(master->ScriptsReady()); } void TestInjection(bool expect_css, bool expect_script) { // Load a page affected by the content script and test to see the effect. FilePath test_file; PathService::Get(chrome::DIR_TEST_DATA, &test_file); test_file = test_file.AppendASCII("extensions") .AppendASCII("test_file.html"); ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file)); bool result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(" L"document.defaultView.getComputedStyle(document.body, null)." L"getPropertyValue('background-color') == 'rgb(245, 245, 220)')", &result); EXPECT_EQ(expect_css, result); result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(document.title == 'Modified')", &result); EXPECT_EQ(expect_script, result); } FilePath preferences_file_; FilePath extensions_dir_; FilePath user_scripts_dir_; bool enable_extensions_; FilePath load_extension_; }; // ExtensionsStartupTest // Ensures that we can startup the browser with --enable-extensions and some // extensions installed and see them run and do basic things. class ExtensionsStartupTest : public ExtensionStartupTestBase { public: ExtensionsStartupTest() { enable_extensions_ = true; } }; IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, Test) { WaitForServicesToStart(4, true); // 1 component extension and 3 others. TestInjection(true, true); } // ExtensionsLoadTest // Ensures that we can startup the browser with --load-extension and see them // run. class ExtensionsLoadTest : public ExtensionStartupTestBase { public: ExtensionsLoadTest() { PathService::Get(chrome::DIR_TEST_DATA, &load_extension_); load_extension_ = load_extension_ .AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj") .AppendASCII("1.0.0.0"); } }; IN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, Test) { WaitForServicesToStart(1, false); TestInjection(true, true); } <commit_msg>Do not make the tests fail on failed file deletes.<commit_after>// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "chrome/browser/browser.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/user_script_master.h" #include "chrome/browser/profile.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_details.h" #include "chrome/common/notification_observer.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "net/base/net_util.h" // This file contains high-level startup tests for the extensions system. We've // had many silly bugs where command line flags did not get propagated correctly // into the services, so we didn't start correctly. class ExtensionStartupTestBase : public InProcessBrowserTest { public: ExtensionStartupTestBase() : enable_extensions_(false) { } protected: // InProcessBrowserTest virtual void SetUpCommandLine(CommandLine* command_line) { EnableDOMAutomation(); FilePath profile_dir; PathService::Get(chrome::DIR_USER_DATA, &profile_dir); profile_dir = profile_dir.AppendASCII("Default"); file_util::CreateDirectory(profile_dir); preferences_file_ = profile_dir.AppendASCII("Preferences"); user_scripts_dir_ = profile_dir.AppendASCII("User Scripts"); extensions_dir_ = profile_dir.AppendASCII("Extensions"); if (enable_extensions_) { FilePath src_dir; PathService::Get(chrome::DIR_TEST_DATA, &src_dir); src_dir = src_dir.AppendASCII("extensions").AppendASCII("good"); file_util::CopyFile(src_dir.AppendASCII("Preferences"), preferences_file_); file_util::CopyDirectory(src_dir.AppendASCII("Extensions"), profile_dir, true); // recursive } else { command_line->AppendSwitch(switches::kDisableExtensions); } if (!load_extension_.value().empty()) { command_line->AppendSwitchWithValue(switches::kLoadExtension, load_extension_.ToWStringHack()); } } virtual void TearDown() { EXPECT_TRUE(file_util::Delete(preferences_file_, false)); // TODO(phajdan.jr): Check return values of the functions below, carefully. file_util::Delete(user_scripts_dir_, true); file_util::Delete(extensions_dir_, true)); } void WaitForServicesToStart(int num_expected_extensions, bool expect_extensions_enabled) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); if (!service->is_ready()) ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY); ASSERT_TRUE(service->is_ready()); ASSERT_EQ(static_cast<uint32>(num_expected_extensions), service->extensions()->size()); ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled()); UserScriptMaster* master = browser()->profile()->GetUserScriptMaster(); if (!master->ScriptsReady()) { ui_test_utils::WaitForNotification( NotificationType::USER_SCRIPTS_UPDATED); } ASSERT_TRUE(master->ScriptsReady()); } void TestInjection(bool expect_css, bool expect_script) { // Load a page affected by the content script and test to see the effect. FilePath test_file; PathService::Get(chrome::DIR_TEST_DATA, &test_file); test_file = test_file.AppendASCII("extensions") .AppendASCII("test_file.html"); ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file)); bool result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(" L"document.defaultView.getComputedStyle(document.body, null)." L"getPropertyValue('background-color') == 'rgb(245, 245, 220)')", &result); EXPECT_EQ(expect_css, result); result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(document.title == 'Modified')", &result); EXPECT_EQ(expect_script, result); } FilePath preferences_file_; FilePath extensions_dir_; FilePath user_scripts_dir_; bool enable_extensions_; FilePath load_extension_; }; // ExtensionsStartupTest // Ensures that we can startup the browser with --enable-extensions and some // extensions installed and see them run and do basic things. class ExtensionsStartupTest : public ExtensionStartupTestBase { public: ExtensionsStartupTest() { enable_extensions_ = true; } }; IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, Test) { WaitForServicesToStart(4, true); // 1 component extension and 3 others. TestInjection(true, true); } // ExtensionsLoadTest // Ensures that we can startup the browser with --load-extension and see them // run. class ExtensionsLoadTest : public ExtensionStartupTestBase { public: ExtensionsLoadTest() { PathService::Get(chrome::DIR_TEST_DATA, &load_extension_); load_extension_ = load_extension_ .AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj") .AppendASCII("1.0.0.0"); } }; IN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, Test) { WaitForServicesToStart(1, false); TestInjection(true, true); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/in_process_webkit/dom_storage_context.h" #include <algorithm> #include "base/file_path.h" #include "base/file_util.h" #include "base/string_util.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/in_process_webkit/dom_storage_area.h" #include "chrome/browser/in_process_webkit/dom_storage_namespace.h" #include "chrome/browser/in_process_webkit/webkit_context.h" #include "chrome/common/dom_storage_common.h" #include "third_party/WebKit/WebKit/chromium/public/WebSecurityOrigin.h" #include "third_party/WebKit/WebKit/chromium/public/WebString.h" #include "webkit/glue/webkit_glue.h" const FilePath::CharType DOMStorageContext::kLocalStorageDirectory[] = FILE_PATH_LITERAL("Local Storage"); const FilePath::CharType DOMStorageContext::kLocalStorageExtension[] = FILE_PATH_LITERAL(".localstorage"); static const FilePath::CharType kLocalStorageOldPath[] = FILE_PATH_LITERAL("localStorage"); // TODO(jorlow): Remove after Chrome 4 ships. static void MigrateLocalStorageDirectory(const FilePath& data_path) { FilePath new_path = data_path.Append( DOMStorageContext::kLocalStorageDirectory); FilePath old_path = data_path.Append(kLocalStorageOldPath); if (!file_util::DirectoryExists(new_path) && file_util::DirectoryExists(old_path)) { file_util::Move(old_path, new_path); } } DOMStorageContext::DOMStorageContext(WebKitContext* webkit_context) : last_storage_area_id_(0), last_session_storage_namespace_id_on_ui_thread_(kLocalStorageNamespaceId), last_session_storage_namespace_id_on_io_thread_(kLocalStorageNamespaceId), webkit_context_(webkit_context) { } DOMStorageContext::~DOMStorageContext() { // This should not go away until all DOM Storage Dispatcher hosts have gone // away. And they remove themselves from this list. DCHECK(dispatcher_host_set_.empty()); for (StorageNamespaceMap::iterator iter(storage_namespace_map_.begin()); iter != storage_namespace_map_.end(); ++iter) { delete iter->second; } } int64 DOMStorageContext::AllocateStorageAreaId() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); return ++last_storage_area_id_; } int64 DOMStorageContext::AllocateSessionStorageNamespaceId() { if (BrowserThread::CurrentlyOn(BrowserThread::UI)) return ++last_session_storage_namespace_id_on_ui_thread_; return --last_session_storage_namespace_id_on_io_thread_; } int64 DOMStorageContext::CloneSessionStorage(int64 original_id) { DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); int64 clone_id = AllocateSessionStorageNamespaceId(); BrowserThread::PostTask( BrowserThread::WEBKIT, FROM_HERE, NewRunnableFunction( &DOMStorageContext::CompleteCloningSessionStorage, this, original_id, clone_id)); return clone_id; } void DOMStorageContext::RegisterStorageArea(DOMStorageArea* storage_area) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); int64 id = storage_area->id(); DCHECK(!GetStorageArea(id)); storage_area_map_[id] = storage_area; } void DOMStorageContext::UnregisterStorageArea(DOMStorageArea* storage_area) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); int64 id = storage_area->id(); DCHECK(GetStorageArea(id)); storage_area_map_.erase(id); } DOMStorageArea* DOMStorageContext::GetStorageArea(int64 id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); StorageAreaMap::iterator iter = storage_area_map_.find(id); if (iter == storage_area_map_.end()) return NULL; return iter->second; } void DOMStorageContext::DeleteSessionStorageNamespace(int64 namespace_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); StorageNamespaceMap::iterator iter = storage_namespace_map_.find(namespace_id); if (iter == storage_namespace_map_.end()) return; DCHECK(iter->second->dom_storage_type() == DOM_STORAGE_SESSION); delete iter->second; storage_namespace_map_.erase(iter); } DOMStorageNamespace* DOMStorageContext::GetStorageNamespace( int64 id, bool allocation_allowed) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); StorageNamespaceMap::iterator iter = storage_namespace_map_.find(id); if (iter != storage_namespace_map_.end()) return iter->second; if (!allocation_allowed) return NULL; if (id == kLocalStorageNamespaceId) return CreateLocalStorage(); return CreateSessionStorage(id); } void DOMStorageContext::RegisterDispatcherHost( DOMStorageDispatcherHost* dispatcher_host) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(dispatcher_host_set_.find(dispatcher_host) == dispatcher_host_set_.end()); dispatcher_host_set_.insert(dispatcher_host); } void DOMStorageContext::UnregisterDispatcherHost( DOMStorageDispatcherHost* dispatcher_host) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(dispatcher_host_set_.find(dispatcher_host) != dispatcher_host_set_.end()); dispatcher_host_set_.erase(dispatcher_host); } const DOMStorageContext::DispatcherHostSet* DOMStorageContext::GetDispatcherHostSet() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); return &dispatcher_host_set_; } void DOMStorageContext::PurgeMemory() { // It is only safe to purge the memory from the LocalStorage namespace, // because it is backed by disk and can be reloaded later. If we purge a // SessionStorage namespace, its data will be gone forever, because it isn't // currently backed by disk. DOMStorageNamespace* local_storage = GetStorageNamespace(kLocalStorageNamespaceId, false); if (local_storage) local_storage->PurgeMemory(); } void DOMStorageContext::DeleteDataModifiedSince( const base::Time& cutoff, const char* url_scheme_to_be_skipped, const std::vector<string16>& protected_origins) { // Make sure that we don't delete a database that's currently being accessed // by unloading all of the databases temporarily. PurgeMemory(); file_util::FileEnumerator file_enumerator( webkit_context_->data_path().Append(kLocalStorageDirectory), false, file_util::FileEnumerator::FILES); for (FilePath path = file_enumerator.Next(); !path.value().empty(); path = file_enumerator.Next()) { WebKit::WebSecurityOrigin web_security_origin = WebKit::WebSecurityOrigin::createFromDatabaseIdentifier( webkit_glue::FilePathToWebString(path.BaseName())); if (EqualsASCII(web_security_origin.protocol(), url_scheme_to_be_skipped)) continue; std::vector<string16>::const_iterator find_iter = std::find(protected_origins.begin(), protected_origins.end(), web_security_origin.databaseIdentifier()); if (find_iter != protected_origins.end()) continue; file_util::FileEnumerator::FindInfo find_info; file_enumerator.GetFindInfo(&find_info); if (file_util::HasFileBeenModifiedSince(find_info, cutoff)) file_util::Delete(path, false); } } void DOMStorageContext::DeleteLocalStorageFile(const FilePath& file_path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); // Make sure that we don't delete a database that's currently being accessed // by unloading all of the databases temporarily. // TODO(bulach): both this method and DeleteDataModifiedSince could purge // only the memory used by the specific file instead of all memory at once. // See http://crbug.com/32000 PurgeMemory(); file_util::Delete(file_path, false); } void DOMStorageContext::DeleteLocalStorageForOrigin(const string16& origin_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); DeleteLocalStorageFile(GetLocalStorageFilePath(origin_id)); } void DOMStorageContext::DeleteAllLocalStorageFiles() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); // Make sure that we don't delete a database that's currently being accessed // by unloading all of the databases temporarily. PurgeMemory(); file_util::FileEnumerator file_enumerator( webkit_context_->data_path().Append(kLocalStorageDirectory), false, file_util::FileEnumerator::FILES); for (FilePath file_path = file_enumerator.Next(); !file_path.empty(); file_path = file_enumerator.Next()) { if (file_path.Extension() == kLocalStorageExtension) file_util::Delete(file_path, false); } } DOMStorageNamespace* DOMStorageContext::CreateLocalStorage() { FilePath data_path = webkit_context_->data_path(); FilePath dir_path; if (!data_path.empty()) { MigrateLocalStorageDirectory(data_path); dir_path = data_path.Append(kLocalStorageDirectory); } DOMStorageNamespace* new_namespace = DOMStorageNamespace::CreateLocalStorageNamespace(this, dir_path); RegisterStorageNamespace(new_namespace); return new_namespace; } DOMStorageNamespace* DOMStorageContext::CreateSessionStorage( int64 namespace_id) { DOMStorageNamespace* new_namespace = DOMStorageNamespace::CreateSessionStorageNamespace(this, namespace_id); RegisterStorageNamespace(new_namespace); return new_namespace; } void DOMStorageContext::RegisterStorageNamespace( DOMStorageNamespace* storage_namespace) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); int64 id = storage_namespace->id(); DCHECK(!GetStorageNamespace(id, false)); storage_namespace_map_[id] = storage_namespace; } /* static */ void DOMStorageContext::CompleteCloningSessionStorage( DOMStorageContext* context, int64 existing_id, int64 clone_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); DOMStorageNamespace* existing_namespace = context->GetStorageNamespace(existing_id, false); // If nothing exists, then there's nothing to clone. if (existing_namespace) context->RegisterStorageNamespace(existing_namespace->Copy(clone_id)); } // static void DOMStorageContext::ClearLocalState(const FilePath& profile_path, const char* url_scheme_to_be_skipped) { file_util::FileEnumerator file_enumerator(profile_path.Append( kLocalStorageDirectory), false, file_util::FileEnumerator::FILES); for (FilePath file_path = file_enumerator.Next(); !file_path.empty(); file_path = file_enumerator.Next()) { if (file_path.Extension() == kLocalStorageExtension) { WebKit::WebSecurityOrigin web_security_origin = WebKit::WebSecurityOrigin::createFromDatabaseIdentifier( webkit_glue::FilePathToWebString(file_path.BaseName())); if (!EqualsASCII(web_security_origin.protocol(), url_scheme_to_be_skipped)) file_util::Delete(file_path, false); } } } FilePath DOMStorageContext::GetLocalStorageFilePath( const string16& origin_id) const { FilePath storageDir = webkit_context_->data_path().Append( DOMStorageContext::kLocalStorageDirectory); FilePath::StringType id = webkit_glue::WebStringToFilePathString(origin_id); return storageDir.Append(id.append(kLocalStorageExtension)); } <commit_msg>Coding style clean up of DomStorageContext.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/in_process_webkit/dom_storage_context.h" #include <algorithm> #include "base/file_path.h" #include "base/file_util.h" #include "base/string_util.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/in_process_webkit/dom_storage_area.h" #include "chrome/browser/in_process_webkit/dom_storage_namespace.h" #include "chrome/browser/in_process_webkit/webkit_context.h" #include "chrome/common/dom_storage_common.h" #include "third_party/WebKit/WebKit/chromium/public/WebSecurityOrigin.h" #include "third_party/WebKit/WebKit/chromium/public/WebString.h" #include "webkit/glue/webkit_glue.h" using WebKit::WebSecurityOrigin; const FilePath::CharType DOMStorageContext::kLocalStorageDirectory[] = FILE_PATH_LITERAL("Local Storage"); const FilePath::CharType DOMStorageContext::kLocalStorageExtension[] = FILE_PATH_LITERAL(".localstorage"); static const FilePath::CharType kLocalStorageOldPath[] = FILE_PATH_LITERAL("localStorage"); // TODO(jorlow): Remove after Chrome 4 ships. static void MigrateLocalStorageDirectory(const FilePath& data_path) { FilePath new_path = data_path.Append( DOMStorageContext::kLocalStorageDirectory); FilePath old_path = data_path.Append(kLocalStorageOldPath); if (!file_util::DirectoryExists(new_path) && file_util::DirectoryExists(old_path)) { file_util::Move(old_path, new_path); } } DOMStorageContext::DOMStorageContext(WebKitContext* webkit_context) : last_storage_area_id_(0), last_session_storage_namespace_id_on_ui_thread_(kLocalStorageNamespaceId), last_session_storage_namespace_id_on_io_thread_(kLocalStorageNamespaceId), webkit_context_(webkit_context) { } DOMStorageContext::~DOMStorageContext() { // This should not go away until all DOM Storage Dispatcher hosts have gone // away. And they remove themselves from this list. DCHECK(dispatcher_host_set_.empty()); for (StorageNamespaceMap::iterator iter(storage_namespace_map_.begin()); iter != storage_namespace_map_.end(); ++iter) { delete iter->second; } } int64 DOMStorageContext::AllocateStorageAreaId() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); return ++last_storage_area_id_; } int64 DOMStorageContext::AllocateSessionStorageNamespaceId() { if (BrowserThread::CurrentlyOn(BrowserThread::UI)) return ++last_session_storage_namespace_id_on_ui_thread_; return --last_session_storage_namespace_id_on_io_thread_; } int64 DOMStorageContext::CloneSessionStorage(int64 original_id) { DCHECK(!BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); int64 clone_id = AllocateSessionStorageNamespaceId(); BrowserThread::PostTask( BrowserThread::WEBKIT, FROM_HERE, NewRunnableFunction( &DOMStorageContext::CompleteCloningSessionStorage, this, original_id, clone_id)); return clone_id; } void DOMStorageContext::RegisterStorageArea(DOMStorageArea* storage_area) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); int64 id = storage_area->id(); DCHECK(!GetStorageArea(id)); storage_area_map_[id] = storage_area; } void DOMStorageContext::UnregisterStorageArea(DOMStorageArea* storage_area) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); int64 id = storage_area->id(); DCHECK(GetStorageArea(id)); storage_area_map_.erase(id); } DOMStorageArea* DOMStorageContext::GetStorageArea(int64 id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); StorageAreaMap::iterator iter = storage_area_map_.find(id); if (iter == storage_area_map_.end()) return NULL; return iter->second; } void DOMStorageContext::DeleteSessionStorageNamespace(int64 namespace_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); StorageNamespaceMap::iterator iter = storage_namespace_map_.find(namespace_id); if (iter == storage_namespace_map_.end()) return; DCHECK(iter->second->dom_storage_type() == DOM_STORAGE_SESSION); delete iter->second; storage_namespace_map_.erase(iter); } DOMStorageNamespace* DOMStorageContext::GetStorageNamespace( int64 id, bool allocation_allowed) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); StorageNamespaceMap::iterator iter = storage_namespace_map_.find(id); if (iter != storage_namespace_map_.end()) return iter->second; if (!allocation_allowed) return NULL; if (id == kLocalStorageNamespaceId) return CreateLocalStorage(); return CreateSessionStorage(id); } void DOMStorageContext::RegisterDispatcherHost( DOMStorageDispatcherHost* dispatcher_host) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(dispatcher_host_set_.find(dispatcher_host) == dispatcher_host_set_.end()); dispatcher_host_set_.insert(dispatcher_host); } void DOMStorageContext::UnregisterDispatcherHost( DOMStorageDispatcherHost* dispatcher_host) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(dispatcher_host_set_.find(dispatcher_host) != dispatcher_host_set_.end()); dispatcher_host_set_.erase(dispatcher_host); } const DOMStorageContext::DispatcherHostSet* DOMStorageContext::GetDispatcherHostSet() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); return &dispatcher_host_set_; } void DOMStorageContext::PurgeMemory() { // It is only safe to purge the memory from the LocalStorage namespace, // because it is backed by disk and can be reloaded later. If we purge a // SessionStorage namespace, its data will be gone forever, because it isn't // currently backed by disk. DOMStorageNamespace* local_storage = GetStorageNamespace(kLocalStorageNamespaceId, false); if (local_storage) local_storage->PurgeMemory(); } void DOMStorageContext::DeleteDataModifiedSince( const base::Time& cutoff, const char* url_scheme_to_be_skipped, const std::vector<string16>& protected_origins) { // Make sure that we don't delete a database that's currently being accessed // by unloading all of the databases temporarily. PurgeMemory(); file_util::FileEnumerator file_enumerator( webkit_context_->data_path().Append(kLocalStorageDirectory), false, file_util::FileEnumerator::FILES); for (FilePath path = file_enumerator.Next(); !path.value().empty(); path = file_enumerator.Next()) { WebSecurityOrigin web_security_origin = WebSecurityOrigin::createFromDatabaseIdentifier( webkit_glue::FilePathToWebString(path.BaseName())); if (EqualsASCII(web_security_origin.protocol(), url_scheme_to_be_skipped)) continue; std::vector<string16>::const_iterator find_iter = std::find(protected_origins.begin(), protected_origins.end(), web_security_origin.databaseIdentifier()); if (find_iter != protected_origins.end()) continue; file_util::FileEnumerator::FindInfo find_info; file_enumerator.GetFindInfo(&find_info); if (file_util::HasFileBeenModifiedSince(find_info, cutoff)) file_util::Delete(path, false); } } void DOMStorageContext::DeleteLocalStorageFile(const FilePath& file_path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); // Make sure that we don't delete a database that's currently being accessed // by unloading all of the databases temporarily. // TODO(bulach): both this method and DeleteDataModifiedSince could purge // only the memory used by the specific file instead of all memory at once. // See http://crbug.com/32000 PurgeMemory(); file_util::Delete(file_path, false); } void DOMStorageContext::DeleteLocalStorageForOrigin(const string16& origin_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); DeleteLocalStorageFile(GetLocalStorageFilePath(origin_id)); } void DOMStorageContext::DeleteAllLocalStorageFiles() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); // Make sure that we don't delete a database that's currently being accessed // by unloading all of the databases temporarily. PurgeMemory(); file_util::FileEnumerator file_enumerator( webkit_context_->data_path().Append(kLocalStorageDirectory), false, file_util::FileEnumerator::FILES); for (FilePath file_path = file_enumerator.Next(); !file_path.empty(); file_path = file_enumerator.Next()) { if (file_path.Extension() == kLocalStorageExtension) file_util::Delete(file_path, false); } } DOMStorageNamespace* DOMStorageContext::CreateLocalStorage() { FilePath data_path = webkit_context_->data_path(); FilePath dir_path; if (!data_path.empty()) { MigrateLocalStorageDirectory(data_path); dir_path = data_path.Append(kLocalStorageDirectory); } DOMStorageNamespace* new_namespace = DOMStorageNamespace::CreateLocalStorageNamespace(this, dir_path); RegisterStorageNamespace(new_namespace); return new_namespace; } DOMStorageNamespace* DOMStorageContext::CreateSessionStorage( int64 namespace_id) { DOMStorageNamespace* new_namespace = DOMStorageNamespace::CreateSessionStorageNamespace(this, namespace_id); RegisterStorageNamespace(new_namespace); return new_namespace; } void DOMStorageContext::RegisterStorageNamespace( DOMStorageNamespace* storage_namespace) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); int64 id = storage_namespace->id(); DCHECK(!GetStorageNamespace(id, false)); storage_namespace_map_[id] = storage_namespace; } /* static */ void DOMStorageContext::CompleteCloningSessionStorage( DOMStorageContext* context, int64 existing_id, int64 clone_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT)); DOMStorageNamespace* existing_namespace = context->GetStorageNamespace(existing_id, false); // If nothing exists, then there's nothing to clone. if (existing_namespace) context->RegisterStorageNamespace(existing_namespace->Copy(clone_id)); } // static void DOMStorageContext::ClearLocalState(const FilePath& profile_path, const char* url_scheme_to_be_skipped) { file_util::FileEnumerator file_enumerator(profile_path.Append( kLocalStorageDirectory), false, file_util::FileEnumerator::FILES); for (FilePath file_path = file_enumerator.Next(); !file_path.empty(); file_path = file_enumerator.Next()) { if (file_path.Extension() == kLocalStorageExtension) { WebSecurityOrigin web_security_origin = WebSecurityOrigin::createFromDatabaseIdentifier( webkit_glue::FilePathToWebString(file_path.BaseName())); if (!EqualsASCII(web_security_origin.protocol(), url_scheme_to_be_skipped)) { file_util::Delete(file_path, false); } } } } FilePath DOMStorageContext::GetLocalStorageFilePath( const string16& origin_id) const { FilePath storageDir = webkit_context_->data_path().Append( DOMStorageContext::kLocalStorageDirectory); FilePath::StringType id = webkit_glue::WebStringToFilePathString(origin_id); return storageDir.Append(id.append(kLocalStorageExtension)); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/password_manager/login_database.h" #include "base/utf_string_conversions.h" // TODO: Actually encrypt passwords on Linux. std::string LoginDatabase::EncryptedString(const string16& plain_text) const { return UTF16ToUTF8(plain_text); } string16 LoginDatabase::DecryptedString(const std::string& cipher_text) const { return ASCIIToUTF16(cipher_text); } <commit_msg>Linux: fix retrieving passwords with non-ASCII characters from the default password store. TEST=save a password containing a non-ASCII character, it should autofill correctly BUG=54065 Review URL: http://codereview.chromium.org/3316014<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/password_manager/login_database.h" #include "base/utf_string_conversions.h" // TODO: Actually encrypt passwords on Linux. std::string LoginDatabase::EncryptedString(const string16& plain_text) const { return UTF16ToUTF8(plain_text); } string16 LoginDatabase::DecryptedString(const std::string& cipher_text) const { return UTF8ToUTF16(cipher_text); } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2009-2012, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #ifndef ORGANIZED_COMPRESSION_HPP #define ORGANIZED_COMPRESSION_HPP #include <pcl/compression/organized_pointcloud_compression.h> #include <pcl/pcl_macros.h> #include <pcl/point_cloud.h> #include <pcl/common/boost.h> #include <pcl/common/eigen.h> #include <pcl/common/common.h> #include <pcl/common/io.h> #include <pcl/compression/libpng_wrapper.h> #include <pcl/compression/organized_pointcloud_conversion.h> #include <string> #include <vector> #include <limits> #include <assert.h> namespace pcl { namespace io { ////////////////////////////////////////////////////////////////////////////////////////////// template<typename PointT> void OrganizedPointCloudCompression<PointT>::encodePointCloud (const PointCloudConstPtr &cloud_arg, std::ostream& compressedDataOut_arg, bool doColorEncoding, bool bShowStatistics_arg, int pngLevel_arg, float depthQuantization_arg) { uint32_t cloud_width = cloud_arg->width; uint32_t cloud_height = cloud_arg->height; float maxDepth, vocalLength; analyzeOrganizedCloud (cloud_arg, maxDepth, vocalLength); // encode header identifier compressedDataOut_arg.write (reinterpret_cast<const char*> (frameHeaderIdentifier_), strlen (frameHeaderIdentifier_)); // encode point cloud width compressedDataOut_arg.write (reinterpret_cast<const char*> (&cloud_width), sizeof (cloud_width)); // encode frame type height compressedDataOut_arg.write (reinterpret_cast<const char*> (&cloud_height), sizeof (cloud_height)); // encode frame max depth compressedDataOut_arg.write (reinterpret_cast<const char*> (&maxDepth), sizeof (maxDepth)); // encode frame focal lenght compressedDataOut_arg.write (reinterpret_cast<const char*> (&vocalLength), sizeof (vocalLength)); // encode frame depth quantization compressedDataOut_arg.write (reinterpret_cast<const char*> (&depthQuantization_arg), sizeof (depthQuantization_arg)); // disparity and rgb image data std::vector<uint16_t> disparityData; std::vector<uint8_t> rgbData; // compressed disparity and rgb image data std::vector<uint8_t> compressedDisparity; std::vector<uint8_t> compressedRGB; uint32_t compressedDisparitySize = 0; uint32_t compressedRGBSize = 0; // Convert point cloud to disparity and rgb image OrganizedConversion<PointT>::convert (*cloud_arg, maxDepth, depthQuantization_arg, disparityData, rgbData); // Compress disparity information encodeMonoImageToPNG (disparityData, cloud_width, cloud_height, compressedDisparity, pngLevel_arg); compressedDisparitySize = static_cast<uint32_t>(compressedDisparity.size()); // Encode size of compressed disparity image data compressedDataOut_arg.write (reinterpret_cast<const char*> (&compressedDisparitySize), sizeof (compressedDisparitySize)); // Output compressed disparity to ostream compressedDataOut_arg.write (reinterpret_cast<const char*> (&compressedDisparity[0]), compressedDisparity.size () * sizeof(uint8_t)); // Compress color information if (CompressionPointTraits<PointT>::hasColor && doColorEncoding) encodeRGBImageToPNG (rgbData, cloud_width, cloud_height, compressedRGB, 1 /*Z_BEST_SPEED*/); compressedRGBSize = static_cast<uint32_t>(compressedRGB.size ()); // Encode size of compressed RGB image data compressedDataOut_arg.write (reinterpret_cast<const char*> (&compressedRGBSize), sizeof (compressedRGBSize)); // Output compressed disparity to ostream compressedDataOut_arg.write (reinterpret_cast<const char*> (&compressedRGB[0]), compressedRGB.size () * sizeof(uint8_t)); if (bShowStatistics_arg) { uint64_t pointCount = cloud_width * cloud_height; float bytesPerPoint = static_cast<float> (compressedDisparitySize+compressedRGBSize) / static_cast<float> (pointCount); PCL_INFO("*** POINTCLOUD ENCODING ***\n"); PCL_INFO("Number of encoded points: %ld\n", pointCount); PCL_INFO("Size of uncompressed point cloud: %.2f kBytes\n", (static_cast<float> (pointCount) * CompressionPointTraits<PointT>::bytesPerPoint) / 1024.0f); PCL_INFO("Size of compressed point cloud: %.2f kBytes\n", static_cast<float> (compressedDisparitySize+compressedRGBSize) / 1024.0f); PCL_INFO("Total bytes per point: %.4f bytes\n", static_cast<float> (bytesPerPoint)); PCL_INFO("Total compression percentage: %.4f%%\n", (bytesPerPoint) / (CompressionPointTraits<PointT>::bytesPerPoint) * 100.0f); PCL_INFO("Compression ratio: %.2f\n\n", static_cast<float> (CompressionPointTraits<PointT>::bytesPerPoint) / bytesPerPoint); } } ////////////////////////////////////////////////////////////////////////////////////////////// template<typename PointT> void OrganizedPointCloudCompression<PointT>::decodePointCloud (std::istream& compressedDataIn_arg, PointCloudPtr &cloud_arg, bool bShowStatistics_arg) { // sync to frame header unsigned int headerIdPos = 0; while (headerIdPos < strlen (frameHeaderIdentifier_)) { char readChar; compressedDataIn_arg.read (static_cast<char*> (&readChar), sizeof (readChar)); if (readChar != frameHeaderIdentifier_[headerIdPos++]) headerIdPos = (frameHeaderIdentifier_[0] == readChar) ? 1 : 0; } uint32_t cloud_width; uint32_t cloud_height; float maxDepth, vocalLength; float depthQuantization; // reading frame header compressedDataIn_arg.read (reinterpret_cast<char*> (&cloud_width), sizeof (cloud_width)); compressedDataIn_arg.read (reinterpret_cast<char*> (&cloud_height), sizeof (cloud_height)); compressedDataIn_arg.read (reinterpret_cast<char*> (&maxDepth), sizeof (maxDepth)); compressedDataIn_arg.read (reinterpret_cast<char*> (&vocalLength), sizeof (vocalLength)); compressedDataIn_arg.read (reinterpret_cast<char*> (&depthQuantization), sizeof (depthQuantization)); // disparity and rgb image data std::vector<uint16_t> disparityData; std::vector<uint8_t> rgbData; // compressed disparity and rgb image data std::vector<uint8_t> compressedDisparity; std::vector<uint8_t> compressedRGB; uint32_t compressedDisparitySize; uint32_t compressedRGBSize; // reading compressed disparity data compressedDataIn_arg.read (reinterpret_cast<char*> (&compressedDisparitySize), sizeof (compressedDisparitySize)); compressedDisparity.resize (compressedDisparitySize); compressedDataIn_arg.read (reinterpret_cast<char*> (&compressedDisparity[0]), compressedDisparitySize * sizeof(uint8_t)); // reading compressed rgb data compressedDataIn_arg.read (reinterpret_cast<char*> (&compressedRGBSize), sizeof (compressedRGBSize)); compressedRGB.resize (compressedRGBSize); compressedDataIn_arg.read (reinterpret_cast<char*> (&compressedRGB[0]), compressedRGBSize * sizeof(uint8_t)); // PNG decoded parameters size_t png_width; size_t png_height; unsigned int png_channels; // decode PNG compressed disparity data decodePNGToImage (compressedDisparity, disparityData, png_width, png_height, png_channels); // decode PNG compressed rgb data decodePNGToImage (compressedRGB, rgbData, png_width, png_height, png_channels); // reconstruct point cloud OrganizedConversion<PointT>::convert (disparityData, rgbData, cloud_width, cloud_height, maxDepth, depthQuantization, vocalLength, *cloud_arg); if (bShowStatistics_arg) { uint64_t pointCount = cloud_width * cloud_height; float bytesPerPoint = static_cast<float> (compressedDisparitySize+compressedRGBSize) / static_cast<float> (pointCount); PCL_INFO("*** POINTCLOUD DECODING ***\n"); PCL_INFO("Number of encoded points: %ld\n", pointCount); PCL_INFO("Size of uncompressed point cloud: %.2f kBytes\n", (static_cast<float> (pointCount) * CompressionPointTraits<PointT>::bytesPerPoint) / 1024.0f); PCL_INFO("Size of compressed point cloud: %.2f kBytes\n", static_cast<float> (compressedDisparitySize+compressedRGBSize) / 1024.0f); PCL_INFO("Total bytes per point: %.4f bytes\n", static_cast<float> (bytesPerPoint)); PCL_INFO("Total compression percentage: %.4f%%\n", (bytesPerPoint) / (CompressionPointTraits<PointT>::bytesPerPoint) * 100.0f); PCL_INFO("Compression ratio: %.2f\n\n", static_cast<float> (CompressionPointTraits<PointT>::bytesPerPoint) / bytesPerPoint); } } ////////////////////////////////////////////////////////////////////////////////////////////// template<typename PointT> void OrganizedPointCloudCompression<PointT>::analyzeOrganizedCloud (PointCloudConstPtr cloud_arg, float& maxDepth_arg, float& vocalLength_arg) const { size_t width, height, it; int centerX, centerY; int x, y; float maxDepth; float focalLength; width = cloud_arg->width; height = cloud_arg->height; // Center of organized point cloud centerX = static_cast<int> (width / 2); centerY = static_cast<int> (height / 2); // Ensure we have an organized point cloud assert((width>1) && (height>1)); assert(width*height == cloud_arg->points.size()); maxDepth = 0; focalLength = 0; it = 0; for (y = -centerY; y < +centerY; ++y) for (x = -centerX; x < +centerX; ++x) { const PointT& point = cloud_arg->points[it++]; if (pcl::isFinite (point)) { if (maxDepth < point.z) { // Update maximum depth maxDepth = point.z; // Calculate focal length focalLength = 2.0f / (point.x / (static_cast<float> (x) * point.z) + point.y / (static_cast<float> (y) * point.z)); } } } // Update return values maxDepth_arg = maxDepth; vocalLength_arg = focalLength; } } } #endif <commit_msg>fixed eof detection in organized_pointcloud_compression class<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2009-2012, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #ifndef ORGANIZED_COMPRESSION_HPP #define ORGANIZED_COMPRESSION_HPP #include <pcl/compression/organized_pointcloud_compression.h> #include <pcl/pcl_macros.h> #include <pcl/point_cloud.h> #include <pcl/common/boost.h> #include <pcl/common/eigen.h> #include <pcl/common/common.h> #include <pcl/common/io.h> #include <pcl/compression/libpng_wrapper.h> #include <pcl/compression/organized_pointcloud_conversion.h> #include <string> #include <vector> #include <limits> #include <assert.h> namespace pcl { namespace io { ////////////////////////////////////////////////////////////////////////////////////////////// template<typename PointT> void OrganizedPointCloudCompression<PointT>::encodePointCloud (const PointCloudConstPtr &cloud_arg, std::ostream& compressedDataOut_arg, bool doColorEncoding, bool bShowStatistics_arg, int pngLevel_arg, float depthQuantization_arg) { uint32_t cloud_width = cloud_arg->width; uint32_t cloud_height = cloud_arg->height; float maxDepth, vocalLength; analyzeOrganizedCloud (cloud_arg, maxDepth, vocalLength); // encode header identifier compressedDataOut_arg.write (reinterpret_cast<const char*> (frameHeaderIdentifier_), strlen (frameHeaderIdentifier_)); // encode point cloud width compressedDataOut_arg.write (reinterpret_cast<const char*> (&cloud_width), sizeof (cloud_width)); // encode frame type height compressedDataOut_arg.write (reinterpret_cast<const char*> (&cloud_height), sizeof (cloud_height)); // encode frame max depth compressedDataOut_arg.write (reinterpret_cast<const char*> (&maxDepth), sizeof (maxDepth)); // encode frame focal lenght compressedDataOut_arg.write (reinterpret_cast<const char*> (&vocalLength), sizeof (vocalLength)); // encode frame depth quantization compressedDataOut_arg.write (reinterpret_cast<const char*> (&depthQuantization_arg), sizeof (depthQuantization_arg)); // disparity and rgb image data std::vector<uint16_t> disparityData; std::vector<uint8_t> rgbData; // compressed disparity and rgb image data std::vector<uint8_t> compressedDisparity; std::vector<uint8_t> compressedRGB; uint32_t compressedDisparitySize = 0; uint32_t compressedRGBSize = 0; // Convert point cloud to disparity and rgb image OrganizedConversion<PointT>::convert (*cloud_arg, maxDepth, depthQuantization_arg, disparityData, rgbData); // Compress disparity information encodeMonoImageToPNG (disparityData, cloud_width, cloud_height, compressedDisparity, pngLevel_arg); compressedDisparitySize = static_cast<uint32_t>(compressedDisparity.size()); // Encode size of compressed disparity image data compressedDataOut_arg.write (reinterpret_cast<const char*> (&compressedDisparitySize), sizeof (compressedDisparitySize)); // Output compressed disparity to ostream compressedDataOut_arg.write (reinterpret_cast<const char*> (&compressedDisparity[0]), compressedDisparity.size () * sizeof(uint8_t)); // Compress color information if (CompressionPointTraits<PointT>::hasColor && doColorEncoding) encodeRGBImageToPNG (rgbData, cloud_width, cloud_height, compressedRGB, 1 /*Z_BEST_SPEED*/); compressedRGBSize = static_cast<uint32_t>(compressedRGB.size ()); // Encode size of compressed RGB image data compressedDataOut_arg.write (reinterpret_cast<const char*> (&compressedRGBSize), sizeof (compressedRGBSize)); // Output compressed disparity to ostream compressedDataOut_arg.write (reinterpret_cast<const char*> (&compressedRGB[0]), compressedRGB.size () * sizeof(uint8_t)); if (bShowStatistics_arg) { uint64_t pointCount = cloud_width * cloud_height; float bytesPerPoint = static_cast<float> (compressedDisparitySize+compressedRGBSize) / static_cast<float> (pointCount); PCL_INFO("*** POINTCLOUD ENCODING ***\n"); PCL_INFO("Number of encoded points: %ld\n", pointCount); PCL_INFO("Size of uncompressed point cloud: %.2f kBytes\n", (static_cast<float> (pointCount) * CompressionPointTraits<PointT>::bytesPerPoint) / 1024.0f); PCL_INFO("Size of compressed point cloud: %.2f kBytes\n", static_cast<float> (compressedDisparitySize+compressedRGBSize) / 1024.0f); PCL_INFO("Total bytes per point: %.4f bytes\n", static_cast<float> (bytesPerPoint)); PCL_INFO("Total compression percentage: %.4f%%\n", (bytesPerPoint) / (CompressionPointTraits<PointT>::bytesPerPoint) * 100.0f); PCL_INFO("Compression ratio: %.2f\n\n", static_cast<float> (CompressionPointTraits<PointT>::bytesPerPoint) / bytesPerPoint); } } ////////////////////////////////////////////////////////////////////////////////////////////// template<typename PointT> void OrganizedPointCloudCompression<PointT>::decodePointCloud (std::istream& compressedDataIn_arg, PointCloudPtr &cloud_arg, bool bShowStatistics_arg) { uint32_t cloud_width; uint32_t cloud_height; float maxDepth, vocalLength; float depthQuantization; // disparity and rgb image data std::vector<uint16_t> disparityData; std::vector<uint8_t> rgbData; // compressed disparity and rgb image data std::vector<uint8_t> compressedDisparity; std::vector<uint8_t> compressedRGB; uint32_t compressedDisparitySize; uint32_t compressedRGBSize; // PNG decoded parameters size_t png_width = 0; size_t png_height = 0; unsigned int png_channels = 1; // sync to frame header unsigned int headerIdPos = 0; bool valid_stream = true; while (valid_stream && (headerIdPos < strlen (frameHeaderIdentifier_))) { char readChar; compressedDataIn_arg.read (static_cast<char*> (&readChar), sizeof (readChar)); if (readChar != frameHeaderIdentifier_[headerIdPos++]) headerIdPos = (frameHeaderIdentifier_[0] == readChar) ? 1 : 0; valid_stream=compressedDataIn_arg.good (); } if (valid_stream) { // reading frame header compressedDataIn_arg.read (reinterpret_cast<char*> (&cloud_width), sizeof (cloud_width)); compressedDataIn_arg.read (reinterpret_cast<char*> (&cloud_height), sizeof (cloud_height)); compressedDataIn_arg.read (reinterpret_cast<char*> (&maxDepth), sizeof (maxDepth)); compressedDataIn_arg.read (reinterpret_cast<char*> (&vocalLength), sizeof (vocalLength)); compressedDataIn_arg.read (reinterpret_cast<char*> (&depthQuantization), sizeof (depthQuantization)); // reading compressed disparity data compressedDataIn_arg.read (reinterpret_cast<char*> (&compressedDisparitySize), sizeof (compressedDisparitySize)); compressedDisparity.resize (compressedDisparitySize); compressedDataIn_arg.read (reinterpret_cast<char*> (&compressedDisparity[0]), compressedDisparitySize * sizeof(uint8_t)); // reading compressed rgb data compressedDataIn_arg.read (reinterpret_cast<char*> (&compressedRGBSize), sizeof (compressedRGBSize)); compressedRGB.resize (compressedRGBSize); compressedDataIn_arg.read (reinterpret_cast<char*> (&compressedRGB[0]), compressedRGBSize * sizeof(uint8_t)); // decode PNG compressed disparity data decodePNGToImage (compressedDisparity, disparityData, png_width, png_height, png_channels); // decode PNG compressed rgb data decodePNGToImage (compressedRGB, rgbData, png_width, png_height, png_channels); } // reconstruct point cloud OrganizedConversion<PointT>::convert (disparityData, rgbData, cloud_width, cloud_height, maxDepth, depthQuantization, vocalLength, *cloud_arg); if (bShowStatistics_arg) { uint64_t pointCount = cloud_width * cloud_height; float bytesPerPoint = static_cast<float> (compressedDisparitySize+compressedRGBSize) / static_cast<float> (pointCount); PCL_INFO("*** POINTCLOUD DECODING ***\n"); PCL_INFO("Number of encoded points: %ld\n", pointCount); PCL_INFO("Size of uncompressed point cloud: %.2f kBytes\n", (static_cast<float> (pointCount) * CompressionPointTraits<PointT>::bytesPerPoint) / 1024.0f); PCL_INFO("Size of compressed point cloud: %.2f kBytes\n", static_cast<float> (compressedDisparitySize+compressedRGBSize) / 1024.0f); PCL_INFO("Total bytes per point: %.4f bytes\n", static_cast<float> (bytesPerPoint)); PCL_INFO("Total compression percentage: %.4f%%\n", (bytesPerPoint) / (CompressionPointTraits<PointT>::bytesPerPoint) * 100.0f); PCL_INFO("Compression ratio: %.2f\n\n", static_cast<float> (CompressionPointTraits<PointT>::bytesPerPoint) / bytesPerPoint); } } ////////////////////////////////////////////////////////////////////////////////////////////// template<typename PointT> void OrganizedPointCloudCompression<PointT>::analyzeOrganizedCloud (PointCloudConstPtr cloud_arg, float& maxDepth_arg, float& vocalLength_arg) const { size_t width, height, it; int centerX, centerY; int x, y; float maxDepth; float focalLength; width = cloud_arg->width; height = cloud_arg->height; // Center of organized point cloud centerX = static_cast<int> (width / 2); centerY = static_cast<int> (height / 2); // Ensure we have an organized point cloud assert((width>1) && (height>1)); assert(width*height == cloud_arg->points.size()); maxDepth = 0; focalLength = 0; it = 0; for (y = -centerY; y < +centerY; ++y) for (x = -centerX; x < +centerX; ++x) { const PointT& point = cloud_arg->points[it++]; if (pcl::isFinite (point)) { if (maxDepth < point.z) { // Update maximum depth maxDepth = point.z; // Calculate focal length focalLength = 2.0f / (point.x / (static_cast<float> (x) * point.z) + point.y / (static_cast<float> (y) * point.z)); } } } // Update return values maxDepth_arg = maxDepth; vocalLength_arg = focalLength; } } } #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2012-2015 Daniele Bartolini and individual contributors. * License: https://github.com/taylor001/crown/blob/master/LICENSE */ #include "config.h" #include "debug_line.h" #include "device.h" #include "log.h" #include "lua_environment.h" #include "material_manager.h" #include "resource_manager.h" #include "resource_package.h" #include "types.h" #include "world.h" #include "memory.h" #include "os.h" #define MAX_SUBSYSTEMS_HEAP 8 * 1024 * 1024 namespace crown { Device::Device(const ConfigSettings& cs, Filesystem& fs) : _allocator(default_allocator(), MAX_SUBSYSTEMS_HEAP) , _width(0) , _height(0) , _is_init(false) , _is_running(false) , _is_paused(false) , _frame_count(0) , _last_time(0) , _current_time(0) , _last_delta_time(0.0f) , _time_since_start(0.0) , _cs(cs) , _fs(fs) , _boot_package_id(cs.boot_package) , _boot_script_id(cs.boot_script) , _boot_package(NULL) , _lua_environment(NULL) , _resource_manager(NULL) , _worlds(default_allocator()) { } void Device::init() { // Initialize CE_LOGI("Initializing Crown Engine %s...", version()); // Create resource manager CE_LOGD("Creating resource manager..."); _resource_manager = CE_NEW(_allocator, ResourceManager)(_fs); CE_LOGD("Creating material manager..."); material_manager::init(); debug_line::init(); _lua_environment = CE_NEW(_allocator, LuaEnvironment)(); _lua_environment->load_libs(); CE_LOGD("Crown Engine initialized."); CE_LOGD("Initializing Game..."); _is_init = true; _is_running = true; _last_time = os::clocktime(); _boot_package = create_resource_package(_boot_package_id); _boot_package->load(); _boot_package->flush(); _lua_environment->execute((LuaResource*)_resource_manager->get(SCRIPT_TYPE, _boot_script_id)); _lua_environment->call_global("init", 0); } void Device::shutdown() { CE_ASSERT(_is_init, "Engine is not initialized"); // Shutdowns the game _lua_environment->call_global("shutdown", 0); _boot_package->unload(); destroy_resource_package(*_boot_package); CE_DELETE(_allocator, _lua_environment); CE_LOGD("Releasing material manager..."); debug_line::shutdown(); material_manager::shutdown(); CE_LOGD("Releasing resource manager..."); CE_DELETE(_allocator, _resource_manager); _allocator.clear(); _is_init = false; } ResourceManager* Device::resource_manager() { return _resource_manager; } LuaEnvironment* Device::lua_environment() { return _lua_environment; } void Device::quit() { _is_running = false; } void Device::pause() { _is_paused = true; CE_LOGI("Engine paused."); } void Device::unpause() { _is_paused = false; CE_LOGI("Engine unpaused."); } bool Device::is_running() const { return _is_running; } uint64_t Device::frame_count() const { return _frame_count; } float Device::last_delta_time() const { return _last_delta_time; } double Device::time_since_start() const { return _time_since_start; } void Device::update() { _current_time = os::clocktime(); const int64_t time = _current_time - _last_time; _last_time = _current_time; const double freq = (double) os::clockfrequency(); _last_delta_time = time * (1.0 / freq); _time_since_start += _last_delta_time; if (!_is_paused) { _resource_manager->complete_requests(); _lua_environment->call_global("update", 1, ARGUMENT_FLOAT, last_delta_time()); _lua_environment->call_global("render", 1, ARGUMENT_FLOAT, last_delta_time()); } _frame_count++; _lua_environment->clear_temporaries(); } void Device::render_world(World& world, Camera* camera) { world.render(camera); } World* Device::create_world() { World* w = CE_NEW(default_allocator(), World)(*_resource_manager, *_lua_environment); array::push_back(_worlds, w); return w; } void Device::destroy_world(World& w) { for (uint32_t i = 0, n = array::size(_worlds); i < n; ++i) { if (&w == _worlds[i]) { CE_DELETE(default_allocator(), &w); _worlds[i] = _worlds[n - 1]; array::pop_back(_worlds); return; } } CE_ASSERT(false, "Bad world"); } ResourcePackage* Device::create_resource_package(StringId64 id) { return CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager); } void Device::destroy_resource_package(ResourcePackage& package) { CE_DELETE(default_allocator(), &package); } void Device::reload(StringId64 type, StringId64 name) { } namespace device_globals { char _buffer[sizeof(Device)]; Device* _device = NULL; void init(const ConfigSettings& cs, Filesystem& fs) { CE_ASSERT(_device == NULL, "Crown already initialized"); _device = new (_buffer) Device(cs, fs); } void shutdown() { _device->~Device(); _device = NULL; } } // namespace device_globals Device* device() { return device_globals::_device; } } // namespace crown <commit_msg>Add SCRIPT_TYPE reload<commit_after>/* * Copyright (c) 2012-2015 Daniele Bartolini and individual contributors. * License: https://github.com/taylor001/crown/blob/master/LICENSE */ #include "config.h" #include "debug_line.h" #include "device.h" #include "log.h" #include "lua_environment.h" #include "material_manager.h" #include "resource_manager.h" #include "resource_package.h" #include "types.h" #include "world.h" #include "memory.h" #include "os.h" #define MAX_SUBSYSTEMS_HEAP 8 * 1024 * 1024 namespace crown { Device::Device(const ConfigSettings& cs, Filesystem& fs) : _allocator(default_allocator(), MAX_SUBSYSTEMS_HEAP) , _width(0) , _height(0) , _is_init(false) , _is_running(false) , _is_paused(false) , _frame_count(0) , _last_time(0) , _current_time(0) , _last_delta_time(0.0f) , _time_since_start(0.0) , _cs(cs) , _fs(fs) , _boot_package_id(cs.boot_package) , _boot_script_id(cs.boot_script) , _boot_package(NULL) , _lua_environment(NULL) , _resource_manager(NULL) , _worlds(default_allocator()) { } void Device::init() { // Initialize CE_LOGI("Initializing Crown Engine %s...", version()); // Create resource manager CE_LOGD("Creating resource manager..."); _resource_manager = CE_NEW(_allocator, ResourceManager)(_fs); CE_LOGD("Creating material manager..."); material_manager::init(); debug_line::init(); _lua_environment = CE_NEW(_allocator, LuaEnvironment)(); _lua_environment->load_libs(); CE_LOGD("Crown Engine initialized."); CE_LOGD("Initializing Game..."); _is_init = true; _is_running = true; _last_time = os::clocktime(); _boot_package = create_resource_package(_boot_package_id); _boot_package->load(); _boot_package->flush(); _lua_environment->execute((LuaResource*)_resource_manager->get(SCRIPT_TYPE, _boot_script_id)); _lua_environment->call_global("init", 0); } void Device::shutdown() { CE_ASSERT(_is_init, "Engine is not initialized"); // Shutdowns the game _lua_environment->call_global("shutdown", 0); _boot_package->unload(); destroy_resource_package(*_boot_package); CE_DELETE(_allocator, _lua_environment); CE_LOGD("Releasing material manager..."); debug_line::shutdown(); material_manager::shutdown(); CE_LOGD("Releasing resource manager..."); CE_DELETE(_allocator, _resource_manager); _allocator.clear(); _is_init = false; } ResourceManager* Device::resource_manager() { return _resource_manager; } LuaEnvironment* Device::lua_environment() { return _lua_environment; } void Device::quit() { _is_running = false; } void Device::pause() { _is_paused = true; CE_LOGI("Engine paused."); } void Device::unpause() { _is_paused = false; CE_LOGI("Engine unpaused."); } bool Device::is_running() const { return _is_running; } uint64_t Device::frame_count() const { return _frame_count; } float Device::last_delta_time() const { return _last_delta_time; } double Device::time_since_start() const { return _time_since_start; } void Device::update() { _current_time = os::clocktime(); const int64_t time = _current_time - _last_time; _last_time = _current_time; const double freq = (double) os::clockfrequency(); _last_delta_time = time * (1.0 / freq); _time_since_start += _last_delta_time; if (!_is_paused) { _resource_manager->complete_requests(); _lua_environment->call_global("update", 1, ARGUMENT_FLOAT, last_delta_time()); _lua_environment->call_global("render", 1, ARGUMENT_FLOAT, last_delta_time()); } _frame_count++; _lua_environment->clear_temporaries(); } void Device::render_world(World& world, Camera* camera) { world.render(camera); } World* Device::create_world() { World* w = CE_NEW(default_allocator(), World)(*_resource_manager, *_lua_environment); array::push_back(_worlds, w); return w; } void Device::destroy_world(World& w) { for (uint32_t i = 0, n = array::size(_worlds); i < n; ++i) { if (&w == _worlds[i]) { CE_DELETE(default_allocator(), &w); _worlds[i] = _worlds[n - 1]; array::pop_back(_worlds); return; } } CE_ASSERT(false, "Bad world"); } ResourcePackage* Device::create_resource_package(StringId64 id) { return CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager); } void Device::destroy_resource_package(ResourcePackage& package) { CE_DELETE(default_allocator(), &package); } void Device::reload(StringId64 type, StringId64 name) { const void* old_resource = _resource_manager->get(type, name); _resource_manager->reload(type, name); const void* new_resource = _resource_manager->get(type, name); if (type == SCRIPT_TYPE) { _lua_environment->execute((const LuaResource*)new_resource); } } namespace device_globals { char _buffer[sizeof(Device)]; Device* _device = NULL; void init(const ConfigSettings& cs, Filesystem& fs) { CE_ASSERT(_device == NULL, "Crown already initialized"); _device = new (_buffer) Device(cs, fs); } void shutdown() { _device->~Device(); _device = NULL; } } // namespace device_globals Device* device() { return device_globals::_device; } } // namespace crown <|endoftext|>
<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/chromedriver/chrome/devtools_http_client.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/json/json_reader.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/stringprintf.h" #include "base/threading/platform_thread.h" #include "base/time/time.h" #include "base/values.h" #include "chrome/test/chromedriver/chrome/devtools_client_impl.h" #include "chrome/test/chromedriver/chrome/log.h" #include "chrome/test/chromedriver/chrome/status.h" #include "chrome/test/chromedriver/chrome/version.h" #include "chrome/test/chromedriver/chrome/web_view_impl.h" #include "chrome/test/chromedriver/net/net_util.h" #include "chrome/test/chromedriver/net/url_request_context_getter.h" namespace { Status FakeCloseFrontends() { return Status(kOk); } } // namespace WebViewInfo::WebViewInfo(const std::string& id, const std::string& debugger_url, const std::string& url, Type type) : id(id), debugger_url(debugger_url), url(url), type(type) {} WebViewInfo::~WebViewInfo() {} bool WebViewInfo::IsFrontend() const { return url.find("chrome-devtools://") == 0u; } WebViewsInfo::WebViewsInfo() {} WebViewsInfo::WebViewsInfo(const std::vector<WebViewInfo>& info) : views_info(info) {} WebViewsInfo::~WebViewsInfo() {} const WebViewInfo& WebViewsInfo::Get(int index) const { return views_info[index]; } size_t WebViewsInfo::GetSize() const { return views_info.size(); } const WebViewInfo* WebViewsInfo::GetForId(const std::string& id) const { for (size_t i = 0; i < views_info.size(); ++i) { if (views_info[i].id == id) return &views_info[i]; } return NULL; } DevToolsHttpClient::DevToolsHttpClient( const NetAddress& address, scoped_refptr<URLRequestContextGetter> context_getter, const SyncWebSocketFactory& socket_factory) : context_getter_(context_getter), socket_factory_(socket_factory), server_url_("http://" + address.ToString()), web_socket_url_prefix_(base::StringPrintf( "ws://%s/devtools/page/", address.ToString().c_str())) {} DevToolsHttpClient::~DevToolsHttpClient() {} Status DevToolsHttpClient::Init(const base::TimeDelta& timeout) { base::TimeTicks deadline = base::TimeTicks::Now() + timeout; std::string devtools_version; while (true) { Status status = GetVersion(&devtools_version); if (status.IsOk()) break; if (status.code() != kChromeNotReachable || base::TimeTicks::Now() > deadline) { return status; } base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(50)); } int kToTBuildNo = 9999; if (devtools_version.empty()) { // Content Shell has an empty product version and a fake user agent. // There's no way to detect the actual version, so assume it is tip of tree. version_ = "content shell"; build_no_ = kToTBuildNo; return Status(kOk); } if (devtools_version.find("Version/") == 0u) { version_ = "webview"; build_no_ = kToTBuildNo; return Status(kOk); } std::string prefix = "Chrome/"; if (devtools_version.find(prefix) != 0u) { return Status(kUnknownError, "unrecognized Chrome version: " + devtools_version); } std::string stripped_version = devtools_version.substr(prefix.length()); int temp_build_no; std::vector<std::string> version_parts; base::SplitString(stripped_version, '.', &version_parts); if (version_parts.size() != 4 || !base::StringToInt(version_parts[2], &temp_build_no)) { return Status(kUnknownError, "unrecognized Chrome version: " + devtools_version); } version_ = stripped_version; build_no_ = temp_build_no; return Status(kOk); } Status DevToolsHttpClient::GetWebViewsInfo(WebViewsInfo* views_info) { std::string data; if (!FetchUrlAndLog(server_url_ + "/json", context_getter_.get(), &data)) return Status(kChromeNotReachable); return internal::ParseWebViewsInfo(data, views_info); } scoped_ptr<DevToolsClient> DevToolsHttpClient::CreateClient( const std::string& id) { return scoped_ptr<DevToolsClient>(new DevToolsClientImpl( socket_factory_, web_socket_url_prefix_ + id, id, base::Bind( &DevToolsHttpClient::CloseFrontends, base::Unretained(this), id))); } Status DevToolsHttpClient::CloseWebView(const std::string& id) { std::string data; if (!FetchUrlAndLog( server_url_ + "/json/close/" + id, context_getter_.get(), &data)) { return Status(kOk); // Closing the last web view leads chrome to quit. } // Wait for the target window to be completely closed. base::TimeTicks deadline = base::TimeTicks::Now() + base::TimeDelta::FromSeconds(20); while (base::TimeTicks::Now() < deadline) { WebViewsInfo views_info; Status status = GetWebViewsInfo(&views_info); if (status.code() == kChromeNotReachable) return Status(kOk); if (status.IsError()) return status; if (!views_info.GetForId(id)) return Status(kOk); base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(50)); } return Status(kUnknownError, "failed to close window in 20 seconds"); } Status DevToolsHttpClient::ActivateWebView(const std::string& id) { std::string data; if (!FetchUrlAndLog( server_url_ + "/json/activate/" + id, context_getter_.get(), &data)) return Status(kUnknownError, "cannot activate web view"); return Status(kOk); } const std::string& DevToolsHttpClient::version() const { return version_; } int DevToolsHttpClient::build_no() const { return build_no_; } Status DevToolsHttpClient::GetVersion(std::string* version) { std::string data; if (!FetchUrlAndLog( server_url_ + "/json/version", context_getter_.get(), &data)) return Status(kChromeNotReachable); return internal::ParseVersionInfo(data, version); } Status DevToolsHttpClient::CloseFrontends(const std::string& for_client_id) { WebViewsInfo views_info; Status status = GetWebViewsInfo(&views_info); if (status.IsError()) return status; // Close frontends. Usually frontends are docked in the same page, although // some may be in tabs (undocked, chrome://inspect, the DevTools // discovery page, etc.). Tabs can be closed via the DevTools HTTP close // URL, but docked frontends can only be closed, by design, by connecting // to them and clicking the close button. Close the tab frontends first // in case one of them is debugging a docked frontend, which would prevent // the code from being able to connect to the docked one. std::list<std::string> tab_frontend_ids; std::list<std::string> docked_frontend_ids; for (size_t i = 0; i < views_info.GetSize(); ++i) { const WebViewInfo& view_info = views_info.Get(i); if (view_info.IsFrontend()) { if (view_info.type == WebViewInfo::kPage) tab_frontend_ids.push_back(view_info.id); else if (view_info.type == WebViewInfo::kOther) docked_frontend_ids.push_back(view_info.id); else return Status(kUnknownError, "unknown type of DevTools frontend"); } } for (std::list<std::string>::const_iterator it = tab_frontend_ids.begin(); it != tab_frontend_ids.end(); ++it) { status = CloseWebView(*it); if (status.IsError()) return status; } for (std::list<std::string>::const_iterator it = docked_frontend_ids.begin(); it != docked_frontend_ids.end(); ++it) { scoped_ptr<DevToolsClient> client(new DevToolsClientImpl( socket_factory_, web_socket_url_prefix_ + *it, *it, base::Bind(&FakeCloseFrontends))); scoped_ptr<WebViewImpl> web_view( new WebViewImpl(*it, build_no_, client.Pass())); status = web_view->ConnectIfNecessary(); // Ignore disconnected error, because the debugger might have closed when // its container page was closed above. if (status.IsError() && status.code() != kDisconnected) return status; scoped_ptr<base::Value> result; status = web_view->EvaluateScript( std::string(), "document.querySelector('*[id^=\"close-button-\"]').click();", &result); // Ignore disconnected error, because it may be closed already. if (status.IsError() && status.code() != kDisconnected) return status; } // Wait until DevTools UI disconnects from the given web view. base::TimeTicks deadline = base::TimeTicks::Now() + base::TimeDelta::FromSeconds(20); while (base::TimeTicks::Now() < deadline) { status = GetWebViewsInfo(&views_info); if (status.IsError()) return status; const WebViewInfo* view_info = views_info.GetForId(for_client_id); if (!view_info) { return Status(kDisconnected, "DevTools client closed during closing UI debuggers"); } if (view_info->debugger_url.size()) return Status(kOk); base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(50)); } return Status(kUnknownError, "failed to close UI debuggers"); } bool DevToolsHttpClient::FetchUrlAndLog(const std::string& url, URLRequestContextGetter* getter, std::string* response) { VLOG(1) << "DevTools request: " << url; bool ok = FetchUrl(url, getter, response); if (ok) { VLOG(1) << "DevTools response: " << *response; } else { VLOG(1) << "DevTools request failed"; } return ok; } namespace internal { Status ParseWebViewsInfo(const std::string& data, WebViewsInfo* views_info) { scoped_ptr<base::Value> value(base::JSONReader::Read(data)); if (!value.get()) return Status(kUnknownError, "DevTools returned invalid JSON"); base::ListValue* list; if (!value->GetAsList(&list)) return Status(kUnknownError, "DevTools did not return list"); std::vector<WebViewInfo> temp_views_info; for (size_t i = 0; i < list->GetSize(); ++i) { base::DictionaryValue* info; if (!list->GetDictionary(i, &info)) return Status(kUnknownError, "DevTools contains non-dictionary item"); std::string id; if (!info->GetString("id", &id)) return Status(kUnknownError, "DevTools did not include id"); std::string type; if (!info->GetString("type", &type)) return Status(kUnknownError, "DevTools did not include type"); std::string url; if (!info->GetString("url", &url)) return Status(kUnknownError, "DevTools did not include url"); std::string debugger_url; info->GetString("webSocketDebuggerUrl", &debugger_url); if (type == "page") temp_views_info.push_back( WebViewInfo(id, debugger_url, url, WebViewInfo::kPage)); else if (type == "other") temp_views_info.push_back( WebViewInfo(id, debugger_url, url, WebViewInfo::kOther)); else return Status(kUnknownError, "DevTools returned unknown type:" + type); } *views_info = WebViewsInfo(temp_views_info); return Status(kOk); } Status ParseVersionInfo(const std::string& data, std::string* version) { scoped_ptr<base::Value> value(base::JSONReader::Read(data)); if (!value.get()) return Status(kUnknownError, "version info not in JSON"); base::DictionaryValue* dict; if (!value->GetAsDictionary(&dict)) return Status(kUnknownError, "version info not a dictionary"); if (!dict->GetString("Browser", version)) { return Status( kUnknownError, "Chrome version must be >= " + GetMinimumSupportedChromeVersion(), Status(kUnknownError, "version info doesn't include string 'Browser'")); } return Status(kOk); } } // namespace internal <commit_msg>[chromedriver] Fix a confusing error message.<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/chromedriver/chrome/devtools_http_client.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/json/json_reader.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/stringprintf.h" #include "base/threading/platform_thread.h" #include "base/time/time.h" #include "base/values.h" #include "chrome/test/chromedriver/chrome/devtools_client_impl.h" #include "chrome/test/chromedriver/chrome/log.h" #include "chrome/test/chromedriver/chrome/status.h" #include "chrome/test/chromedriver/chrome/version.h" #include "chrome/test/chromedriver/chrome/web_view_impl.h" #include "chrome/test/chromedriver/net/net_util.h" #include "chrome/test/chromedriver/net/url_request_context_getter.h" namespace { Status FakeCloseFrontends() { return Status(kOk); } } // namespace WebViewInfo::WebViewInfo(const std::string& id, const std::string& debugger_url, const std::string& url, Type type) : id(id), debugger_url(debugger_url), url(url), type(type) {} WebViewInfo::~WebViewInfo() {} bool WebViewInfo::IsFrontend() const { return url.find("chrome-devtools://") == 0u; } WebViewsInfo::WebViewsInfo() {} WebViewsInfo::WebViewsInfo(const std::vector<WebViewInfo>& info) : views_info(info) {} WebViewsInfo::~WebViewsInfo() {} const WebViewInfo& WebViewsInfo::Get(int index) const { return views_info[index]; } size_t WebViewsInfo::GetSize() const { return views_info.size(); } const WebViewInfo* WebViewsInfo::GetForId(const std::string& id) const { for (size_t i = 0; i < views_info.size(); ++i) { if (views_info[i].id == id) return &views_info[i]; } return NULL; } DevToolsHttpClient::DevToolsHttpClient( const NetAddress& address, scoped_refptr<URLRequestContextGetter> context_getter, const SyncWebSocketFactory& socket_factory) : context_getter_(context_getter), socket_factory_(socket_factory), server_url_("http://" + address.ToString()), web_socket_url_prefix_(base::StringPrintf( "ws://%s/devtools/page/", address.ToString().c_str())) {} DevToolsHttpClient::~DevToolsHttpClient() {} Status DevToolsHttpClient::Init(const base::TimeDelta& timeout) { base::TimeTicks deadline = base::TimeTicks::Now() + timeout; std::string devtools_version; while (true) { Status status = GetVersion(&devtools_version); if (status.IsOk()) break; if (status.code() != kChromeNotReachable || base::TimeTicks::Now() > deadline) { return status; } base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(50)); } int kToTBuildNo = 9999; if (devtools_version.empty()) { // Content Shell has an empty product version and a fake user agent. // There's no way to detect the actual version, so assume it is tip of tree. version_ = "content shell"; build_no_ = kToTBuildNo; return Status(kOk); } if (devtools_version.find("Version/") == 0u) { version_ = "webview"; build_no_ = kToTBuildNo; return Status(kOk); } std::string prefix = "Chrome/"; if (devtools_version.find(prefix) != 0u) { return Status(kUnknownError, "unrecognized Chrome version: " + devtools_version); } std::string stripped_version = devtools_version.substr(prefix.length()); int temp_build_no; std::vector<std::string> version_parts; base::SplitString(stripped_version, '.', &version_parts); if (version_parts.size() != 4 || !base::StringToInt(version_parts[2], &temp_build_no)) { return Status(kUnknownError, "unrecognized Chrome version: " + devtools_version); } version_ = stripped_version; build_no_ = temp_build_no; return Status(kOk); } Status DevToolsHttpClient::GetWebViewsInfo(WebViewsInfo* views_info) { std::string data; if (!FetchUrlAndLog(server_url_ + "/json", context_getter_.get(), &data)) return Status(kChromeNotReachable); return internal::ParseWebViewsInfo(data, views_info); } scoped_ptr<DevToolsClient> DevToolsHttpClient::CreateClient( const std::string& id) { return scoped_ptr<DevToolsClient>(new DevToolsClientImpl( socket_factory_, web_socket_url_prefix_ + id, id, base::Bind( &DevToolsHttpClient::CloseFrontends, base::Unretained(this), id))); } Status DevToolsHttpClient::CloseWebView(const std::string& id) { std::string data; if (!FetchUrlAndLog( server_url_ + "/json/close/" + id, context_getter_.get(), &data)) { return Status(kOk); // Closing the last web view leads chrome to quit. } // Wait for the target window to be completely closed. base::TimeTicks deadline = base::TimeTicks::Now() + base::TimeDelta::FromSeconds(20); while (base::TimeTicks::Now() < deadline) { WebViewsInfo views_info; Status status = GetWebViewsInfo(&views_info); if (status.code() == kChromeNotReachable) return Status(kOk); if (status.IsError()) return status; if (!views_info.GetForId(id)) return Status(kOk); base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(50)); } return Status(kUnknownError, "failed to close window in 20 seconds"); } Status DevToolsHttpClient::ActivateWebView(const std::string& id) { std::string data; if (!FetchUrlAndLog( server_url_ + "/json/activate/" + id, context_getter_.get(), &data)) return Status(kUnknownError, "cannot activate web view"); return Status(kOk); } const std::string& DevToolsHttpClient::version() const { return version_; } int DevToolsHttpClient::build_no() const { return build_no_; } Status DevToolsHttpClient::GetVersion(std::string* version) { std::string data; if (!FetchUrlAndLog( server_url_ + "/json/version", context_getter_.get(), &data)) return Status(kChromeNotReachable); return internal::ParseVersionInfo(data, version); } Status DevToolsHttpClient::CloseFrontends(const std::string& for_client_id) { WebViewsInfo views_info; Status status = GetWebViewsInfo(&views_info); if (status.IsError()) return status; // Close frontends. Usually frontends are docked in the same page, although // some may be in tabs (undocked, chrome://inspect, the DevTools // discovery page, etc.). Tabs can be closed via the DevTools HTTP close // URL, but docked frontends can only be closed, by design, by connecting // to them and clicking the close button. Close the tab frontends first // in case one of them is debugging a docked frontend, which would prevent // the code from being able to connect to the docked one. std::list<std::string> tab_frontend_ids; std::list<std::string> docked_frontend_ids; for (size_t i = 0; i < views_info.GetSize(); ++i) { const WebViewInfo& view_info = views_info.Get(i); if (view_info.IsFrontend()) { if (view_info.type == WebViewInfo::kPage) tab_frontend_ids.push_back(view_info.id); else if (view_info.type == WebViewInfo::kOther) docked_frontend_ids.push_back(view_info.id); else return Status(kUnknownError, "unknown type of DevTools frontend"); } } for (std::list<std::string>::const_iterator it = tab_frontend_ids.begin(); it != tab_frontend_ids.end(); ++it) { status = CloseWebView(*it); if (status.IsError()) return status; } for (std::list<std::string>::const_iterator it = docked_frontend_ids.begin(); it != docked_frontend_ids.end(); ++it) { scoped_ptr<DevToolsClient> client(new DevToolsClientImpl( socket_factory_, web_socket_url_prefix_ + *it, *it, base::Bind(&FakeCloseFrontends))); scoped_ptr<WebViewImpl> web_view( new WebViewImpl(*it, build_no_, client.Pass())); status = web_view->ConnectIfNecessary(); // Ignore disconnected error, because the debugger might have closed when // its container page was closed above. if (status.IsError() && status.code() != kDisconnected) return status; scoped_ptr<base::Value> result; status = web_view->EvaluateScript( std::string(), "document.querySelector('*[id^=\"close-button-\"]').click();", &result); // Ignore disconnected error, because it may be closed already. if (status.IsError() && status.code() != kDisconnected) return status; } // Wait until DevTools UI disconnects from the given web view. base::TimeTicks deadline = base::TimeTicks::Now() + base::TimeDelta::FromSeconds(20); while (base::TimeTicks::Now() < deadline) { status = GetWebViewsInfo(&views_info); if (status.IsError()) return status; const WebViewInfo* view_info = views_info.GetForId(for_client_id); if (!view_info) return Status(kNoSuchWindow, "window was already closed"); if (view_info->debugger_url.size()) return Status(kOk); base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(50)); } return Status(kUnknownError, "failed to close UI debuggers"); } bool DevToolsHttpClient::FetchUrlAndLog(const std::string& url, URLRequestContextGetter* getter, std::string* response) { VLOG(1) << "DevTools request: " << url; bool ok = FetchUrl(url, getter, response); if (ok) { VLOG(1) << "DevTools response: " << *response; } else { VLOG(1) << "DevTools request failed"; } return ok; } namespace internal { Status ParseWebViewsInfo(const std::string& data, WebViewsInfo* views_info) { scoped_ptr<base::Value> value(base::JSONReader::Read(data)); if (!value.get()) return Status(kUnknownError, "DevTools returned invalid JSON"); base::ListValue* list; if (!value->GetAsList(&list)) return Status(kUnknownError, "DevTools did not return list"); std::vector<WebViewInfo> temp_views_info; for (size_t i = 0; i < list->GetSize(); ++i) { base::DictionaryValue* info; if (!list->GetDictionary(i, &info)) return Status(kUnknownError, "DevTools contains non-dictionary item"); std::string id; if (!info->GetString("id", &id)) return Status(kUnknownError, "DevTools did not include id"); std::string type; if (!info->GetString("type", &type)) return Status(kUnknownError, "DevTools did not include type"); std::string url; if (!info->GetString("url", &url)) return Status(kUnknownError, "DevTools did not include url"); std::string debugger_url; info->GetString("webSocketDebuggerUrl", &debugger_url); if (type == "page") temp_views_info.push_back( WebViewInfo(id, debugger_url, url, WebViewInfo::kPage)); else if (type == "other") temp_views_info.push_back( WebViewInfo(id, debugger_url, url, WebViewInfo::kOther)); else return Status(kUnknownError, "DevTools returned unknown type:" + type); } *views_info = WebViewsInfo(temp_views_info); return Status(kOk); } Status ParseVersionInfo(const std::string& data, std::string* version) { scoped_ptr<base::Value> value(base::JSONReader::Read(data)); if (!value.get()) return Status(kUnknownError, "version info not in JSON"); base::DictionaryValue* dict; if (!value->GetAsDictionary(&dict)) return Status(kUnknownError, "version info not a dictionary"); if (!dict->GetString("Browser", version)) { return Status( kUnknownError, "Chrome version must be >= " + GetMinimumSupportedChromeVersion(), Status(kUnknownError, "version info doesn't include string 'Browser'")); } return Status(kOk); } } // namespace internal <|endoftext|>
<commit_before>/* * master.cpp - master program for Team PI * * Wire(0) -> capTouch -> pixies -> SRF08s -> slave2 -> slave3 * Wire1 -> slave1 * by Brian Chen * (C) Team PI 2015 */ #include <WProgram.h> #include <i2c_t3.h> #include <SPI.h> #include <slaves.h> #include <piCommon.h> #include <PixyI2C.h> // modified for i2c_t3 #include <SRF08.h> #include <fastTrig.h> #include <PID.h> #include <DebugUtils.h> #define LED 13 #define RAMMING_SPEED 200 #define NORMAL_SPEED 130 uint32_t loopCount = 0; /**********************************************************/ /* Slave1 */ /**********************************************************/ union float2bytes { float f; uint8_t b[sizeof(float)]; }; float2bytes f2b; uint8_t inBuffer[22] = {0}; float bearing; float bearing_offset; int32_t bearing_int; /**********************************************************/ /* Orbit */ /**********************************************************/ float orbit_l = 0.5; float orbit_k = 1.0; int16_t targetDir; uint8_t targetVelocity; /**********************************************************/ /* Face forwards */ /**********************************************************/ #define BEARING_KP 0.8 #define BEARING_KD 0 int32_t targetBearing = 0; int32_t rotatationCorrection; PID bearingPID (&bearing_int, &rotatationCorrection, &targetBearing, BEARING_KP, 0, BEARING_KD, -255, 255, 1000); /**********************************************************/ /* Backspin */ /**********************************************************/ int16_t backspinSpeed = 0; /**********************************************************/ /* Kicker */ /**********************************************************/ #define KICK_TIME 4000 #define KICK_DELAY 30 #define KICK_DURATION 90 #define KICK_SIG 21 #define KICK_ANA A3 bool kicking = false; bool kickDelayComplete = false; elapsedMillis capChargedTime = 0; /**********************************************************/ /* Camera */ /**********************************************************/ #define PIXY1_ADDRESS 0x54 // default i2c address #define MIN_BLOCK_AREA 200 PixyI2C pixy1(PIXY1_ADDRESS); int16_t blocks = 0; int16_t goalAngle = 0; int16_t goalAngle_rel_field = 0; uint16_t goalArea = 0; elapsedMillis lGoalDetectTime = 0; bool goalDetected = false; /**********************************************************/ /* Ultrasonics */ /**********************************************************/ #define SRF_BACK_ADDRESS 0x70 // 0xE0 #define SRF_RIGHT_ADDRESS 0x71 // 0xE2 #define SRF_LEFT_ADDRESS 0x72 // 0xE4 SRF08 srfBack(SRF_BACK_ADDRESS); SRF08 srfRight(SRF_RIGHT_ADDRESS); SRF08 srfLeft(SRF_LEFT_ADDRESS); int16_t backDistance, rightDistance, leftDistance; /**********************************************************/ /* TSOPS */ /**********************************************************/ uint8_t tsopAngleByte; int16_t tsopAngle; int16_t tsopAngle_r_goal; // tsop angle relative to goal uint8_t tsopStrength; uint8_t ballDistance; uint8_t tsopData[24] = {0}; /**********************************************************/ /* LASER */ /**********************************************************/ #define LASER_SIG A1 #define LASER_REF 152 bool ballInZone = false; void kick(){ if (!kicking){ // not yet kicking start kick kicking = true; capChargedTime = 0; Serial.print(millis()); Serial.println("KICK_MOTORS"); } } void checkEndKick(){ if (kicking){ if (!kickDelayComplete && capChargedTime > KICK_DELAY){ kickDelayComplete = true; digitalWriteFast(KICK_SIG, HIGH); capChargedTime = 0; // now effectively discharge time Serial.print(millis()); Serial.println("KICK"); } else if (kickDelayComplete){ // currently actually kicking if (capChargedTime >= KICK_DURATION){ // end kick kicking = false; kickDelayComplete = false; digitalWriteFast(KICK_SIG, LOW); capChargedTime = 0; //Serial.print(analogRead(KICK_ANA)); Serial.print(millis()); Serial.println("END"); } } } else{ digitalWriteFast(KICK_SIG, LOW); } } void calibIMUOffset(){ Slave1.requestPacket(SLAVE1_COMMANDS::CALIB_OFFSET); // for (int i = 0; i < 50; i++){ // Slave1.requestPacket(SLAVE1_COMMANDS::REQUEST_STANDARD_PACKET); // Slave1.receivePacket(inBuffer, 7, true); // f2b.b[0] = inBuffer[2]; // f2b.b[1] = inBuffer[3]; // f2b.b[2] = inBuffer[4]; // f2b.b[3] = inBuffer[5]; // bearing_offset += -f2b.f; // delay(1); // } // bearing_offset /= 50; } void getSlave1Data(){ Slave1.requestPacket(SLAVE1_COMMANDS::REQUEST_STANDARD_PACKET); Slave1.receivePacket(inBuffer, 7, true); f2b.b[0] = inBuffer[2]; f2b.b[1] = inBuffer[3]; f2b.b[2] = inBuffer[4]; f2b.b[3] = inBuffer[5]; bearing = f2b.f; bearing_int = (int32_t)(bearing); TOBEARING180(bearing_int); TOBEARING180(bearing); } void getSlave2Data(){ Slave2.getTSOPAngleStrength(tsopAngle, tsopStrength); TOBEARING180(tsopAngle); tsopAngle_r_goal = tsopAngle - goalAngle; TOBEARING180(tsopAngle_r_goal); } void getGoalData(){ goalArea = pixy1.blocks[0].width * pixy1.blocks[0].height; if (blocks > 0 && blocks < 1000 && goalArea > MIN_BLOCK_AREA && abs(bearing) < 90 ){ goalDetected = true; goalAngle = (pixy1.blocks[0].x - 160) * 75 / 360; goalAngle_rel_field = goalAngle + bearing_int; lGoalDetectTime = 0; } else if (lGoalDetectTime > 100){ // hasn't seen goal for 100ms goalDetected = false; goalAngle = 0; } } void getBackspinSpeed(){ if (!kicking){ if (tsopStrength > 70){ if (abs(targetDir) < 60){ if (ballInZone){ // we're going forwards and we have the ball // no need for too much spin backspinSpeed = 200; } else{ // forwards but ball not here yet! backspinSpeed = 200; } } else{ if (ballInZone){ // we're not going forwards but we have the ball // best to spin a bit more as we need to guide the ball more backspinSpeed = 150; } else{ // most common. Should only spin when ball is in front if (abs(tsopAngle) < 60){ backspinSpeed = 120; } else{ // no chance of getting ball any time soon backspinSpeed = 0; } } } } else{ // no ball detected! backspinSpeed = 0; } } else{ backspinSpeed = -255; } } void checkBallInZone(){ if (analogRead(LASER_SIG) < LASER_REF && abs(tsopAngle) < 30 && tsopStrength > 150){ ballInZone = true; } else{ ballInZone = false; } } void serialDebug(){ Serial.printf("%d\t%d\t%d\t%.0f\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", micros(), goalAngle_rel_field, goalArea, bearing, backDistance, rightDistance, leftDistance, tsopAngle, tsopStrength, ballInZone, targetDir, targetVelocity, rotatationCorrection); if(Serial.available()){ char serialCommand = Serial.read(); CLEARSERIAL(); // make sure you only read first byte and clear everything else if (serialCommand == 'i'){ Serial.println("DEBUG INFO"); Serial.printf("%s %s %s %s %s %s %s %s %s %s %s %s %s %s \n", "micros()", "goalAngle_rel_field", "goalArea", "bearing", "backDistance", "rightDistance", "leftDistance", "tsopAngle", "tsopStrength", "ballInZone", "targetDir", "targetVelocity", "rotatationCorrection"); Serial.println("PRESS ANY KEY TO CONTINUE"); // wait for key while(!Serial.available()); CLEARSERIAL(); } else{ Serial.println("UNKNOWN COMMAND"); } } } int main(void){ Serial.begin(115200); Wire.begin(I2C_MASTER, 0x00, I2C_PINS_18_19, I2C_PULLUP_EXT, I2C_RATE_400); SPI.setSCK(14); SPI.begin(); Slave1.begin(115200); Slave2.begin(); Slave3.begin(); pinMode(LED, OUTPUT); pinMode(LASER_SIG, INPUT); pinMode(KICK_SIG, OUTPUT); pinMode(KICK_ANA, INPUT); digitalWrite(KICK_SIG, LOW); digitalWrite(LED, HIGH); delay(1000); calibIMUOffset(); while(1){ // save some time here as reading srf08's has seen to dramatically decrease performance switch(loopCount % 4){ case 0: blocks = pixy1.getBlocks(); break; case 1: srfBack.getRangeIfCan(backDistance); break; case 2: srfRight.getRangeIfCan(rightDistance); break; case 3: srfLeft.getRangeIfCan(leftDistance); break; } /* orientation/imu */ getSlave1Data(); /* end orientation/imu */ /* tsops */ getSlave2Data(); /* end tsops */ /* goal detection */ getGoalData(); /* end goal detection */ /* face forwards */ if (goalDetected){ targetBearing = goalAngle_rel_field; } else{ targetBearing = 0; } bearingPID.update(); /* end face forwards */ /* ball in zone */ checkBallInZone(); /* end ball in zone */ /*movement control*/ targetVelocity = NORMAL_SPEED; orbit_k = 1; if (tsopStrength > 156){ orbit_k = 1.1; } else if (tsopStrength > 150){ orbit_k = 1.05; } else if (tsopStrength > 140){ orbit_k = 1.0; } else if (tsopStrength > 130){ orbit_k = 1.0; } else if (tsopStrength > 120){ orbit_k = 1; } else if (tsopStrength > 100){ orbit_k = 1; } else if (tsopStrength > 70){ orbit_k = 1; } else{ targetVelocity = 0; } // if (tsopAngle > 90){ // targetDir = (orbit_k * 180 - 90 + tsopAngle); // } // else if (tsopAngle < -90){ // targetDir = (orbit_k * -180 + 90 + tsopAngle); // } // else{ targetDir = orbit_k * (270 - abs(tsopAngle)) / 90 * tsopAngle; // } goalDetected = true; goalAngle = 0; if (ballInZone && goalDetected && abs(goalAngle) < 10){ // GO! targetDir = goalAngle; targetVelocity = RAMMING_SPEED; // kick! if (capChargedTime > KICK_TIME){ kick(); } } checkEndKick(); /* end movement control */ /* backspin control */ getBackspinSpeed(); /* end backspin control */ if (targetDir < 0) targetDir += 360; targetDir = targetDir * 255/360; // Slave3.moveRobot((uint8_t)targetDir, targetVelocity, rotatationCorrection); Slave3.moveMotorE(backspinSpeed); /* debugging */ serialDebug(); /* end debugging */ loopCount++; // update loop count } }<commit_msg>increased min block area to reaonsable size<commit_after>/* * master.cpp - master program for Team PI * * Wire(0) -> capTouch -> pixies -> SRF08s -> slave2 -> slave3 * Wire1 -> slave1 * by Brian Chen * (C) Team PI 2015 */ #include <WProgram.h> #include <i2c_t3.h> #include <SPI.h> #include <slaves.h> #include <piCommon.h> #include <PixyI2C.h> // modified for i2c_t3 #include <SRF08.h> #include <fastTrig.h> #include <PID.h> #include <DebugUtils.h> #define LED 13 #define RAMMING_SPEED 200 #define NORMAL_SPEED 130 uint32_t loopCount = 0; /**********************************************************/ /* Slave1 */ /**********************************************************/ union float2bytes { float f; uint8_t b[sizeof(float)]; }; float2bytes f2b; uint8_t inBuffer[22] = {0}; float bearing; float bearing_offset; int32_t bearing_int; /**********************************************************/ /* Orbit */ /**********************************************************/ float orbit_l = 0.5; float orbit_k = 1.0; int16_t targetDir; uint8_t targetVelocity; /**********************************************************/ /* Face forwards */ /**********************************************************/ #define BEARING_KP 0.8 #define BEARING_KD 0 int32_t targetBearing = 0; int32_t rotatationCorrection; PID bearingPID (&bearing_int, &rotatationCorrection, &targetBearing, BEARING_KP, 0, BEARING_KD, -255, 255, 1000); /**********************************************************/ /* Backspin */ /**********************************************************/ int16_t backspinSpeed = 0; /**********************************************************/ /* Kicker */ /**********************************************************/ #define KICK_TIME 4000 #define KICK_DELAY 30 #define KICK_DURATION 90 #define KICK_SIG 21 #define KICK_ANA A3 bool kicking = false; bool kickDelayComplete = false; elapsedMillis capChargedTime = 0; /**********************************************************/ /* Camera */ /**********************************************************/ #define PIXY1_ADDRESS 0x54 // default i2c address #define MIN_BLOCK_AREA 1500 PixyI2C pixy1(PIXY1_ADDRESS); int16_t blocks = 0; int16_t goalAngle = 0; int16_t goalAngle_rel_field = 0; uint16_t goalArea = 0; elapsedMillis lGoalDetectTime = 0; bool goalDetected = false; /**********************************************************/ /* Ultrasonics */ /**********************************************************/ #define SRF_BACK_ADDRESS 0x70 // 0xE0 #define SRF_RIGHT_ADDRESS 0x71 // 0xE2 #define SRF_LEFT_ADDRESS 0x72 // 0xE4 SRF08 srfBack(SRF_BACK_ADDRESS); SRF08 srfRight(SRF_RIGHT_ADDRESS); SRF08 srfLeft(SRF_LEFT_ADDRESS); int16_t backDistance, rightDistance, leftDistance; /**********************************************************/ /* TSOPS */ /**********************************************************/ uint8_t tsopAngleByte; int16_t tsopAngle; int16_t tsopAngle_r_goal; // tsop angle relative to goal uint8_t tsopStrength; uint8_t ballDistance; uint8_t tsopData[24] = {0}; /**********************************************************/ /* LASER */ /**********************************************************/ #define LASER_SIG A1 #define LASER_REF 152 bool ballInZone = false; void kick(){ if (!kicking){ // not yet kicking start kick kicking = true; capChargedTime = 0; Serial.print(millis()); Serial.println("KICK_MOTORS"); } } void checkEndKick(){ if (kicking){ if (!kickDelayComplete && capChargedTime > KICK_DELAY){ kickDelayComplete = true; digitalWriteFast(KICK_SIG, HIGH); capChargedTime = 0; // now effectively discharge time Serial.print(millis()); Serial.println("KICK"); } else if (kickDelayComplete){ // currently actually kicking if (capChargedTime >= KICK_DURATION){ // end kick kicking = false; kickDelayComplete = false; digitalWriteFast(KICK_SIG, LOW); capChargedTime = 0; //Serial.print(analogRead(KICK_ANA)); Serial.print(millis()); Serial.println("END"); } } } else{ digitalWriteFast(KICK_SIG, LOW); } } void calibIMUOffset(){ Slave1.requestPacket(SLAVE1_COMMANDS::CALIB_OFFSET); // for (int i = 0; i < 50; i++){ // Slave1.requestPacket(SLAVE1_COMMANDS::REQUEST_STANDARD_PACKET); // Slave1.receivePacket(inBuffer, 7, true); // f2b.b[0] = inBuffer[2]; // f2b.b[1] = inBuffer[3]; // f2b.b[2] = inBuffer[4]; // f2b.b[3] = inBuffer[5]; // bearing_offset += -f2b.f; // delay(1); // } // bearing_offset /= 50; } void getSlave1Data(){ Slave1.requestPacket(SLAVE1_COMMANDS::REQUEST_STANDARD_PACKET); Slave1.receivePacket(inBuffer, 7, true); f2b.b[0] = inBuffer[2]; f2b.b[1] = inBuffer[3]; f2b.b[2] = inBuffer[4]; f2b.b[3] = inBuffer[5]; bearing = f2b.f; bearing_int = (int32_t)(bearing); TOBEARING180(bearing_int); TOBEARING180(bearing); } void getSlave2Data(){ Slave2.getTSOPAngleStrength(tsopAngle, tsopStrength); TOBEARING180(tsopAngle); tsopAngle_r_goal = tsopAngle - goalAngle; TOBEARING180(tsopAngle_r_goal); } void getGoalData(){ goalArea = pixy1.blocks[0].width * pixy1.blocks[0].height; if (blocks > 0 && blocks < 1000 && goalArea > MIN_BLOCK_AREA && abs(bearing) < 90 ){ goalDetected = true; goalAngle = (pixy1.blocks[0].x - 160) * 75 / 360; goalAngle_rel_field = goalAngle + bearing_int; lGoalDetectTime = 0; } else if (lGoalDetectTime > 100){ // hasn't seen goal for 100ms goalDetected = false; goalAngle = 0; } } void getBackspinSpeed(){ if (!kicking){ if (tsopStrength > 70){ if (abs(targetDir) < 60){ if (ballInZone){ // we're going forwards and we have the ball // no need for too much spin backspinSpeed = 200; } else{ // forwards but ball not here yet! backspinSpeed = 200; } } else{ if (ballInZone){ // we're not going forwards but we have the ball // best to spin a bit more as we need to guide the ball more backspinSpeed = 150; } else{ // most common. Should only spin when ball is in front if (abs(tsopAngle) < 60){ backspinSpeed = 120; } else{ // no chance of getting ball any time soon backspinSpeed = 0; } } } } else{ // no ball detected! backspinSpeed = 0; } } else{ backspinSpeed = -255; } } void checkBallInZone(){ if (analogRead(LASER_SIG) < LASER_REF && abs(tsopAngle) < 30 && tsopStrength > 150){ ballInZone = true; } else{ ballInZone = false; } } void serialDebug(){ Serial.printf("%d\t%d\t%d\t%.0f\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", micros(), goalAngle_rel_field, goalArea, bearing, backDistance, rightDistance, leftDistance, tsopAngle, tsopStrength, ballInZone, targetDir, targetVelocity, rotatationCorrection); if(Serial.available()){ char serialCommand = Serial.read(); CLEARSERIAL(); // make sure you only read first byte and clear everything else if (serialCommand == 'i'){ Serial.println("DEBUG INFO"); Serial.printf("%s %s %s %s %s %s %s %s %s %s %s %s %s %s \n", "micros()", "goalAngle_rel_field", "goalArea", "bearing", "backDistance", "rightDistance", "leftDistance", "tsopAngle", "tsopStrength", "ballInZone", "targetDir", "targetVelocity", "rotatationCorrection"); Serial.println("PRESS ANY KEY TO CONTINUE"); // wait for key while(!Serial.available()); CLEARSERIAL(); } else{ Serial.println("UNKNOWN COMMAND"); } } } int main(void){ Serial.begin(115200); Wire.begin(I2C_MASTER, 0x00, I2C_PINS_18_19, I2C_PULLUP_EXT, I2C_RATE_400); SPI.setSCK(14); SPI.begin(); Slave1.begin(115200); Slave2.begin(); Slave3.begin(); pinMode(LED, OUTPUT); pinMode(LASER_SIG, INPUT); pinMode(KICK_SIG, OUTPUT); pinMode(KICK_ANA, INPUT); digitalWrite(KICK_SIG, LOW); digitalWrite(LED, HIGH); delay(1000); calibIMUOffset(); while(1){ // save some time here as reading srf08's has seen to dramatically decrease performance switch(loopCount % 4){ case 0: blocks = pixy1.getBlocks(); break; case 1: srfBack.getRangeIfCan(backDistance); break; case 2: srfRight.getRangeIfCan(rightDistance); break; case 3: srfLeft.getRangeIfCan(leftDistance); break; } /* orientation/imu */ getSlave1Data(); /* end orientation/imu */ /* tsops */ getSlave2Data(); /* end tsops */ /* goal detection */ getGoalData(); /* end goal detection */ /* face forwards */ if (goalDetected){ targetBearing = goalAngle_rel_field; } else{ targetBearing = 0; } bearingPID.update(); /* end face forwards */ /* ball in zone */ checkBallInZone(); /* end ball in zone */ /*movement control*/ targetVelocity = NORMAL_SPEED; orbit_k = 1; if (tsopStrength > 156){ orbit_k = 1.1; } else if (tsopStrength > 150){ orbit_k = 1.05; } else if (tsopStrength > 140){ orbit_k = 1.0; } else if (tsopStrength > 130){ orbit_k = 1.0; } else if (tsopStrength > 120){ orbit_k = 1; } else if (tsopStrength > 100){ orbit_k = 1; } else if (tsopStrength > 70){ orbit_k = 1; } else{ targetVelocity = 0; } // if (tsopAngle > 90){ // targetDir = (orbit_k * 180 - 90 + tsopAngle); // } // else if (tsopAngle < -90){ // targetDir = (orbit_k * -180 + 90 + tsopAngle); // } // else{ targetDir = orbit_k * (270 - abs(tsopAngle)) / 90 * tsopAngle; // } goalDetected = true; goalAngle = 0; if (ballInZone && goalDetected && abs(goalAngle) < 10){ // GO! targetDir = goalAngle; targetVelocity = RAMMING_SPEED; // kick! if (capChargedTime > KICK_TIME){ kick(); } } checkEndKick(); /* end movement control */ /* backspin control */ getBackspinSpeed(); /* end backspin control */ if (targetDir < 0) targetDir += 360; targetDir = targetDir * 255/360; // Slave3.moveRobot((uint8_t)targetDir, targetVelocity, rotatationCorrection); Slave3.moveMotorE(backspinSpeed); /* debugging */ serialDebug(); /* end debugging */ loopCount++; // update loop count } }<|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <cstdlib> #include <ctime> #include <iostream> #include <fstream> #include <itksys/SystemTools.hxx> #include "mitkPixelType.h" #include "itkImageRegionIterator.h" #include "itkImageFileReader.h" #include <mitkIOUtil.h> template< class D, class T > mitk::TeemDiffusionTensor3DReconstructionImageFilter<D,T> ::TeemDiffusionTensor3DReconstructionImageFilter(): m_EstimateErrorImage(false),m_Sigma(-19191919), m_EstimationMethod(TeemTensorEstimationMethodsLLS), m_NumIterations(1),m_ConfidenceThreshold(-19191919.0), m_ConfidenceFuzzyness(0.0),m_MinPlausibleValue(1.0) { } template< class D, class T > mitk::TeemDiffusionTensor3DReconstructionImageFilter<D,T> ::~TeemDiffusionTensor3DReconstructionImageFilter() { } void file_replace(std::string filename, std::string what, std::string with) { ofstream myfile2; std::locale C("C"); std::locale originalLocale2 = myfile2.getloc(); myfile2.imbue(C); char filename2[512]; sprintf(filename2, "%s2",filename.c_str()); myfile2.open (filename2); std::string line; ifstream myfile (filename.c_str()); std::locale originalLocale = myfile.getloc(); myfile.imbue(C); if (myfile.is_open()) { while (! myfile.eof() ) { getline (myfile,line); itksys::SystemTools::ReplaceString(line,what.c_str(),with.c_str()); myfile2 << line << std::endl; } myfile.close(); } myfile2.close(); itksys::SystemTools::RemoveFile(filename.c_str()); rename(filename2,filename.c_str()); myfile.imbue( originalLocale ); myfile2.imbue( originalLocale2 ); } // do the work template< class D, class T > void mitk::TeemDiffusionTensor3DReconstructionImageFilter<D,T> ::Update() { // save input image to nrrd file in temp-folder char filename[512]; srand((unsigned)time(0)); int random_integer = rand(); sprintf( filename, "dwi_%d.nhdr",random_integer); try { mitk::IOUtil::Save(m_Input, filename.c_str()); } catch (itk::ExceptionObject e) { std::cout << e << std::endl; } file_replace(filename,"vector","list"); // build up correct command from input params char command[4096]; sprintf( command, "tend estim -i %s -B kvp -o tensors_%d.nhdr -knownB0 true", filename, random_integer); //m_DiffusionImages; if(m_EstimateErrorImage) { sprintf( command, "%s -ee error_image_%d.nhdr", command, random_integer); } if(m_Sigma != -19191919) { sprintf( command, "%s -sigma %f", command, m_Sigma); } switch(m_EstimationMethod) { case TeemTensorEstimationMethodsLLS: sprintf( command, "%s -est lls", command); break; case TeemTensorEstimationMethodsMLE: sprintf( command, "%s -est mle", command); break; case TeemTensorEstimationMethodsNLS: sprintf( command, "%s -est nls", command); break; case TeemTensorEstimationMethodsWLS: sprintf( command, "%s -est wls", command); break; } sprintf( command, "%s -wlsi %d", command, m_NumIterations); if(m_ConfidenceThreshold != -19191919.0) { sprintf( command, "%s -t %f", command, m_ConfidenceThreshold); } sprintf( command, "%s -soft %f", command, m_ConfidenceFuzzyness); sprintf( command, "%s -mv %f", command, m_MinPlausibleValue); // call tend estim command std::cout << "Calling <" << command << ">" << std::endl; int success = system(command); if(!success) { MITK_ERROR << "system command could not be called!"; } remove(filename); sprintf( filename, "dwi_%d.raw", random_integer); remove(filename); // change kind from tensor to vector sprintf( filename, "tensors_%d.nhdr", random_integer); file_replace(filename,"3D-masked-symmetric-matrix","vector"); // read result as mitk::Image and provide it in m_Output typedef itk::ImageFileReader<VectorImageType> FileReaderType; typename FileReaderType::Pointer reader = FileReaderType::New(); reader->SetFileName(filename); reader->Update(); typename VectorImageType::Pointer vecImage = reader->GetOutput(); remove(filename); sprintf( filename, "tensors_%d.raw", random_integer); remove(filename); typename ItkTensorImageType::Pointer itkTensorImage = ItkTensorImageType::New(); itkTensorImage->SetSpacing( vecImage->GetSpacing() ); // Set the image spacing itkTensorImage->SetOrigin( vecImage->GetOrigin() ); // Set the image origin itkTensorImage->SetDirection( vecImage->GetDirection() ); // Set the image direction itkTensorImage->SetLargestPossibleRegion( vecImage->GetLargestPossibleRegion() ); itkTensorImage->SetBufferedRegion( vecImage->GetLargestPossibleRegion() ); itkTensorImage->SetRequestedRegion( vecImage->GetLargestPossibleRegion() ); itkTensorImage->Allocate(); itk::ImageRegionIterator<VectorImageType> it(vecImage, vecImage->GetLargestPossibleRegion()); itk::ImageRegionIterator<ItkTensorImageType> it2(itkTensorImage, itkTensorImage->GetLargestPossibleRegion()); it2 = it2.Begin(); //#pragma omp parallel private (it) { for(it=it.Begin();!it.IsAtEnd(); ++it, ++it2) { //#pragma omp single nowait { VectorType vec = it.Get(); TensorType tensor; for(int i=1;i<7;i++) tensor[i-1] = vec[i] * vec[0]; it2.Set( tensor ); } } // end for } // end ompparallel m_OutputItk = mitk::TensorImage::New(); m_OutputItk->InitializeByItk(itkTensorImage.GetPointer()); m_OutputItk->SetVolume( itkTensorImage->GetBufferPointer() ); // in case: read resulting error-image and provide it in m_ErrorImage if(m_EstimateErrorImage) { // open error image here } } <commit_msg>COMP: variable is already a c string<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <cstdlib> #include <ctime> #include <iostream> #include <fstream> #include <itksys/SystemTools.hxx> #include "mitkPixelType.h" #include "itkImageRegionIterator.h" #include "itkImageFileReader.h" #include <mitkIOUtil.h> template< class D, class T > mitk::TeemDiffusionTensor3DReconstructionImageFilter<D,T> ::TeemDiffusionTensor3DReconstructionImageFilter(): m_EstimateErrorImage(false),m_Sigma(-19191919), m_EstimationMethod(TeemTensorEstimationMethodsLLS), m_NumIterations(1),m_ConfidenceThreshold(-19191919.0), m_ConfidenceFuzzyness(0.0),m_MinPlausibleValue(1.0) { } template< class D, class T > mitk::TeemDiffusionTensor3DReconstructionImageFilter<D,T> ::~TeemDiffusionTensor3DReconstructionImageFilter() { } void file_replace(std::string filename, std::string what, std::string with) { ofstream myfile2; std::locale C("C"); std::locale originalLocale2 = myfile2.getloc(); myfile2.imbue(C); char filename2[512]; sprintf(filename2, "%s2",filename.c_str()); myfile2.open (filename2); std::string line; ifstream myfile (filename.c_str()); std::locale originalLocale = myfile.getloc(); myfile.imbue(C); if (myfile.is_open()) { while (! myfile.eof() ) { getline (myfile,line); itksys::SystemTools::ReplaceString(line,what.c_str(),with.c_str()); myfile2 << line << std::endl; } myfile.close(); } myfile2.close(); itksys::SystemTools::RemoveFile(filename.c_str()); rename(filename2,filename.c_str()); myfile.imbue( originalLocale ); myfile2.imbue( originalLocale2 ); } // do the work template< class D, class T > void mitk::TeemDiffusionTensor3DReconstructionImageFilter<D,T> ::Update() { // save input image to nrrd file in temp-folder char filename[512]; srand((unsigned)time(0)); int random_integer = rand(); sprintf( filename, "dwi_%d.nhdr",random_integer); try { mitk::IOUtil::Save(m_Input, filename); } catch (itk::ExceptionObject e) { std::cout << e << std::endl; } file_replace(filename,"vector","list"); // build up correct command from input params char command[4096]; sprintf( command, "tend estim -i %s -B kvp -o tensors_%d.nhdr -knownB0 true", filename, random_integer); //m_DiffusionImages; if(m_EstimateErrorImage) { sprintf( command, "%s -ee error_image_%d.nhdr", command, random_integer); } if(m_Sigma != -19191919) { sprintf( command, "%s -sigma %f", command, m_Sigma); } switch(m_EstimationMethod) { case TeemTensorEstimationMethodsLLS: sprintf( command, "%s -est lls", command); break; case TeemTensorEstimationMethodsMLE: sprintf( command, "%s -est mle", command); break; case TeemTensorEstimationMethodsNLS: sprintf( command, "%s -est nls", command); break; case TeemTensorEstimationMethodsWLS: sprintf( command, "%s -est wls", command); break; } sprintf( command, "%s -wlsi %d", command, m_NumIterations); if(m_ConfidenceThreshold != -19191919.0) { sprintf( command, "%s -t %f", command, m_ConfidenceThreshold); } sprintf( command, "%s -soft %f", command, m_ConfidenceFuzzyness); sprintf( command, "%s -mv %f", command, m_MinPlausibleValue); // call tend estim command std::cout << "Calling <" << command << ">" << std::endl; int success = system(command); if(!success) { MITK_ERROR << "system command could not be called!"; } remove(filename); sprintf( filename, "dwi_%d.raw", random_integer); remove(filename); // change kind from tensor to vector sprintf( filename, "tensors_%d.nhdr", random_integer); file_replace(filename,"3D-masked-symmetric-matrix","vector"); // read result as mitk::Image and provide it in m_Output typedef itk::ImageFileReader<VectorImageType> FileReaderType; typename FileReaderType::Pointer reader = FileReaderType::New(); reader->SetFileName(filename); reader->Update(); typename VectorImageType::Pointer vecImage = reader->GetOutput(); remove(filename); sprintf( filename, "tensors_%d.raw", random_integer); remove(filename); typename ItkTensorImageType::Pointer itkTensorImage = ItkTensorImageType::New(); itkTensorImage->SetSpacing( vecImage->GetSpacing() ); // Set the image spacing itkTensorImage->SetOrigin( vecImage->GetOrigin() ); // Set the image origin itkTensorImage->SetDirection( vecImage->GetDirection() ); // Set the image direction itkTensorImage->SetLargestPossibleRegion( vecImage->GetLargestPossibleRegion() ); itkTensorImage->SetBufferedRegion( vecImage->GetLargestPossibleRegion() ); itkTensorImage->SetRequestedRegion( vecImage->GetLargestPossibleRegion() ); itkTensorImage->Allocate(); itk::ImageRegionIterator<VectorImageType> it(vecImage, vecImage->GetLargestPossibleRegion()); itk::ImageRegionIterator<ItkTensorImageType> it2(itkTensorImage, itkTensorImage->GetLargestPossibleRegion()); it2 = it2.Begin(); //#pragma omp parallel private (it) { for(it=it.Begin();!it.IsAtEnd(); ++it, ++it2) { //#pragma omp single nowait { VectorType vec = it.Get(); TensorType tensor; for(int i=1;i<7;i++) tensor[i-1] = vec[i] * vec[0]; it2.Set( tensor ); } } // end for } // end ompparallel m_OutputItk = mitk::TensorImage::New(); m_OutputItk->InitializeByItk(itkTensorImage.GetPointer()); m_OutputItk->SetVolume( itkTensorImage->GetBufferPointer() ); // in case: read resulting error-image and provide it in m_ErrorImage if(m_EstimateErrorImage) { // open error image here } } <|endoftext|>
<commit_before>//@ {"targets":[{"name":"serializer.hpp","type":"include"}]} #ifndef TEMPLE_SERIALIZER_HPP #define TEMPLE_SERIALIZER_HPP #include "item.hpp" #include "treenode.hpp" #include <stack> namespace Temple { namespace { template<class Callback> class VisitorBase { public: virtual bool atEnd() const noexcept=0; virtual void advance() noexcept=0; virtual void itemProcess(Callback& cb) const=0; virtual ~VisitorBase()=default; char terminator() const noexcept {return m_terminator;} protected: explicit VisitorBase(char term) noexcept: m_terminator(term) {} private: char m_terminator; }; template<class Callback,class Container> class Visitor:public VisitorBase<Callback> { public: explicit Visitor(Container&&)=delete; explicit Visitor(const Container& container,char term): VisitorBase<Callback>(term) ,m_begin(container.begin()) ,m_current(container.begin()) ,m_end(container.end()) {} bool atEnd() const noexcept {return m_current==m_end;} bool atBegin() const noexcept {return m_current==m_begin;} void advance() noexcept {++m_current;} void itemProcess(Callback& cb) const {cb(*m_current,*this);} static auto create(const Container& cnt,char term) {return std::unique_ptr<VisitorBase<Callback>>(new Visitor(cnt,term));} private: typename Container::const_iterator m_begin; typename Container::const_iterator m_current; typename Container::const_iterator m_end; }; template<class Cstr,class Sink> static void write(Cstr src,Sink& sink) { while(true) { auto ch_in=*src; if(ch_in=='\0') {return;} if(ch_in=='\\' || ch_in=='\"') {putc('\\',sink);} putc(ch_in,sink); ++src; } } template<class StorageModel,class Sink> class Acceptor { public: using MapType=typename StorageModel::template MapType< std::unique_ptr< ItemBase<StorageModel> > > ; using CompoundArray=typename StorageModel::template ArrayType<MapType>; using VisitorArray=Visitor<Acceptor,CompoundArray>; using VisitorMap=Visitor<Acceptor,MapType>; explicit Acceptor(ItemBase<StorageModel>&&)=delete; explicit Acceptor(const ItemBase<StorageModel>& root,Sink& sink):r_sink(sink) { if(root.array()) {m_stack.push(VisitorArray::create(root.template value<CompoundArray>(),']') );} else {m_stack.push(VisitorMap::create(root.template value<MapType>(),'}'));} } void run() { while(!m_stack.empty()) { auto& visitor=m_stack.top(); if(visitor->atEnd()) { putc(visitor->terminator(),r_sink); m_stack.pop(); } else { visitor->itemProcess(*this); visitor->advance(); } } } void operator()(const MapType& node_current,const VisitorArray& visitor) { putc(visitor.atBegin()?'[':',',r_sink); m_stack.push(VisitorMap::create(node_current,'}')); } void operator()(const typename MapType::value_type& node_current,const VisitorMap& visitor) { putc(visitor.atBegin()?'{':',',r_sink); putc('"',r_sink); write(node_current.first.c_str(),r_sink); putc('"',r_sink); } private: Sink& r_sink; std::stack< std::unique_ptr< VisitorBase<Acceptor> > > m_stack; }; } template<class StorageModel,class Sink> void temple_store(const ItemBase<StorageModel>& root,Sink& sink) {Acceptor<StorageModel,Sink>(root,sink).run();} } #endif <commit_msg>Fixed empty objects<commit_after>//@ {"targets":[{"name":"serializer.hpp","type":"include"}]} #ifndef TEMPLE_SERIALIZER_HPP #define TEMPLE_SERIALIZER_HPP #include "item.hpp" #include "treenode.hpp" #include <stack> namespace Temple { namespace { template<class Callback> class VisitorBase { public: virtual bool atEnd() const noexcept=0; virtual void advance() noexcept=0; virtual void itemProcess(Callback& cb) const=0; virtual ~VisitorBase()=default; char terminator() const noexcept {return m_terminator;} protected: explicit VisitorBase(char term) noexcept: m_terminator(term) {} private: char m_terminator; }; template<class Callback,class Container> class Visitor:public VisitorBase<Callback> { public: explicit Visitor(Container&&)=delete; explicit Visitor(const Container& container,char term): VisitorBase<Callback>(term) ,m_begin(container.begin()) ,m_current(container.begin()) ,m_end(container.end()) {} bool atEnd() const noexcept {return m_current==m_end;} bool atBegin() const noexcept {return m_current==m_begin;} void advance() noexcept {++m_current;} void itemProcess(Callback& cb) const {cb(*m_current,*this);} static auto create(const Container& cnt,char term) {return std::unique_ptr<VisitorBase<Callback>>(new Visitor(cnt,term));} private: typename Container::const_iterator m_begin; typename Container::const_iterator m_current; typename Container::const_iterator m_end; }; template<class Cstr,class Sink> static void write(Cstr src,Sink& sink) { while(true) { auto ch_in=*src; if(ch_in=='\0') {return;} if(ch_in=='\\' || ch_in=='\"') {putc('\\',sink);} putc(ch_in,sink); ++src; } } template<class StorageModel,class Sink> class Acceptor { public: using MapType=typename StorageModel::template MapType< std::unique_ptr< ItemBase<StorageModel> > > ; using CompoundArray=typename StorageModel::template ArrayType<MapType>; using VisitorArray=Visitor<Acceptor,CompoundArray>; using VisitorMap=Visitor<Acceptor,MapType>; explicit Acceptor(ItemBase<StorageModel>&&)=delete; explicit Acceptor(const ItemBase<StorageModel>& root,Sink& sink):r_sink(sink) { if(root.array()) {m_stack.push(VisitorArray::create(root.template value<CompoundArray>(),']') );} else {m_stack.push(VisitorMap::create(root.template value<MapType>(),'}'));} } void run() { while(!m_stack.empty()) { auto& visitor=m_stack.top(); if(visitor->atEnd()) { putc(visitor->terminator(),r_sink); m_stack.pop(); } else { visitor->itemProcess(*this); visitor->advance(); } } } void operator()(const MapType& node_current,const VisitorArray& visitor) { putc(visitor.atBegin()?'[':',',r_sink); m_stack.push(VisitorMap::create(node_current,'}')); } void operator()(const typename MapType::value_type& node_current,const VisitorMap& visitor) { putc(visitor.atBegin()?'{':',',r_sink); putc('"',r_sink); write(node_current.first.c_str(),r_sink); auto type_current=node_current.second->type(); fprintf(r_sink,"\",%s:",type(type_current)); if(type_current==Type::COMPOUND) { auto node=VisitorMap::create(node_current.second->template value<MapType>(),'}'); putc('\n',r_sink); if(node->atEnd()) {putc('{',r_sink);} m_stack.push(std::move(node)); } else if(type_current==Type::COMPOUND_ARRAY) { auto node=VisitorArray::create(node_current.second->template value<CompoundArray>(),'}'); putc('\n',r_sink); if(node->atEnd()) {putc('[',r_sink);} m_stack.push(std::move(node)); } else {} } private: Sink& r_sink; std::stack< std::unique_ptr< VisitorBase<Acceptor> > > m_stack; }; } template<class StorageModel,class Sink> void temple_store(const ItemBase<StorageModel>& root,Sink& sink) {Acceptor<StorageModel,Sink>(root,sink).run();} } #endif <|endoftext|>
<commit_before>/** * @file * @brief Implementation of detector histogramming module * @copyright MIT License */ #include "DetectorHistogrammerModule.hpp" #include <algorithm> #include <memory> #include <string> #include <utility> #include "core/geometry/HybridPixelDetectorModel.hpp" #include "core/messenger/Messenger.hpp" #include "core/utils/log.h" #include "tools/ROOT.h" using namespace allpix; DetectorHistogrammerModule::DetectorHistogrammerModule(Configuration config, Messenger* messenger, std::shared_ptr<Detector> detector) : Module(config, detector), config_(std::move(config)), detector_(std::move(detector)), pixels_message_(nullptr) { // Bind pixel hits message messenger->bindSingle(this, &DetectorHistogrammerModule::pixels_message_, MsgFlags::REQUIRED); } void DetectorHistogrammerModule::init() { // Fetch detector model auto model = detector_->getModel(); // Create histogram of hitmap LOG(TRACE) << "Creating histograms"; std::string hit_map_name = "hit_map"; std::string hit_map_title = "Hitmap for " + detector_->getName() + ";x (pixels);y (pixels)"; hit_map = new TH2I(hit_map_name.c_str(), hit_map_title.c_str(), model->getNPixels().x(), -0.5, model->getNPixels().x() - 0.5, model->getNPixels().y(), -0.5, model->getNPixels().y() - 0.5); // Create histogram of cluster map std::string cluster_map_name = "cluster_map"; std::string cluster_map_title = "Cluster map for " + detector_->getName() + ";x (pixels);y (pixels)"; cluster_map = new TH2I(cluster_map_name.c_str(), cluster_map_title.c_str(), model->getNPixels().x(), -0.5, model->getNPixels().x() - 0.5, model->getNPixels().y(), -0.5, model->getNPixels().y() - 0.5); // Create cluster size plots std::string cluster_size_name = "cluster_size"; std::string cluster_size_title = "Cluster size for " + detector_->getName() + ";size;number"; cluster_size = new TH1I(cluster_size_name.c_str(), cluster_size_title.c_str(), model->getNPixels().x() * model->getNPixels().y(), 0.5, model->getNPixels().x() * model->getNPixels().y() + 0.5); std::string cluster_size_x_name = "cluster_size_x"; std::string cluster_size_x_title = "Cluster size X for " + detector_->getName() + ";size;number"; cluster_size_x = new TH1I(cluster_size_x_name.c_str(), cluster_size_x_title.c_str(), model->getNPixels().x(), 0.5, model->getNPixels().x() + 0.5); std::string cluster_size_y_name = "cluster_size_y"; std::string cluster_size_y_title = "Cluster size Y for " + detector_->getName() + ";size;number"; cluster_size_y = new TH1I(cluster_size_y_name.c_str(), cluster_size_y_title.c_str(), model->getNPixels().y(), 0.5, model->getNPixels().y() + 0.5); // Create event size plot std::string event_size_name = "event_size"; std::string event_size_title = "Event size for " + detector_->getName() + ";size;number"; event_size = new TH1I(event_size_name.c_str(), event_size_title.c_str(), model->getNPixels().x() * model->getNPixels().y(), 0.5, model->getNPixels().x() * model->getNPixels().y() + 0.5); // Create number of clusters plot std::string n_cluster_name = "n_cluster"; std::string n_cluster_title = "Number of clusters for " + detector_->getName() + ";size;number"; n_cluster = new TH1I(n_cluster_name.c_str(), n_cluster_title.c_str(), model->getNPixels().x() * model->getNPixels().y(), 0.5, model->getNPixels().x() * model->getNPixels().y() + 0.5); // Create cluster charge plot std::string cluster_charge_name = "cluster_charge"; std::string cluster_charge_title = "Cluster charge for " + detector_->getName() + ";size;number"; cluster_charge = new TH1D(cluster_charge_name.c_str(), cluster_charge_title.c_str(), 200, 0., 100.); } void DetectorHistogrammerModule::run(unsigned int) { LOG(DEBUG) << "Adding hits in " << pixels_message_->getData().size() << " pixels"; // Fill 2D hitmap histogram for(auto& pixel_charge : pixels_message_->getData()) { auto pixel_idx = pixel_charge.getPixel().getIndex(); // Add pixel hit_map->Fill(pixel_idx.x(), pixel_idx.y()); // Update statistics total_vector_ += pixel_idx; total_hits_ += 1; } // Perform a clustering doClustering(); // Evaluate the clusters for(auto clus : clusters_) { LOG(DEBUG) << "Cluster, size " << clus->getClusterSize() << " :"; for(auto& pixel : clus->getPixelHits()) { LOG(DEBUG) << pixel->getPixel().getIndex(); } // Fill cluster histograms cluster_size->Fill(static_cast<double>(clus->getClusterSize())); auto clusSizesXY = clus->getClusterSizeXY(); cluster_size_x->Fill(clusSizesXY.first); cluster_size_y->Fill(clusSizesXY.second); auto clusPos = clus->getClusterPosition(); cluster_map->Fill(clusPos.x(), clusPos.y()); cluster_charge->Fill(clus->getClusterCharge() * 1.e-3); } // Fill further histograms event_size->Fill(static_cast<double>(pixels_message_->getData().size())); n_cluster->Fill(static_cast<double>(clusters_.size())); clusters_.clear(); } void DetectorHistogrammerModule::finalize() { // Print statistics if(total_hits_ != 0) { LOG(INFO) << "Plotted " << total_hits_ << " hits in total, mean position is " << total_vector_ / static_cast<double>(total_hits_); } else { LOG(WARNING) << "No hits plotted"; } // FIXME Set more useful spacing maximum for cluster size histogram auto xmax = std::ceil(cluster_size->GetBinCenter(cluster_size->FindLastBinAbove()) + 1); cluster_size->GetXaxis()->SetRangeUser(0, xmax); // Set cluster size axis spacing if(static_cast<int>(xmax) < 10) { cluster_size->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true); } xmax = std::ceil(cluster_size_x->GetBinCenter(cluster_size_x->FindLastBinAbove()) + 1); cluster_size_x->GetXaxis()->SetRangeUser(0, xmax); // Set cluster size_x axis spacing if(static_cast<int>(xmax) < 10) { cluster_size_x->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true); } xmax = std::ceil(cluster_size_y->GetBinCenter(cluster_size_y->FindLastBinAbove()) + 1); cluster_size_y->GetXaxis()->SetRangeUser(0, xmax); // Set cluster size_y axis spacing if(static_cast<int>(xmax) < 10) { cluster_size_y->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true); } // FIXME Set more useful spacing maximum for event size histogram xmax = std::ceil(event_size->GetBinCenter(event_size->FindLastBinAbove()) + 1); event_size->GetXaxis()->SetRangeUser(0, xmax); // Set event size axis spacing if(static_cast<int>(xmax) < 10) { event_size->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true); } // FIXME Set more useful spacing maximum for n_cluster histogram xmax = std::ceil(n_cluster->GetBinCenter(n_cluster->FindLastBinAbove()) + 1); n_cluster->GetXaxis()->SetRangeUser(0, xmax); // Set cluster size axis spacing if(static_cast<int>(xmax) < 10) { n_cluster->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true); } // FIXME Set more useful spacing maximum for cluster_charge histogram xmax = std::ceil(cluster_charge->GetBinCenter(cluster_charge->FindLastBinAbove()) + 1); cluster_charge->GetXaxis()->SetRangeUser(0, xmax); // Set cluster size axis spacing if(static_cast<int>(xmax) < 10) { cluster_charge->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true); } // Set default drawing option histogram for hitmap hit_map->SetOption("colz"); // Set hit_map axis spacing if(static_cast<int>(hit_map->GetXaxis()->GetXmax()) < 10) { hit_map->GetXaxis()->SetNdivisions(static_cast<int>(hit_map->GetXaxis()->GetXmax()) + 1, 0, 0, true); } if(static_cast<int>(hit_map->GetYaxis()->GetXmax()) < 10) { hit_map->GetYaxis()->SetNdivisions(static_cast<int>(hit_map->GetYaxis()->GetXmax()) + 1, 0, 0, true); } cluster_map->SetOption("colz"); // Set cluster_map axis spacing if(static_cast<int>(cluster_map->GetXaxis()->GetXmax()) < 10) { cluster_map->GetXaxis()->SetNdivisions(static_cast<int>(cluster_map->GetXaxis()->GetXmax()) + 1, 0, 0, true); } if(static_cast<int>(cluster_map->GetYaxis()->GetXmax()) < 10) { cluster_map->GetYaxis()->SetNdivisions(static_cast<int>(cluster_map->GetYaxis()->GetXmax()) + 1, 0, 0, true); } // Write histograms LOG(TRACE) << "Writing histograms to file"; hit_map->Write(); cluster_map->Write(); cluster_size->Write(); cluster_size_x->Write(); cluster_size_y->Write(); event_size->Write(); n_cluster->Write(); cluster_charge->Write(); } void DetectorHistogrammerModule::doClustering() { for(auto& pixel_hit : pixels_message_->getData()) { Cluster* clus; if(not checkAdjacentPixels(&pixel_hit)) { LOG(DEBUG) << "Creating new cluster: " << pixel_hit.getPixel().getIndex(); clus = new Cluster(&pixel_hit); clusters_.push_back(clus); } } } bool DetectorHistogrammerModule::isInCluster(const PixelHit* pixel_hit) { for(auto clus : clusters_) { for(auto& hit : clus->getPixelHits()) { if(pixel_hit == hit) { return true; } } } return false; } bool DetectorHistogrammerModule::checkAdjacentPixels(const PixelHit* pixel_hit) { auto hit_idx = pixel_hit->getPixel().getIndex(); for(auto clus : clusters_) { for(auto& pixel_other : clus->getPixelHits()) { auto other_idx = pixel_other->getPixel().getIndex(); auto distx = std::max(hit_idx.x(), other_idx.x()) - std::min(hit_idx.x(), other_idx.x()); auto disty = std::max(hit_idx.y(), other_idx.y()) - std::min(hit_idx.y(), other_idx.y()); if(distx <= 1 and disty <= 1) { LOG(DEBUG) << "Adding pixel to cluster: " << hit_idx; bool ret = clus->addPixelHit(pixel_hit); if(ret == false) { LOG(DEBUG) << "Hit has already been added to this cluster: " << hit_idx; } return true; } } } return false; } <commit_msg>Change axes labels<commit_after>/** * @file * @brief Implementation of detector histogramming module * @copyright MIT License */ #include "DetectorHistogrammerModule.hpp" #include <algorithm> #include <memory> #include <string> #include <utility> #include "core/geometry/HybridPixelDetectorModel.hpp" #include "core/messenger/Messenger.hpp" #include "core/utils/log.h" #include "tools/ROOT.h" using namespace allpix; DetectorHistogrammerModule::DetectorHistogrammerModule(Configuration config, Messenger* messenger, std::shared_ptr<Detector> detector) : Module(config, detector), config_(std::move(config)), detector_(std::move(detector)), pixels_message_(nullptr) { // Bind pixel hits message messenger->bindSingle(this, &DetectorHistogrammerModule::pixels_message_, MsgFlags::REQUIRED); } void DetectorHistogrammerModule::init() { // Fetch detector model auto model = detector_->getModel(); // Create histogram of hitmap LOG(TRACE) << "Creating histograms"; std::string hit_map_name = "hit_map"; std::string hit_map_title = "Hitmap for " + detector_->getName() + ";x (pixels);y (pixels)"; hit_map = new TH2I(hit_map_name.c_str(), hit_map_title.c_str(), model->getNPixels().x(), -0.5, model->getNPixels().x() - 0.5, model->getNPixels().y(), -0.5, model->getNPixels().y() - 0.5); // Create histogram of cluster map std::string cluster_map_name = "cluster_map"; std::string cluster_map_title = "Cluster map for " + detector_->getName() + ";x (pixels);y (pixels)"; cluster_map = new TH2I(cluster_map_name.c_str(), cluster_map_title.c_str(), model->getNPixels().x(), -0.5, model->getNPixels().x() - 0.5, model->getNPixels().y(), -0.5, model->getNPixels().y() - 0.5); // Create cluster size plots std::string cluster_size_name = "cluster_size"; std::string cluster_size_title = "Cluster size for " + detector_->getName() + ";cluster size [px];clusters"; cluster_size = new TH1I(cluster_size_name.c_str(), cluster_size_title.c_str(), model->getNPixels().x() * model->getNPixels().y(), 0.5, model->getNPixels().x() * model->getNPixels().y() + 0.5); std::string cluster_size_x_name = "cluster_size_x"; std::string cluster_size_x_title = "Cluster size X for " + detector_->getName() + ";cluster size x [px];clusters"; cluster_size_x = new TH1I(cluster_size_x_name.c_str(), cluster_size_x_title.c_str(), model->getNPixels().x(), 0.5, model->getNPixels().x() + 0.5); std::string cluster_size_y_name = "cluster_size_y"; std::string cluster_size_y_title = "Cluster size Y for " + detector_->getName() + ";cluster size y [px];clusters"; cluster_size_y = new TH1I(cluster_size_y_name.c_str(), cluster_size_y_title.c_str(), model->getNPixels().y(), 0.5, model->getNPixels().y() + 0.5); // Create event size plot std::string event_size_name = "event_size"; std::string event_size_title = "Event size for " + detector_->getName() + ";event size [px];events"; event_size = new TH1I(event_size_name.c_str(), event_size_title.c_str(), model->getNPixels().x() * model->getNPixels().y(), 0.5, model->getNPixels().x() * model->getNPixels().y() + 0.5); // Create number of clusters plot std::string n_cluster_name = "n_cluster"; std::string n_cluster_title = "Number of clusters for " + detector_->getName() + ";size;clusters"; n_cluster = new TH1I(n_cluster_name.c_str(), n_cluster_title.c_str(), model->getNPixels().x() * model->getNPixels().y(), 0.5, model->getNPixels().x() * model->getNPixels().y() + 0.5); // Create cluster charge plot std::string cluster_charge_name = "cluster_charge"; std::string cluster_charge_title = "Cluster charge for " + detector_->getName() + ";cluster charge [ke];clusters"; cluster_charge = new TH1D(cluster_charge_name.c_str(), cluster_charge_title.c_str(), 200, 0., 100.); } void DetectorHistogrammerModule::run(unsigned int) { LOG(DEBUG) << "Adding hits in " << pixels_message_->getData().size() << " pixels"; // Fill 2D hitmap histogram for(auto& pixel_charge : pixels_message_->getData()) { auto pixel_idx = pixel_charge.getPixel().getIndex(); // Add pixel hit_map->Fill(pixel_idx.x(), pixel_idx.y()); // Update statistics total_vector_ += pixel_idx; total_hits_ += 1; } // Perform a clustering doClustering(); // Evaluate the clusters for(auto clus : clusters_) { LOG(DEBUG) << "Cluster, size " << clus->getClusterSize() << " :"; for(auto& pixel : clus->getPixelHits()) { LOG(DEBUG) << pixel->getPixel().getIndex(); } // Fill cluster histograms cluster_size->Fill(static_cast<double>(clus->getClusterSize())); auto clusSizesXY = clus->getClusterSizeXY(); cluster_size_x->Fill(clusSizesXY.first); cluster_size_y->Fill(clusSizesXY.second); auto clusPos = clus->getClusterPosition(); cluster_map->Fill(clusPos.x(), clusPos.y()); cluster_charge->Fill(clus->getClusterCharge() * 1.e-3); } // Fill further histograms event_size->Fill(static_cast<double>(pixels_message_->getData().size())); n_cluster->Fill(static_cast<double>(clusters_.size())); clusters_.clear(); } void DetectorHistogrammerModule::finalize() { // Print statistics if(total_hits_ != 0) { LOG(INFO) << "Plotted " << total_hits_ << " hits in total, mean position is " << total_vector_ / static_cast<double>(total_hits_); } else { LOG(WARNING) << "No hits plotted"; } // FIXME Set more useful spacing maximum for cluster size histogram auto xmax = std::ceil(cluster_size->GetBinCenter(cluster_size->FindLastBinAbove()) + 1); cluster_size->GetXaxis()->SetRangeUser(0, xmax); // Set cluster size axis spacing if(static_cast<int>(xmax) < 10) { cluster_size->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true); } xmax = std::ceil(cluster_size_x->GetBinCenter(cluster_size_x->FindLastBinAbove()) + 1); cluster_size_x->GetXaxis()->SetRangeUser(0, xmax); // Set cluster size_x axis spacing if(static_cast<int>(xmax) < 10) { cluster_size_x->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true); } xmax = std::ceil(cluster_size_y->GetBinCenter(cluster_size_y->FindLastBinAbove()) + 1); cluster_size_y->GetXaxis()->SetRangeUser(0, xmax); // Set cluster size_y axis spacing if(static_cast<int>(xmax) < 10) { cluster_size_y->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true); } // FIXME Set more useful spacing maximum for event size histogram xmax = std::ceil(event_size->GetBinCenter(event_size->FindLastBinAbove()) + 1); event_size->GetXaxis()->SetRangeUser(0, xmax); // Set event size axis spacing if(static_cast<int>(xmax) < 10) { event_size->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true); } // FIXME Set more useful spacing maximum for n_cluster histogram xmax = std::ceil(n_cluster->GetBinCenter(n_cluster->FindLastBinAbove()) + 1); n_cluster->GetXaxis()->SetRangeUser(0, xmax); // Set cluster size axis spacing if(static_cast<int>(xmax) < 10) { n_cluster->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true); } // FIXME Set more useful spacing maximum for cluster_charge histogram xmax = std::ceil(cluster_charge->GetBinCenter(cluster_charge->FindLastBinAbove()) + 1); cluster_charge->GetXaxis()->SetRangeUser(0, xmax); // Set cluster size axis spacing if(static_cast<int>(xmax) < 10) { cluster_charge->GetXaxis()->SetNdivisions(static_cast<int>(xmax) + 1, 0, 0, true); } // Set default drawing option histogram for hitmap hit_map->SetOption("colz"); // Set hit_map axis spacing if(static_cast<int>(hit_map->GetXaxis()->GetXmax()) < 10) { hit_map->GetXaxis()->SetNdivisions(static_cast<int>(hit_map->GetXaxis()->GetXmax()) + 1, 0, 0, true); } if(static_cast<int>(hit_map->GetYaxis()->GetXmax()) < 10) { hit_map->GetYaxis()->SetNdivisions(static_cast<int>(hit_map->GetYaxis()->GetXmax()) + 1, 0, 0, true); } cluster_map->SetOption("colz"); // Set cluster_map axis spacing if(static_cast<int>(cluster_map->GetXaxis()->GetXmax()) < 10) { cluster_map->GetXaxis()->SetNdivisions(static_cast<int>(cluster_map->GetXaxis()->GetXmax()) + 1, 0, 0, true); } if(static_cast<int>(cluster_map->GetYaxis()->GetXmax()) < 10) { cluster_map->GetYaxis()->SetNdivisions(static_cast<int>(cluster_map->GetYaxis()->GetXmax()) + 1, 0, 0, true); } // Write histograms LOG(TRACE) << "Writing histograms to file"; hit_map->Write(); cluster_map->Write(); cluster_size->Write(); cluster_size_x->Write(); cluster_size_y->Write(); event_size->Write(); n_cluster->Write(); cluster_charge->Write(); } void DetectorHistogrammerModule::doClustering() { for(auto& pixel_hit : pixels_message_->getData()) { Cluster* clus; if(not checkAdjacentPixels(&pixel_hit)) { LOG(DEBUG) << "Creating new cluster: " << pixel_hit.getPixel().getIndex(); clus = new Cluster(&pixel_hit); clusters_.push_back(clus); } } } bool DetectorHistogrammerModule::isInCluster(const PixelHit* pixel_hit) { for(auto clus : clusters_) { for(auto& hit : clus->getPixelHits()) { if(pixel_hit == hit) { return true; } } } return false; } bool DetectorHistogrammerModule::checkAdjacentPixels(const PixelHit* pixel_hit) { auto hit_idx = pixel_hit->getPixel().getIndex(); for(auto clus : clusters_) { for(auto& pixel_other : clus->getPixelHits()) { auto other_idx = pixel_other->getPixel().getIndex(); auto distx = std::max(hit_idx.x(), other_idx.x()) - std::min(hit_idx.x(), other_idx.x()); auto disty = std::max(hit_idx.y(), other_idx.y()) - std::min(hit_idx.y(), other_idx.y()); if(distx <= 1 and disty <= 1) { LOG(DEBUG) << "Adding pixel to cluster: " << hit_idx; bool ret = clus->addPixelHit(pixel_hit); if(ret == false) { LOG(DEBUG) << "Hit has already been added to this cluster: " << hit_idx; } return true; } } } return false; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chrome_thread.h" #include "chrome/browser/speech/speech_input_bubble_controller.h" #include "gfx/rect.h" #include "testing/gtest/include/gtest/gtest.h" namespace speech_input { // A mock bubble class which fakes a focus change or recognition cancel by the // user and closing of the info bubble. class MockSpeechInputBubble : public SpeechInputBubble { public: enum BubbleType { BUBBLE_TEST_FOCUS_CHANGED, BUBBLE_TEST_RECOGNITION_CANCELLED }; MockSpeechInputBubble(TabContents*, Delegate* delegate, const gfx::Rect&) { MessageLoop::current()->PostTask( FROM_HERE, NewRunnableFunction(&InvokeDelegate, delegate)); } static void InvokeDelegate(Delegate* delegate) { if (type_ == BUBBLE_TEST_FOCUS_CHANGED) delegate->InfoBubbleClosed(); else delegate->RecognitionCancelled(); } static void set_type(BubbleType type) { type_ = type; } virtual void SetRecognizingMode() {} private: static BubbleType type_; }; // The test fixture. class SpeechInputBubbleControllerTest : public SpeechInputBubbleControllerDelegate, public testing::Test { public: SpeechInputBubbleControllerTest() : io_loop_(MessageLoop::TYPE_IO), ui_thread_(ChromeThread::UI), // constructs a new thread and loop io_thread_(ChromeThread::IO, &io_loop_), // resuses main thread loop recognition_cancelled_(false), focus_changed_(false) { } // SpeechInputBubbleControllerDelegate methods. virtual void RecognitionCancelled(int caller_id) { EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::IO)); recognition_cancelled_ = true; MessageLoop::current()->Quit(); } virtual void SpeechInputFocusChanged(int caller_id) { EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::IO)); focus_changed_ = true; MessageLoop::current()->Quit(); } // testing::Test methods. virtual void SetUp() { SpeechInputBubble::set_factory( &SpeechInputBubbleControllerTest::CreateBubble); ui_thread_.Start(); } virtual void TearDown() { SpeechInputBubble::set_factory(NULL); ui_thread_.Stop(); } static SpeechInputBubble* CreateBubble(TabContents* tab_contents, SpeechInputBubble::Delegate* delegate, const gfx::Rect& element_rect) { EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::UI)); return new MockSpeechInputBubble(tab_contents, delegate, element_rect); } protected: // The main thread of the test is marked as the IO thread and we create a new // one for the UI thread. MessageLoop io_loop_; ChromeThread ui_thread_; ChromeThread io_thread_; bool recognition_cancelled_; bool focus_changed_; }; MockSpeechInputBubble::BubbleType MockSpeechInputBubble::type_ = MockSpeechInputBubble::BUBBLE_TEST_FOCUS_CHANGED; // Test that the speech bubble UI gets created in the UI thread and that the // focus changed callback comes back in the IO thread. TEST_F(SpeechInputBubbleControllerTest, TestFocusChanged) { MockSpeechInputBubble::set_type( MockSpeechInputBubble::BUBBLE_TEST_FOCUS_CHANGED); scoped_refptr<SpeechInputBubbleController> controller( new SpeechInputBubbleController(this)); controller->CreateBubble(0, 1, 1, gfx::Rect(1, 1)); MessageLoop::current()->Run(); EXPECT_TRUE(focus_changed_); EXPECT_FALSE(recognition_cancelled_); } // Test that the speech bubble UI gets created in the UI thread and that the // recognition cancelled callback comes back in the IO thread. TEST_F(SpeechInputBubbleControllerTest, TestRecognitionCancelled) { MockSpeechInputBubble::set_type( MockSpeechInputBubble::BUBBLE_TEST_RECOGNITION_CANCELLED); scoped_refptr<SpeechInputBubbleController> controller( new SpeechInputBubbleController(this)); controller->CreateBubble(0, 1, 1, gfx::Rect(1, 1)); MessageLoop::current()->Run(); EXPECT_TRUE(recognition_cancelled_); EXPECT_FALSE(focus_changed_); } } // namespace speech_input <commit_msg>Marked SpeechInputBubbleControllerTest.TestFocusChanged as disabled.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chrome_thread.h" #include "chrome/browser/speech/speech_input_bubble_controller.h" #include "gfx/rect.h" #include "testing/gtest/include/gtest/gtest.h" namespace speech_input { // A mock bubble class which fakes a focus change or recognition cancel by the // user and closing of the info bubble. class MockSpeechInputBubble : public SpeechInputBubble { public: enum BubbleType { BUBBLE_TEST_FOCUS_CHANGED, BUBBLE_TEST_RECOGNITION_CANCELLED }; MockSpeechInputBubble(TabContents*, Delegate* delegate, const gfx::Rect&) { MessageLoop::current()->PostTask( FROM_HERE, NewRunnableFunction(&InvokeDelegate, delegate)); } static void InvokeDelegate(Delegate* delegate) { if (type_ == BUBBLE_TEST_FOCUS_CHANGED) delegate->InfoBubbleClosed(); else delegate->RecognitionCancelled(); } static void set_type(BubbleType type) { type_ = type; } virtual void SetRecognizingMode() {} private: static BubbleType type_; }; // The test fixture. class SpeechInputBubbleControllerTest : public SpeechInputBubbleControllerDelegate, public testing::Test { public: SpeechInputBubbleControllerTest() : io_loop_(MessageLoop::TYPE_IO), ui_thread_(ChromeThread::UI), // constructs a new thread and loop io_thread_(ChromeThread::IO, &io_loop_), // resuses main thread loop recognition_cancelled_(false), focus_changed_(false) { } // SpeechInputBubbleControllerDelegate methods. virtual void RecognitionCancelled(int caller_id) { EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::IO)); recognition_cancelled_ = true; MessageLoop::current()->Quit(); } virtual void SpeechInputFocusChanged(int caller_id) { EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::IO)); focus_changed_ = true; MessageLoop::current()->Quit(); } // testing::Test methods. virtual void SetUp() { SpeechInputBubble::set_factory( &SpeechInputBubbleControllerTest::CreateBubble); ui_thread_.Start(); } virtual void TearDown() { SpeechInputBubble::set_factory(NULL); ui_thread_.Stop(); } static SpeechInputBubble* CreateBubble(TabContents* tab_contents, SpeechInputBubble::Delegate* delegate, const gfx::Rect& element_rect) { EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::UI)); return new MockSpeechInputBubble(tab_contents, delegate, element_rect); } protected: // The main thread of the test is marked as the IO thread and we create a new // one for the UI thread. MessageLoop io_loop_; ChromeThread ui_thread_; ChromeThread io_thread_; bool recognition_cancelled_; bool focus_changed_; }; MockSpeechInputBubble::BubbleType MockSpeechInputBubble::type_ = MockSpeechInputBubble::BUBBLE_TEST_FOCUS_CHANGED; // Test that the speech bubble UI gets created in the UI thread and that the // focus changed callback comes back in the IO thread. // // Crashes on Win only. http://crbug.com/54044 #if defined(OS_WIN) #define MAYBE_TestFocusChanged DISABLED_TestFocusChanged #else #define MAYBE_TestFocusChanged TestFocusChanged #endif TEST_F(SpeechInputBubbleControllerTest, MAYBE_TestFocusChanged) { MockSpeechInputBubble::set_type( MockSpeechInputBubble::BUBBLE_TEST_FOCUS_CHANGED); scoped_refptr<SpeechInputBubbleController> controller( new SpeechInputBubbleController(this)); controller->CreateBubble(0, 1, 1, gfx::Rect(1, 1)); MessageLoop::current()->Run(); EXPECT_TRUE(focus_changed_); EXPECT_FALSE(recognition_cancelled_); } // Test that the speech bubble UI gets created in the UI thread and that the // recognition cancelled callback comes back in the IO thread. TEST_F(SpeechInputBubbleControllerTest, TestRecognitionCancelled) { MockSpeechInputBubble::set_type( MockSpeechInputBubble::BUBBLE_TEST_RECOGNITION_CANCELLED); scoped_refptr<SpeechInputBubbleController> controller( new SpeechInputBubbleController(this)); controller->CreateBubble(0, 1, 1, gfx::Rect(1, 1)); MessageLoop::current()->Run(); EXPECT_TRUE(recognition_cancelled_); EXPECT_FALSE(focus_changed_); } } // namespace speech_input <|endoftext|>
<commit_before>// 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 "chrome/browser/ui/extensions/extension_action_view_controller.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/extensions/api/commands/command_service.h" #include "chrome/browser/extensions/api/extension_action/extension_action_api.h" #include "chrome/browser/extensions/extension_action.h" #include "chrome/browser/extensions/extension_view_host.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/session_tab_helper.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/extensions/accelerator_priority.h" #include "chrome/browser/ui/extensions/extension_action_platform_delegate.h" #include "chrome/browser/ui/toolbar/toolbar_action_view_delegate.h" #include "chrome/common/extensions/api/extension_action/action_info.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/notification_types.h" #include "extensions/common/extension.h" #include "extensions/common/manifest_constants.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_skia_operations.h" using extensions::ActionInfo; using extensions::CommandService; ExtensionActionViewController::ExtensionActionViewController( const extensions::Extension* extension, Browser* browser, ExtensionAction* extension_action) : extension_(extension), browser_(browser), extension_action_(extension_action), popup_host_(nullptr), view_delegate_(nullptr), platform_delegate_(ExtensionActionPlatformDelegate::Create(this)), icon_factory_(browser->profile(), extension, extension_action, this), icon_observer_(nullptr), extension_registry_( extensions::ExtensionRegistry::Get(browser_->profile())) { DCHECK(extension_action); DCHECK(extension_action->action_type() == ActionInfo::TYPE_PAGE || extension_action->action_type() == ActionInfo::TYPE_BROWSER); DCHECK(extension); } ExtensionActionViewController::~ExtensionActionViewController() { } const std::string& ExtensionActionViewController::GetId() const { return extension_->id(); } void ExtensionActionViewController::SetDelegate( ToolbarActionViewDelegate* delegate) { DCHECK((delegate == nullptr) ^ (view_delegate_ == nullptr)); if (delegate) { view_delegate_ = delegate; platform_delegate_->OnDelegateSet(); } else { if (is_showing_popup()) HidePopup(); platform_delegate_.reset(); view_delegate_ = nullptr; } } gfx::Image ExtensionActionViewController::GetIcon( content::WebContents* web_contents) { if (!ExtensionIsValid()) return gfx::Image(); return icon_factory_.GetIcon(SessionTabHelper::IdForTab(web_contents)); } gfx::ImageSkia ExtensionActionViewController::GetIconWithBadge() { if (!ExtensionIsValid()) return gfx::ImageSkia(); content::WebContents* web_contents = view_delegate_->GetCurrentWebContents(); gfx::Size spacing(0, 3); gfx::ImageSkia icon = *GetIcon(web_contents).ToImageSkia(); if (!IsEnabled(web_contents)) icon = gfx::ImageSkiaOperations::CreateTransparentImage(icon, .25); return extension_action_->GetIconWithBadge( icon, SessionTabHelper::IdForTab(web_contents), spacing); } base::string16 ExtensionActionViewController::GetActionName() const { if (!ExtensionIsValid()) return base::string16(); return base::UTF8ToUTF16(extension_->name()); } base::string16 ExtensionActionViewController::GetAccessibleName( content::WebContents* web_contents) const { if (!ExtensionIsValid()) return base::string16(); std::string title = extension_action()->GetTitle(SessionTabHelper::IdForTab(web_contents)); return base::UTF8ToUTF16(title.empty() ? extension()->name() : title); } base::string16 ExtensionActionViewController::GetTooltip( content::WebContents* web_contents) const { return GetAccessibleName(web_contents); } bool ExtensionActionViewController::IsEnabled( content::WebContents* web_contents) const { if (!ExtensionIsValid()) return false; return extension_action_->GetIsVisible( SessionTabHelper::IdForTab(web_contents)) || extensions::ExtensionActionAPI::Get(browser_->profile())-> ExtensionWantsToRun(extension(), web_contents); } bool ExtensionActionViewController::WantsToRun( content::WebContents* web_contents) const { return extensions::ExtensionActionAPI::Get(browser_->profile())-> ExtensionWantsToRun(extension(), web_contents); } bool ExtensionActionViewController::HasPopup( content::WebContents* web_contents) const { if (!ExtensionIsValid()) return false; int tab_id = SessionTabHelper::IdForTab(web_contents); return (tab_id < 0) ? false : extension_action_->HasPopup(tab_id); } void ExtensionActionViewController::HidePopup() { if (is_showing_popup()) { platform_delegate_->CloseOwnPopup(); // We need to do these actions synchronously (instead of closing and then // performing the rest of the cleanup in Observe()) because the extension // host can close asynchronously, and we need to keep the view delegate // up-to-date. OnPopupClosed(); } } gfx::NativeView ExtensionActionViewController::GetPopupNativeView() { return platform_delegate_->GetPopupNativeView(); } ui::MenuModel* ExtensionActionViewController::GetContextMenu() { if (!ExtensionIsValid() || !extension()->ShowConfigureContextMenus()) return nullptr; // Reconstruct the menu every time because the menu's contents are dynamic. context_menu_model_ = make_scoped_refptr(new ExtensionContextMenuModel( extension(), browser_, this)); return context_menu_model_.get(); } bool ExtensionActionViewController::IsMenuRunning() const { return platform_delegate_->IsMenuRunning(); } bool ExtensionActionViewController::CanDrag() const { return true; } bool ExtensionActionViewController::ExecuteAction(bool by_user) { return ExecuteAction(SHOW_POPUP, by_user); } void ExtensionActionViewController::UpdateState() { if (!ExtensionIsValid()) return; view_delegate_->UpdateState(); } bool ExtensionActionViewController::ExecuteAction(PopupShowAction show_action, bool grant_tab_permissions) { if (!ExtensionIsValid()) return false; if (extensions::ExtensionActionAPI::Get(browser_->profile()) ->ExecuteExtensionAction( extension_, browser_, grant_tab_permissions) == ExtensionAction::ACTION_SHOW_POPUP) { GURL popup_url = extension_action_->GetPopupUrl( SessionTabHelper::IdForTab(view_delegate_->GetCurrentWebContents())); return static_cast<ExtensionActionViewController*>( view_delegate_->GetPreferredPopupViewController()) ->ShowPopupWithUrl(show_action, popup_url, grant_tab_permissions); } return false; } void ExtensionActionViewController::PaintExtra( gfx::Canvas* canvas, const gfx::Rect& bounds, content::WebContents* web_contents) const { if (!ExtensionIsValid()) return; int tab_id = SessionTabHelper::IdForTab(web_contents); if (tab_id >= 0) extension_action_->PaintBadge(canvas, bounds, tab_id); } void ExtensionActionViewController::RegisterCommand() { if (!ExtensionIsValid()) return; platform_delegate_->RegisterCommand(); } void ExtensionActionViewController::InspectPopup() { ExecuteAction(SHOW_POPUP_AND_INSPECT, true); } void ExtensionActionViewController::OnIconUpdated() { if (icon_observer_) icon_observer_->OnIconUpdated(); if (view_delegate_) view_delegate_->UpdateState(); } void ExtensionActionViewController::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { // TODO(devlin): Ew. Notifications. Extract out an observer interface for // ExtensionHost and convert this. DCHECK_EQ(extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED, type); extensions::ExtensionHost* host = content::Details<extensions::ExtensionHost>(details).ptr(); if (host == popup_host_) OnPopupClosed(); } bool ExtensionActionViewController::ExtensionIsValid() const { return extension_registry_->enabled_extensions().Contains(extension_->id()); } bool ExtensionActionViewController::GetExtensionCommand( extensions::Command* command) { DCHECK(command); if (!ExtensionIsValid()) return false; CommandService* command_service = CommandService::Get(browser_->profile()); if (extension_action_->action_type() == ActionInfo::TYPE_PAGE) { return command_service->GetPageActionCommand( extension_->id(), CommandService::ACTIVE, command, NULL); } return command_service->GetBrowserActionCommand( extension_->id(), CommandService::ACTIVE, command, NULL); } bool ExtensionActionViewController::ShowPopupWithUrl( PopupShowAction show_action, const GURL& popup_url, bool grant_tab_permissions) { if (!ExtensionIsValid()) return false; bool already_showing = is_showing_popup(); // Always hide the current popup, even if it's not owned by this extension. // Only one popup should be visible at a time. platform_delegate_->CloseActivePopup(); // If we were showing a popup already, then we treat the action to open the // same one as a desire to close it (like clicking a menu button that was // already open). if (already_showing) return false; popup_host_ = platform_delegate_->ShowPopupWithUrl( show_action, popup_url, grant_tab_permissions); if (popup_host_) { // Lazily register for notifications about extension host destructions. static const int kType = extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED; content::Source<content::BrowserContext> source(browser_->profile()); if (!registrar_.IsRegistered(this, kType, source)) registrar_.Add(this, kType, source); view_delegate_->OnPopupShown(grant_tab_permissions); } return is_showing_popup(); } void ExtensionActionViewController::OnPopupClosed() { popup_host_ = nullptr; view_delegate_->OnPopupClosed(); } <commit_msg>[Extensions Toolbar] Observe original profile for extension host notifications<commit_after>// 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 "chrome/browser/ui/extensions/extension_action_view_controller.h" #include "base/logging.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/extensions/api/commands/command_service.h" #include "chrome/browser/extensions/api/extension_action/extension_action_api.h" #include "chrome/browser/extensions/extension_action.h" #include "chrome/browser/extensions/extension_view_host.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/session_tab_helper.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/extensions/accelerator_priority.h" #include "chrome/browser/ui/extensions/extension_action_platform_delegate.h" #include "chrome/browser/ui/toolbar/toolbar_action_view_delegate.h" #include "chrome/common/extensions/api/extension_action/action_info.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/notification_types.h" #include "extensions/common/extension.h" #include "extensions/common/manifest_constants.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_skia_operations.h" using extensions::ActionInfo; using extensions::CommandService; ExtensionActionViewController::ExtensionActionViewController( const extensions::Extension* extension, Browser* browser, ExtensionAction* extension_action) : extension_(extension), browser_(browser), extension_action_(extension_action), popup_host_(nullptr), view_delegate_(nullptr), platform_delegate_(ExtensionActionPlatformDelegate::Create(this)), icon_factory_(browser->profile(), extension, extension_action, this), icon_observer_(nullptr), extension_registry_( extensions::ExtensionRegistry::Get(browser_->profile())) { DCHECK(extension_action); DCHECK(extension_action->action_type() == ActionInfo::TYPE_PAGE || extension_action->action_type() == ActionInfo::TYPE_BROWSER); DCHECK(extension); } ExtensionActionViewController::~ExtensionActionViewController() { } const std::string& ExtensionActionViewController::GetId() const { return extension_->id(); } void ExtensionActionViewController::SetDelegate( ToolbarActionViewDelegate* delegate) { DCHECK((delegate == nullptr) ^ (view_delegate_ == nullptr)); if (delegate) { view_delegate_ = delegate; platform_delegate_->OnDelegateSet(); } else { if (is_showing_popup()) HidePopup(); platform_delegate_.reset(); view_delegate_ = nullptr; } } gfx::Image ExtensionActionViewController::GetIcon( content::WebContents* web_contents) { if (!ExtensionIsValid()) return gfx::Image(); return icon_factory_.GetIcon(SessionTabHelper::IdForTab(web_contents)); } gfx::ImageSkia ExtensionActionViewController::GetIconWithBadge() { if (!ExtensionIsValid()) return gfx::ImageSkia(); content::WebContents* web_contents = view_delegate_->GetCurrentWebContents(); gfx::Size spacing(0, 3); gfx::ImageSkia icon = *GetIcon(web_contents).ToImageSkia(); if (!IsEnabled(web_contents)) icon = gfx::ImageSkiaOperations::CreateTransparentImage(icon, .25); return extension_action_->GetIconWithBadge( icon, SessionTabHelper::IdForTab(web_contents), spacing); } base::string16 ExtensionActionViewController::GetActionName() const { if (!ExtensionIsValid()) return base::string16(); return base::UTF8ToUTF16(extension_->name()); } base::string16 ExtensionActionViewController::GetAccessibleName( content::WebContents* web_contents) const { if (!ExtensionIsValid()) return base::string16(); std::string title = extension_action()->GetTitle(SessionTabHelper::IdForTab(web_contents)); return base::UTF8ToUTF16(title.empty() ? extension()->name() : title); } base::string16 ExtensionActionViewController::GetTooltip( content::WebContents* web_contents) const { return GetAccessibleName(web_contents); } bool ExtensionActionViewController::IsEnabled( content::WebContents* web_contents) const { if (!ExtensionIsValid()) return false; return extension_action_->GetIsVisible( SessionTabHelper::IdForTab(web_contents)) || extensions::ExtensionActionAPI::Get(browser_->profile())-> ExtensionWantsToRun(extension(), web_contents); } bool ExtensionActionViewController::WantsToRun( content::WebContents* web_contents) const { return extensions::ExtensionActionAPI::Get(browser_->profile())-> ExtensionWantsToRun(extension(), web_contents); } bool ExtensionActionViewController::HasPopup( content::WebContents* web_contents) const { if (!ExtensionIsValid()) return false; int tab_id = SessionTabHelper::IdForTab(web_contents); return (tab_id < 0) ? false : extension_action_->HasPopup(tab_id); } void ExtensionActionViewController::HidePopup() { if (is_showing_popup()) { platform_delegate_->CloseOwnPopup(); // We need to do these actions synchronously (instead of closing and then // performing the rest of the cleanup in Observe()) because the extension // host can close asynchronously, and we need to keep the view delegate // up-to-date. OnPopupClosed(); } } gfx::NativeView ExtensionActionViewController::GetPopupNativeView() { return platform_delegate_->GetPopupNativeView(); } ui::MenuModel* ExtensionActionViewController::GetContextMenu() { if (!ExtensionIsValid() || !extension()->ShowConfigureContextMenus()) return nullptr; // Reconstruct the menu every time because the menu's contents are dynamic. context_menu_model_ = make_scoped_refptr(new ExtensionContextMenuModel( extension(), browser_, this)); return context_menu_model_.get(); } bool ExtensionActionViewController::IsMenuRunning() const { return platform_delegate_->IsMenuRunning(); } bool ExtensionActionViewController::CanDrag() const { return true; } bool ExtensionActionViewController::ExecuteAction(bool by_user) { return ExecuteAction(SHOW_POPUP, by_user); } void ExtensionActionViewController::UpdateState() { if (!ExtensionIsValid()) return; view_delegate_->UpdateState(); } bool ExtensionActionViewController::ExecuteAction(PopupShowAction show_action, bool grant_tab_permissions) { if (!ExtensionIsValid()) return false; if (extensions::ExtensionActionAPI::Get(browser_->profile()) ->ExecuteExtensionAction( extension_, browser_, grant_tab_permissions) == ExtensionAction::ACTION_SHOW_POPUP) { GURL popup_url = extension_action_->GetPopupUrl( SessionTabHelper::IdForTab(view_delegate_->GetCurrentWebContents())); return static_cast<ExtensionActionViewController*>( view_delegate_->GetPreferredPopupViewController()) ->ShowPopupWithUrl(show_action, popup_url, grant_tab_permissions); } return false; } void ExtensionActionViewController::PaintExtra( gfx::Canvas* canvas, const gfx::Rect& bounds, content::WebContents* web_contents) const { if (!ExtensionIsValid()) return; int tab_id = SessionTabHelper::IdForTab(web_contents); if (tab_id >= 0) extension_action_->PaintBadge(canvas, bounds, tab_id); } void ExtensionActionViewController::RegisterCommand() { if (!ExtensionIsValid()) return; platform_delegate_->RegisterCommand(); } void ExtensionActionViewController::InspectPopup() { ExecuteAction(SHOW_POPUP_AND_INSPECT, true); } void ExtensionActionViewController::OnIconUpdated() { if (icon_observer_) icon_observer_->OnIconUpdated(); if (view_delegate_) view_delegate_->UpdateState(); } void ExtensionActionViewController::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { // TODO(devlin): Ew. Notifications. Extract out an observer interface for // ExtensionHost and convert this. DCHECK_EQ(extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED, type); extensions::ExtensionHost* host = content::Details<extensions::ExtensionHost>(details).ptr(); if (host == popup_host_) OnPopupClosed(); } bool ExtensionActionViewController::ExtensionIsValid() const { return extension_registry_->enabled_extensions().Contains(extension_->id()); } bool ExtensionActionViewController::GetExtensionCommand( extensions::Command* command) { DCHECK(command); if (!ExtensionIsValid()) return false; CommandService* command_service = CommandService::Get(browser_->profile()); if (extension_action_->action_type() == ActionInfo::TYPE_PAGE) { return command_service->GetPageActionCommand( extension_->id(), CommandService::ACTIVE, command, NULL); } return command_service->GetBrowserActionCommand( extension_->id(), CommandService::ACTIVE, command, NULL); } bool ExtensionActionViewController::ShowPopupWithUrl( PopupShowAction show_action, const GURL& popup_url, bool grant_tab_permissions) { if (!ExtensionIsValid()) return false; bool already_showing = is_showing_popup(); // Always hide the current popup, even if it's not owned by this extension. // Only one popup should be visible at a time. platform_delegate_->CloseActivePopup(); // If we were showing a popup already, then we treat the action to open the // same one as a desire to close it (like clicking a menu button that was // already open). if (already_showing) return false; popup_host_ = platform_delegate_->ShowPopupWithUrl( show_action, popup_url, grant_tab_permissions); if (popup_host_) { // Lazily register for notifications about extension host destructions. static const int kType = extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED; content::Source<content::BrowserContext> source( browser_->profile()->GetOriginalProfile()); if (!registrar_.IsRegistered(this, kType, source)) registrar_.Add(this, kType, source); view_delegate_->OnPopupShown(grant_tab_permissions); } return is_showing_popup(); } void ExtensionActionViewController::OnPopupClosed() { popup_host_ = nullptr; view_delegate_->OnPopupClosed(); } <|endoftext|>
<commit_before>#ifndef KMC_KLANG_EITHER_HPP #define KMC_KLANG_EITHER_HPP #include <cassert> namespace klang { struct LeftTag {}; struct RightTag {}; constexpr LeftTag left_tag; constexpr RightTag right_tag; template <typename L, typename R> class Either { public: Either(LeftTag, const L& left) : is_right_{false}, left_{left} {} Either(LeftTag, L&& left) : is_right_{false}, left_{std::move(left)} {} Either(RightTag, const R& right) : is_right_{true}, right_{right} {} Either(RightTag, R&& right) : is_right_{true}, right_{std::move(right)} {} Either(const Either& that) : is_right_{that.is_right_} { construct(that); } Either(Either&& that) : is_right_{that.is_right_} { construct(std::move(that)); } Either& operator=(const Either& that) { assign(that); return *this; } Either& operator=(Either&& that) { assign(std::move(that)); return *this; } ~Either() { destruct(); } void swap(Either& that) { Either tmp{std::move(*this)}; *this = std::move(that); that = std::move(tmp); } explicit operator bool() const { return is_right_; } const R& operator*() const& { assert(is_right_); return right_; } R& operator*() & { assert(is_right_); return right_; } R&& operator*() && { assert(is_right_); return std::move(right_); } const R* operator->() const { assert(is_right_); return &right_; } R* operator->() { assert(is_right_); return &right_; } template <typename L_, typename R_> friend class Either; friend void swap(Either& lhs, Either& rhs) { lhs.swap(rhs); } friend bool operator==(const Either& lhs, const Either& rhs) { if (lhs.is_right_ != rhs.is_right_) { return false; } else if (lhs.is_right_) { return lhs.right_ == rhs.right_; } else { return lhs.left_ == rhs.left_; } } friend bool operator<(const Either& lhs, const Either& rhs) { if (lhs.is_right_ != rhs.is_right_) { return rhs.is_right_; } else if (lhs.is_right_) { return lhs.right_ < rhs.right_; } else { return lhs.left_ < rhs.left_; } } private: void construct(const Either& src) { if (src.is_right_) { new (&right_) R{src.right_}; } else { new (&left_) L{src.left_}; } } void construct(Either&& src) { if (src.is_right_) { new (&right_) R{std::move(src.right_)}; } else { new (&left_) L{std::move(src.left_)}; } } void assign(const Either& src) { if (is_right_ == src.is_right_) { if (is_right_) { right_ = src.right_; } else { left_ = src.left_; } } else { destruct(); construct(src); is_right_ = src.is_right_; } } void assign(Either&& src) { if (is_right_ == src.is_right_) { if (is_right_) { right_ = std::move(src.right_); } else { left_ = std::move(src.left_); } } else { destruct(); construct(std::move(src)); is_right_ = src.is_right_; } } void destruct() { if (is_right_) { right_.~R(); } else { left_.~L(); } } private: bool is_right_; union { L left_; R right_; }; }; } // namespace klang #endif // KMC_KLANG_EITHER_HPP <commit_msg>Add Left and Right wrapper class<commit_after>#ifndef KMC_KLANG_EITHER_HPP #define KMC_KLANG_EITHER_HPP #include <cassert> #include <utility> namespace klang { struct LeftTag {}; struct RightTag {}; constexpr LeftTag left_tag; constexpr RightTag right_tag; template <typename L> class Left { public: explicit Left(const L& src) : left_{src} {} explicit Left(L&& src) : left_{std::move(src)} {} Left(const Left&) = default; Left(Left&&) = default; Left& operator=(const Left&) = default; Left& operator=(Left&&) = default; void swap(Left& that) { using std::swap; swap(left_, that.left_); } const L& value() const& { return left_; } L&& value() && { return std::move(left_); } template <typename L_> friend class Left; friend void swap(Left& lhs, Left& rhs) { lhs.swap(rhs); } friend bool operator==(const Left& lhs, const Left& rhs) { return lhs.left_ == rhs.left_; } friend bool operator<(const Left& lhs, const Left& rhs) { return lhs.left_ < rhs.left_; } private: L left_; }; template <typename R> class Right { public: explicit Right(const R& src) : right_{src} {} explicit Right(R&& src) : right_{std::move(src)} {} Right(const Right&) = default; Right(Right&&) = default; Right& operator=(const Right&) = default; Right& operator=(Right&&) = default; void swap(Right& that) { using std::swap; swap(right_, that.right_); } const R& value() const& { return right_; } R&& value() && { return std::move(right_); } template <typename R_> friend class Right; friend void swap(Right& lhs, Right& rhs) { lhs.swap(rhs); } friend bool operator==(const Right& lhs, const Right& rhs) { return lhs.right_ == rhs.right_; } friend bool operator<(const Right& lhs, const Right& rhs) { return lhs.right_ < rhs.right_; } private: R right_; }; template <typename L, typename R> class Either { public: Either(LeftTag, const L& left) : is_right_{false}, left_{left} {} Either(LeftTag, L&& left) : is_right_{false}, left_{std::move(left)} {} Either(RightTag, const R& right) : is_right_{true}, right_{right} {} Either(RightTag, R&& right) : is_right_{true}, right_{std::move(right)} {} Either(const Either& that) : is_right_{that.is_right_} { construct(that); } Either(Either&& that) : is_right_{that.is_right_} { construct(std::move(that)); } Either& operator=(const Either& that) { assign(that); return *this; } Either& operator=(Either&& that) { assign(std::move(that)); return *this; } ~Either() { destruct(); } void swap(Either& that) { Either tmp{std::move(*this)}; *this = std::move(that); that = std::move(tmp); } explicit operator bool() const { return is_right_; } const R& operator*() const& { assert(is_right_); return right_; } R& operator*() & { assert(is_right_); return right_; } R&& operator*() && { assert(is_right_); return std::move(right_); } const R* operator->() const { assert(is_right_); return &right_; } R* operator->() { assert(is_right_); return &right_; } template <typename L_, typename R_> friend class Either; friend void swap(Either& lhs, Either& rhs) { lhs.swap(rhs); } friend bool operator==(const Either& lhs, const Either& rhs) { if (lhs.is_right_ != rhs.is_right_) { return false; } else if (lhs.is_right_) { return lhs.right_ == rhs.right_; } else { return lhs.left_ == rhs.left_; } } friend bool operator<(const Either& lhs, const Either& rhs) { if (lhs.is_right_ != rhs.is_right_) { return rhs.is_right_; } else if (lhs.is_right_) { return lhs.right_ < rhs.right_; } else { return lhs.left_ < rhs.left_; } } private: void construct(const Either& src) { if (src.is_right_) { new (&right_) R{src.right_}; } else { new (&left_) L{src.left_}; } } void construct(Either&& src) { if (src.is_right_) { new (&right_) R{std::move(src.right_)}; } else { new (&left_) L{std::move(src.left_)}; } } void assign(const Either& src) { if (is_right_ == src.is_right_) { if (is_right_) { right_ = src.right_; } else { left_ = src.left_; } } else { destruct(); construct(src); is_right_ = src.is_right_; } } void assign(Either&& src) { if (is_right_ == src.is_right_) { if (is_right_) { right_ = std::move(src.right_); } else { left_ = std::move(src.left_); } } else { destruct(); construct(std::move(src)); is_right_ = src.is_right_; } } void destruct() { if (is_right_) { right_.~R(); } else { left_.~L(); } } private: bool is_right_; union { L left_; R right_; }; }; } // namespace klang #endif // KMC_KLANG_EITHER_HPP <|endoftext|>
<commit_before>#include "ovpCBoxAlgorithmStimulationListener.h" using namespace OpenViBE; using namespace OpenViBE::Kernel; using namespace OpenViBE::Plugins; using namespace OpenViBEPlugins; using namespace OpenViBEPlugins::Tools; boolean CBoxAlgorithmStimulationListener::initialize(void) { IBox& l_rStaticBoxContext=this->getStaticBoxContext(); for(uint32 i=0; i<l_rStaticBoxContext.getInputCount(); i++) { IAlgorithmProxy* m_pStreamDecoder=&this->getAlgorithmManager().getAlgorithm(this->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StimulationStreamDecoder)); m_pStreamDecoder->initialize(); m_vStreamDecoder.push_back(m_pStreamDecoder); } CString l_sSettingValue; l_rStaticBoxContext.getSettingValue(0, l_sSettingValue); m_eLogLevel=static_cast<ELogLevel>(getTypeManager().getEnumerationEntryValueFromName(OV_TypeId_LogLevel, l_sSettingValue)); return true; } boolean CBoxAlgorithmStimulationListener::uninitialize(void) { IBox& l_rStaticBoxContext=this->getStaticBoxContext(); for(uint32 i=0; i<l_rStaticBoxContext.getInputCount(); i++) { m_vStreamDecoder[i]->uninitialize(); this->getAlgorithmManager().releaseAlgorithm(*m_vStreamDecoder[i]); } m_vStreamDecoder.clear(); return true; } boolean CBoxAlgorithmStimulationListener::processInput(uint32 ui32InputIndex) { getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess(); return true; } boolean CBoxAlgorithmStimulationListener::process(void) { IBox& l_rStaticBoxContext=this->getStaticBoxContext(); IBoxIO& l_rDynamicBoxContext=this->getDynamicBoxContext(); for(uint32 i=0; i<l_rStaticBoxContext.getInputCount(); i++) { for(uint32 j=0; j<l_rDynamicBoxContext.getInputChunkCount(i); j++) { TParameterHandler < const IMemoryBuffer* > ip_pMemoryBufferToDecode(m_vStreamDecoder[i]->getInputParameter(OVP_GD_Algorithm_StimulationStreamDecoder_InputParameterId_MemoryBufferToDecode)); TParameterHandler < const IStimulationSet* > op_pStimulationSet(m_vStreamDecoder[i]->getOutputParameter(OVP_GD_Algorithm_StimulationStreamDecoder_OutputParameterId_StimulationSet)); ip_pMemoryBufferToDecode=l_rDynamicBoxContext.getInputChunk(i, j); m_vStreamDecoder[i]->process(); if(m_vStreamDecoder[i]->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedHeader)) { } if(m_vStreamDecoder[i]->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedBuffer)) { CString l_sInputName; l_rStaticBoxContext.getInputName(i, l_sInputName); for(uint64 k=0; k<op_pStimulationSet->getStimulationCount(); k++) { this->getLogManager() << m_eLogLevel << "For input " << i << " with name " << l_sInputName << " got stimulation " << op_pStimulationSet->getStimulationIdentifier(k) << "[" << this->getTypeManager().getEnumerationEntryNameFromValue(OV_TypeId_Stimulation, op_pStimulationSet->getStimulationIdentifier(k)) << "]" << " at date " << time64(op_pStimulationSet->getStimulationDate(k)) << " and duration " << time64(op_pStimulationSet->getStimulationDuration(k)) << "\n"; } } if(m_vStreamDecoder[i]->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedEnd)) { } l_rDynamicBoxContext.markInputAsDeprecated(i, j); } } return true; } <commit_msg>openvibe-plugins/tools * ovpCBoxAlgorithmStimulationListener.cpp : added a warning message when a stimulation date is out of chunk range<commit_after>#include "ovpCBoxAlgorithmStimulationListener.h" using namespace OpenViBE; using namespace OpenViBE::Kernel; using namespace OpenViBE::Plugins; using namespace OpenViBEPlugins; using namespace OpenViBEPlugins::Tools; boolean CBoxAlgorithmStimulationListener::initialize(void) { IBox& l_rStaticBoxContext=this->getStaticBoxContext(); for(uint32 i=0; i<l_rStaticBoxContext.getInputCount(); i++) { IAlgorithmProxy* m_pStreamDecoder=&this->getAlgorithmManager().getAlgorithm(this->getAlgorithmManager().createAlgorithm(OVP_GD_ClassId_Algorithm_StimulationStreamDecoder)); m_pStreamDecoder->initialize(); m_vStreamDecoder.push_back(m_pStreamDecoder); } CString l_sSettingValue; l_rStaticBoxContext.getSettingValue(0, l_sSettingValue); m_eLogLevel=static_cast<ELogLevel>(getTypeManager().getEnumerationEntryValueFromName(OV_TypeId_LogLevel, l_sSettingValue)); return true; } boolean CBoxAlgorithmStimulationListener::uninitialize(void) { IBox& l_rStaticBoxContext=this->getStaticBoxContext(); for(uint32 i=0; i<l_rStaticBoxContext.getInputCount(); i++) { m_vStreamDecoder[i]->uninitialize(); this->getAlgorithmManager().releaseAlgorithm(*m_vStreamDecoder[i]); } m_vStreamDecoder.clear(); return true; } boolean CBoxAlgorithmStimulationListener::processInput(uint32 ui32InputIndex) { getBoxAlgorithmContext()->markAlgorithmAsReadyToProcess(); return true; } boolean CBoxAlgorithmStimulationListener::process(void) { IBox& l_rStaticBoxContext=this->getStaticBoxContext(); IBoxIO& l_rDynamicBoxContext=this->getDynamicBoxContext(); for(uint32 i=0; i<l_rStaticBoxContext.getInputCount(); i++) { for(uint32 j=0; j<l_rDynamicBoxContext.getInputChunkCount(i); j++) { TParameterHandler < const IMemoryBuffer* > ip_pMemoryBufferToDecode(m_vStreamDecoder[i]->getInputParameter(OVP_GD_Algorithm_StimulationStreamDecoder_InputParameterId_MemoryBufferToDecode)); TParameterHandler < const IStimulationSet* > op_pStimulationSet(m_vStreamDecoder[i]->getOutputParameter(OVP_GD_Algorithm_StimulationStreamDecoder_OutputParameterId_StimulationSet)); ip_pMemoryBufferToDecode=l_rDynamicBoxContext.getInputChunk(i, j); m_vStreamDecoder[i]->process(); if(m_vStreamDecoder[i]->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedHeader)) { } if(m_vStreamDecoder[i]->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedBuffer)) { CString l_sInputName; l_rStaticBoxContext.getInputName(i, l_sInputName); for(uint64 k=0; k<op_pStimulationSet->getStimulationCount(); k++) { this->getLogManager() << m_eLogLevel << "For input " << i << " with name " << l_sInputName << " got stimulation " << op_pStimulationSet->getStimulationIdentifier(k) << "[" << this->getTypeManager().getEnumerationEntryNameFromValue(OV_TypeId_Stimulation, op_pStimulationSet->getStimulationIdentifier(k)) << "]" << " at date " << time64(op_pStimulationSet->getStimulationDate(k)) << " and duration " << time64(op_pStimulationSet->getStimulationDuration(k)) << "\n"; if(op_pStimulationSet->getStimulationDate(k) < l_rDynamicBoxContext.getInputChunkStartTime(i, j) || op_pStimulationSet->getStimulationDate(k) > l_rDynamicBoxContext.getInputChunkEndTime(i, j)) { this->getLogManager() << LogLevel_Warning << "The stimulation date is out of chunk range ! " << " Stimulation date is " << time64(op_pStimulationSet->getStimulationDate(k)) << " and chunk range is [" << time64(l_rDynamicBoxContext.getInputChunkStartTime(i, j)) << ", " << time64(l_rDynamicBoxContext.getInputChunkEndTime(i, j)) << "]\n"; } } } if(m_vStreamDecoder[i]->isOutputTriggerActive(OVP_GD_Algorithm_StimulationStreamDecoder_OutputTriggerId_ReceivedEnd)) { } l_rDynamicBoxContext.markInputAsDeprecated(i, j); } } return true; } <|endoftext|>
<commit_before>#include "engine.h" #include "random.h" #include "gameEntity.h" #include "Updatable.h" #include "collisionable.h" #ifdef __linux__ #include <fenv.h> #endif #ifdef __WIN32__ #include <float.h> #endif #ifdef DEBUG #include <typeinfo> int DEBUG_PobjCount; PObject* DEBUG_PobjListStart; #endif #ifdef ENABLE_CRASH_LOGGER #ifdef __WIN32__ //Exception handler for mingw, from https://github.com/jrfonseca/drmingw #include <exchndl.h> #endif//__WIN32__ #endif//ENABLE_CRASH_LOGGER Engine* engine; Engine::Engine() { engine = this; #ifdef ENABLE_CRASH_LOGGER #ifdef __WIN32__ ExcHndlInit(); #endif//__WIN32__ #endif//ENABLE_CRASH_LOGGER #ifdef __linux__ feenableexcept(FE_DIVBYZERO | FE_INVALID); #endif #ifdef __WIN32__ unsigned int current_word = 0; _controlfp_s(&current_word, _EM_INVALID | _EM_ZERODIVIDE, _MCW_EM); #endif initRandom(); windowManager = nullptr; CollisionManager::initialize(); InputHandler::initialize(); gameSpeed = 1.0; running = true; elapsedTime = 0.0; soundManager = new SoundManager(); } Engine::~Engine() { if (windowManager) windowManager->close(); delete soundManager; soundManager = nullptr; } void Engine::registerObject(string name, P<PObject> obj) { objectMap[name] = obj; } P<PObject> Engine::getObject(string name) { if (!objectMap[name]) return NULL; return objectMap[name]; } void Engine::runMainLoop() { windowManager = dynamic_cast<WindowManager*>(*getObject("windowManager")); if (!windowManager) { sf::Clock frameTimeClock; while(running) { float delta = frameTimeClock.getElapsedTime().asSeconds(); frameTimeClock.restart(); if (delta > 0.5) delta = 0.5; if (delta < 0.001) delta = 0.001; delta *= gameSpeed; entityList.update(); foreach(Updatable, u, updatableList) u->update(delta); elapsedTime += delta; CollisionManager::handleCollisions(delta); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); sf::sleep(sf::seconds(1.0/60.0 - delta)); //if (elapsedTime > 2.0) // break; } }else{ sf::Clock frameTimeClock; #ifdef DEBUG sf::Clock debugOutputClock; #endif while(running && windowManager->window.isOpen()) { InputHandler::preEventsUpdate(); // Handle events sf::Event event; while (windowManager->window.pollEvent(event)) { handleEvent(event); } InputHandler::postEventsUpdate(); #ifdef DEBUG if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape) && windowManager->hasFocus()) running = false; if (debugOutputClock.getElapsedTime().asSeconds() > 1.0) { printf("Object count: %4d %4d %4d\n", DEBUG_PobjCount, updatableList.size(), entityList.size()); debugOutputClock.restart(); } #endif float delta = frameTimeClock.restart().asSeconds(); if (delta > 0.5) delta = 0.5; if (delta < 0.001) delta = 0.001; delta *= gameSpeed; #ifdef DEBUG if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tab)) delta /= 5.0; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tilde)) delta *= 5.0; #endif EngineTiming engine_timing; sf::Clock engine_timing_clock; entityList.update(); foreach(Updatable, u, updatableList) u->update(delta); elapsedTime += delta; engine_timing.update = engine_timing_clock.restart().asSeconds(); CollisionManager::handleCollisions(delta); engine_timing.collision = engine_timing_clock.restart().asSeconds(); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); // Clear the window windowManager->render(); engine_timing.render = engine_timing_clock.restart().asSeconds(); engine_timing.server_update = 0.0f; if (game_server) engine_timing.server_update = game_server->getUpdateTime(); last_engine_timing = engine_timing; } soundManager->stopMusic(); } } void Engine::handleEvent(sf::Event& event) { // Window closed: exit if ((event.type == sf::Event::Closed)) running = false; if (event.type == sf::Event::GainedFocus) windowManager->windowHasFocus = true; if (event.type == sf::Event::LostFocus) windowManager->windowHasFocus = false; #ifdef DEBUG if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::L)) { int n = 0; printf("---------------------\n"); for(PObject* obj = DEBUG_PobjListStart; obj; obj = obj->DEBUG_PobjListNext) printf("%c%4d: %4d: %s\n", obj->isDestroyed() ? '>' : ' ', n++, obj->getRefCount(), typeid(*obj).name()); printf("---------------------\n"); } #endif InputHandler::handleEvent(event); if (event.type == sf::Event::Resized) windowManager->setupView(); #ifdef __ANDROID__ //Focus lost and focus gained events are used when the application window is created and destroyed. if (event.type == sf::Event::LostFocus) running = false; //The MouseEntered and MouseLeft events are received when the activity needs to pause or resume. if (event.type == sf::Event::MouseLeft) { //Pause is when a small popup is on top of the window. So keep running. while(windowManager->window.isOpen() && windowManager->window.waitEvent(event)) { if (event.type != sf::Event::MouseLeft) handleEvent(event); if (event.type == sf::Event::MouseEntered) break; } } #endif//__ANDROID__ } void Engine::setGameSpeed(float speed) { gameSpeed = speed; } float Engine::getGameSpeed() { return gameSpeed; } float Engine::getElapsedTime() { return elapsedTime; } Engine::EngineTiming Engine::getEngineTiming() { return last_engine_timing; } void Engine::shutdown() { running = false; } <commit_msg>Revert "Enable floating point exceptions."<commit_after>#include "engine.h" #include "random.h" #include "gameEntity.h" #include "Updatable.h" #include "collisionable.h" #ifdef DEBUG #include <typeinfo> int DEBUG_PobjCount; PObject* DEBUG_PobjListStart; #endif #ifdef ENABLE_CRASH_LOGGER #ifdef __WIN32__ //Exception handler for mingw, from https://github.com/jrfonseca/drmingw #include <exchndl.h> #endif//__WIN32__ #endif//ENABLE_CRASH_LOGGER Engine* engine; Engine::Engine() { engine = this; #ifdef ENABLE_CRASH_LOGGER #ifdef __WIN32__ ExcHndlInit(); #endif//__WIN32__ #endif//ENABLE_CRASH_LOGGER initRandom(); windowManager = nullptr; CollisionManager::initialize(); InputHandler::initialize(); gameSpeed = 1.0; running = true; elapsedTime = 0.0; soundManager = new SoundManager(); } Engine::~Engine() { if (windowManager) windowManager->close(); delete soundManager; soundManager = nullptr; } void Engine::registerObject(string name, P<PObject> obj) { objectMap[name] = obj; } P<PObject> Engine::getObject(string name) { if (!objectMap[name]) return NULL; return objectMap[name]; } void Engine::runMainLoop() { windowManager = dynamic_cast<WindowManager*>(*getObject("windowManager")); if (!windowManager) { sf::Clock frameTimeClock; while(running) { float delta = frameTimeClock.getElapsedTime().asSeconds(); frameTimeClock.restart(); if (delta > 0.5) delta = 0.5; if (delta < 0.001) delta = 0.001; delta *= gameSpeed; entityList.update(); foreach(Updatable, u, updatableList) u->update(delta); elapsedTime += delta; CollisionManager::handleCollisions(delta); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); sf::sleep(sf::seconds(1.0/60.0 - delta)); //if (elapsedTime > 2.0) // break; } }else{ sf::Clock frameTimeClock; #ifdef DEBUG sf::Clock debugOutputClock; #endif while(running && windowManager->window.isOpen()) { InputHandler::preEventsUpdate(); // Handle events sf::Event event; while (windowManager->window.pollEvent(event)) { handleEvent(event); } InputHandler::postEventsUpdate(); #ifdef DEBUG if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape) && windowManager->hasFocus()) running = false; if (debugOutputClock.getElapsedTime().asSeconds() > 1.0) { printf("Object count: %4d %4d %4d\n", DEBUG_PobjCount, updatableList.size(), entityList.size()); debugOutputClock.restart(); } #endif float delta = frameTimeClock.restart().asSeconds(); if (delta > 0.5) delta = 0.5; if (delta < 0.001) delta = 0.001; delta *= gameSpeed; #ifdef DEBUG if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tab)) delta /= 5.0; if (sf::Keyboard::isKeyPressed(sf::Keyboard::Tilde)) delta *= 5.0; #endif EngineTiming engine_timing; sf::Clock engine_timing_clock; entityList.update(); foreach(Updatable, u, updatableList) u->update(delta); elapsedTime += delta; engine_timing.update = engine_timing_clock.restart().asSeconds(); CollisionManager::handleCollisions(delta); engine_timing.collision = engine_timing_clock.restart().asSeconds(); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); // Clear the window windowManager->render(); engine_timing.render = engine_timing_clock.restart().asSeconds(); engine_timing.server_update = 0.0f; if (game_server) engine_timing.server_update = game_server->getUpdateTime(); last_engine_timing = engine_timing; } soundManager->stopMusic(); } } void Engine::handleEvent(sf::Event& event) { // Window closed: exit if ((event.type == sf::Event::Closed)) running = false; if (event.type == sf::Event::GainedFocus) windowManager->windowHasFocus = true; if (event.type == sf::Event::LostFocus) windowManager->windowHasFocus = false; #ifdef DEBUG if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::L)) { int n = 0; printf("---------------------\n"); for(PObject* obj = DEBUG_PobjListStart; obj; obj = obj->DEBUG_PobjListNext) printf("%c%4d: %4d: %s\n", obj->isDestroyed() ? '>' : ' ', n++, obj->getRefCount(), typeid(*obj).name()); printf("---------------------\n"); } #endif InputHandler::handleEvent(event); if (event.type == sf::Event::Resized) windowManager->setupView(); #ifdef __ANDROID__ //Focus lost and focus gained events are used when the application window is created and destroyed. if (event.type == sf::Event::LostFocus) running = false; //The MouseEntered and MouseLeft events are received when the activity needs to pause or resume. if (event.type == sf::Event::MouseLeft) { //Pause is when a small popup is on top of the window. So keep running. while(windowManager->window.isOpen() && windowManager->window.waitEvent(event)) { if (event.type != sf::Event::MouseLeft) handleEvent(event); if (event.type == sf::Event::MouseEntered) break; } } #endif//__ANDROID__ } void Engine::setGameSpeed(float speed) { gameSpeed = speed; } float Engine::getGameSpeed() { return gameSpeed; } float Engine::getElapsedTime() { return elapsedTime; } Engine::EngineTiming Engine::getEngineTiming() { return last_engine_timing; } void Engine::shutdown() { running = false; } <|endoftext|>
<commit_before>// Module: Log4CPLUS // File: filter.cxx // Created: 5/2003 // Author: Tad E. Smith // // // Copyright 2003-2015 Tad E. Smith // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <log4cplus/spi/filter.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/helpers/stringhelper.h> #include <log4cplus/helpers/property.h> #include <log4cplus/spi/loggingevent.h> #include <log4cplus/thread/syncprims-pub-impl.h> namespace log4cplus { namespace spi { /////////////////////////////////////////////////////////////////////////////// // global methods /////////////////////////////////////////////////////////////////////////////// FilterResult checkFilter(const Filter* filter, const InternalLoggingEvent& event) { const Filter* currentFilter = filter; while(currentFilter) { FilterResult result = currentFilter->decide(event); if(result != NEUTRAL) { return result; } currentFilter = currentFilter->next.get(); } return ACCEPT; } /////////////////////////////////////////////////////////////////////////////// // Filter implementation /////////////////////////////////////////////////////////////////////////////// Filter::Filter() { } Filter::~Filter() { } void Filter::appendFilter(FilterPtr filter) { if (! next) next = filter; else next->appendFilter(filter); } /////////////////////////////////////////////////////////////////////////////// // DenyAllFilter implementation /////////////////////////////////////////////////////////////////////////////// DenyAllFilter::DenyAllFilter () { } DenyAllFilter::DenyAllFilter (const helpers::Properties&) { } FilterResult DenyAllFilter::decide(const InternalLoggingEvent&) const { return DENY; } /////////////////////////////////////////////////////////////////////////////// // LogLevelMatchFilter implementation /////////////////////////////////////////////////////////////////////////////// LogLevelMatchFilter::LogLevelMatchFilter() { init(); } LogLevelMatchFilter::LogLevelMatchFilter(const helpers::Properties& properties) { init(); properties.getBool (acceptOnMatch, LOG4CPLUS_TEXT("AcceptOnMatch")); tstring const & log_level_to_match = properties.getProperty( LOG4CPLUS_TEXT("LogLevelToMatch") ); logLevelToMatch = getLogLevelManager().fromString(log_level_to_match); } void LogLevelMatchFilter::init() { acceptOnMatch = true; logLevelToMatch = NOT_SET_LOG_LEVEL; } FilterResult LogLevelMatchFilter::decide(const InternalLoggingEvent& event) const { if(logLevelToMatch == NOT_SET_LOG_LEVEL) { return NEUTRAL; } bool matchOccured = (logLevelToMatch == event.getLogLevel()); if(matchOccured) { return (acceptOnMatch ? ACCEPT : DENY); } else { return NEUTRAL; } } /////////////////////////////////////////////////////////////////////////////// // LogLevelRangeFilter implementation /////////////////////////////////////////////////////////////////////////////// LogLevelRangeFilter::LogLevelRangeFilter() { init(); } LogLevelRangeFilter::LogLevelRangeFilter(const helpers::Properties& properties) { init(); properties.getBool (acceptOnMatch = false, LOG4CPLUS_TEXT("AcceptOnMatch")); tstring const & log_level_min = properties.getProperty( LOG4CPLUS_TEXT("LogLevelMin") ); logLevelMin = getLogLevelManager().fromString(log_level_min); tstring const & log_level_max = properties.getProperty( LOG4CPLUS_TEXT("LogLevelMax") ); logLevelMax = getLogLevelManager().fromString(log_level_max); } void LogLevelRangeFilter::init() { acceptOnMatch = true; logLevelMin = NOT_SET_LOG_LEVEL; logLevelMax = NOT_SET_LOG_LEVEL; } FilterResult LogLevelRangeFilter::decide(const InternalLoggingEvent& event) const { if((logLevelMin != NOT_SET_LOG_LEVEL) && (event.getLogLevel() < logLevelMin)) { // priority of event is less than minimum return DENY; } if((logLevelMax != NOT_SET_LOG_LEVEL) && (event.getLogLevel() > logLevelMax)) { // priority of event is greater than maximum return DENY; } if(acceptOnMatch) { // this filter set up to bypass later filters and always return // accept if priority in range return ACCEPT; } else { // event is ok for this filter; allow later filters to have a look... return NEUTRAL; } } /////////////////////////////////////////////////////////////////////////////// // StringMatchFilter implementation /////////////////////////////////////////////////////////////////////////////// StringMatchFilter::StringMatchFilter() { init(); } StringMatchFilter::StringMatchFilter(const helpers::Properties& properties) { init(); properties.getBool (acceptOnMatch = false, LOG4CPLUS_TEXT("AcceptOnMatch")); stringToMatch = properties.getProperty( LOG4CPLUS_TEXT("StringToMatch") ); } void StringMatchFilter::init() { acceptOnMatch = true; } FilterResult StringMatchFilter::decide(const InternalLoggingEvent& event) const { const tstring& message = event.getMessage(); if(stringToMatch.empty () || message.empty ()) { return NEUTRAL; } if(message.find(stringToMatch) == tstring::npos) { return NEUTRAL; } else { // we've got a match return (acceptOnMatch ? ACCEPT : DENY); } } // // // FunctionFilter::FunctionFilter (FunctionFilter::Function f) : function (std::move (f)) { } FilterResult FunctionFilter::decide(const InternalLoggingEvent& event) const { return function (event); } } } // namespace log4cplus { namespace spi { <commit_msg>Cover DenyAllFilter and LogLevelMatchFilter by unit tests.<commit_after>// Module: Log4CPLUS // File: filter.cxx // Created: 5/2003 // Author: Tad E. Smith // // // Copyright 2003-2015 Tad E. Smith // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <log4cplus/spi/filter.h> #include <log4cplus/helpers/loglog.h> #include <log4cplus/helpers/stringhelper.h> #include <log4cplus/helpers/property.h> #include <log4cplus/spi/loggingevent.h> #include <log4cplus/thread/syncprims-pub-impl.h> #if defined (LOG4CPLUS_WITH_UNIT_TESTS) #include <log4cplus/logger.h> #include <catch.hpp> #endif namespace log4cplus { namespace spi { /////////////////////////////////////////////////////////////////////////////// // global methods /////////////////////////////////////////////////////////////////////////////// FilterResult checkFilter(const Filter* filter, const InternalLoggingEvent& event) { const Filter* currentFilter = filter; while(currentFilter) { FilterResult result = currentFilter->decide(event); if(result != NEUTRAL) { return result; } currentFilter = currentFilter->next.get(); } return ACCEPT; } /////////////////////////////////////////////////////////////////////////////// // Filter implementation /////////////////////////////////////////////////////////////////////////////// Filter::Filter() { } Filter::~Filter() { } void Filter::appendFilter(FilterPtr filter) { if (! next) next = filter; else next->appendFilter(filter); } /////////////////////////////////////////////////////////////////////////////// // DenyAllFilter implementation /////////////////////////////////////////////////////////////////////////////// DenyAllFilter::DenyAllFilter () { } DenyAllFilter::DenyAllFilter (const helpers::Properties&) { } FilterResult DenyAllFilter::decide(const InternalLoggingEvent&) const { return DENY; } /////////////////////////////////////////////////////////////////////////////// // LogLevelMatchFilter implementation /////////////////////////////////////////////////////////////////////////////// LogLevelMatchFilter::LogLevelMatchFilter() { init(); } LogLevelMatchFilter::LogLevelMatchFilter(const helpers::Properties& properties) { init(); properties.getBool (acceptOnMatch, LOG4CPLUS_TEXT("AcceptOnMatch")); tstring const & log_level_to_match = properties.getProperty( LOG4CPLUS_TEXT("LogLevelToMatch") ); logLevelToMatch = getLogLevelManager().fromString(log_level_to_match); } void LogLevelMatchFilter::init() { acceptOnMatch = true; logLevelToMatch = NOT_SET_LOG_LEVEL; } FilterResult LogLevelMatchFilter::decide(const InternalLoggingEvent& event) const { if(logLevelToMatch == NOT_SET_LOG_LEVEL) { return NEUTRAL; } bool matchOccured = (logLevelToMatch == event.getLogLevel()); if(matchOccured) { return (acceptOnMatch ? ACCEPT : DENY); } else { return NEUTRAL; } } /////////////////////////////////////////////////////////////////////////////// // LogLevelRangeFilter implementation /////////////////////////////////////////////////////////////////////////////// LogLevelRangeFilter::LogLevelRangeFilter() { init(); } LogLevelRangeFilter::LogLevelRangeFilter(const helpers::Properties& properties) { init(); properties.getBool (acceptOnMatch = false, LOG4CPLUS_TEXT("AcceptOnMatch")); tstring const & log_level_min = properties.getProperty( LOG4CPLUS_TEXT("LogLevelMin") ); logLevelMin = getLogLevelManager().fromString(log_level_min); tstring const & log_level_max = properties.getProperty( LOG4CPLUS_TEXT("LogLevelMax") ); logLevelMax = getLogLevelManager().fromString(log_level_max); } void LogLevelRangeFilter::init() { acceptOnMatch = true; logLevelMin = NOT_SET_LOG_LEVEL; logLevelMax = NOT_SET_LOG_LEVEL; } FilterResult LogLevelRangeFilter::decide(const InternalLoggingEvent& event) const { if((logLevelMin != NOT_SET_LOG_LEVEL) && (event.getLogLevel() < logLevelMin)) { // priority of event is less than minimum return DENY; } if((logLevelMax != NOT_SET_LOG_LEVEL) && (event.getLogLevel() > logLevelMax)) { // priority of event is greater than maximum return DENY; } if(acceptOnMatch) { // this filter set up to bypass later filters and always return // accept if priority in range return ACCEPT; } else { // event is ok for this filter; allow later filters to have a look... return NEUTRAL; } } /////////////////////////////////////////////////////////////////////////////// // StringMatchFilter implementation /////////////////////////////////////////////////////////////////////////////// StringMatchFilter::StringMatchFilter() { init(); } StringMatchFilter::StringMatchFilter(const helpers::Properties& properties) { init(); properties.getBool (acceptOnMatch = false, LOG4CPLUS_TEXT("AcceptOnMatch")); stringToMatch = properties.getProperty( LOG4CPLUS_TEXT("StringToMatch") ); } void StringMatchFilter::init() { acceptOnMatch = true; } FilterResult StringMatchFilter::decide(const InternalLoggingEvent& event) const { const tstring& message = event.getMessage(); if(stringToMatch.empty () || message.empty ()) { return NEUTRAL; } if(message.find(stringToMatch) == tstring::npos) { return NEUTRAL; } else { // we've got a match return (acceptOnMatch ? ACCEPT : DENY); } } // // // FunctionFilter::FunctionFilter (FunctionFilter::Function f) : function (std::move (f)) { } FilterResult FunctionFilter::decide(const InternalLoggingEvent& event) const { return function (event); } #if defined (LOG4CPLUS_WITH_UNIT_TESTS) CATCH_TEST_CASE ("Filter", "[filter]") { FilterPtr filter; Logger log (Logger::getInstance (LOG4CPLUS_TEXT ("test"))); InternalLoggingEvent info_ev (log.getName (), INFO_LOG_LEVEL, LOG4CPLUS_C_STR_TO_TSTRING (LOG4CPLUS_TEXT ("info log message")), __FILE__, __LINE__); InternalLoggingEvent error_ev (log.getName (), ERROR_LOG_LEVEL, LOG4CPLUS_C_STR_TO_TSTRING (LOG4CPLUS_TEXT ("error log message")), __FILE__, __LINE__); CATCH_SECTION ("deny all filter") { filter = new DenyAllFilter; CATCH_REQUIRE (filter->decide (info_ev) == DENY); CATCH_REQUIRE (checkFilter (filter.get (), info_ev) == DENY); } CATCH_SECTION ("log level match filter") { helpers::Properties props; props.setProperty (LOG4CPLUS_TEXT("LogLevelToMatch"), LOG4CPLUS_TEXT ("INFO")); filter = new LogLevelMatchFilter (props); CATCH_REQUIRE (filter->decide (info_ev) == ACCEPT); } } #endif } } // namespace log4cplus { namespace spi { <|endoftext|>
<commit_before>#include "filters.hh" #include "buffer.hh" #include "selection.hh" namespace Kakoune { void preserve_indent(Buffer& buffer, Selection& selection, String& content) { if (content == "\n") { BufferIterator line_begin = buffer.iterator_at_line_begin(selection.last() - 1); BufferIterator first_non_white = line_begin; while ((*first_non_white == '\t' or *first_non_white == ' ') and not first_non_white.is_end()) ++first_non_white; content += buffer.string(line_begin, first_non_white); } } void cleanup_whitespaces(Buffer& buffer, Selection& selection, String& content) { const BufferIterator& position = selection.last(); if (content[0] == '\n' and not position.is_begin()) { BufferIterator whitespace_start = position-1; while ((*whitespace_start == ' ' or *whitespace_start == '\t') and not whitespace_start .is_begin()) --whitespace_start; ++whitespace_start; if (whitespace_start!= position) buffer.erase(whitespace_start, position); } } void expand_tabulations(Buffer& buffer, Selection& selection, String& content) { const int tabstop = buffer.options()["tabstop"].get<int>(); if (content == "\t") { int column = 0; const BufferIterator& position = selection.last(); for (auto line_it = buffer.iterator_at_line_begin(position); line_it != position; ++line_it) { kak_assert(*line_it != '\n'); if (*line_it == '\t') column += tabstop - (column % tabstop); else ++column; } int count = tabstop - (column % tabstop); content = String(); for (int i = 0; i < count; ++i) content += ' '; } } struct RegexFilter { RegexFilter(const String& line_match, const String& insert_match, const String& replacement) : m_line_match(line_match.c_str()), m_insert_match(insert_match.c_str()), m_replacement(replacement.c_str()) {} void operator() (Buffer& buffer, Selection& selection, String& content) { const auto& position = selection.last(); auto line_begin = buffer.iterator_at_line_begin(position); boost::match_results<BufferIterator> results; if (boost::regex_match(content.c_str(), m_insert_match) and boost::regex_match(line_begin, position, results, m_line_match)) { content = results.format(m_replacement.c_str()); auto it = std::find(content.begin(), content.end(), '$'); if (it != content.end()) { ++it; if (it != content.end() && *it == 'c') { String suffix(it+1, content.end()); content = String(content.begin(), it-1); auto first = selection.first(); auto last = selection.last(); buffer.insert(position, suffix); if (selection.first() == selection.last()) selection.first() -= suffix.length(); selection.last() -= suffix.length(); } } } } private: Regex m_line_match; Regex m_insert_match; String m_replacement; }; FilterAndId regex_filter_factory(const FilterParameters& params) { if (params.size() != 3) throw runtime_error("wrong parameter count"); return FilterAndId{"re" + params[0] + "__" + params[1], RegexFilter{params[0], params[1], params[2]}}; } template<void (*filter_func)(Buffer&, Selection&, String&)> class SimpleFilterFactory { public: SimpleFilterFactory(const String& id) : m_id(id) {} FilterAndId operator()(const FilterParameters& params) const { return FilterAndId(m_id, FilterFunc(filter_func)); } private: String m_id; }; FilterAndId filter_group_factory(const FilterParameters& params) { if (params.size() != 1) throw runtime_error("wrong parameter count"); return FilterAndId(params[0], FilterGroup()); } void register_filters() { FilterRegistry& registry = FilterRegistry::instance(); registry.register_func("preserve_indent", SimpleFilterFactory<preserve_indent>("preserve_indent")); registry.register_func("cleanup_whitespaces", SimpleFilterFactory<cleanup_whitespaces>("cleanup_whitespaces")); registry.register_func("expand_tabulations", SimpleFilterFactory<expand_tabulations>("expand_tabulations")); registry.register_func("regex", regex_filter_factory); registry.register_func("group", filter_group_factory); } } <commit_msg>minor code cleanups in filters.cc<commit_after>#include "filters.hh" #include "buffer.hh" #include "selection.hh" namespace Kakoune { void preserve_indent(Buffer& buffer, Selection& selection, String& content) { if (content == "\n") { BufferCoord line_begin{selection.last().line(), 0}; auto first_non_white = buffer.iterator_at(line_begin); while ((*first_non_white == '\t' or *first_non_white == ' ') and not first_non_white.is_end()) ++first_non_white; content += buffer.string(line_begin, first_non_white); } } void cleanup_whitespaces(Buffer& buffer, Selection& selection, String& content) { const auto position = buffer.iterator_at(selection.last()); if (content[0] == '\n' and not position.is_begin()) { auto whitespace_start = position-1; while ((*whitespace_start == ' ' or *whitespace_start == '\t') and not whitespace_start .is_begin()) --whitespace_start; ++whitespace_start; if (whitespace_start != position) buffer.erase(whitespace_start, position); } } void expand_tabulations(Buffer& buffer, Selection& selection, String& content) { const int tabstop = buffer.options()["tabstop"].get<int>(); if (content == "\t") { int column = 0; const auto position = buffer.iterator_at(selection.last()); for (auto it = buffer.iterator_at_line_begin(position); it != position; ++it) { kak_assert(*it != '\n'); if (*it == '\t') column += tabstop - (column % tabstop); else ++column; } CharCount count = tabstop - (column % tabstop); content = String(' ', count); } } struct RegexFilter { RegexFilter(const String& line_match, const String& insert_match, const String& replacement) : m_line_match(line_match.c_str()), m_insert_match(insert_match.c_str()), m_replacement(replacement.c_str()) {} void operator() (Buffer& buffer, Selection& selection, String& content) { const auto position = buffer.iterator_at(selection.last()); auto line_begin = buffer.iterator_at_line_begin(position); boost::match_results<BufferIterator> results; if (boost::regex_match(content.c_str(), m_insert_match) and boost::regex_match(line_begin, position, results, m_line_match)) { content = results.format(m_replacement.c_str()); auto it = std::find(content.begin(), content.end(), '$'); if (it != content.end()) { ++it; if (it != content.end() && *it == 'c') { String suffix(it+1, content.end()); content = String(content.begin(), it-1); auto first = selection.first(); auto last = selection.last(); buffer.insert(position, suffix); if (selection.first() == selection.last()) selection.first() -= suffix.length(); selection.last() -= suffix.length(); } } } } private: Regex m_line_match; Regex m_insert_match; String m_replacement; }; FilterAndId regex_filter_factory(const FilterParameters& params) { if (params.size() != 3) throw runtime_error("wrong parameter count"); return FilterAndId{"re" + params[0] + "__" + params[1], RegexFilter{params[0], params[1], params[2]}}; } template<void (*filter_func)(Buffer&, Selection&, String&)> class SimpleFilterFactory { public: SimpleFilterFactory(const String& id) : m_id(id) {} FilterAndId operator()(const FilterParameters& params) const { return FilterAndId(m_id, FilterFunc(filter_func)); } private: String m_id; }; FilterAndId filter_group_factory(const FilterParameters& params) { if (params.size() != 1) throw runtime_error("wrong parameter count"); return FilterAndId(params[0], FilterGroup()); } void register_filters() { FilterRegistry& registry = FilterRegistry::instance(); registry.register_func("preserve_indent", SimpleFilterFactory<preserve_indent>("preserve_indent")); registry.register_func("cleanup_whitespaces", SimpleFilterFactory<cleanup_whitespaces>("cleanup_whitespaces")); registry.register_func("expand_tabulations", SimpleFilterFactory<expand_tabulations>("expand_tabulations")); registry.register_func("regex", regex_filter_factory); registry.register_func("group", filter_group_factory); } } <|endoftext|>
<commit_before>/* * Copyright 2001, 2002, 2006, 2011 Adrian Thurston <thurston@complang.org> */ /* * Setting conditions and merging states with conditions are similar activities * when expressed in code. The critical difference is that a merge is a union * of multiple paths. We have to take both paths. Setting a condition, however, * is a restriction. We have to expand the transition to follow both values of * the condition, then remove the one that is not set. */ #include "fsmgraph.h" #include "mergesort.h" #include "parsedata.h" #include <assert.h> #include <iostream> long TransAp::condFullSize() { return condSpace == 0 ? 1 : condSpace->fullSize(); } void FsmAp::expandConds( StateAp *fromState, TransAp *trans, const CondSet &fromCS, const CondSet &mergedCS ) { /* Need to transform condition element to the merged set. */ for ( CondList::Iter cti = trans->tcap()->condList; cti.lte(); cti++ ) { long origVal = cti->key.getVal(); long newVal = 0; /* Iterate the bit positions in the from set. */ for ( CondSet::Iter csi = fromCS; csi.lte(); csi++ ) { /* If set, find it in the merged set and flip the bit to 1. */ if ( origVal & (1 << csi.pos()) ) { /* The condition is set. Find the bit position in the merged * set. */ Action **cim = mergedCS.find( *csi ); long bitPos = (cim - mergedCS.data); newVal |= 1 << bitPos; } } if ( origVal != newVal ) cti->key = newVal; } /* Need to double up the whole transition list for each condition test in * merged that is not in from. The one we add has the bit in question set. * */ for ( CondSet::Iter csi = mergedCS; csi.lte(); csi++ ) { Action **cim = fromCS.find( *csi ); if ( cim == 0 ) { CondList newItems; for ( CondList::Iter cti = trans->tcap()->condList; cti.lte(); cti++ ) { /* Sub-transition for conditions. */ CondAp *cond = new CondAp( trans ); /* Attach only if our caller wants the expanded transitions * attached. */ attachTrans( fromState, cti->toState, cond ); /* Call the user callback to add in the original source transition. */ addInTrans( cond, cti.ptr ); cond->key = cti->key.getVal() | (1 << csi.pos()); newItems.append( cond ); } /* Merge newItems in. Both the condList and newItems are sorted. Make * a sorted list out of them. */ CondAp *dest = trans->tcap()->condList.head; while ( dest != 0 && newItems.head != 0 ) { if ( newItems.head->key.getVal() > dest->key.getVal() ) { dest = dest->next; } else { /* Pop the item for insertion. */ CondAp *ins = newItems.detachFirst(); trans->tcap()->condList.addBefore( dest, ins ); } } /* Append the rest of the items. */ trans->tcap()->condList.append( newItems ); } } } void FsmAp::expandCondTransitions( StateAp *fromState, TransAp *destTrans, TransAp *srcTrans ) { CondSet destCS, srcCS; CondSet mergedCS; if ( destTrans->condSpace != 0 ) destCS.insert( destTrans->condSpace->condSet ); if ( srcTrans->condSpace != 0 ) srcCS.insert( srcTrans->condSpace->condSet ); mergedCS.insert( destCS ); mergedCS.insert( srcCS ); expandConds( fromState, destTrans, destCS, mergedCS ); expandConds( fromState, srcTrans, srcCS, mergedCS ); CondSpace *mergedCondSpace = addCondSpace( mergedCS ); destTrans->condSpace = mergedCondSpace; } CondSpace *FsmAp::addCondSpace( const CondSet &condSet ) { CondSpace *condSpace = ctx->condData->condSpaceMap.find( condSet ); if ( condSpace == 0 ) { condSpace = new CondSpace( condSet ); ctx->condData->condSpaceMap.insert( condSpace ); } return condSpace; } void FsmAp::embedCondition( MergeData &md, StateAp *state, Action *condAction, bool sense ) { for ( TransList::Iter tr = state->outList; tr.lte(); tr++ ) { /* The original cond set. */ CondSet origCS; if ( tr->condSpace != 0 ) origCS.insert( tr->condSpace->condSet ); /* The merged cond set. */ CondSet mergedCS; mergedCS.insert( origCS ); mergedCS.insert( condAction ); /* Allocate a cond space for the merged set. */ CondSpace *mergedCondSpace = addCondSpace( mergedCS ); tr->condSpace = mergedCondSpace; /* Translate original condition values, making space for the new bit * (possibly) introduced by the condition embedding. */ for ( CondList::Iter cti = tr->tcap()->condList; cti.lte(); cti++ ) { long origVal = cti->key.getVal(); long newVal = 0; /* For every set bit in the orig, find it's position in the merged * and set the bit appropriately. */ for ( CondSet::Iter csi = origCS; csi.lte(); csi++ ) { /* If set, find it in the merged set and flip the bit to 1. If * not set, there is nothing to do (convenient eh?) */ if ( origVal & (1 << csi.pos()) ) { /* The condition is set. Find the bit position in the * merged set. */ Action **cim = mergedCS.find( *csi ); long bitPos = (cim - mergedCS.data); newVal |= 1 << bitPos; } } if ( origVal != newVal ) { std::cerr << "orig: " << origVal << " new: " << newVal << std::endl; cti->key = newVal; } /* Now set the new bit appropriately. Since it defaults to zero we * only take action if sense is positive. */ if ( sense ) { Action **cim = mergedCS.find( condAction ); int pos = cim - mergedCS.data; cti->key = cti->key.getVal() | (1 << pos); } } } } void FsmAp::embedCondition( StateAp *state, Action *condAction, bool sense ) { MergeData md; /* Turn on misfit accounting to possibly catch the old start state. */ setMisfitAccounting( true ); /* Worker. */ embedCondition( md, state, condAction, sense ); /* Fill in any states that were newed up as combinations of others. */ fillInStates( md ); /* Remove the misfits and turn off misfit accounting. */ removeMisfits(); setMisfitAccounting( false ); } <commit_msg>condition embedding now replaces the TransDataAp with the cond version<commit_after>/* * Copyright 2001, 2002, 2006, 2011 Adrian Thurston <thurston@complang.org> */ /* * Setting conditions and merging states with conditions are similar activities * when expressed in code. The critical difference is that a merge is a union * of multiple paths. We have to take both paths. Setting a condition, however, * is a restriction. We have to expand the transition to follow both values of * the condition, then remove the one that is not set. */ #include "fsmgraph.h" #include "mergesort.h" #include "parsedata.h" #include <assert.h> #include <iostream> long TransAp::condFullSize() { return condSpace == 0 ? 1 : condSpace->fullSize(); } void FsmAp::expandConds( StateAp *fromState, TransAp *trans, const CondSet &fromCS, const CondSet &mergedCS ) { /* Need to transform condition element to the merged set. */ for ( CondList::Iter cti = trans->tcap()->condList; cti.lte(); cti++ ) { long origVal = cti->key.getVal(); long newVal = 0; /* Iterate the bit positions in the from set. */ for ( CondSet::Iter csi = fromCS; csi.lte(); csi++ ) { /* If set, find it in the merged set and flip the bit to 1. */ if ( origVal & (1 << csi.pos()) ) { /* The condition is set. Find the bit position in the merged * set. */ Action **cim = mergedCS.find( *csi ); long bitPos = (cim - mergedCS.data); newVal |= 1 << bitPos; } } if ( origVal != newVal ) cti->key = newVal; } /* Need to double up the whole transition list for each condition test in * merged that is not in from. The one we add has the bit in question set. * */ for ( CondSet::Iter csi = mergedCS; csi.lte(); csi++ ) { Action **cim = fromCS.find( *csi ); if ( cim == 0 ) { CondList newItems; for ( CondList::Iter cti = trans->tcap()->condList; cti.lte(); cti++ ) { /* Sub-transition for conditions. */ CondAp *cond = new CondAp( trans ); /* Attach only if our caller wants the expanded transitions * attached. */ attachTrans( fromState, cti->toState, cond ); /* Call the user callback to add in the original source transition. */ addInTrans( cond, cti.ptr ); cond->key = cti->key.getVal() | (1 << csi.pos()); newItems.append( cond ); } /* Merge newItems in. Both the condList and newItems are sorted. Make * a sorted list out of them. */ CondAp *dest = trans->tcap()->condList.head; while ( dest != 0 && newItems.head != 0 ) { if ( newItems.head->key.getVal() > dest->key.getVal() ) { dest = dest->next; } else { /* Pop the item for insertion. */ CondAp *ins = newItems.detachFirst(); trans->tcap()->condList.addBefore( dest, ins ); } } /* Append the rest of the items. */ trans->tcap()->condList.append( newItems ); } } } void FsmAp::expandCondTransitions( StateAp *fromState, TransAp *destTrans, TransAp *srcTrans ) { CondSet destCS, srcCS; CondSet mergedCS; if ( destTrans->condSpace != 0 ) destCS.insert( destTrans->condSpace->condSet ); if ( srcTrans->condSpace != 0 ) srcCS.insert( srcTrans->condSpace->condSet ); mergedCS.insert( destCS ); mergedCS.insert( srcCS ); expandConds( fromState, destTrans, destCS, mergedCS ); expandConds( fromState, srcTrans, srcCS, mergedCS ); CondSpace *mergedCondSpace = addCondSpace( mergedCS ); destTrans->condSpace = mergedCondSpace; } CondSpace *FsmAp::addCondSpace( const CondSet &condSet ) { CondSpace *condSpace = ctx->condData->condSpaceMap.find( condSet ); if ( condSpace == 0 ) { condSpace = new CondSpace( condSet ); ctx->condData->condSpaceMap.insert( condSpace ); } return condSpace; } void FsmAp::embedCondition( MergeData &md, StateAp *state, Action *condAction, bool sense ) { /* First replace TransDataAp with cond versions. */ TransList destList; for ( TransList::Iter tr = state->outList; tr.lte(); ) { TransList::Iter next = tr.next(); if ( tr->plain() ) { TransDataAp *trans = tr->tdap(); /* Detach in list. */ TransCondAp *newTrans = new TransCondAp(); newTrans->lowKey = trans->lowKey; newTrans->highKey = trans->highKey; newTrans->condSpace = tr->condSpace; CondAp *newCond = new CondAp( newTrans ); newCond->key = 0; newTrans->condList.append( newCond ); newCond->lmActionTable.setActions( trans->lmActionTable ); newCond->actionTable.setActions( trans->actionTable ); newCond->priorTable.setPriors( trans->priorTable ); attachTrans( state, trans->toState, newCond ); detachTrans( state, trans->toState, trans ); delete trans; destList.append( newTrans ); } else { destList.append( tr ); } tr = next; } state->outList.abandon(); state->outList.transfer( destList ); for ( TransList::Iter tr = state->outList; tr.lte(); tr++ ) { /* The original cond set. */ CondSet origCS; if ( tr->condSpace != 0 ) origCS.insert( tr->condSpace->condSet ); /* The merged cond set. */ CondSet mergedCS; mergedCS.insert( origCS ); mergedCS.insert( condAction ); /* Allocate a cond space for the merged set. */ CondSpace *mergedCondSpace = addCondSpace( mergedCS ); tr->condSpace = mergedCondSpace; /* Translate original condition values, making space for the new bit * (possibly) introduced by the condition embedding. */ for ( CondList::Iter cti = tr->tcap()->condList; cti.lte(); cti++ ) { long origVal = cti->key.getVal(); long newVal = 0; /* For every set bit in the orig, find it's position in the merged * and set the bit appropriately. */ for ( CondSet::Iter csi = origCS; csi.lte(); csi++ ) { /* If set, find it in the merged set and flip the bit to 1. If * not set, there is nothing to do (convenient eh?) */ if ( origVal & (1 << csi.pos()) ) { /* The condition is set. Find the bit position in the * merged set. */ Action **cim = mergedCS.find( *csi ); long bitPos = (cim - mergedCS.data); newVal |= 1 << bitPos; } } if ( origVal != newVal ) { std::cerr << "orig: " << origVal << " new: " << newVal << std::endl; cti->key = newVal; } /* Now set the new bit appropriately. Since it defaults to zero we * only take action if sense is positive. */ if ( sense ) { Action **cim = mergedCS.find( condAction ); int pos = cim - mergedCS.data; cti->key = cti->key.getVal() | (1 << pos); } } } } void FsmAp::embedCondition( StateAp *state, Action *condAction, bool sense ) { MergeData md; /* Turn on misfit accounting to possibly catch the old start state. */ setMisfitAccounting( true ); /* Worker. */ embedCondition( md, state, condAction, sense ); /* Fill in any states that were newed up as combinations of others. */ fillInStates( md ); /* Remove the misfits and turn off misfit accounting. */ removeMisfits(); setMisfitAccounting( false ); } <|endoftext|>
<commit_before>// Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule // // 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 <chrono> #include <fstream> #include <iostream> #include <random> #include <string> #include <vector> #include "src/ext/cpputil/include/command_line/command_line.h" #include "src/ext/cpputil/include/serialize/line_reader.h" #include "src/ext/cpputil/include/serialize/span_reader.h" #include "src/ext/cpputil/include/signal/debug_handler.h" #include "src/ext/cpputil/include/system/terminal.h" #include "src/state/cpu_states.h" #include "src/stategen/stategen.h" #include "tools/args/target.h" #include "tools/gadgets/sandbox.h" #include "tools/gadgets/target.h" #include "tools/io/tunit.h" #include "tools/ui/console.h" using namespace cpputil; using namespace std; using namespace stoke; auto& io_opt = Heading::create("I/O options:"); auto& bin = ValueArg<string>::create("bin") .usage("<path/to/bin>") .description("Executable binary containing function to generate testcases for"); auto& args = ValueArg<string, LineReader<>>::create("args") .usage("<arg1 arg2 ... argn>") .description("Optional command line arguments to pass to binary") .default_val(""); auto& out = ValueArg<string>::create("o") .alternate("out") .usage("<path/to/file.tc>") .description("File to write testcases to (defaults to console if unspecified)") .required(); auto& common_opt = Heading::create("Common options:"); auto& max_tc = ValueArg<size_t>::create("max_testcases") .usage("<int>") .description("The maximum number of testcases to generate") .default_val(16); auto& trace_opt = Heading::create("Trace options:"); auto& fxn = ValueArg<string>::create("fxn") .usage("<string>") .description("Function to generate testcases for") .default_val("main"); auto& begin_line = ValueArg<size_t>::create("begin_line") .usage("<int>") .description("The line number to begin recording from") .default_val(1); auto& end_lines = ValueArg<vector<size_t>>::create("end_lines") .usage("{ 0 1 ... 9 }") .description("Line number to end recording on; recording always stops on returns") .default_val({}); auto& max_stack = ValueArg<uint64_t>::create("max_stack") .usage("<bytes>") .description("The maximum number of bytes to assume could be stack") .default_val(1024); auto& autogen_opt = Heading::create("Autogen options:"); auto& max_attempts = ValueArg<uint64_t>::create("max_attempts") .usage("<int>") .description("The maximum number of attempts to make at generating a testcase") .default_val(16); auto& max_memory = ValueArg<uint64_t>::create("max_memory") .usage("<bytes>") .description("The maximum number of bytes to allocate to stack or heap") .default_val(1024); auto& stack_size = ValueArg<size_t>::create("stack_size") .usage("<int>") .description("The minimum stack size available to the testcase") .default_val(16); auto& conv_opt = Heading::create("File conversion options:"); auto& compress = FlagArg::create("compress") .description("Convert testcase file from text to binary"); auto& decompress = FlagArg::create("decompress") .description("Convert testcase file from binary to text"); auto& in = ValueArg<string>::create("in") .alternate("i") .usage("<path/to/file.tc>") .description("Path to testcases file") .default_val("in.tc"); int auto_gen() { TargetGadget target; SandboxGadget sb({}); StateGen sg(&sb, stack_size.value()); sg.set_max_attempts(max_attempts.value()) .set_max_memory(max_stack.value()); CpuStates tcs; for (size_t i = 0, ie = max_tc.value(); i < ie; ++i) { CpuState tc; if (sg.get(tc, target)) { tcs.push_back(tc); } } if (tcs.empty()) { Console::error(1) << "Unable to generate testcases!" << endl; } if (out.value() != "") { ofstream ofs(out.value()); tcs.write_text(ofs); } else { tcs.write_text(Console::msg()); Console::msg() << endl; } return 0; } int trace(const string& argv0) { string here = argv0; here = here.substr(0, here.find_last_of("/") + 1); const string pin_path = here + "../src/ext/pin-2.13-62732-gcc.4.4.7-linux/"; const string so_path = pin_path + "source/tools/stoke/obj-intel64/"; Terminal term; term << pin_path << "pin -injection child -t " << so_path << "testcase.so "; term << "-f " << fxn.value() << " "; if (out.value() != "") { term << "-o " << out.value() << " "; } term << "-x " << max_stack.value() << " "; term << "-n " << max_tc.value() << " "; term << "-b " << begin_line.value() << " "; term << "-e \" "; for (auto e : end_lines.value()) { term << e << " "; } term << "\" "; term << " -- " << bin.value() << " " << args.value() << endl; return 0; } int do_compress() { ifstream ifs(in.value()); if (!ifs.is_open()) { Console::error(1) << "Unable to open input file: " << in.value() << "!" << endl; } CpuStates cs; cs.read_text(ifs); if (ifs.fail()) { Console::error(1) << "Unable to read input file: " << in.value() << "!" << endl; } if (out.value() != "") { ofstream ofs(out.value()); cs.write_bin(ofs); } else { cs.write_bin(Console::msg()); Console::msg() << endl; } return 0; } int do_decompress() { ifstream ifs(in.value()); if (!ifs.is_open()) { Console::error(1) << "Unable to open input file: " << in.value() << "!" << endl; } CpuStates cs; cs.read_bin(ifs); if (ifs.fail()) { Console::error(1) << "Unable to read input file: " << in.value() << "!" << endl; } if (out.value() != "") { ofstream ofs(out.value()); cs.write_text(ofs); } else { cs.write_text(Console::msg()); Console::msg() << endl; } return 0; } int main(int argc, char** argv) { target_arg.required(false); CommandLineConfig::strict_with_convenience(argc, argv); DebugHandler::install_sigsegv(); DebugHandler::install_sigill(); if (compress.value()) { return do_compress(); } else if (decompress.value()) { return do_decompress(); } else if (target_arg.has_been_provided()) { return auto_gen(); } else { return trace(argv[0]); } } <commit_msg>--out in stoke_testcase is not required<commit_after>// Copyright 2013-2015 Eric Schkufza, Rahul Sharma, Berkeley Churchill, Stefan Heule // // 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 <chrono> #include <fstream> #include <iostream> #include <random> #include <string> #include <vector> #include "src/ext/cpputil/include/command_line/command_line.h" #include "src/ext/cpputil/include/serialize/line_reader.h" #include "src/ext/cpputil/include/serialize/span_reader.h" #include "src/ext/cpputil/include/signal/debug_handler.h" #include "src/ext/cpputil/include/system/terminal.h" #include "src/state/cpu_states.h" #include "src/stategen/stategen.h" #include "tools/args/target.h" #include "tools/gadgets/sandbox.h" #include "tools/gadgets/target.h" #include "tools/io/tunit.h" #include "tools/ui/console.h" using namespace cpputil; using namespace std; using namespace stoke; auto& io_opt = Heading::create("I/O options:"); auto& bin = ValueArg<string>::create("bin") .usage("<path/to/bin>") .description("Executable binary containing function to generate testcases for"); auto& args = ValueArg<string, LineReader<>>::create("args") .usage("<arg1 arg2 ... argn>") .description("Optional command line arguments to pass to binary") .default_val(""); auto& out = ValueArg<string>::create("o") .alternate("out") .usage("<path/to/file.tc>") .description("File to write testcases to (defaults to console if unspecified)"); auto& common_opt = Heading::create("Common options:"); auto& max_tc = ValueArg<size_t>::create("max_testcases") .usage("<int>") .description("The maximum number of testcases to generate") .default_val(16); auto& trace_opt = Heading::create("Trace options:"); auto& fxn = ValueArg<string>::create("fxn") .usage("<string>") .description("Function to generate testcases for") .default_val("main"); auto& begin_line = ValueArg<size_t>::create("begin_line") .usage("<int>") .description("The line number to begin recording from") .default_val(1); auto& end_lines = ValueArg<vector<size_t>>::create("end_lines") .usage("{ 0 1 ... 9 }") .description("Line number to end recording on; recording always stops on returns") .default_val({}); auto& max_stack = ValueArg<uint64_t>::create("max_stack") .usage("<bytes>") .description("The maximum number of bytes to assume could be stack") .default_val(1024); auto& autogen_opt = Heading::create("Autogen options:"); auto& max_attempts = ValueArg<uint64_t>::create("max_attempts") .usage("<int>") .description("The maximum number of attempts to make at generating a testcase") .default_val(16); auto& max_memory = ValueArg<uint64_t>::create("max_memory") .usage("<bytes>") .description("The maximum number of bytes to allocate to stack or heap") .default_val(1024); auto& stack_size = ValueArg<size_t>::create("stack_size") .usage("<int>") .description("The minimum stack size available to the testcase") .default_val(16); auto& conv_opt = Heading::create("File conversion options:"); auto& compress = FlagArg::create("compress") .description("Convert testcase file from text to binary"); auto& decompress = FlagArg::create("decompress") .description("Convert testcase file from binary to text"); auto& in = ValueArg<string>::create("in") .alternate("i") .usage("<path/to/file.tc>") .description("Path to testcases file") .default_val("in.tc"); int auto_gen() { TargetGadget target; SandboxGadget sb({}); StateGen sg(&sb, stack_size.value()); sg.set_max_attempts(max_attempts.value()) .set_max_memory(max_stack.value()); CpuStates tcs; for (size_t i = 0, ie = max_tc.value(); i < ie; ++i) { CpuState tc; if (sg.get(tc, target)) { tcs.push_back(tc); } } if (tcs.empty()) { Console::error(1) << "Unable to generate testcases!" << endl; } if (out.has_been_provided()) { ofstream ofs(out.value()); tcs.write_text(ofs); } else { tcs.write_text(Console::msg()); Console::msg() << endl; } return 0; } int trace(const string& argv0) { string here = argv0; here = here.substr(0, here.find_last_of("/") + 1); const string pin_path = here + "../src/ext/pin-2.13-62732-gcc.4.4.7-linux/"; const string so_path = pin_path + "source/tools/stoke/obj-intel64/"; Terminal term; term << pin_path << "pin -injection child -t " << so_path << "testcase.so "; term << "-f " << fxn.value() << " "; if (out.has_been_provided()) { term << "-o " << out.value() << " "; } term << "-x " << max_stack.value() << " "; term << "-n " << max_tc.value() << " "; term << "-b " << begin_line.value() << " "; term << "-e \" "; for (auto e : end_lines.value()) { term << e << " "; } term << "\" "; term << " -- " << bin.value() << " " << args.value() << endl; return 0; } int do_compress() { ifstream ifs(in.value()); if (!ifs.is_open()) { Console::error(1) << "Unable to open input file: " << in.value() << "!" << endl; } CpuStates cs; cs.read_text(ifs); if (ifs.fail()) { Console::error(1) << "Unable to read input file: " << in.value() << "!" << endl; } if (out.has_been_provided()) { ofstream ofs(out.value()); cs.write_bin(ofs); } else { cs.write_bin(Console::msg()); Console::msg() << endl; } return 0; } int do_decompress() { ifstream ifs(in.value()); if (!ifs.is_open()) { Console::error(1) << "Unable to open input file: " << in.value() << "!" << endl; } CpuStates cs; cs.read_bin(ifs); if (ifs.fail()) { Console::error(1) << "Unable to read input file: " << in.value() << "!" << endl; } if (out.has_been_provided()) { ofstream ofs(out.value()); cs.write_text(ofs); } else { cs.write_text(Console::msg()); Console::msg() << endl; } return 0; } int main(int argc, char** argv) { target_arg.required(false); CommandLineConfig::strict_with_convenience(argc, argv); DebugHandler::install_sigsegv(); DebugHandler::install_sigill(); if (compress.value()) { return do_compress(); } else if (decompress.value()) { return do_decompress(); } else if (target_arg.has_been_provided()) { return auto_gen(); } else { return trace(argv[0]); } } <|endoftext|>
<commit_before>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2018 Intel Corporation. All Rights Reserved. #include <iostream> #include "librealsense2/rs.hpp" #include "tclap/CmdLine.h" #include "converters/converter-csv.hpp" #include "converters/converter-png.hpp" #include "converters/converter-raw.hpp" #include "converters/converter-ply.hpp" #include "converters/converter-bin.hpp" #include <mutex> #define SECONDS_TO_NANOSECONDS 1000000000 using namespace std; using namespace TCLAP; int main(int argc, char** argv) try { rs2::log_to_file(RS2_LOG_SEVERITY_WARN); // Parse command line arguments CmdLine cmd("librealsense rs-convert tool", ' '); ValueArg<string> inputFilename("i", "input", "ROS-bag filename", true, "", "ros-bag-file"); ValueArg<string> outputFilenamePng("p", "output-png", "output PNG file(s) path", false, "", "png-path"); ValueArg<string> outputFilenameCsv("v", "output-csv", "output CSV (depth matrix) file(s) path", false, "", "csv-path"); ValueArg<string> outputFilenameRaw("r", "output-raw", "output RAW file(s) path", false, "", "raw-path"); ValueArg<string> outputFilenamePly("l", "output-ply", "output PLY file(s) path", false, "", "ply-path"); ValueArg<string> outputFilenameBin("b", "output-bin", "output BIN (depth matrix) file(s) path", false, "", "bin-path"); SwitchArg switchDepth("d", "depth", "convert depth frames (default - all supported)", false); SwitchArg switchColor("c", "color", "convert color frames (default - all supported)", false); ValueArg <string> frameNumberStart("f", "first-framenumber", "ignore frames whose frame number is less than this value", false, "", "first-framenumber"); ValueArg <string> frameNumberEnd("t", "last-framenumber", "ignore frames whose frame number is greater than this value", false, "", "last-framenumber"); ValueArg <string> startTime("s", "start-time", "ignore frames whose timestamp is less than this value (the first frame is at time 0)", false, "", "start-time"); ValueArg <string> endTime("e", "end-time", "ignore frames whose timestamp is greater than this value (the first frame is at time 0)", false, "", "end-time"); cmd.add(inputFilename); cmd.add(frameNumberEnd); cmd.add(frameNumberStart); cmd.add(endTime); cmd.add(startTime); cmd.add(outputFilenamePng); cmd.add(outputFilenameCsv); cmd.add(outputFilenameRaw); cmd.add(outputFilenamePly); cmd.add(outputFilenameBin); cmd.add(switchDepth); cmd.add(switchColor); cmd.parse(argc, argv); vector<shared_ptr<rs2::tools::converter::converter_base>> converters; shared_ptr<rs2::tools::converter::converter_ply> plyconverter; rs2_stream streamType = switchDepth.isSet() ? rs2_stream::RS2_STREAM_DEPTH : switchColor.isSet() ? rs2_stream::RS2_STREAM_COLOR : rs2_stream::RS2_STREAM_ANY; if (outputFilenameCsv.isSet()) { converters.push_back( make_shared<rs2::tools::converter::converter_csv>( outputFilenameCsv.getValue() , streamType)); } if (outputFilenamePng.isSet()) { converters.push_back( make_shared<rs2::tools::converter::converter_png>( outputFilenamePng.getValue() , streamType)); } if (outputFilenameRaw.isSet()) { converters.push_back( make_shared<rs2::tools::converter::converter_raw>( outputFilenameRaw.getValue() , streamType)); } if (outputFilenameBin.isSet()) { converters.push_back( make_shared<rs2::tools::converter::converter_bin>( outputFilenameBin.getValue())); } if (converters.empty() && !outputFilenamePly.isSet()) { throw runtime_error("output not defined"); } unsigned long long first_frame = 0; unsigned long long last_frame = 0; uint64_t start_time = 0; uint64_t end_time = 0; if (frameNumberStart.isSet()) { first_frame = stoi(frameNumberStart.getValue()); } if (frameNumberEnd.isSet()) { last_frame = stoi(frameNumberEnd.getValue()); } if (startTime.isSet()) { start_time = (uint64_t) (SECONDS_TO_NANOSECONDS * (std::strtod( startTime.getValue().c_str(), nullptr ))); } if (endTime.isSet()) { end_time = (uint64_t) (SECONDS_TO_NANOSECONDS * (std::strtod( endTime.getValue().c_str(), nullptr ))); } //in order to convert frames into ply we need synced depth and color frames, //therefore we use pipeline if (outputFilenamePly.isSet()) { // Since we are running in blocking "non-real-time" mode, // we don't want to prevent process termination if some of the frames // did not find a match and hence were not serviced auto pipe = std::shared_ptr<rs2::pipeline>( new rs2::pipeline(), [](rs2::pipeline*) {}); plyconverter = make_shared<rs2::tools::converter::converter_ply>( outputFilenamePly.getValue()); rs2::config cfg; cfg.enable_device_from_file(inputFilename.getValue()); pipe->start(cfg); auto device = pipe->get_active_profile().get_device(); rs2::playback playback = device.as<rs2::playback>(); playback.set_real_time(false); auto duration = playback.get_duration(); int progress = 0; auto frameNumber = 0ULL; rs2::frameset frameset; uint64_t posCurr = playback.get_position(); // try_wait_for_frames will keep repeating the last frame at the end of the file, // so we need to exit the look in some other way! while (pipe->try_wait_for_frames(&frameset, 1000)) { int posP = static_cast<int>(posCurr * 100. / duration.count()); if (posP > progress) { progress = posP; cout << posP << "%" << "\r" << flush; } frameNumber = frameset[0].get_frame_number(); bool process_frame = true; if (frameNumberStart.isSet() && frameNumber < first_frame) process_frame = false; else if (frameNumberEnd.isSet() && frameNumber > last_frame) process_frame = false; else if (startTime.isSet() && posCurr < start_time) process_frame = false; else if (endTime.isSet() && posCurr > end_time) process_frame = false; if( process_frame ) { plyconverter->convert(frameset); plyconverter->wait(); } auto posNext = playback.get_position(); // NOTE: posNext will be 0 if there is no next frame! if( posNext <= posCurr ) break; posCurr = posNext; } } // for every converter other than ply, // we get the frames from playback sensors // and convert them one by one if( ! converters.empty() ) { rs2::context ctx; auto playback = ctx.load_device(inputFilename.getValue()); playback.set_real_time(false); std::vector<rs2::sensor> sensors = playback.query_sensors(); std::mutex mutex; auto duration = playback.get_duration(); int progress = 0; uint64_t posLast = playback.get_position(); for (auto sensor : sensors) { if (!sensor.get_stream_profiles().size()) { continue; } sensor.open(sensor.get_stream_profiles()); sensor.start([&](rs2::frame frame) { std::lock_guard<std::mutex> lock(mutex); auto frameNumber = frame.get_frame_number(); auto frame_time = playback.get_position(); if (frameNumberStart.isSet() && frameNumber < first_frame) return; if (frameNumberEnd.isSet() && frameNumber > last_frame) return; if (startTime.isSet() && frame_time < start_time) return; if (endTime.isSet() && frame_time > end_time) return; for_each(converters.begin(), converters.end(), [&frame](shared_ptr<rs2::tools::converter::converter_base>& converter) { converter->convert(frame); }); for_each(converters.begin(), converters.end(), [](shared_ptr<rs2::tools::converter::converter_base>& converter) { converter->wait(); }); }); } //we need to clear the output of ply progress ("100%") before writing //the progress of the other converters in the same line cout << "\r \r"; while (true) { int posP = static_cast<int>(posLast * 100. / duration.count()); if (posP > progress) { progress = posP; cout << posP << "%" << "\r" << flush; } const uint64_t posCurr = playback.get_position(); if (static_cast<int64_t>(posCurr - posLast) < 0) { break; } posLast = posCurr; } for (auto sensor : sensors) { if (!sensor.get_stream_profiles().size()) { continue; } sensor.stop(); sensor.close(); } } cout << endl; //print statistics for ply converter. if (outputFilenamePly.isSet()) { cout << plyconverter->get_statistics() << endl; } for_each(converters.begin(), converters.end(), [](shared_ptr<rs2::tools::converter::converter_base>& converter) { cout << converter->get_statistics() << endl; }); return EXIT_SUCCESS; } catch (const rs2::error & e) { cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << endl; return EXIT_FAILURE; } catch (const exception & e) { cerr << e.what() << endl; return EXIT_FAILURE; } catch (...) { cerr << "some error" << endl; return EXIT_FAILURE; } <commit_msg>CR fixes<commit_after>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2018 Intel Corporation. All Rights Reserved. #include <iostream> #include "librealsense2/rs.hpp" #include "tclap/CmdLine.h" #include "converters/converter-csv.hpp" #include "converters/converter-png.hpp" #include "converters/converter-raw.hpp" #include "converters/converter-ply.hpp" #include "converters/converter-bin.hpp" #include <mutex> #define SECONDS_TO_NANOSECONDS 1000000000 using namespace std; using namespace TCLAP; int main(int argc, char** argv) try { rs2::log_to_file(RS2_LOG_SEVERITY_WARN); // Parse command line arguments CmdLine cmd("librealsense rs-convert tool", ' '); ValueArg<string> inputFilename("i", "input", "ROS-bag filename", true, "", "ros-bag-file"); ValueArg<string> outputFilenamePng("p", "output-png", "output PNG file(s) path", false, "", "png-path"); ValueArg<string> outputFilenameCsv("v", "output-csv", "output CSV (depth matrix) file(s) path", false, "", "csv-path"); ValueArg<string> outputFilenameRaw("r", "output-raw", "output RAW file(s) path", false, "", "raw-path"); ValueArg<string> outputFilenamePly("l", "output-ply", "output PLY file(s) path", false, "", "ply-path"); ValueArg<string> outputFilenameBin("b", "output-bin", "output BIN (depth matrix) file(s) path", false, "", "bin-path"); SwitchArg switchDepth("d", "depth", "convert depth frames (default - all supported)", false); SwitchArg switchColor("c", "color", "convert color frames (default - all supported)", false); ValueArg <string> frameNumberStart("f", "first-framenumber", "ignore frames whose frame number is less than this value", false, "", "first-framenumber"); ValueArg <string> frameNumberEnd("t", "last-framenumber", "ignore frames whose frame number is greater than this value", false, "", "last-framenumber"); ValueArg <string> startTime("s", "start-time", "ignore frames whose timestamp is less than this value (the first frame is at time 0)", false, "", "start-time"); ValueArg <string> endTime("e", "end-time", "ignore frames whose timestamp is greater than this value (the first frame is at time 0)", false, "", "end-time"); cmd.add(inputFilename); cmd.add(frameNumberEnd); cmd.add(frameNumberStart); cmd.add(endTime); cmd.add(startTime); cmd.add(outputFilenamePng); cmd.add(outputFilenameCsv); cmd.add(outputFilenameRaw); cmd.add(outputFilenamePly); cmd.add(outputFilenameBin); cmd.add(switchDepth); cmd.add(switchColor); cmd.parse(argc, argv); vector<shared_ptr<rs2::tools::converter::converter_base>> converters; shared_ptr<rs2::tools::converter::converter_ply> plyconverter; rs2_stream streamType = switchDepth.isSet() ? rs2_stream::RS2_STREAM_DEPTH : switchColor.isSet() ? rs2_stream::RS2_STREAM_COLOR : rs2_stream::RS2_STREAM_ANY; if (outputFilenameCsv.isSet()) { converters.push_back( make_shared<rs2::tools::converter::converter_csv>( outputFilenameCsv.getValue() , streamType)); } if (outputFilenamePng.isSet()) { converters.push_back( make_shared<rs2::tools::converter::converter_png>( outputFilenamePng.getValue() , streamType)); } if (outputFilenameRaw.isSet()) { converters.push_back( make_shared<rs2::tools::converter::converter_raw>( outputFilenameRaw.getValue() , streamType)); } if (outputFilenameBin.isSet()) { converters.push_back( make_shared<rs2::tools::converter::converter_bin>( outputFilenameBin.getValue())); } if (converters.empty() && !outputFilenamePly.isSet()) { throw runtime_error("output not defined"); } unsigned long long first_frame = 0; unsigned long long last_frame = 0; uint64_t start_time = 0; uint64_t end_time = 0; if (frameNumberStart.isSet()) { first_frame = stoi(frameNumberStart.getValue()); } if (frameNumberEnd.isSet()) { last_frame = stoi(frameNumberEnd.getValue()); } if (startTime.isSet()) { start_time = (uint64_t) (SECONDS_TO_NANOSECONDS * (std::strtod( startTime.getValue().c_str(), nullptr ))); } if (endTime.isSet()) { end_time = (uint64_t) (SECONDS_TO_NANOSECONDS * (std::strtod( endTime.getValue().c_str(), nullptr ))); } //in order to convert frames into ply we need synced depth and color frames, //therefore we use pipeline if (outputFilenamePly.isSet()) { // Since we are running in blocking "non-real-time" mode, // we don't want to prevent process termination if some of the frames // did not find a match and hence were not serviced auto pipe = std::shared_ptr<rs2::pipeline>( new rs2::pipeline(), [](rs2::pipeline*) {}); plyconverter = make_shared<rs2::tools::converter::converter_ply>( outputFilenamePly.getValue()); rs2::config cfg; cfg.enable_device_from_file(inputFilename.getValue()); pipe->start(cfg); auto device = pipe->get_active_profile().get_device(); rs2::playback playback = device.as<rs2::playback>(); playback.set_real_time(false); auto duration = playback.get_duration(); int progress = 0; auto frameNumber = 0ULL; rs2::frameset frameset; uint64_t posCurr = playback.get_position(); // try_wait_for_frames will keep repeating the last frame at the end of the file, // so we need to exit the look in some other way! while (pipe->try_wait_for_frames(&frameset, 1000)) { int posP = static_cast<int>(posCurr * 100. / duration.count()); if (posP > progress) { progress = posP; cout << posP << "%" << "\r" << flush; } frameNumber = frameset[0].get_frame_number(); bool process_frame = true; if (frameNumberStart.isSet() && frameNumber < first_frame) process_frame = false; else if (frameNumberEnd.isSet() && frameNumber > last_frame) process_frame = false; else if (startTime.isSet() && posCurr < start_time) process_frame = false; else if (endTime.isSet() && posCurr > end_time) process_frame = false; if( process_frame ) { plyconverter->convert(frameset); plyconverter->wait(); } auto posNext = playback.get_position(); // NOTE: posNext will be 0 if there is no next frame! if( posNext < posCurr ) break; posCurr = posNext; } } // for every converter other than ply, // we get the frames from playback sensors // and convert them one by one if( ! converters.empty() ) { rs2::context ctx; auto playback = ctx.load_device(inputFilename.getValue()); playback.set_real_time(false); std::vector<rs2::sensor> sensors = playback.query_sensors(); std::mutex mutex; auto duration = playback.get_duration(); int progress = 0; uint64_t posCurr = playback.get_position(); for (auto sensor : sensors) { if (!sensor.get_stream_profiles().size()) { continue; } sensor.open(sensor.get_stream_profiles()); sensor.start([&](rs2::frame frame) { std::lock_guard<std::mutex> lock(mutex); auto frameNumber = frame.get_frame_number(); if (frameNumberStart.isSet() && frameNumber < first_frame) return; if (frameNumberEnd.isSet() && frameNumber > last_frame) return; if (startTime.isSet() && posCurr < start_time) return; if (endTime.isSet() && posCurr > end_time) return; for_each(converters.begin(), converters.end(), [&frame](shared_ptr<rs2::tools::converter::converter_base>& converter) { converter->convert(frame); }); for_each(converters.begin(), converters.end(), [](shared_ptr<rs2::tools::converter::converter_base>& converter) { converter->wait(); }); }); } //we need to clear the output of ply progress ("100%") before writing //the progress of the other converters in the same line cout << "\r \r"; while (true) { int posP = static_cast<int>(posCurr * 100. / duration.count()); if (posP > progress) { progress = posP; cout << posP << "%" << "\r" << flush; } const uint64_t posNext = playback.get_position(); if (posNext < posCurr) { break; } posCurr = posNext; } for (auto sensor : sensors) { if (!sensor.get_stream_profiles().size()) { continue; } sensor.stop(); sensor.close(); } } cout << endl; //print statistics for ply converter. if (outputFilenamePly.isSet()) { cout << plyconverter->get_statistics() << endl; } for_each(converters.begin(), converters.end(), [](shared_ptr<rs2::tools::converter::converter_base>& converter) { cout << converter->get_statistics() << endl; }); return EXIT_SUCCESS; } catch (const rs2::error & e) { cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << endl; return EXIT_FAILURE; } catch (const exception & e) { cerr << e.what() << endl; return EXIT_FAILURE; } catch (...) { cerr << "some error" << endl; return EXIT_FAILURE; } <|endoftext|>
<commit_before>// fontnik #include <node_fontnik/glyphs.hpp> // node #include <node_buffer.h> #include <nan.h> namespace node_fontnik { struct RangeBaton { v8::Persistent<v8::Function> callback; Glyphs *glyphs; std::string fontstack; std::string range; std::vector<std::uint32_t> chars; bool error; std::string error_name; }; v8::Persistent<v8::FunctionTemplate> Glyphs::constructor; Glyphs::Glyphs() : node::ObjectWrap() { glyphs = fontnik::Glyphs(); } Glyphs::Glyphs(const char *data, size_t length) : node::ObjectWrap() { glyphs = fontnik::Glyphs(data, length); } Glyphs::~Glyphs() {} void Glyphs::Init(v8::Handle<v8::Object> target) { v8::HandleScope scope; v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New); v8::Local<v8::String> name = NanNew<v8::String>("Glyphs"); constructor = v8::Persistent<v8::FunctionTemplate>::New(tpl); // node::ObjectWrap uses the first internal field to store the wrapped pointer. constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->SetClassName(name); // Add all prototype methods, getters and setters here. NODE_SET_PROTOTYPE_METHOD(constructor, "serialize", Serialize); NODE_SET_PROTOTYPE_METHOD(constructor, "range", Range); // This has to be last, otherwise the properties won't show up on the // object in JavaScript. target->Set(name, constructor->GetFunction()); } v8::Handle<v8::Value> Glyphs::New(const v8::Arguments& args) { if (!args.IsConstructCall()) { return NanThrowTypeError("Constructor must be called with new keyword"); } if (args.Length() > 0 && !node::Buffer::HasInstance(args[0])) { return NanThrowTypeError("First argument may only be a buffer"); } Glyphs* glyphs; if (args.Length() < 1) { glyphs = new Glyphs(); } else { v8::Local<v8::Object> buffer = args[0]->ToObject(); glyphs = new Glyphs(node::Buffer::Data(buffer), node::Buffer::Length(buffer)); } glyphs->Wrap(args.This()); return args.This(); } bool Glyphs::HasInstance(v8::Handle<v8::Value> val) { if (!val->IsObject()) return false; return constructor->HasInstance(val->ToObject()); } v8::Handle<v8::Value> Glyphs::Serialize(const v8::Arguments& args) { v8::HandleScope scope; std::string serialized = node::ObjectWrap::Unwrap<Glyphs>(args.This())->glyphs.Serialize(); return scope.Close(node::Buffer::New(serialized.data(), serialized.length())->handle_); } v8::Handle<v8::Value> Glyphs::Range(const v8::Arguments& args) { v8::HandleScope scope; // Validate arguments. if (args.Length() < 1 || !args[0]->IsString()) { return NanThrowTypeError("fontstack must be a string"); } if (args.Length() < 2 || !args[1]->IsString()) { return NanThrowTypeError("range must be a string"); } if (args.Length() < 3 || !args[2]->IsArray()) { return NanThrowTypeError("chars must be an array"); } if (args.Length() < 4 || !args[3]->IsFunction()) { return NanThrowTypeError("callback must be a function"); } v8::String::Utf8Value fontstack(args[0]->ToString()); v8::String::Utf8Value range(args[1]->ToString()); v8::Local<v8::Array> charsArray = v8::Local<v8::Array>::Cast(args[2]); v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(args[3]); unsigned array_size = charsArray->Length(); std::vector<std::uint32_t> chars; for (unsigned i=0; i < array_size; i++) { chars.push_back(charsArray->Get(i)->IntegerValue()); } Glyphs *glyphs = node::ObjectWrap::Unwrap<Glyphs>(args.This()); RangeBaton* baton = new RangeBaton(); baton->callback = v8::Persistent<v8::Function>::New(callback); baton->glyphs = glyphs; baton->fontstack = *fontstack; baton->range = *range; baton->chars = chars; uv_work_t *req = new uv_work_t(); req->data = baton; int status = uv_queue_work(uv_default_loop(), req, AsyncRange, (uv_after_work_cb)RangeAfter); assert(status == 0); NanReturnUndefined(); } void Glyphs::AsyncRange(uv_work_t* req) { RangeBaton* baton = static_cast<RangeBaton*>(req->data); try { baton->glyphs->glyphs.Range(baton->fontstack, baton->range, baton->chars); } catch(const std::runtime_error &e) { baton->error = true; baton->error_name = e.what(); return; } } void Glyphs::RangeAfter(uv_work_t* req) { v8::HandleScope scope; RangeBaton* baton = static_cast<RangeBaton*>(req->data); const unsigned argc = 1; v8::TryCatch try_catch; if (baton->error) { v8::Local<v8::Value> argv[argc] = { v8::Exception::Error(v8::String::New(baton->error_name.c_str())) }; baton->callback->Call(v8::Context::GetCurrent()->Global(), argc, argv); } else { v8::Local<v8::Value> argv[argc] = { v8::Local<v8::Value>::New(v8::Null()) }; baton->callback->Call(v8::Context::GetCurrent()->Global(), argc, argv); } if (try_catch.HasCaught()) { node::FatalException(try_catch); } baton->callback.Dispose(); delete baton; delete req; } } // ns node_fontnik <commit_msg>More NaN<commit_after>// fontnik #include <node_fontnik/glyphs.hpp> // node #include <node_buffer.h> #include <nan.h> namespace node_fontnik { struct RangeBaton { v8::Persistent<v8::Function> callback; Glyphs *glyphs; std::string fontstack; std::string range; std::vector<std::uint32_t> chars; bool error; std::string error_name; }; v8::Persistent<v8::FunctionTemplate> Glyphs::constructor; Glyphs::Glyphs() : node::ObjectWrap() { glyphs = fontnik::Glyphs(); } Glyphs::Glyphs(const char *data, size_t length) : node::ObjectWrap() { glyphs = fontnik::Glyphs(data, length); } Glyphs::~Glyphs() {} void Glyphs::Init(v8::Handle<v8::Object> target) { NanScope(); v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New); v8::Local<v8::String> name = NanNew<v8::String>("Glyphs"); constructor = v8::Persistent<v8::FunctionTemplate>::New(tpl); // node::ObjectWrap uses the first internal field to store the wrapped pointer. constructor->InstanceTemplate()->SetInternalFieldCount(1); constructor->SetClassName(name); // Add all prototype methods, getters and setters here. NODE_SET_PROTOTYPE_METHOD(constructor, "serialize", Serialize); NODE_SET_PROTOTYPE_METHOD(constructor, "range", Range); // This has to be last, otherwise the properties won't show up on the // object in JavaScript. target->Set(name, constructor->GetFunction()); } v8::Handle<v8::Value> Glyphs::New(const v8::Arguments& args) { if (!args.IsConstructCall()) { return NanThrowTypeError("Constructor must be called with new keyword"); } if (args.Length() > 0 && !node::Buffer::HasInstance(args[0])) { return NanThrowTypeError("First argument may only be a buffer"); } Glyphs* glyphs; if (args.Length() < 1) { glyphs = new Glyphs(); } else { v8::Local<v8::Object> buffer = args[0]->ToObject(); glyphs = new Glyphs(node::Buffer::Data(buffer), node::Buffer::Length(buffer)); } glyphs->Wrap(args.This()); return args.This(); } bool Glyphs::HasInstance(v8::Handle<v8::Value> val) { if (!val->IsObject()) return false; return constructor->HasInstance(val->ToObject()); } NAN_METHOD(Glyphs::Serialize) { NanScope(); std::string serialized = node::ObjectWrap::Unwrap<Glyphs>(args.This())->glyphs.Serialize(); return scope.Close(node::Buffer::New(serialized.data(), serialized.length())->handle_); } NAN_METHOD(Glyphs::Range) { NanScope(); // Validate arguments. if (args.Length() < 1 || !args[0]->IsString()) { return NanThrowTypeError("fontstack must be a string"); } if (args.Length() < 2 || !args[1]->IsString()) { return NanThrowTypeError("range must be a string"); } if (args.Length() < 3 || !args[2]->IsArray()) { return NanThrowTypeError("chars must be an array"); } if (args.Length() < 4 || !args[3]->IsFunction()) { return NanThrowTypeError("callback must be a function"); } v8::String::Utf8Value fontstack(args[0]->ToString()); v8::String::Utf8Value range(args[1]->ToString()); v8::Local<v8::Array> charsArray = v8::Local<v8::Array>::Cast(args[2]); v8::Local<v8::Function> callback = v8::Local<v8::Function>::Cast(args[3]); unsigned array_size = charsArray->Length(); std::vector<std::uint32_t> chars; for (unsigned i=0; i < array_size; i++) { chars.push_back(charsArray->Get(i)->IntegerValue()); } Glyphs *glyphs = node::ObjectWrap::Unwrap<Glyphs>(args.This()); RangeBaton* baton = new RangeBaton(); baton->callback = v8::Persistent<v8::Function>::New(callback); baton->glyphs = glyphs; baton->fontstack = *fontstack; baton->range = *range; baton->chars = chars; uv_work_t *req = new uv_work_t(); req->data = baton; int status = uv_queue_work(uv_default_loop(), req, AsyncRange, (uv_after_work_cb)RangeAfter); assert(status == 0); NanReturnUndefined(); } void Glyphs::AsyncRange(uv_work_t* req) { RangeBaton* baton = static_cast<RangeBaton*>(req->data); try { baton->glyphs->glyphs.Range(baton->fontstack, baton->range, baton->chars); } catch(const std::runtime_error &e) { baton->error = true; baton->error_name = e.what(); return; } } void Glyphs::RangeAfter(uv_work_t* req) { NanScope(); RangeBaton* baton = static_cast<RangeBaton*>(req->data); const unsigned argc = 1; v8::TryCatch try_catch; v8::Local<v8::Context> ctx = NanGetCurrentContext(); if (baton->error) { v8::Local<v8::Value> argv[argc] = { v8::Exception::Error(NanNew<v8::String>(baton->error_name.c_str())) }; baton->callback->Call(ctx->Global(), argc, argv); } else { v8::Local<v8::Value> argv[argc] = { v8::Local<v8::Value>::New(NanNull()) }; baton->callback->Call(ctx->Global(), argc, argv); } if (try_catch.HasCaught()) { node::FatalException(try_catch); } baton->callback.Dispose(); delete baton; delete req; } } // ns node_fontnik <|endoftext|>
<commit_before> #include "function.h" #include "value.h" #include "closure.h" #include "gi.h" #include "gobject.h" #include "debug.h" using namespace v8; namespace GNodeJS { static G_DEFINE_QUARK(gnode_js_object, gnode_js_object); static G_DEFINE_QUARK(gnode_js_template, gnode_js_template); static bool InitGParameterFromProperty(GParameter *parameter, void *klass, Handle<String> name, Handle<Value> value) { String::Utf8Value name_str (name); GParamSpec *pspec = g_object_class_find_property (G_OBJECT_CLASS (klass), *name_str); if (pspec == NULL) return false; parameter->name = pspec->name; g_value_init (&parameter->value, G_PARAM_SPEC_VALUE_TYPE (pspec)); V8ToGValue (&parameter->value, value); return true; } static bool InitGParametersFromProperty(GParameter **parameters_p, int *n_parameters_p, void *klass, Handle<Object> property_hash) { Local<Array> properties = property_hash->GetOwnPropertyNames (); int n_parameters = properties->Length (); GParameter *parameters = g_new0 (GParameter, n_parameters); for (int i = 0; i < n_parameters; i++) { Local<Value> name = properties->Get (i); Local<Value> value = property_hash->Get (name); if (!InitGParameterFromProperty (&parameters[i], klass, name->ToString (), value)) return false; } *parameters_p = parameters; *n_parameters_p = n_parameters; return true; } static void ToggleNotify(gpointer user_data, GObject *gobject, gboolean toggle_down); static void AssociateGObject(Isolate *isolate, Handle<Object> object, GObject *gobject) { object->SetAlignedPointerInInternalField (0, gobject); g_object_ref_sink (gobject); g_object_add_toggle_ref (gobject, ToggleNotify, NULL); Persistent<Object> *persistent = new Persistent<Object>(isolate, object); g_object_set_qdata (gobject, gnode_js_object_quark (), persistent); } static void GObjectConstructor(const FunctionCallbackInfo<Value> &args) { Isolate *isolate = args.GetIsolate (); /* The flow of this function is a bit twisty. * There's two cases for when this code is called: * user code doing `new Gtk.Widget({ ... })`, and * internal code as part of WrapperFromGObject, where * the constructor is called with one external. */ if (!args.IsConstructCall ()) { THROW(Exception::TypeError, "Not a construct call."); return; } Handle<Object> self = args.This (); if (args[0]->IsExternal ()) { /* The External case. This is how WrapperFromGObject is called. */ void *data = External::Cast (*args[0])->Value (); GObject *gobject = G_OBJECT (data); AssociateGObject (isolate, self, gobject); } else { /* User code calling `new Gtk.Widget({ ... })` */ GObject *gobject; GIBaseInfo *info = (GIBaseInfo *) External::Cast (*args.Data ())->Value (); GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info); void *klass = g_type_class_ref (gtype); GParameter *parameters = NULL; int n_parameters = 0; if (args[0]->IsObject ()) { Local<Object> property_hash = args[0]->ToObject (); if (!InitGParametersFromProperty (&parameters, &n_parameters, klass, property_hash)) { THROW(Exception::TypeError, "Unable to make GParameters."); goto out; } } gobject = (GObject *) g_object_newv (gtype, n_parameters, parameters); AssociateGObject (isolate, self, gobject); out: g_free (parameters); g_type_class_unref (klass); } } static void SignalConnectInternal(const FunctionCallbackInfo<Value> &args, bool after) { Isolate *isolate = args.GetIsolate (); GObject *gobject = GObjectFromWrapper (args.This ()); String::Utf8Value signal_name (args[0]->ToString ()); Handle<Function> callback = Local<Function>::Cast (args[1]->ToObject ()); GClosure *gclosure = MakeClosure (isolate, callback); ulong handler_id = g_signal_connect_closure (gobject, *signal_name, gclosure, after); args.GetReturnValue ().Set(Integer::NewFromUnsigned (isolate, handler_id)); } static void SignalConnect(const FunctionCallbackInfo<Value> &args) { SignalConnectInternal (args, false); } static Handle<FunctionTemplate> GetBaseClassTemplate(Isolate *isolate) { Local<FunctionTemplate> tpl = FunctionTemplate::New (isolate); Handle<ObjectTemplate> proto = tpl->PrototypeTemplate (); proto->Set (String::NewFromUtf8 (isolate, "connect"), FunctionTemplate::New (isolate, SignalConnect)->GetFunction ()); return tpl; } static Handle<FunctionTemplate> GetClassTemplateFromGI(Isolate *isolate, GIBaseInfo *info); static void ClassDestroyed(const WeakCallbackData<FunctionTemplate, GIBaseInfo> &data) { GIBaseInfo *info = data.GetParameter (); GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info); void *type_data = g_type_get_qdata (gtype, gnode_js_template_quark ()); assert (type_data != NULL); Persistent<FunctionTemplate> *persistent = (Persistent<FunctionTemplate> *) type_data; delete persistent; g_type_set_qdata (gtype, gnode_js_template_quark (), NULL); g_base_info_unref (info); } static Handle<FunctionTemplate> GetClassTemplate(Isolate *isolate, GIBaseInfo *info, GType gtype) { void *data = g_type_get_qdata (gtype, gnode_js_template_quark ()); if (data) { Persistent<FunctionTemplate> *persistent = (Persistent<FunctionTemplate> *) data; Handle<FunctionTemplate> tpl = Handle<FunctionTemplate>::New (isolate, *persistent); return tpl; } else { //printf("\x1b[38;5;201mGetClassTemplate \x1b[93m%lu\x1b[0m %s \n", gtype, g_type_name(gtype)); //const char *class_name = g_base_info_get_name (info); const char *class_name = g_type_name (gtype); Handle<FunctionTemplate> tpl = FunctionTemplate::New (isolate, GObjectConstructor, External::New (isolate, info)); tpl->SetClassName (String::NewFromUtf8 (isolate, class_name)); tpl->InstanceTemplate ()->SetInternalFieldCount (1); Persistent<FunctionTemplate> *persistent = new Persistent<FunctionTemplate>(isolate, tpl); persistent->SetWeak (g_base_info_ref (info), ClassDestroyed); g_type_set_qdata (gtype, gnode_js_template_quark (), persistent); GIObjectInfo *parent_info = g_object_info_get_parent (info); if (parent_info) { Handle<FunctionTemplate> parent_tpl = GetClassTemplateFromGI (isolate, (GIBaseInfo *) parent_info); tpl->Inherit (parent_tpl); } else { tpl->Inherit (GetBaseClassTemplate (isolate)); } return tpl; } } static Handle<FunctionTemplate> GetClassTemplateFromGI(Isolate *isolate, GIBaseInfo *info) { GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info); return GetClassTemplate (isolate, info, gtype); } static Handle<FunctionTemplate> GetClassTemplateFromGType(Isolate *isolate, GType gtype) { GIRepository *repo = g_irepository_get_default (); GIBaseInfo *info = g_irepository_find_by_gtype (repo, gtype); while (info == NULL) { gtype = g_type_parent(gtype); info = g_irepository_find_by_gtype (repo, gtype); } return GetClassTemplate (isolate, info, gtype); } Handle<Function> MakeClass(Isolate *isolate, GIBaseInfo *info) { Handle<FunctionTemplate> tpl = GetClassTemplateFromGI (isolate, info); return tpl->GetFunction (); } static void ObjectDestroyed(const WeakCallbackData<Object, GObject> &data) { GObject *gobject = data.GetParameter (); void *type_data = g_object_get_qdata (gobject, gnode_js_object_quark ()); assert (type_data != NULL); Persistent<Object> *persistent = (Persistent<Object> *) type_data; delete persistent; /* We're destroying the wrapper object, so make sure to clear out * the qdata that points back to us. */ g_object_set_qdata (gobject, gnode_js_object_quark (), NULL); g_object_unref (gobject); } static void ToggleNotify(gpointer user_data, GObject *gobject, gboolean toggle_down) { void *data = g_object_get_qdata (gobject, gnode_js_object_quark ()); assert (data != NULL); Persistent<Object> *persistent = (Persistent<Object> *) data; if (toggle_down) { /* We're dropping from 2 refs to 1 ref. We are the last holder. Make * sure that that our weak ref is installed. */ persistent->SetWeak (gobject, ObjectDestroyed); } else { /* We're going from 1 ref to 2 refs. We can't let our wrapper be * collected, so make sure that our reference is persistent */ persistent->ClearWeak (); } } Handle<Value> WrapperFromGObject(Isolate *isolate, GIBaseInfo *info, GObject *gobject) { void *data = g_object_get_qdata (gobject, gnode_js_object_quark ()); if (data) { /* Easy case: we already have an object. */ Persistent<Object> *persistent = (Persistent<Object> *) data; Handle<Object> obj = Handle<Object>::New (isolate, *persistent); return obj; } else { GType type = G_OBJECT_TYPE(gobject); const char *name = G_OBJECT_TYPE_NAME(gobject); //GTypePlugin *plugin = g_type_get_plugin(type); void *klass = g_type_class_ref (type); DEBUG("GObject: %s \n", name); printf("\x1b[38;5;202mclass: %s \x1b[0;93m %lu \x1b[0m\n", G_OBJECT_CLASS_NAME (klass), G_OBJECT_CLASS_TYPE (klass) ); print_type(type); if (info != NULL) { print_info(info); //if (GI_IS_OBJECT_INFO(info)) { //GIBaseInfo *class_info = g_object_info_get_class_struct(info); //print_info(class_info); //g_base_info_unref(class_info); //} } Handle<FunctionTemplate> tpl; tpl = GetClassTemplateFromGType (isolate, type); Handle<Function> constructor = tpl->GetFunction (); Handle<Value> gobject_external = External::New (isolate, gobject); Handle<Value> args[] = { gobject_external }; Handle<Object> obj = constructor->NewInstance (1, args); //g_base_info_unref(info); g_type_class_unref (klass); return obj; } } GObject * GObjectFromWrapper(Handle<Value> value) { Handle<Object> object = value->ToObject (); void *data = object->GetAlignedPointerFromInternalField (0); GObject *gobject = G_OBJECT (data); return gobject; } }; <commit_msg><commit_after> #include "function.h" #include "value.h" #include "closure.h" #include "gi.h" #include "gobject.h" #include "debug.h" using namespace v8; namespace GNodeJS { static G_DEFINE_QUARK(gnode_js_object, gnode_js_object); static G_DEFINE_QUARK(gnode_js_template, gnode_js_template); static bool InitGParameterFromProperty(GParameter *parameter, void *klass, Handle<String> name, Handle<Value> value) { String::Utf8Value name_str (name); GParamSpec *pspec = g_object_class_find_property (G_OBJECT_CLASS (klass), *name_str); if (pspec == NULL) return false; parameter->name = pspec->name; g_value_init (&parameter->value, G_PARAM_SPEC_VALUE_TYPE (pspec)); V8ToGValue (&parameter->value, value); return true; } static bool InitGParametersFromProperty(GParameter **parameters_p, int *n_parameters_p, void *klass, Handle<Object> property_hash) { Local<Array> properties = property_hash->GetOwnPropertyNames (); int n_parameters = properties->Length (); GParameter *parameters = g_new0 (GParameter, n_parameters); for (int i = 0; i < n_parameters; i++) { Local<Value> name = properties->Get (i); Local<Value> value = property_hash->Get (name); if (!InitGParameterFromProperty (&parameters[i], klass, name->ToString (), value)) return false; } *parameters_p = parameters; *n_parameters_p = n_parameters; return true; } static void ToggleNotify(gpointer user_data, GObject *gobject, gboolean toggle_down); static void AssociateGObject(Isolate *isolate, Handle<Object> object, GObject *gobject) { object->SetAlignedPointerInInternalField (0, gobject); g_object_ref_sink (gobject); g_object_add_toggle_ref (gobject, ToggleNotify, NULL); Persistent<Object> *persistent = new Persistent<Object>(isolate, object); g_object_set_qdata (gobject, gnode_js_object_quark (), persistent); } static void GObjectConstructor(const FunctionCallbackInfo<Value> &args) { Isolate *isolate = args.GetIsolate (); /* The flow of this function is a bit twisty. * There's two cases for when this code is called: * user code doing `new Gtk.Widget({ ... })`, and * internal code as part of WrapperFromGObject, where * the constructor is called with one external. */ if (!args.IsConstructCall ()) { THROW(Exception::TypeError, "Not a construct call."); return; } Handle<Object> self = args.This (); if (args[0]->IsExternal ()) { /* The External case. This is how WrapperFromGObject is called. */ void *data = External::Cast (*args[0])->Value (); GObject *gobject = G_OBJECT (data); AssociateGObject (isolate, self, gobject); } else { /* User code calling `new Gtk.Widget({ ... })` */ GObject *gobject; GIBaseInfo *info = (GIBaseInfo *) External::Cast (*args.Data ())->Value (); GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info); void *klass = g_type_class_ref (gtype); GParameter *parameters = NULL; int n_parameters = 0; if (args[0]->IsObject ()) { Local<Object> property_hash = args[0]->ToObject (); if (!InitGParametersFromProperty (&parameters, &n_parameters, klass, property_hash)) { THROW(Exception::TypeError, "Unable to make GParameters."); goto out; } } gobject = (GObject *) g_object_newv (gtype, n_parameters, parameters); AssociateGObject (isolate, self, gobject); out: g_free (parameters); g_type_class_unref (klass); } } static void SignalConnectInternal(const Nan::FunctionCallbackInfo<v8::Value> &args, bool after) { Isolate *isolate = args.GetIsolate (); GObject *gobject = GObjectFromWrapper (args.This ()); String::Utf8Value signal_name (args[0]->ToString ()); Handle<Function> callback = Local<Function>::Cast (args[1]->ToObject ()); GClosure *gclosure = MakeClosure (isolate, callback); ulong handler_id = g_signal_connect_closure (gobject, *signal_name, gclosure, after); args.GetReturnValue ().Set(Integer::NewFromUnsigned (isolate, handler_id)); } NAN_METHOD(SignalConnect) { SignalConnectInternal(info, false); } static Handle<FunctionTemplate> GetBaseClassTemplate(Isolate *isolate) { Local<FunctionTemplate> tpl = FunctionTemplate::New (isolate); Nan::SetPrototypeMethod(tpl, "on", SignalConnect); Nan::SetPrototypeMethod(tpl, "connect", SignalConnect); Nan::SetPrototypeMethod(tpl, "addEventListener", SignalConnect); return tpl; } static Handle<FunctionTemplate> GetClassTemplateFromGI(Isolate *isolate, GIBaseInfo *info); static void ClassDestroyed(const WeakCallbackData<FunctionTemplate, GIBaseInfo> &data) { GIBaseInfo *info = data.GetParameter (); GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info); void *type_data = g_type_get_qdata (gtype, gnode_js_template_quark ()); assert (type_data != NULL); Persistent<FunctionTemplate> *persistent = (Persistent<FunctionTemplate> *) type_data; delete persistent; g_type_set_qdata (gtype, gnode_js_template_quark (), NULL); g_base_info_unref (info); } static Handle<FunctionTemplate> GetClassTemplate(Isolate *isolate, GIBaseInfo *info, GType gtype) { void *data = g_type_get_qdata (gtype, gnode_js_template_quark ()); if (data) { Persistent<FunctionTemplate> *persistent = (Persistent<FunctionTemplate> *) data; Handle<FunctionTemplate> tpl = Handle<FunctionTemplate>::New (isolate, *persistent); return tpl; } else { //printf("\x1b[38;5;201mGetClassTemplate \x1b[93m%lu\x1b[0m %s \n", gtype, g_type_name(gtype)); //const char *class_name = g_base_info_get_name (info); const char *class_name = g_type_name (gtype); Handle<FunctionTemplate> tpl = FunctionTemplate::New (isolate, GObjectConstructor, External::New (isolate, info)); tpl->SetClassName (String::NewFromUtf8 (isolate, class_name)); tpl->InstanceTemplate ()->SetInternalFieldCount (1); Persistent<FunctionTemplate> *persistent = new Persistent<FunctionTemplate>(isolate, tpl); persistent->SetWeak (g_base_info_ref (info), ClassDestroyed); g_type_set_qdata (gtype, gnode_js_template_quark (), persistent); GIObjectInfo *parent_info = g_object_info_get_parent (info); if (parent_info) { Handle<FunctionTemplate> parent_tpl = GetClassTemplateFromGI (isolate, (GIBaseInfo *) parent_info); tpl->Inherit (parent_tpl); } else { tpl->Inherit (GetBaseClassTemplate (isolate)); } return tpl; } } static Handle<FunctionTemplate> GetClassTemplateFromGI(Isolate *isolate, GIBaseInfo *info) { GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) info); return GetClassTemplate (isolate, info, gtype); } static Handle<FunctionTemplate> GetClassTemplateFromGType(Isolate *isolate, GType gtype) { GIRepository *repo = g_irepository_get_default (); GIBaseInfo *info = g_irepository_find_by_gtype (repo, gtype); while (info == NULL) { gtype = g_type_parent(gtype); info = g_irepository_find_by_gtype (repo, gtype); } return GetClassTemplate (isolate, info, gtype); } Handle<Function> MakeClass(Isolate *isolate, GIBaseInfo *info) { Handle<FunctionTemplate> tpl = GetClassTemplateFromGI (isolate, info); return tpl->GetFunction (); } static void ObjectDestroyed(const WeakCallbackData<Object, GObject> &data) { GObject *gobject = data.GetParameter (); void *type_data = g_object_get_qdata (gobject, gnode_js_object_quark ()); assert (type_data != NULL); Persistent<Object> *persistent = (Persistent<Object> *) type_data; delete persistent; /* We're destroying the wrapper object, so make sure to clear out * the qdata that points back to us. */ g_object_set_qdata (gobject, gnode_js_object_quark (), NULL); g_object_unref (gobject); } static void ToggleNotify(gpointer user_data, GObject *gobject, gboolean toggle_down) { void *data = g_object_get_qdata (gobject, gnode_js_object_quark ()); assert (data != NULL); Persistent<Object> *persistent = (Persistent<Object> *) data; if (toggle_down) { /* We're dropping from 2 refs to 1 ref. We are the last holder. Make * sure that that our weak ref is installed. */ persistent->SetWeak (gobject, ObjectDestroyed); } else { /* We're going from 1 ref to 2 refs. We can't let our wrapper be * collected, so make sure that our reference is persistent */ persistent->ClearWeak (); } } Handle<Value> WrapperFromGObject(Isolate *isolate, GIBaseInfo *info, GObject *gobject) { void *data = g_object_get_qdata (gobject, gnode_js_object_quark ()); if (data) { /* Easy case: we already have an object. */ Persistent<Object> *persistent = (Persistent<Object> *) data; Handle<Object> obj = Handle<Object>::New (isolate, *persistent); return obj; } else { GType type = G_OBJECT_TYPE(gobject); const char *name = G_OBJECT_TYPE_NAME(gobject); //GTypePlugin *plugin = g_type_get_plugin(type); void *klass = g_type_class_ref (type); DEBUG("GObject: %s \n", name); printf("\x1b[38;5;202mclass: %s \x1b[0;93m %lu \x1b[0m\n", G_OBJECT_CLASS_NAME (klass), G_OBJECT_CLASS_TYPE (klass) ); print_type(type); if (info != NULL) { print_info(info); //if (GI_IS_OBJECT_INFO(info)) { //GIBaseInfo *class_info = g_object_info_get_class_struct(info); //print_info(class_info); //g_base_info_unref(class_info); //} } Handle<FunctionTemplate> tpl; tpl = GetClassTemplateFromGType (isolate, type); Handle<Function> constructor = tpl->GetFunction (); Handle<Value> gobject_external = External::New (isolate, gobject); Handle<Value> args[] = { gobject_external }; Handle<Object> obj = constructor->NewInstance (1, args); //g_base_info_unref(info); g_type_class_unref (klass); return obj; } } GObject * GObjectFromWrapper(Handle<Value> value) { Handle<Object> object = value->ToObject (); void *data = object->GetAlignedPointerFromInternalField (0); GObject *gobject = G_OBJECT (data); return gobject; } }; <|endoftext|>
<commit_before>/****************************************************************************** * 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. *****************************************************************************/ /** * @file **/ #include "modules/planning/scenarios/side_pass/side_pass_stop_on_wait_point.h" #include <algorithm> #include <vector> #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/proto/pnc_point.pb.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/speed_profile_generator.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { namespace scenario { namespace side_pass { using apollo::common::TrajectoryPoint; using apollo::common::PathPoint; using apollo::common::math::Vec2d; using apollo::common::VehicleConfigHelper; constexpr double kExtraMarginforStopOnWaitPointStage = 3.0; Stage::StageStatus SidePassStopOnWaitPoint::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { ADEBUG << "Processing SidePassStopOnWaitPoint"; const ReferenceLineInfo& reference_line_info = frame->reference_line_info().front(); const ReferenceLine& reference_line = reference_line_info.reference_line(); const PathDecision& path_decision = reference_line_info.path_decision(); if (GetContext()->path_data_.discretized_path().path_points().empty()) { AERROR << "path data is empty."; return Stage::ERROR; } if (!GetContext()->path_data_.UpdateFrenetFramePath(&reference_line)) { return Stage::ERROR; } const auto adc_frenet_frame_point_ = reference_line.GetFrenetPoint(frame->PlanningStartPoint().path_point()); if (!GetContext()->path_data_.LeftTrimWithRefS(adc_frenet_frame_point_)) { return Stage::ERROR; } if (GetContext()->path_data_.discretized_path().path_points().empty()) { AERROR << "path data is empty after trim."; return Stage::ERROR; } for (const auto& p : GetContext()->path_data_.discretized_path().path_points()) { ADEBUG << p.ShortDebugString(); } // Get the nearest obstacle const Obstacle* nearest_obstacle = nullptr; if (!GetTheNearestObstacle(reference_line, path_decision.obstacles(), &nearest_obstacle)) { AERROR << "Failed while running the function to get nearest obstacle."; return Stage::ERROR; } // If the nearest obstacle, provided it exists, is moving, // then quit the side_pass stage. if (nearest_obstacle) { if (nearest_obstacle->speed() > GetContext()->scenario_config_.block_obstacle_min_speed()) { ADEBUG << "The nearest obstacle to side-pass is moving."; next_stage_ = ScenarioConfig::NO_STAGE; return Stage::FINISHED; } } ADEBUG << "Got the nearest obstacle if there is one."; // Get the "wait point". PathPoint first_path_point = GetContext()->path_data_.discretized_path().path_points().front(); PathPoint last_path_point; bool should_not_move_at_all = false; if (!GetMoveForwardLastPathPoint(reference_line, nearest_obstacle, &last_path_point, &should_not_move_at_all)) { ADEBUG << "Fail to get move forward last path point."; return Stage::ERROR; } if (should_not_move_at_all) { ADEBUG << "The ADC is already at a stop point."; next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY; return Stage::FINISHED; // return FINISHED if it's already at "wait point". } ADEBUG << "first_path_point: " << first_path_point.ShortDebugString(); ADEBUG << "last_path_point : " << last_path_point.ShortDebugString(); double move_forward_distance = last_path_point.s() - first_path_point.s(); ADEBUG << "move_forward_distance: " << move_forward_distance; // Wait until everything is clear. if (!IsFarAwayFromObstacles(reference_line, path_decision.obstacles(), first_path_point, last_path_point)) { // wait here, do nothing this cycle. auto& rfl_info = frame->mutable_reference_line_info()->front(); *(rfl_info.mutable_path_data()) = GetContext()->path_data_; *(rfl_info.mutable_speed_data()) = SpeedProfileGenerator::GenerateFallbackSpeedProfile(); rfl_info.set_trajectory_type(ADCTrajectory::NORMAL); DiscretizedTrajectory trajectory; if (!rfl_info.CombinePathAndSpeedProfile( frame->PlanningStartPoint().relative_time(), frame->PlanningStartPoint().path_point().s(), &trajectory)) { AERROR << "Fail to aggregate planning trajectory."; return Stage::RUNNING; } rfl_info.SetTrajectory(trajectory); rfl_info.SetDrivable(true); ADEBUG << "waiting until obstacles are far away."; return Stage::RUNNING; } // (1) call proceed with cautious constexpr double kSidePassCreepSpeed = 2.33; // m/s auto& rfl_info = frame->mutable_reference_line_info()->front(); *(rfl_info.mutable_speed_data()) = SpeedProfileGenerator::GenerateFixedDistanceCreepProfile( move_forward_distance, kSidePassCreepSpeed); for (const auto& sd : rfl_info.mutable_speed_data()->speed_vector()) { ADEBUG << sd.ShortDebugString(); } // (2) combine path and speed. *(rfl_info.mutable_path_data()) = GetContext()->path_data_; rfl_info.set_trajectory_type(ADCTrajectory::NORMAL); DiscretizedTrajectory trajectory; if (!rfl_info.CombinePathAndSpeedProfile( frame->PlanningStartPoint().relative_time(), frame->PlanningStartPoint().path_point().s(), &trajectory)) { AERROR << "Fail to aggregate planning trajectory."; return Stage::RUNNING; } rfl_info.SetTrajectory(trajectory); rfl_info.SetDrivable(true); constexpr double kBuffer = 0.3; if (move_forward_distance < kBuffer) { next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY; } return Stage::FINISHED; } bool SidePassStopOnWaitPoint::IsFarAwayFromObstacles( const ReferenceLine& reference_line, const IndexedList<std::string, Obstacle>& indexed_obstacle_list, const PathPoint& first_path_point, const PathPoint& last_path_point) { common::SLPoint first_sl_point; if (!reference_line.XYToSL(Vec2d(first_path_point.x(), first_path_point.y()), &first_sl_point)) { AERROR << "Failed to get the projection from TrajectoryPoint onto " "reference_line"; return false; } common::SLPoint last_sl_point; if (!reference_line.XYToSL(Vec2d(last_path_point.x(), last_path_point.y()), &last_sl_point)) { AERROR << "Failed to get the projection from TrajectoryPoint onto " "reference_line"; return false; } // Go through every obstacle, check if there is any in the no_obs_zone, // which will be used by the proceed_with_caution movement. for (const auto* obstacle : indexed_obstacle_list.Items()) { if (obstacle->IsVirtual()) { continue; } // Check the s-direction. double obs_start_s = obstacle->PerceptionSLBoundary().start_s(); double obs_end_s = obstacle->PerceptionSLBoundary().end_s(); if (obs_end_s < first_sl_point.s() || obs_start_s > last_sl_point.s() + kExtraMarginforStopOnWaitPointStage) { continue; } // Check the l-direction. double lane_left_width_at_start_s = 0.0; double lane_left_width_at_end_s = 0.0; double lane_right_width_at_start_s = 0.0; double lane_right_width_at_end_s = 0.0; reference_line.GetLaneWidth(obs_start_s, &lane_left_width_at_start_s, &lane_right_width_at_start_s); reference_line.GetLaneWidth(obs_end_s, &lane_left_width_at_end_s, &lane_right_width_at_end_s); double lane_left_width = std::min(std::abs(lane_left_width_at_start_s), std::abs(lane_left_width_at_end_s)); double lane_right_width = std::min(std::abs(lane_right_width_at_start_s), std::abs(lane_right_width_at_end_s)); double obs_start_l = obstacle->PerceptionSLBoundary().start_l(); double obs_end_l = obstacle->PerceptionSLBoundary().end_l(); if (obs_start_l < lane_left_width && -obs_end_l < lane_right_width) { return false; } } return true; } bool SidePassStopOnWaitPoint::GetTheNearestObstacle( const ReferenceLine& reference_line, const IndexedList<std::string, Obstacle>& indexed_obstacle_list, const Obstacle** nearest_obstacle) { // Get the first path point. This can be used later to // filter out other obstaces that are behind ADC. PathPoint first_path_point = GetContext()->path_data_.discretized_path().path_points().front(); common::SLPoint first_sl_point; if (!reference_line.XYToSL(Vec2d(first_path_point.x(), first_path_point.y()), &first_sl_point)) { AERROR << "Failed to get the projection from TrajectoryPoint onto " "reference_line"; return false; } // Go through every obstacle. bool exist_nearest_obs = false; *nearest_obstacle = nullptr; double s_of_nearest_obs = 0.0; for (const auto* obstacle : indexed_obstacle_list.Items()) { ADEBUG << "Looking at Obstacle: " << obstacle->Id(); if (obstacle->IsVirtual()) { continue; } // Check the s-direction. Rule out those obstacles that are behind ADC. double obs_start_s = obstacle->PerceptionSLBoundary().start_s(); double obs_end_s = obstacle->PerceptionSLBoundary().end_s(); if (obs_end_s <= first_sl_point.s()) { ADEBUG << "Obstacle behind ADC. Rule out."; continue; } // Check the l-direction. Rule out those obstacles that are not // blocking our drive-way. // TODO(all): should make this a GFLAG because this is also used by // side_pass_scenario.cc. They should be consistent. constexpr double kLBufferThreshold = 0.3; // unit: m const double driving_width = reference_line.GetDrivingWidth(obstacle->PerceptionSLBoundary()); const double adc_width = VehicleConfigHelper::GetConfig().vehicle_param().width(); // Refresh the s of the nearest obstacle if needed. if (driving_width - adc_width - FLAGS_static_decision_nudge_l_buffer <= kLBufferThreshold) { // if (obs_start_l < lane_left_width && -obs_end_l < lane_right_width) { ADEBUG << "Obstacle is not completely outside the current lane."; if (!exist_nearest_obs) { ADEBUG << "Updating the nearest obstacle to: obstacle_" << obstacle->Id(); exist_nearest_obs = true; *nearest_obstacle = obstacle; s_of_nearest_obs = obs_start_s; } else { if (obs_start_s < s_of_nearest_obs) { ADEBUG << "Updating the nearest obstacle to: obstacle_" << obstacle->Id(); *nearest_obstacle = obstacle; s_of_nearest_obs = obs_start_s; } } } } return true; } bool SidePassStopOnWaitPoint::GetMoveForwardLastPathPoint( const ReferenceLine& reference_line, const Obstacle* nearest_obstacle, PathPoint* const last_path_point, bool* should_not_move_at_all) { *should_not_move_at_all = false; int count = 0; bool exist_nearest_obs = (nearest_obstacle != nullptr); double s_max = 0.0; if (exist_nearest_obs) { ADEBUG << "There exists a nearest obstacle."; s_max = nearest_obstacle->PerceptionSLBoundary().start_s(); } for (const auto& path_point : GetContext()->path_data_.discretized_path().path_points()) { // Get the four corner points ABCD of ADC at every path point, // and keep checking until it gets out of the current lane or // reaches the nearest obstacle (in the same lane) ahead. const auto& vehicle_box = common::VehicleConfigHelper::Instance()->GetBoundingBox(path_point); std::vector<Vec2d> ABCDpoints = vehicle_box.GetAllCorners(); bool is_out_of_curr_lane = false; for (size_t i = 0; i < ABCDpoints.size(); i++) { // For each corner point, project it onto reference_line common::SLPoint curr_point_sl; if (!reference_line.XYToSL(ABCDpoints[i], &curr_point_sl)) { AERROR << "Failed to get the projection from point onto " "reference_line"; return false; } // Get the lane width at the current s indicated by path_point double curr_point_left_width = 0.0; double curr_point_right_width = 0.0; reference_line.GetLaneWidth(curr_point_sl.s(), &curr_point_left_width, &curr_point_right_width); // Check if this corner point is within the lane: if (curr_point_sl.l() > std::abs(curr_point_left_width) || curr_point_sl.l() < -std::abs(curr_point_right_width)) { is_out_of_curr_lane = true; break; } // Check if this corner point is before the nearest obstacle: if (exist_nearest_obs && curr_point_sl.s() > s_max) { is_out_of_curr_lane = true; break; } } if (is_out_of_curr_lane) { if (count == 0) { // The current ADC, without moving at all, is already at least // partially out of the current lane. *should_not_move_at_all = true; return true; } break; } else { *last_path_point = path_point; } CHECK_GE(path_point.s(), 0.0); ++count; } return true; } } // namespace side_pass } // namespace scenario } // namespace planning } // namespace apollo <commit_msg>Planning: removed unused code.<commit_after>/****************************************************************************** * 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. *****************************************************************************/ /** * @file **/ #include "modules/planning/scenarios/side_pass/side_pass_stop_on_wait_point.h" #include <algorithm> #include <vector> #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/proto/pnc_point.pb.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/speed_profile_generator.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { namespace scenario { namespace side_pass { using apollo::common::TrajectoryPoint; using apollo::common::PathPoint; using apollo::common::math::Vec2d; using apollo::common::VehicleConfigHelper; constexpr double kExtraMarginforStopOnWaitPointStage = 3.0; Stage::StageStatus SidePassStopOnWaitPoint::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { ADEBUG << "Processing SidePassStopOnWaitPoint"; const ReferenceLineInfo& reference_line_info = frame->reference_line_info().front(); const ReferenceLine& reference_line = reference_line_info.reference_line(); const PathDecision& path_decision = reference_line_info.path_decision(); if (GetContext()->path_data_.discretized_path().path_points().empty()) { AERROR << "path data is empty."; return Stage::ERROR; } if (!GetContext()->path_data_.UpdateFrenetFramePath(&reference_line)) { return Stage::ERROR; } const auto adc_frenet_frame_point_ = reference_line.GetFrenetPoint(frame->PlanningStartPoint().path_point()); if (!GetContext()->path_data_.LeftTrimWithRefS(adc_frenet_frame_point_)) { return Stage::ERROR; } if (GetContext()->path_data_.discretized_path().path_points().empty()) { AERROR << "path data is empty after trim."; return Stage::ERROR; } for (const auto& p : GetContext()->path_data_.discretized_path().path_points()) { ADEBUG << p.ShortDebugString(); } // Get the nearest obstacle const Obstacle* nearest_obstacle = nullptr; if (!GetTheNearestObstacle(reference_line, path_decision.obstacles(), &nearest_obstacle)) { AERROR << "Failed while running the function to get nearest obstacle."; return Stage::ERROR; } // If the nearest obstacle, provided it exists, is moving, // then quit the side_pass stage. if (nearest_obstacle) { if (nearest_obstacle->speed() > GetContext()->scenario_config_.block_obstacle_min_speed()) { ADEBUG << "The nearest obstacle to side-pass is moving."; next_stage_ = ScenarioConfig::NO_STAGE; return Stage::FINISHED; } } ADEBUG << "Got the nearest obstacle if there is one."; // Get the "wait point". PathPoint first_path_point = GetContext()->path_data_.discretized_path().path_points().front(); PathPoint last_path_point; bool should_not_move_at_all = false; if (!GetMoveForwardLastPathPoint(reference_line, nearest_obstacle, &last_path_point, &should_not_move_at_all)) { ADEBUG << "Fail to get move forward last path point."; return Stage::ERROR; } if (should_not_move_at_all) { ADEBUG << "The ADC is already at a stop point."; next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY; return Stage::FINISHED; // return FINISHED if it's already at "wait point". } ADEBUG << "first_path_point: " << first_path_point.ShortDebugString(); ADEBUG << "last_path_point : " << last_path_point.ShortDebugString(); double move_forward_distance = last_path_point.s() - first_path_point.s(); ADEBUG << "move_forward_distance: " << move_forward_distance; // Wait until everything is clear. if (!IsFarAwayFromObstacles(reference_line, path_decision.obstacles(), first_path_point, last_path_point)) { // wait here, do nothing this cycle. auto& rfl_info = frame->mutable_reference_line_info()->front(); *(rfl_info.mutable_path_data()) = GetContext()->path_data_; *(rfl_info.mutable_speed_data()) = SpeedProfileGenerator::GenerateFallbackSpeedProfile(); rfl_info.set_trajectory_type(ADCTrajectory::NORMAL); DiscretizedTrajectory trajectory; if (!rfl_info.CombinePathAndSpeedProfile( frame->PlanningStartPoint().relative_time(), frame->PlanningStartPoint().path_point().s(), &trajectory)) { AERROR << "Fail to aggregate planning trajectory."; return Stage::RUNNING; } rfl_info.SetTrajectory(trajectory); rfl_info.SetDrivable(true); ADEBUG << "waiting until obstacles are far away."; return Stage::RUNNING; } // (1) call proceed with cautious constexpr double kSidePassCreepSpeed = 2.33; // m/s auto& rfl_info = frame->mutable_reference_line_info()->front(); *(rfl_info.mutable_speed_data()) = SpeedProfileGenerator::GenerateFixedDistanceCreepProfile( move_forward_distance, kSidePassCreepSpeed); for (const auto& sd : rfl_info.mutable_speed_data()->speed_vector()) { ADEBUG << sd.ShortDebugString(); } // (2) combine path and speed. *(rfl_info.mutable_path_data()) = GetContext()->path_data_; rfl_info.set_trajectory_type(ADCTrajectory::NORMAL); DiscretizedTrajectory trajectory; if (!rfl_info.CombinePathAndSpeedProfile( frame->PlanningStartPoint().relative_time(), frame->PlanningStartPoint().path_point().s(), &trajectory)) { AERROR << "Fail to aggregate planning trajectory."; return Stage::RUNNING; } rfl_info.SetTrajectory(trajectory); rfl_info.SetDrivable(true); constexpr double kBuffer = 0.3; if (move_forward_distance < kBuffer) { next_stage_ = ScenarioConfig::SIDE_PASS_DETECT_SAFETY; } return Stage::FINISHED; } bool SidePassStopOnWaitPoint::IsFarAwayFromObstacles( const ReferenceLine& reference_line, const IndexedList<std::string, Obstacle>& indexed_obstacle_list, const PathPoint& first_path_point, const PathPoint& last_path_point) { common::SLPoint first_sl_point; if (!reference_line.XYToSL(Vec2d(first_path_point.x(), first_path_point.y()), &first_sl_point)) { AERROR << "Failed to get the projection from TrajectoryPoint onto " "reference_line"; return false; } common::SLPoint last_sl_point; if (!reference_line.XYToSL(Vec2d(last_path_point.x(), last_path_point.y()), &last_sl_point)) { AERROR << "Failed to get the projection from TrajectoryPoint onto " "reference_line"; return false; } // Go through every obstacle, check if there is any in the no_obs_zone, // which will be used by the proceed_with_caution movement. for (const auto* obstacle : indexed_obstacle_list.Items()) { if (obstacle->IsVirtual()) { continue; } // Check the s-direction. double obs_start_s = obstacle->PerceptionSLBoundary().start_s(); double obs_end_s = obstacle->PerceptionSLBoundary().end_s(); if (obs_end_s < first_sl_point.s() || obs_start_s > last_sl_point.s() + kExtraMarginforStopOnWaitPointStage) { continue; } // Check the l-direction. double lane_left_width_at_start_s = 0.0; double lane_left_width_at_end_s = 0.0; double lane_right_width_at_start_s = 0.0; double lane_right_width_at_end_s = 0.0; reference_line.GetLaneWidth(obs_start_s, &lane_left_width_at_start_s, &lane_right_width_at_start_s); reference_line.GetLaneWidth(obs_end_s, &lane_left_width_at_end_s, &lane_right_width_at_end_s); double lane_left_width = std::min(std::abs(lane_left_width_at_start_s), std::abs(lane_left_width_at_end_s)); double lane_right_width = std::min(std::abs(lane_right_width_at_start_s), std::abs(lane_right_width_at_end_s)); double obs_start_l = obstacle->PerceptionSLBoundary().start_l(); double obs_end_l = obstacle->PerceptionSLBoundary().end_l(); if (obs_start_l < lane_left_width && -obs_end_l < lane_right_width) { return false; } } return true; } bool SidePassStopOnWaitPoint::GetTheNearestObstacle( const ReferenceLine& reference_line, const IndexedList<std::string, Obstacle>& indexed_obstacle_list, const Obstacle** nearest_obstacle) { // Get the first path point. This can be used later to // filter out other obstaces that are behind ADC. PathPoint first_path_point = GetContext()->path_data_.discretized_path().path_points().front(); common::SLPoint first_sl_point; if (!reference_line.XYToSL(Vec2d(first_path_point.x(), first_path_point.y()), &first_sl_point)) { AERROR << "Failed to get the projection from TrajectoryPoint onto " "reference_line"; return false; } // Go through every obstacle. bool exist_nearest_obs = false; *nearest_obstacle = nullptr; double s_of_nearest_obs = 0.0; for (const auto* obstacle : indexed_obstacle_list.Items()) { ADEBUG << "Looking at Obstacle: " << obstacle->Id(); if (obstacle->IsVirtual()) { continue; } // Check the s-direction. Rule out those obstacles that are behind ADC. double obs_start_s = obstacle->PerceptionSLBoundary().start_s(); double obs_end_s = obstacle->PerceptionSLBoundary().end_s(); if (obs_end_s <= first_sl_point.s()) { ADEBUG << "Obstacle behind ADC. Rule out."; continue; } // Check the l-direction. Rule out those obstacles that are not // blocking our drive-way. // TODO(all): should make this a GFLAG because this is also used by // side_pass_scenario.cc. They should be consistent. constexpr double kLBufferThreshold = 0.3; // unit: m const double driving_width = reference_line.GetDrivingWidth(obstacle->PerceptionSLBoundary()); const double adc_width = VehicleConfigHelper::GetConfig().vehicle_param().width(); // Refresh the s of the nearest obstacle if needed. if (driving_width - adc_width - FLAGS_static_decision_nudge_l_buffer <= kLBufferThreshold) { ADEBUG << "Obstacle is not completely outside the current lane."; if (!exist_nearest_obs) { ADEBUG << "Updating the nearest obstacle to: obstacle_" << obstacle->Id(); exist_nearest_obs = true; *nearest_obstacle = obstacle; s_of_nearest_obs = obs_start_s; } else { if (obs_start_s < s_of_nearest_obs) { ADEBUG << "Updating the nearest obstacle to: obstacle_" << obstacle->Id(); *nearest_obstacle = obstacle; s_of_nearest_obs = obs_start_s; } } } } return true; } bool SidePassStopOnWaitPoint::GetMoveForwardLastPathPoint( const ReferenceLine& reference_line, const Obstacle* nearest_obstacle, PathPoint* const last_path_point, bool* should_not_move_at_all) { *should_not_move_at_all = false; int count = 0; bool exist_nearest_obs = (nearest_obstacle != nullptr); double s_max = 0.0; if (exist_nearest_obs) { ADEBUG << "There exists a nearest obstacle."; s_max = nearest_obstacle->PerceptionSLBoundary().start_s(); } for (const auto& path_point : GetContext()->path_data_.discretized_path().path_points()) { // Get the four corner points ABCD of ADC at every path point, // and keep checking until it gets out of the current lane or // reaches the nearest obstacle (in the same lane) ahead. const auto& vehicle_box = common::VehicleConfigHelper::Instance()->GetBoundingBox(path_point); std::vector<Vec2d> ABCDpoints = vehicle_box.GetAllCorners(); bool is_out_of_curr_lane = false; for (size_t i = 0; i < ABCDpoints.size(); i++) { // For each corner point, project it onto reference_line common::SLPoint curr_point_sl; if (!reference_line.XYToSL(ABCDpoints[i], &curr_point_sl)) { AERROR << "Failed to get the projection from point onto " "reference_line"; return false; } // Get the lane width at the current s indicated by path_point double curr_point_left_width = 0.0; double curr_point_right_width = 0.0; reference_line.GetLaneWidth(curr_point_sl.s(), &curr_point_left_width, &curr_point_right_width); // Check if this corner point is within the lane: if (curr_point_sl.l() > std::abs(curr_point_left_width) || curr_point_sl.l() < -std::abs(curr_point_right_width)) { is_out_of_curr_lane = true; break; } // Check if this corner point is before the nearest obstacle: if (exist_nearest_obs && curr_point_sl.s() > s_max) { is_out_of_curr_lane = true; break; } } if (is_out_of_curr_lane) { if (count == 0) { // The current ADC, without moving at all, is already at least // partially out of the current lane. *should_not_move_at_all = true; return true; } break; } else { *last_path_point = path_point; } CHECK_GE(path_point.s(), 0.0); ++count; } return true; } } // namespace side_pass } // namespace scenario } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>#include <string> #include <ostream> #include <fstream> #include <sstream> #include <SDL.h> #include "../include/logger.h" Util::Logger::Logger(const std::string &file) : fileOut(file.c_str()), output(fileOut) { } Util::Logger::Logger(std::ostream &os) : output(os) { } void Util::Logger::log(const std::string &msg){ timeStamp(); output << msg; } std::string Util::Logger::timeStamp(){ float sec = SDL_GetTicks() / 1000.f; int hrs = sec / 3600; int min = sec / 60 - hrs * 3600; sec = static_cast<int>(sec - hrs * 3600 - min * 60); std::stringstream ss; ss << hrs << ":" << min << ":" << sec << "\n"; return ss.str(); } Util::Logger& Util::Logger::operator<<(std::ostream&(*f)(std::ostream&)){ output << f; return *this; }<commit_msg>Removing the endline from the timestamp<commit_after>#include <string> #include <ostream> #include <fstream> #include <sstream> #include <SDL.h> #include "../include/logger.h" Util::Logger::Logger(const std::string &file) : fileOut(file.c_str()), output(fileOut) { } Util::Logger::Logger(std::ostream &os) : output(os) { } void Util::Logger::log(const std::string &msg){ timeStamp(); output << msg; } std::string Util::Logger::timeStamp(){ float sec = SDL_GetTicks() / 1000.f; int hrs = sec / 3600; int min = sec / 60 - hrs * 3600; sec = static_cast<int>(sec - hrs * 3600 - min * 60); std::stringstream ss; ss << hrs << ":" << min << ":" << sec; return ss.str(); } Util::Logger& Util::Logger::operator<<(std::ostream&(*f)(std::ostream&)){ output << f; return *this; }<|endoftext|>
<commit_before>// Copyright (c) 2014, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: yanshiguang02@baidu.com #include "logging.h" #include <assert.h> #include <boost/bind.hpp> #include <queue> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string> #include <syscall.h> #include <sys/time.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include "mutex.h" #include "thread.h" #include "timer.h" namespace baidu { namespace common { int g_log_level = INFO; int64_t g_log_size = 0; int32_t g_log_count = 0; FILE* g_log_file = stdout; std::string g_log_file_name; FILE* g_warning_file = NULL; std::queue<std::string> g_log_queue; bool GetNewLog(bool append) { char buf[30]; struct timeval tv; gettimeofday(&tv, NULL); const time_t seconds = tv.tv_sec; struct tm t; localtime_r(&seconds, &t); snprintf(buf, 30, "%02d-%02d.%02d:%02d:%02d.%06d", t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, static_cast<int>(tv.tv_usec)); std::string full_path(g_log_file_name + "."); full_path.append(buf); size_t idx = full_path.rfind('/'); if (idx == std::string::npos) { idx = 0; } else { idx += 1; } const char* mode = append ? "ab" : "wb"; FILE* fp = fopen(full_path.c_str(), mode); if (fp == NULL) { return false; } if (g_log_file != stdout) { fclose(g_log_file); } g_log_file = fp; remove(g_log_file_name.c_str()); symlink(full_path.substr(idx).c_str(), g_log_file_name.c_str()); if (0 == g_log_count) { return true; } g_log_queue.push(full_path); while (static_cast<int64_t>(g_log_queue.size()) > g_log_count) { std::string to_del = g_log_queue.front(); remove(to_del.c_str()); g_log_queue.pop(); } return true; } void SetLogLevel(int level) { g_log_level = level; } class AsyncLogger { public: AsyncLogger() : jobs_(&mu_), done_(&mu_), stopped_(false), size_(0) { thread_.Start(boost::bind(&AsyncLogger::AsyncWriter, this)); } ~AsyncLogger() { stopped_ = true; { MutexLock lock(&mu_); jobs_.Signal(); } thread_.Join(); // close fd } void WriteLog(int log_level, const char* buffer, int32_t len) { std::string* log_str = new std::string(buffer, len); MutexLock lock(&mu_); buffer_queue_.push(make_pair(log_level, log_str)); jobs_.Signal(); } void AsyncWriter() { MutexLock lock(&mu_); while (1) { int loglen = 0; int wflen = 0; while (!buffer_queue_.empty()) { int log_level = buffer_queue_.front().first; std::string* str = buffer_queue_.front().second; buffer_queue_.pop(); if (g_log_file != stdout && g_log_size && static_cast<int64_t>(size_ + str->length()) > g_log_size) { GetNewLog(false); size_ = 0; } mu_.Unlock(); if (str && !str->empty()) { fwrite(str->data(), 1, str->size(), g_log_file); loglen += str->size(); if (g_warning_file && log_level >= 8) { fwrite(str->data(), 1, str->size(), g_warning_file); wflen += str->size(); } if (g_log_size) size_ += str->length(); } delete str; mu_.Lock(); } if (loglen) fflush(g_log_file); if (wflen) fflush(g_warning_file); if (stopped_) { break; } done_.Broadcast(); jobs_.Wait(); } } void Flush() { MutexLock lock(&mu_); buffer_queue_.push(std::make_pair(0, reinterpret_cast<std::string*>(NULL))); jobs_.Signal(); done_.Wait(); } private: Mutex mu_; CondVar jobs_; CondVar done_; bool stopped_; int64_t size_; Thread thread_; std::queue<std::pair<int, std::string*> > buffer_queue_; }; AsyncLogger g_logger; bool SetWarningFile(const char* path, bool append) { const char* mode = append ? "ab" : "wb"; FILE* fp = fopen(path, mode); if (fp == NULL) { return false; } if (g_warning_file) { fclose(g_warning_file); } g_warning_file = fp; return true; } bool RecoverHistory(const char* path) { std::string log_path(path); size_t idx = log_path.rfind('/'); std::string dir = "./"; std::string log(path); if (idx != std::string::npos) { dir = log_path.substr(0, idx + 1); log = log_path.substr(idx + 1); } struct dirent *entry = NULL; DIR *dir_ptr = opendir(dir.c_str()); if (dir_ptr == NULL) { return false; } std::vector<std::string> loglist; while (entry = readdir(dir_ptr)) { if (std::string(entry->d_name).find(log) != std::string::npos) { std::string file_name = dir + std::string(entry->d_name); struct stat sta; if (-1 == lstat(file_name.c_str(), &sta)) { return false; } if (S_ISREG(sta.st_mode)) { loglist.push_back(dir + std::string(entry->d_name)); } } } closedir(dir_ptr); std::sort(loglist.begin(), loglist.end()); for (size_t idx = g_log_count < static_cast<int32_t>(loglist.size()) ? loglist.size() - g_log_count : 0; idx < loglist.size(); ++idx) { g_log_queue.push(loglist[idx]); } return true; } bool SetLogFile(const char* path, bool append) { g_log_file_name.assign(path); return GetNewLog(append); } bool SetLogSize(int size) { if (size < 0) { return false; } g_log_size = static_cast<int64_t>(size) << 20; return true; } bool SetLogCount(int count) { if (count < 0) { return false; } g_log_count = count; if (!RecoverHistory(g_log_file_name.c_str())) { return false; } return true; } void Logv(int log_level, const char* format, va_list ap) { static __thread uint64_t thread_id = 0; if (thread_id == 0) { thread_id = syscall(__NR_gettid); } // We try twice: the first time with a fixed-size stack allocated buffer, // and the second time with a much larger dynamically allocated buffer. char buffer[500]; for (int iter = 0; iter < 2; iter++) { char* base; int bufsize; if (iter == 0) { bufsize = sizeof(buffer); base = buffer; } else { bufsize = 30000; base = new char[bufsize]; } char* p = base; char* limit = base + bufsize; int32_t rlen = timer::now_time_str(p, limit - p); p += rlen; p += snprintf(p, limit - p, " %lld ", static_cast<long long unsigned int>(thread_id)); // Print the message if (p < limit) { va_list backup_ap; va_copy(backup_ap, ap); p += vsnprintf(p, limit - p, format, backup_ap); va_end(backup_ap); } // Truncate to available space if necessary if (p >= limit) { if (iter == 0) { continue; // Try again with larger buffer } else { p = limit - 1; } } // Add newline if necessary if (p == base || p[-1] != '\n') { *p++ = '\n'; } assert(p <= limit); //fwrite(base, 1, p - base, g_log_file); //fflush(g_log_file); //if (g_warning_file && log_level >= 8) { // fwrite(base, 1, p - base, g_warning_file); // fflush(g_warning_file); //} g_logger.WriteLog(log_level, base, p - base); if (log_level == FATAL) { g_logger.Flush(); } if (base != buffer) { delete[] base; } break; } } void Log(int level, const char* fmt, ...) { va_list ap; va_start(ap, fmt); if (level >= g_log_level) { Logv(level, fmt, ap); } va_end(ap); if (level == FATAL) { abort(); } } LogStream::LogStream(int level) : level_(level) {} LogStream::~LogStream() { Log(level_, "%s", oss_.str().c_str()); } } // namespace common } // namespace baidu /* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */ <commit_msg>fix cr note<commit_after>// Copyright (c) 2014, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: yanshiguang02@baidu.com #include "logging.h" #include <assert.h> #include <boost/bind.hpp> #include <queue> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string> #include <syscall.h> #include <sys/time.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include "mutex.h" #include "thread.h" #include "timer.h" namespace baidu { namespace common { int g_log_level = INFO; int64_t g_log_size = 0; int32_t g_log_count = 0; FILE* g_log_file = stdout; std::string g_log_file_name; FILE* g_warning_file = NULL; std::queue<std::string> g_log_queue; bool GetNewLog(bool append) { char buf[30]; struct timeval tv; gettimeofday(&tv, NULL); const time_t seconds = tv.tv_sec; struct tm t; localtime_r(&seconds, &t); snprintf(buf, 30, "%02d-%02d.%02d:%02d:%02d.%06d", t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, static_cast<int>(tv.tv_usec)); std::string full_path(g_log_file_name + "."); full_path.append(buf); size_t idx = full_path.rfind('/'); if (idx == std::string::npos) { idx = 0; } else { idx += 1; } const char* mode = append ? "ab" : "wb"; FILE* fp = fopen(full_path.c_str(), mode); if (fp == NULL) { return false; } if (g_log_file != stdout) { fclose(g_log_file); } g_log_file = fp; remove(g_log_file_name.c_str()); symlink(full_path.substr(idx).c_str(), g_log_file_name.c_str()); if (0 == g_log_count) { return true; } g_log_queue.push(full_path); while (static_cast<int64_t>(g_log_queue.size()) > g_log_count) { std::string to_del = g_log_queue.front(); remove(to_del.c_str()); g_log_queue.pop(); } return true; } void SetLogLevel(int level) { g_log_level = level; } class AsyncLogger { public: AsyncLogger() : jobs_(&mu_), done_(&mu_), stopped_(false), size_(0) { thread_.Start(boost::bind(&AsyncLogger::AsyncWriter, this)); } ~AsyncLogger() { stopped_ = true; { MutexLock lock(&mu_); jobs_.Signal(); } thread_.Join(); // close fd } void WriteLog(int log_level, const char* buffer, int32_t len) { std::string* log_str = new std::string(buffer, len); MutexLock lock(&mu_); buffer_queue_.push(make_pair(log_level, log_str)); jobs_.Signal(); } void AsyncWriter() { MutexLock lock(&mu_); while (1) { int loglen = 0; int wflen = 0; while (!buffer_queue_.empty()) { int log_level = buffer_queue_.front().first; std::string* str = buffer_queue_.front().second; buffer_queue_.pop(); if (g_log_file != stdout && g_log_size && static_cast<int64_t>(size_ + str->length()) > g_log_size) { GetNewLog(false); size_ = 0; } mu_.Unlock(); if (str && !str->empty()) { fwrite(str->data(), 1, str->size(), g_log_file); loglen += str->size(); if (g_warning_file && log_level >= 8) { fwrite(str->data(), 1, str->size(), g_warning_file); wflen += str->size(); } if (g_log_size) size_ += str->length(); } delete str; mu_.Lock(); } if (loglen) fflush(g_log_file); if (wflen) fflush(g_warning_file); if (stopped_) { break; } done_.Broadcast(); jobs_.Wait(); } } void Flush() { MutexLock lock(&mu_); buffer_queue_.push(std::make_pair(0, reinterpret_cast<std::string*>(NULL))); jobs_.Signal(); done_.Wait(); } private: Mutex mu_; CondVar jobs_; CondVar done_; bool stopped_; int64_t size_; Thread thread_; std::queue<std::pair<int, std::string*> > buffer_queue_; }; AsyncLogger g_logger; bool SetWarningFile(const char* path, bool append) { const char* mode = append ? "ab" : "wb"; FILE* fp = fopen(path, mode); if (fp == NULL) { return false; } if (g_warning_file) { fclose(g_warning_file); } g_warning_file = fp; return true; } bool RecoverHistory(const char* path) { std::string log_path(path); size_t idx = log_path.rfind('/'); std::string dir = "./"; std::string log(path); if (idx != std::string::npos) { dir = log_path.substr(0, idx + 1); log = log_path.substr(idx + 1); } struct dirent *entry = NULL; DIR *dir_ptr = opendir(dir.c_str()); if (dir_ptr == NULL) { return false; } std::vector<std::string> loglist; while (entry = readdir(dir_ptr)) { if (std::string(entry->d_name).find(log) != std::string::npos) { std::string file_name = dir + std::string(entry->d_name); struct stat sta; if (-1 == lstat(file_name.c_str(), &sta)) { return false; } if (S_ISREG(sta.st_mode)) { loglist.push_back(dir + std::string(entry->d_name)); } } } closedir(dir_ptr); std::sort(loglist.begin(), loglist.end()); for (std::vector<std::string>::iterator it = loglist.begin(); it != loglist.end(); ++it) { g_log_queue.push(loglist[idx]); } while (static_cast<int64_t>(g_log_queue.size()) > g_log_count) { std::string to_del = g_log_queue.front(); remove(to_del.c_str()); g_log_queue.pop(); } return true; } bool SetLogFile(const char* path, bool append) { g_log_file_name.assign(path); return GetNewLog(append); } bool SetLogSize(int size) { if (size < 0) { return false; } g_log_size = static_cast<int64_t>(size) << 20; return true; } bool SetLogCount(int count) { if (count < 0) { return false; } g_log_count = count; if (!RecoverHistory(g_log_file_name.c_str())) { return false; } return true; } void Logv(int log_level, const char* format, va_list ap) { static __thread uint64_t thread_id = 0; if (thread_id == 0) { thread_id = syscall(__NR_gettid); } // We try twice: the first time with a fixed-size stack allocated buffer, // and the second time with a much larger dynamically allocated buffer. char buffer[500]; for (int iter = 0; iter < 2; iter++) { char* base; int bufsize; if (iter == 0) { bufsize = sizeof(buffer); base = buffer; } else { bufsize = 30000; base = new char[bufsize]; } char* p = base; char* limit = base + bufsize; int32_t rlen = timer::now_time_str(p, limit - p); p += rlen; p += snprintf(p, limit - p, " %lld ", static_cast<long long unsigned int>(thread_id)); // Print the message if (p < limit) { va_list backup_ap; va_copy(backup_ap, ap); p += vsnprintf(p, limit - p, format, backup_ap); va_end(backup_ap); } // Truncate to available space if necessary if (p >= limit) { if (iter == 0) { continue; // Try again with larger buffer } else { p = limit - 1; } } // Add newline if necessary if (p == base || p[-1] != '\n') { *p++ = '\n'; } assert(p <= limit); //fwrite(base, 1, p - base, g_log_file); //fflush(g_log_file); //if (g_warning_file && log_level >= 8) { // fwrite(base, 1, p - base, g_warning_file); // fflush(g_warning_file); //} g_logger.WriteLog(log_level, base, p - base); if (log_level == FATAL) { g_logger.Flush(); } if (base != buffer) { delete[] base; } break; } } void Log(int level, const char* fmt, ...) { va_list ap; va_start(ap, fmt); if (level >= g_log_level) { Logv(level, fmt, ap); } va_end(ap); if (level == FATAL) { abort(); } } LogStream::LogStream(int level) : level_(level) {} LogStream::~LogStream() { Log(level_, "%s", oss_.str().c_str()); } } // namespace common } // namespace baidu /* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */ <|endoftext|>
<commit_before>// 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 <queue> #include "base/command_line.h" #include "base/path_service.h" #include "base/thread_task_runner_handle.h" #include "chrome/browser/extensions/api/desktop_capture/desktop_capture_api.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/media/fake_desktop_media_list.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/test/browser_test_utils.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" namespace extensions { namespace { struct TestFlags { bool expect_screens; bool expect_windows; content::DesktopMediaID selected_source; bool cancelled; // Following flags are set by FakeDesktopMediaPicker when it's created and // deleted. bool picker_created; bool picker_deleted; }; class FakeDesktopMediaPicker : public DesktopMediaPicker { public: explicit FakeDesktopMediaPicker(TestFlags* expectation) : expectation_(expectation), weak_factory_(this) { expectation_->picker_created = true; } virtual ~FakeDesktopMediaPicker() { expectation_->picker_deleted = true; } // DesktopMediaPicker interface. virtual void Show(gfx::NativeWindow context, gfx::NativeWindow parent, const base::string16& app_name, scoped_ptr<DesktopMediaList> model, const DoneCallback& done_callback) OVERRIDE { if (!expectation_->cancelled) { // Post a task to call the callback asynchronously. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&FakeDesktopMediaPicker::CallCallback, weak_factory_.GetWeakPtr(), done_callback)); } else { // If we expect the dialog to be cancelled then store the callback to // retain reference to the callback handler. done_callback_ = done_callback; } } private: void CallCallback(DoneCallback done_callback) { done_callback.Run(expectation_->selected_source); } TestFlags* expectation_; DoneCallback done_callback_; base::WeakPtrFactory<FakeDesktopMediaPicker> weak_factory_; DISALLOW_COPY_AND_ASSIGN(FakeDesktopMediaPicker); }; class FakeDesktopMediaPickerFactory : public DesktopCaptureChooseDesktopMediaFunction::PickerFactory { public: FakeDesktopMediaPickerFactory() {} virtual ~FakeDesktopMediaPickerFactory() {} void SetTestFlags(TestFlags* test_flags, int tests_count) { test_flags_ = test_flags; tests_count_ = tests_count; current_test_ = 0; } // DesktopCaptureChooseDesktopMediaFunction::PickerFactory interface. virtual scoped_ptr<DesktopMediaList> CreateModel( bool show_screens, bool show_windows) OVERRIDE { EXPECT_LE(current_test_, tests_count_); if (current_test_ >= tests_count_) return scoped_ptr<DesktopMediaList>(); EXPECT_EQ(test_flags_[current_test_].expect_screens, show_screens); EXPECT_EQ(test_flags_[current_test_].expect_windows, show_windows); return scoped_ptr<DesktopMediaList>(new FakeDesktopMediaList()); } virtual scoped_ptr<DesktopMediaPicker> CreatePicker() OVERRIDE { EXPECT_LE(current_test_, tests_count_); if (current_test_ >= tests_count_) return scoped_ptr<DesktopMediaPicker>(); ++current_test_; return scoped_ptr<DesktopMediaPicker>( new FakeDesktopMediaPicker(test_flags_ + current_test_ - 1)); } private: TestFlags* test_flags_; int tests_count_; int current_test_; DISALLOW_COPY_AND_ASSIGN(FakeDesktopMediaPickerFactory); }; class DesktopCaptureApiTest : public ExtensionApiTest { public: DesktopCaptureApiTest() { DesktopCaptureChooseDesktopMediaFunction:: SetPickerFactoryForTests(&picker_factory_); } virtual ~DesktopCaptureApiTest() { DesktopCaptureChooseDesktopMediaFunction:: SetPickerFactoryForTests(NULL); } protected: GURL GetURLForPath(const std::string& host, const std::string& path) { std::string port = base::IntToString(embedded_test_server()->port()); GURL::Replacements replacements; replacements.SetHostStr(host); replacements.SetPortStr(port); return embedded_test_server()->GetURL(path).ReplaceComponents(replacements); } FakeDesktopMediaPickerFactory picker_factory_; }; } // namespace // Flaky on Windows: http://crbug.com/301887 #if defined(OS_WIN) #define MAYBE_ChooseDesktopMedia DISABLED_ChooseDesktopMedia #else #define MAYBE_ChooseDesktopMedia ChooseDesktopMedia #endif IN_PROC_BROWSER_TEST_F(DesktopCaptureApiTest, MAYBE_ChooseDesktopMedia) { // Each element in the following array corresponds to one test in // chrome/test/data/extensions/api_test/desktop_capture/test.js . TestFlags test_flags[] = { // pickerUiCanceled() { true, true, content::DesktopMediaID() }, // chooseMedia() { true, true, content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0) }, // screensOnly() { true, false, content::DesktopMediaID() }, // WindowsOnly() { false, true, content::DesktopMediaID() }, // chooseMediaAndGetStream() { true, true, content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0) }, // chooseMediaAndTryGetStreamWithInvalidId() { true, true, content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0) }, // cancelDialog() { true, true, content::DesktopMediaID(), true }, }; picker_factory_.SetTestFlags(test_flags, arraysize(test_flags)); ASSERT_TRUE(RunExtensionTest("desktop_capture")) << message_; } // Test is flaky http://crbug.com/301887. IN_PROC_BROWSER_TEST_F(DesktopCaptureApiTest, DISABLED_Delegation) { // Initialize test server. base::FilePath test_data; EXPECT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data)); embedded_test_server()->ServeFilesFromDirectory(test_data.AppendASCII( "extensions/api_test/desktop_capture_delegate")); ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady()); host_resolver()->AddRule("*", embedded_test_server()->base_url().host()); // Load extension. base::FilePath extension_path = test_data_dir_.AppendASCII("desktop_capture_delegate"); const Extension* extension = LoadExtensionWithFlags( extension_path, ExtensionBrowserTest::kFlagNone); ASSERT_TRUE(extension); ui_test_utils::NavigateToURL( browser(), GetURLForPath("example.com", "/example.com.html")); TestFlags test_flags[] = { { true, true, content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0) }, { true, true, content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0) }, { true, true, content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0), true }, }; picker_factory_.SetTestFlags(test_flags, arraysize(test_flags)); bool result; content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(content::ExecuteScriptAndExtractBool( web_contents, "getStream()", &result)); EXPECT_TRUE(result); ASSERT_TRUE(content::ExecuteScriptAndExtractBool( web_contents, "getStreamWithInvalidId()", &result)); EXPECT_TRUE(result); // Verify that the picker is closed once the tab is closed. content::WebContentsDestroyedWatcher destroyed_watcher(web_contents); ASSERT_TRUE(content::ExecuteScriptAndExtractBool( web_contents, "openPickerDialogAndReturn()", &result)); EXPECT_TRUE(result); EXPECT_TRUE(test_flags[2].picker_created); EXPECT_FALSE(test_flags[2].picker_deleted); web_contents->Close(); destroyed_watcher.Wait(); EXPECT_TRUE(test_flags[2].picker_deleted); } } // namespace extensions <commit_msg>Update the DesktopCapture Api test to use a proper screen id.<commit_after>// 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 <queue> #include "base/command_line.h" #include "base/path_service.h" #include "base/thread_task_runner_handle.h" #include "chrome/browser/extensions/api/desktop_capture/desktop_capture_api.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/media/fake_desktop_media_list.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/test/browser_test_utils.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capture_types.h" namespace extensions { namespace { struct TestFlags { bool expect_screens; bool expect_windows; content::DesktopMediaID selected_source; bool cancelled; // Following flags are set by FakeDesktopMediaPicker when it's created and // deleted. bool picker_created; bool picker_deleted; }; class FakeDesktopMediaPicker : public DesktopMediaPicker { public: explicit FakeDesktopMediaPicker(TestFlags* expectation) : expectation_(expectation), weak_factory_(this) { expectation_->picker_created = true; } virtual ~FakeDesktopMediaPicker() { expectation_->picker_deleted = true; } // DesktopMediaPicker interface. virtual void Show(gfx::NativeWindow context, gfx::NativeWindow parent, const base::string16& app_name, scoped_ptr<DesktopMediaList> model, const DoneCallback& done_callback) OVERRIDE { if (!expectation_->cancelled) { // Post a task to call the callback asynchronously. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&FakeDesktopMediaPicker::CallCallback, weak_factory_.GetWeakPtr(), done_callback)); } else { // If we expect the dialog to be cancelled then store the callback to // retain reference to the callback handler. done_callback_ = done_callback; } } private: void CallCallback(DoneCallback done_callback) { done_callback.Run(expectation_->selected_source); } TestFlags* expectation_; DoneCallback done_callback_; base::WeakPtrFactory<FakeDesktopMediaPicker> weak_factory_; DISALLOW_COPY_AND_ASSIGN(FakeDesktopMediaPicker); }; class FakeDesktopMediaPickerFactory : public DesktopCaptureChooseDesktopMediaFunction::PickerFactory { public: FakeDesktopMediaPickerFactory() {} virtual ~FakeDesktopMediaPickerFactory() {} void SetTestFlags(TestFlags* test_flags, int tests_count) { test_flags_ = test_flags; tests_count_ = tests_count; current_test_ = 0; } // DesktopCaptureChooseDesktopMediaFunction::PickerFactory interface. virtual scoped_ptr<DesktopMediaList> CreateModel( bool show_screens, bool show_windows) OVERRIDE { EXPECT_LE(current_test_, tests_count_); if (current_test_ >= tests_count_) return scoped_ptr<DesktopMediaList>(); EXPECT_EQ(test_flags_[current_test_].expect_screens, show_screens); EXPECT_EQ(test_flags_[current_test_].expect_windows, show_windows); return scoped_ptr<DesktopMediaList>(new FakeDesktopMediaList()); } virtual scoped_ptr<DesktopMediaPicker> CreatePicker() OVERRIDE { EXPECT_LE(current_test_, tests_count_); if (current_test_ >= tests_count_) return scoped_ptr<DesktopMediaPicker>(); ++current_test_; return scoped_ptr<DesktopMediaPicker>( new FakeDesktopMediaPicker(test_flags_ + current_test_ - 1)); } private: TestFlags* test_flags_; int tests_count_; int current_test_; DISALLOW_COPY_AND_ASSIGN(FakeDesktopMediaPickerFactory); }; class DesktopCaptureApiTest : public ExtensionApiTest { public: DesktopCaptureApiTest() { DesktopCaptureChooseDesktopMediaFunction:: SetPickerFactoryForTests(&picker_factory_); } virtual ~DesktopCaptureApiTest() { DesktopCaptureChooseDesktopMediaFunction:: SetPickerFactoryForTests(NULL); } protected: GURL GetURLForPath(const std::string& host, const std::string& path) { std::string port = base::IntToString(embedded_test_server()->port()); GURL::Replacements replacements; replacements.SetHostStr(host); replacements.SetPortStr(port); return embedded_test_server()->GetURL(path).ReplaceComponents(replacements); } FakeDesktopMediaPickerFactory picker_factory_; }; } // namespace // Flaky on Windows: http://crbug.com/301887 #if defined(OS_WIN) #define MAYBE_ChooseDesktopMedia DISABLED_ChooseDesktopMedia #else #define MAYBE_ChooseDesktopMedia ChooseDesktopMedia #endif IN_PROC_BROWSER_TEST_F(DesktopCaptureApiTest, MAYBE_ChooseDesktopMedia) { // Each element in the following array corresponds to one test in // chrome/test/data/extensions/api_test/desktop_capture/test.js . TestFlags test_flags[] = { // pickerUiCanceled() { true, true, content::DesktopMediaID() }, // chooseMedia() { true, true, content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0) }, // screensOnly() { true, false, content::DesktopMediaID() }, // WindowsOnly() { false, true, content::DesktopMediaID() }, // chooseMediaAndGetStream() { true, true, content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, webrtc::kFullDesktopScreenId) }, // chooseMediaAndTryGetStreamWithInvalidId() { true, true, content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, webrtc::kFullDesktopScreenId) }, // cancelDialog() { true, true, content::DesktopMediaID(), true }, }; picker_factory_.SetTestFlags(test_flags, arraysize(test_flags)); ASSERT_TRUE(RunExtensionTest("desktop_capture")) << message_; } // Test is flaky http://crbug.com/301887. IN_PROC_BROWSER_TEST_F(DesktopCaptureApiTest, DISABLED_Delegation) { // Initialize test server. base::FilePath test_data; EXPECT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data)); embedded_test_server()->ServeFilesFromDirectory(test_data.AppendASCII( "extensions/api_test/desktop_capture_delegate")); ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady()); host_resolver()->AddRule("*", embedded_test_server()->base_url().host()); // Load extension. base::FilePath extension_path = test_data_dir_.AppendASCII("desktop_capture_delegate"); const Extension* extension = LoadExtensionWithFlags( extension_path, ExtensionBrowserTest::kFlagNone); ASSERT_TRUE(extension); ui_test_utils::NavigateToURL( browser(), GetURLForPath("example.com", "/example.com.html")); TestFlags test_flags[] = { { true, true, content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0) }, { true, true, content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0) }, { true, true, content::DesktopMediaID(content::DesktopMediaID::TYPE_SCREEN, 0), true }, }; picker_factory_.SetTestFlags(test_flags, arraysize(test_flags)); bool result; content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(content::ExecuteScriptAndExtractBool( web_contents, "getStream()", &result)); EXPECT_TRUE(result); ASSERT_TRUE(content::ExecuteScriptAndExtractBool( web_contents, "getStreamWithInvalidId()", &result)); EXPECT_TRUE(result); // Verify that the picker is closed once the tab is closed. content::WebContentsDestroyedWatcher destroyed_watcher(web_contents); ASSERT_TRUE(content::ExecuteScriptAndExtractBool( web_contents, "openPickerDialogAndReturn()", &result)); EXPECT_TRUE(result); EXPECT_TRUE(test_flags[2].picker_created); EXPECT_FALSE(test_flags[2].picker_deleted); web_contents->Close(); destroyed_watcher.Wait(); EXPECT_TRUE(test_flags[2].picker_deleted); } } // namespace extensions <|endoftext|>
<commit_before> /**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "s60mediaplayercontrol.h" #include "s60mediaplayersession.h" #include <QtCore/qdir.h> #include <QtCore/qurl.h> #include <QtCore/qdebug.h> S60MediaPlayerControl::S60MediaPlayerControl(MS60MediaPlayerResolver& mediaPlayerResolver, QObject *parent) : QMediaPlayerControl(parent), m_mediaPlayerResolver(mediaPlayerResolver), m_session(NULL), m_stream(NULL) { } S60MediaPlayerControl::~S60MediaPlayerControl() { } qint64 S60MediaPlayerControl::position() const { if (m_session) return m_session->position(); return 0; } qint64 S60MediaPlayerControl::duration() const { if (m_session) return m_session->duration(); return -1; } QMediaPlayer::State S60MediaPlayerControl::state() const { if (m_session) return m_session->state(); return QMediaPlayer::StoppedState; } QMediaPlayer::MediaStatus S60MediaPlayerControl::mediaStatus() const { if (m_session) return m_session->mediaStatus(); return m_mediaSettings.mediaStatus(); } int S60MediaPlayerControl::bufferStatus() const { if (m_session) return m_session->bufferStatus(); return 0; } int S60MediaPlayerControl::volume() const { if (m_session) return m_session->volume(); return m_mediaSettings.volume(); } bool S60MediaPlayerControl::isMuted() const { if (m_session) return m_session->isMuted(); return m_mediaSettings.isMuted(); } bool S60MediaPlayerControl::isSeekable() const { if (m_session) return m_session->isSeekable(); return false; } QMediaTimeRange S60MediaPlayerControl::availablePlaybackRanges() const { QMediaTimeRange ranges; if(m_session && m_session->isSeekable()) ranges.addInterval(0, m_session->duration()); return ranges; } qreal S60MediaPlayerControl::playbackRate() const { //None of symbian players supports this. return m_mediaSettings.playbackRate(); } void S60MediaPlayerControl::setPlaybackRate(qreal rate) { //None of symbian players supports this. m_mediaSettings.setPlaybackRate(rate); emit playbackRateChanged(playbackRate()); } void S60MediaPlayerControl::setPosition(qint64 pos) { if (m_session) m_session->setPosition(pos); } void S60MediaPlayerControl::play() { if (m_session) m_session->play(); } void S60MediaPlayerControl::pause() { if (m_session) m_session->pause(); } void S60MediaPlayerControl::stop() { if (m_session) m_session->stop(); } void S60MediaPlayerControl::setVolume(int volume) { int boundVolume = qBound(0, volume, 100); if (boundVolume == m_mediaSettings.volume()) return; m_mediaSettings.setVolume(boundVolume); if (m_session) m_session->setVolume(boundVolume); emit volumeChanged(boundVolume); } void S60MediaPlayerControl::setMuted(bool muted) { if (m_mediaSettings.isMuted() == muted) return; m_mediaSettings.setMuted(muted); if (m_session) m_session->setMuted(muted); emit mutedChanged(muted); } QMediaContent S60MediaPlayerControl::media() const { return m_currentResource; } const QIODevice *S60MediaPlayerControl::mediaStream() const { return m_stream; } void S60MediaPlayerControl::setMedia(const QMediaContent &source, QIODevice *stream) { Q_UNUSED(stream) // we don't want to set & load media again when it is already loaded if (m_session && m_currentResource == source) return; // store to variable as session is created based on the content type. m_currentResource = source; S60MediaPlayerSession *newSession = m_mediaPlayerResolver.PlayerSession(); m_mediaSettings.setMediaStatus(QMediaPlayer::UnknownMediaStatus); if (m_session) m_session->reset(); else { emit mediaStatusChanged(QMediaPlayer::UnknownMediaStatus); emit error(QMediaPlayer::NoError, QString()); } m_session = newSession; if (m_session) m_session->load(source.canonicalUrl()); else { QMediaPlayer::MediaStatus status = (source.isNull()) ? QMediaPlayer::NoMedia : QMediaPlayer::InvalidMedia; m_mediaSettings.setMediaStatus(status); emit stateChanged(QMediaPlayer::StoppedState); emit error((source.isNull()) ? QMediaPlayer::NoError : QMediaPlayer::ResourceError, (source.isNull()) ? "" : tr("Media couldn't be resolved")); emit mediaStatusChanged(status); } emit mediaChanged(m_currentResource); } S60MediaPlayerSession* S60MediaPlayerControl::session() { return m_session; } void S60MediaPlayerControl::setVideoOutput(QObject *output) { S60MediaPlayerSession *session = NULL; session = m_mediaPlayerResolver.VideoPlayerSession(); session->setVideoRenderer(output); } bool S60MediaPlayerControl::isAudioAvailable() const { if (m_session) return m_session->isAudioAvailable(); return false; } bool S60MediaPlayerControl::isVideoAvailable() const { if (m_session) return m_session->isVideoAvailable(); return false; } const S60MediaSettings& S60MediaPlayerControl::mediaControlSettings() const { return m_mediaSettings; } void S60MediaPlayerControl::setAudioEndpoint(const QString& name) { m_mediaSettings.setAudioEndpoint(name); } <commit_msg>Symbian: minor cleanup<commit_after> /**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "s60mediaplayercontrol.h" #include "s60mediaplayersession.h" #include <QtCore/qdir.h> #include <QtCore/qurl.h> #include <QtCore/qdebug.h> S60MediaPlayerControl::S60MediaPlayerControl(MS60MediaPlayerResolver& mediaPlayerResolver, QObject *parent) : QMediaPlayerControl(parent), m_mediaPlayerResolver(mediaPlayerResolver), m_session(NULL), m_stream(NULL) { } S60MediaPlayerControl::~S60MediaPlayerControl() { } qint64 S60MediaPlayerControl::position() const { if (m_session) return m_session->position(); return 0; } qint64 S60MediaPlayerControl::duration() const { if (m_session) return m_session->duration(); return -1; } QMediaPlayer::State S60MediaPlayerControl::state() const { if (m_session) return m_session->state(); return QMediaPlayer::StoppedState; } QMediaPlayer::MediaStatus S60MediaPlayerControl::mediaStatus() const { if (m_session) return m_session->mediaStatus(); return m_mediaSettings.mediaStatus(); } int S60MediaPlayerControl::bufferStatus() const { if (m_session) return m_session->bufferStatus(); return 0; } int S60MediaPlayerControl::volume() const { if (m_session) return m_session->volume(); return m_mediaSettings.volume(); } bool S60MediaPlayerControl::isMuted() const { if (m_session) return m_session->isMuted(); return m_mediaSettings.isMuted(); } bool S60MediaPlayerControl::isSeekable() const { if (m_session) return m_session->isSeekable(); return false; } QMediaTimeRange S60MediaPlayerControl::availablePlaybackRanges() const { QMediaTimeRange ranges; if(m_session && m_session->isSeekable()) ranges.addInterval(0, m_session->duration()); return ranges; } qreal S60MediaPlayerControl::playbackRate() const { // TODO: Add Symbian^3 support return m_mediaSettings.playbackRate(); } void S60MediaPlayerControl::setPlaybackRate(qreal rate) { // TODO: Add Symbian^3 support m_mediaSettings.setPlaybackRate(rate); emit playbackRateChanged(playbackRate()); } void S60MediaPlayerControl::setPosition(qint64 pos) { if (m_session) m_session->setPosition(pos); } void S60MediaPlayerControl::play() { if (m_session) m_session->play(); } void S60MediaPlayerControl::pause() { if (m_session) m_session->pause(); } void S60MediaPlayerControl::stop() { if (m_session) m_session->stop(); } void S60MediaPlayerControl::setVolume(int volume) { int boundVolume = qBound(0, volume, 100); if (boundVolume == m_mediaSettings.volume()) return; m_mediaSettings.setVolume(boundVolume); if (m_session) m_session->setVolume(boundVolume); emit volumeChanged(boundVolume); } void S60MediaPlayerControl::setMuted(bool muted) { if (m_mediaSettings.isMuted() == muted) return; m_mediaSettings.setMuted(muted); if (m_session) m_session->setMuted(muted); emit mutedChanged(muted); } QMediaContent S60MediaPlayerControl::media() const { return m_currentResource; } const QIODevice *S60MediaPlayerControl::mediaStream() const { return m_stream; } void S60MediaPlayerControl::setMedia(const QMediaContent &source, QIODevice *stream) { Q_UNUSED(stream) // we don't want to set & load media again when it is already loaded if (m_session && m_currentResource == source) return; // store to variable as session is created based on the content type. m_currentResource = source; S60MediaPlayerSession *newSession = m_mediaPlayerResolver.PlayerSession(); m_mediaSettings.setMediaStatus(QMediaPlayer::UnknownMediaStatus); if (m_session) m_session->reset(); else { emit mediaStatusChanged(QMediaPlayer::UnknownMediaStatus); emit error(QMediaPlayer::NoError, QString()); } m_session = newSession; if (m_session) m_session->load(source.canonicalUrl()); else { QMediaPlayer::MediaStatus status = (source.isNull()) ? QMediaPlayer::NoMedia : QMediaPlayer::InvalidMedia; m_mediaSettings.setMediaStatus(status); emit stateChanged(QMediaPlayer::StoppedState); emit error((source.isNull()) ? QMediaPlayer::NoError : QMediaPlayer::ResourceError, (source.isNull()) ? "" : tr("Media couldn't be resolved")); emit mediaStatusChanged(status); } emit mediaChanged(m_currentResource); } S60MediaPlayerSession* S60MediaPlayerControl::session() { return m_session; } void S60MediaPlayerControl::setVideoOutput(QObject *output) { m_mediaPlayerResolver.VideoPlayerSession()->setVideoRenderer(output); } bool S60MediaPlayerControl::isAudioAvailable() const { if (m_session) return m_session->isAudioAvailable(); return false; } bool S60MediaPlayerControl::isVideoAvailable() const { if (m_session) return m_session->isVideoAvailable(); return false; } const S60MediaSettings& S60MediaPlayerControl::mediaControlSettings() const { return m_mediaSettings; } void S60MediaPlayerControl::setAudioEndpoint(const QString& name) { m_mediaSettings.setAudioEndpoint(name); } <|endoftext|>
<commit_before>/* Copyright 2017 QReal Research Group * * 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 "pioneerKit/blocks/pioneerBlocksFactory.h" using namespace pioneer::blocks; qReal::interpretation::Block *PioneerBlocksFactory::produceBlock(const qReal::Id &element) { Q_UNUSED(element); return nullptr; } qReal::IdList PioneerBlocksFactory::providedBlocks() const { return { id("GeoTakeoff") , id("GeoLanding") , id("GoToPoint") , id("GoToGPSPoint") , id("PioneerPrint") , id("PioneerSystem") , id("PioneerLed") , id("PioneerMagnet") , id("PioneerYaw") }; } qReal::IdList PioneerBlocksFactory::blocksToDisable() const { return { }; } qReal::IdList PioneerBlocksFactory::blocksToHide() const { return { id("Function") , id("SwitchBlock") , id("Loop") , id("Subprogram") , id("Fork") , id("Join") , id("KillThread") , id("SendMessageThreads") , id("ReceiveMessageThreads") , id("PrintText") , id("ClearScreen") , id("MarkerDown") , id("MarkerUp") }; } <commit_msg>GS request: hide If/EndIf blocks in PIONEER<commit_after>/* Copyright 2017 QReal Research Group * * 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 "pioneerKit/blocks/pioneerBlocksFactory.h" using namespace pioneer::blocks; qReal::interpretation::Block *PioneerBlocksFactory::produceBlock(const qReal::Id &element) { Q_UNUSED(element); return nullptr; } qReal::IdList PioneerBlocksFactory::providedBlocks() const { return { id("GeoTakeoff") , id("GeoLanding") , id("GoToPoint") , id("GoToGPSPoint") , id("PioneerPrint") , id("PioneerSystem") , id("PioneerLed") , id("PioneerMagnet") , id("PioneerYaw") }; } qReal::IdList PioneerBlocksFactory::blocksToDisable() const { return { }; } qReal::IdList PioneerBlocksFactory::blocksToHide() const { return { id("Function") , id("SwitchBlock") , id("Loop") , id("Subprogram") , id("Fork") , id("Join") , id("KillThread") , id("IfBlock") , id("FiBlock") , id("SendMessageThreads") , id("ReceiveMessageThreads") , id("PrintText") , id("ClearScreen") , id("MarkerDown") , id("MarkerUp") }; } <|endoftext|>
<commit_before>/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mem_map.h" #include <sys/mman.h> #include "ScopedFd.h" #include "utils.h" #define USE_ASHMEM 1 #ifdef USE_ASHMEM #include <cutils/ashmem.h> #endif namespace art { #if !defined(NDEBUG) static size_t ParseHex(const std::string& string) { CHECK_EQ(8U, string.size()); const char* str = string.c_str(); char* end; size_t value = strtoul(str, &end, 16); CHECK(end != str) << "Failed to parse hexadecimal value from " << string; CHECK_EQ(*end, '\0') << "Failed to parse hexadecimal value from " << string; return value; } static void CheckMapRegion(uint32_t base, uint32_t limit, uint32_t start, uint32_t end, const std::string& maps) { CHECK(!(base >= start && base < end) // start of new within old && !(limit > start && limit < end) // end of new within old && !(base <= start && limit > end)) // start/end of new includes all of old << StringPrintf("Requested region %08x-%08x overlaps with existing map %08x-%08x\n", base, limit, start, end) << maps; } void CheckMapRequest(byte* addr, size_t length) { if (addr == NULL) { return; } uint32_t base = reinterpret_cast<size_t>(addr); uint32_t limit = base + length; #if defined(__APPLE__) // Mac OS vmmap(1) output currently looks something like this: // Virtual Memory Map of process 51036 (dex2oatd) // Output report format: 2.2 -- 32-bit process // // ==== regions for process 51036 (non-writable and writable regions are interleaved) // __PAGEZERO 00000000-00001000 [ 4K 0K 0K] ---/--- SM=NUL out/host/darwin-x86/bin/dex2oatd // __TEXT 00001000-00015000 [ 80K 80K 0K] r-x/rwx SM=COW out/host/darwin-x86/bin/dex2oatd // __DATA 00015000-00016000 [ 4K 4K 4K] rw-/rwx SM=PRV out/host/darwin-x86/bin/dex2oatd // __LINKEDIT 00016000-00044000 [ 184K 184K 0K] r--/rwx SM=COW out/host/darwin-x86/bin/dex2oatd // __TEXT 00044000-00046000 [ 8K 8K 4K] r-x/rwx SM=COW out/host/darwin-x86/obj/lib/libnativehelper.dylib // __DATA 00046000-00047000 [ 4K 4K 4K] rw-/rwx SM=ZER out/host/darwin-x86/obj/lib/libnativehelper.dylib // __LINKEDIT 00047000-0004a000 [ 12K 12K 0K] r--/rwx SM=COW out/host/darwin-x86/obj/lib/libnativehelper.dylib // ... // TODO: the -v option replaces "-w -resident -dirty -purge -submap -allSplitLibs -noCoalesce" >= 10.6. std::string command(StringPrintf("vmmap -w -resident -submap -allSplitLibs -interleaved %d", getpid())); FILE* fp = popen(command.c_str(), "r"); if (fp == NULL) { PLOG(FATAL) << "popen failed"; } std::vector<char> chars(512); std::string maps; while (fgets(&chars[0], chars.size(), fp) != NULL) { std::string line(&chars[0]); maps += line; if (line.size() < 40 || line[31] != '-') { continue; } std::string start_str(line.substr(23, 8)); std::string end_str(line.substr(32, 8)); uint32_t start = ParseHex(start_str); uint32_t end = ParseHex(end_str); CheckMapRegion(base, limit, start, end, maps); } if (ferror(fp)) { PLOG(FATAL) << "fgets failed"; } if (pclose(fp) == -1) { PLOG(FATAL) << "pclose failed"; } #else // Linux std::string maps; bool read = ReadFileToString("/proc/self/maps", &maps); if (!read) { PLOG(FATAL) << "Failed to read /proc/self/maps"; } // Quick and dirty parse of output like shown below. We only focus // on grabbing the two 32-bit hex values at the start of each line // and will fail on wider addresses found on 64-bit systems. // 00008000-0001f000 r-xp 00000000 b3:01 273 /system/bin/toolbox // 0001f000-00021000 rw-p 00017000 b3:01 273 /system/bin/toolbox // 00021000-00029000 rw-p 00000000 00:00 0 [heap] // 40011000-40053000 r-xp 00000000 b3:01 1050 /system/lib/libc.so // 40053000-40056000 rw-p 00042000 b3:01 1050 /system/lib/libc.so // 40056000-40061000 rw-p 00000000 00:00 0 // 40061000-40063000 r-xp 00000000 b3:01 1107 /system/lib/libusbhost.so // 40063000-40064000 rw-p 00002000 b3:01 1107 /system/lib/libusbhost.so // 4009d000-400a0000 r-xp 00000000 b3:01 1022 /system/lib/liblog.so // 400a0000-400a1000 rw-p 00003000 b3:01 1022 /system/lib/liblog.so // 400b7000-400cc000 r-xp 00000000 b3:01 932 /system/lib/libm.so // 400cc000-400cd000 rw-p 00015000 b3:01 932 /system/lib/libm.so // 400cf000-400d0000 r--p 00000000 00:00 0 // 400e4000-400ec000 r--s 00000000 00:0b 388 /dev/__properties__ (deleted) // 400ec000-400fa000 r-xp 00000000 b3:01 1101 /system/lib/libcutils.so // 400fa000-400fb000 rw-p 0000e000 b3:01 1101 /system/lib/libcutils.so // 400fb000-4010a000 rw-p 00000000 00:00 0 // 4010d000-4010e000 r-xp 00000000 b3:01 929 /system/lib/libstdc++.so // 4010e000-4010f000 rw-p 00001000 b3:01 929 /system/lib/libstdc++.so // b0001000-b0009000 r-xp 00001000 b3:01 1098 /system/bin/linker // b0009000-b000a000 rw-p 00009000 b3:01 1098 /system/bin/linker // b000a000-b0015000 rw-p 00000000 00:00 0 // bee35000-bee56000 rw-p 00000000 00:00 0 [stack] // ffff0000-ffff1000 r-xp 00000000 00:00 0 [vectors] for (size_t i = 0; i < maps.size(); i++) { size_t remaining = maps.size() - i; if (remaining < 8+1+8) { // 00008000-0001f000 LOG(FATAL) << "Failed to parse at pos " << i << "\n" << maps; } std::string start_str(maps.substr(i, 8)); std::string end_str(maps.substr(i+1+8, 8)); uint32_t start = ParseHex(start_str); uint32_t end = ParseHex(end_str); CheckMapRegion(base, limit, start, end, maps); i += 8+1+8; i = maps.find('\n', i); CHECK(i != std::string::npos) << "Failed to find newline from pos " << i << "\n" << maps; } #endif } #else static void CheckMapRequest(byte*, size_t) { } #endif MemMap* MemMap::MapAnonymous(const char* name, byte* addr, size_t length, int prot) { CHECK_NE(0U, length); CHECK_NE(0, prot); size_t page_aligned_size = RoundUp(length, kPageSize); CheckMapRequest(addr, page_aligned_size); #ifdef USE_ASHMEM ScopedFd fd(ashmem_create_region(name, page_aligned_size)); int flags = MAP_PRIVATE; if (fd.get() == -1) { PLOG(ERROR) << "ashmem_create_region failed (" << name << ")"; return NULL; } #else ScopedFd fd(-1); int flags = MAP_PRIVATE | MAP_ANONYMOUS; #endif byte* actual = reinterpret_cast<byte*>(mmap(addr, page_aligned_size, prot, flags, fd.get(), 0)); if (actual == MAP_FAILED) { PLOG(ERROR) << "mmap failed (" << name << ")"; return NULL; } return new MemMap(actual, length, actual, page_aligned_size); } MemMap* MemMap::MapFileAtAddress(byte* addr, size_t length, int prot, int flags, int fd, off_t start) { CHECK_NE(0U, length); CHECK_NE(0, prot); CHECK_NE(0, flags & (MAP_SHARED | MAP_PRIVATE)); // adjust to be page-aligned int page_offset = start % kPageSize; off_t page_aligned_offset = start - page_offset; size_t page_aligned_size = RoundUp(length + page_offset, kPageSize); CheckMapRequest(addr, page_aligned_size); byte* actual = reinterpret_cast<byte*>(mmap(addr, page_aligned_size, prot, flags, fd, page_aligned_offset)); if (actual == MAP_FAILED) { PLOG(ERROR) << "mmap failed"; return NULL; } return new MemMap(actual + page_offset, length, actual, page_aligned_size); } MemMap::~MemMap() { if (base_begin_ == NULL && base_size_ == 0) { return; } int result = munmap(base_begin_, base_size_); if (result == -1) { PLOG(FATAL) << "munmap failed"; } } MemMap::MemMap(byte* begin, size_t size, void* base_begin, size_t base_size) : begin_(begin), size_(size), base_begin_(base_begin), base_size_(base_size) { CHECK(begin_ != NULL); CHECK_NE(size_, 0U); CHECK(base_begin_ != NULL); CHECK_NE(base_size_, 0U); }; } // namespace art <commit_msg>Better diagnostics when an anonymous mmap fails.<commit_after>/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mem_map.h" #include <sys/mman.h> #include "ScopedFd.h" #include "utils.h" #define USE_ASHMEM 1 #ifdef USE_ASHMEM #include <cutils/ashmem.h> #endif namespace art { #if !defined(NDEBUG) static size_t ParseHex(const std::string& string) { CHECK_EQ(8U, string.size()); const char* str = string.c_str(); char* end; size_t value = strtoul(str, &end, 16); CHECK(end != str) << "Failed to parse hexadecimal value from " << string; CHECK_EQ(*end, '\0') << "Failed to parse hexadecimal value from " << string; return value; } static void CheckMapRegion(uint32_t base, uint32_t limit, uint32_t start, uint32_t end, const std::string& maps) { CHECK(!(base >= start && base < end) // start of new within old && !(limit > start && limit < end) // end of new within old && !(base <= start && limit > end)) // start/end of new includes all of old << StringPrintf("Requested region %08x-%08x overlaps with existing map %08x-%08x\n", base, limit, start, end) << maps; } void CheckMapRequest(byte* addr, size_t length) { if (addr == NULL) { return; } uint32_t base = reinterpret_cast<size_t>(addr); uint32_t limit = base + length; #if defined(__APPLE__) // Mac OS vmmap(1) output currently looks something like this: // Virtual Memory Map of process 51036 (dex2oatd) // Output report format: 2.2 -- 32-bit process // // ==== regions for process 51036 (non-writable and writable regions are interleaved) // __PAGEZERO 00000000-00001000 [ 4K 0K 0K] ---/--- SM=NUL out/host/darwin-x86/bin/dex2oatd // __TEXT 00001000-00015000 [ 80K 80K 0K] r-x/rwx SM=COW out/host/darwin-x86/bin/dex2oatd // __DATA 00015000-00016000 [ 4K 4K 4K] rw-/rwx SM=PRV out/host/darwin-x86/bin/dex2oatd // __LINKEDIT 00016000-00044000 [ 184K 184K 0K] r--/rwx SM=COW out/host/darwin-x86/bin/dex2oatd // __TEXT 00044000-00046000 [ 8K 8K 4K] r-x/rwx SM=COW out/host/darwin-x86/obj/lib/libnativehelper.dylib // __DATA 00046000-00047000 [ 4K 4K 4K] rw-/rwx SM=ZER out/host/darwin-x86/obj/lib/libnativehelper.dylib // __LINKEDIT 00047000-0004a000 [ 12K 12K 0K] r--/rwx SM=COW out/host/darwin-x86/obj/lib/libnativehelper.dylib // ... // TODO: the -v option replaces "-w -resident -dirty -purge -submap -allSplitLibs -noCoalesce" >= 10.6. std::string command(StringPrintf("vmmap -w -resident -submap -allSplitLibs -interleaved %d", getpid())); FILE* fp = popen(command.c_str(), "r"); if (fp == NULL) { PLOG(FATAL) << "popen failed"; } std::vector<char> chars(512); std::string maps; while (fgets(&chars[0], chars.size(), fp) != NULL) { std::string line(&chars[0]); maps += line; if (line.size() < 40 || line[31] != '-') { continue; } std::string start_str(line.substr(23, 8)); std::string end_str(line.substr(32, 8)); uint32_t start = ParseHex(start_str); uint32_t end = ParseHex(end_str); CheckMapRegion(base, limit, start, end, maps); } if (ferror(fp)) { PLOG(FATAL) << "fgets failed"; } if (pclose(fp) == -1) { PLOG(FATAL) << "pclose failed"; } #else // Linux std::string maps; bool read = ReadFileToString("/proc/self/maps", &maps); if (!read) { PLOG(FATAL) << "Failed to read /proc/self/maps"; } // Quick and dirty parse of output like shown below. We only focus // on grabbing the two 32-bit hex values at the start of each line // and will fail on wider addresses found on 64-bit systems. // 00008000-0001f000 r-xp 00000000 b3:01 273 /system/bin/toolbox // 0001f000-00021000 rw-p 00017000 b3:01 273 /system/bin/toolbox // 00021000-00029000 rw-p 00000000 00:00 0 [heap] // 40011000-40053000 r-xp 00000000 b3:01 1050 /system/lib/libc.so // 40053000-40056000 rw-p 00042000 b3:01 1050 /system/lib/libc.so // 40056000-40061000 rw-p 00000000 00:00 0 // 40061000-40063000 r-xp 00000000 b3:01 1107 /system/lib/libusbhost.so // 40063000-40064000 rw-p 00002000 b3:01 1107 /system/lib/libusbhost.so // 4009d000-400a0000 r-xp 00000000 b3:01 1022 /system/lib/liblog.so // 400a0000-400a1000 rw-p 00003000 b3:01 1022 /system/lib/liblog.so // 400b7000-400cc000 r-xp 00000000 b3:01 932 /system/lib/libm.so // 400cc000-400cd000 rw-p 00015000 b3:01 932 /system/lib/libm.so // 400cf000-400d0000 r--p 00000000 00:00 0 // 400e4000-400ec000 r--s 00000000 00:0b 388 /dev/__properties__ (deleted) // 400ec000-400fa000 r-xp 00000000 b3:01 1101 /system/lib/libcutils.so // 400fa000-400fb000 rw-p 0000e000 b3:01 1101 /system/lib/libcutils.so // 400fb000-4010a000 rw-p 00000000 00:00 0 // 4010d000-4010e000 r-xp 00000000 b3:01 929 /system/lib/libstdc++.so // 4010e000-4010f000 rw-p 00001000 b3:01 929 /system/lib/libstdc++.so // b0001000-b0009000 r-xp 00001000 b3:01 1098 /system/bin/linker // b0009000-b000a000 rw-p 00009000 b3:01 1098 /system/bin/linker // b000a000-b0015000 rw-p 00000000 00:00 0 // bee35000-bee56000 rw-p 00000000 00:00 0 [stack] // ffff0000-ffff1000 r-xp 00000000 00:00 0 [vectors] for (size_t i = 0; i < maps.size(); i++) { size_t remaining = maps.size() - i; if (remaining < 8+1+8) { // 00008000-0001f000 LOG(FATAL) << "Failed to parse at pos " << i << "\n" << maps; } std::string start_str(maps.substr(i, 8)); std::string end_str(maps.substr(i+1+8, 8)); uint32_t start = ParseHex(start_str); uint32_t end = ParseHex(end_str); CheckMapRegion(base, limit, start, end, maps); i += 8+1+8; i = maps.find('\n', i); CHECK(i != std::string::npos) << "Failed to find newline from pos " << i << "\n" << maps; } #endif } #else static void CheckMapRequest(byte*, size_t) { } #endif MemMap* MemMap::MapAnonymous(const char* name, byte* addr, size_t length, int prot) { CHECK_NE(0U, length); CHECK_NE(0, prot); size_t page_aligned_size = RoundUp(length, kPageSize); CheckMapRequest(addr, page_aligned_size); #ifdef USE_ASHMEM ScopedFd fd(ashmem_create_region(name, page_aligned_size)); int flags = MAP_PRIVATE; if (fd.get() == -1) { PLOG(ERROR) << "ashmem_create_region failed (" << name << ")"; return NULL; } #else ScopedFd fd(-1); int flags = MAP_PRIVATE | MAP_ANONYMOUS; #endif byte* actual = reinterpret_cast<byte*>(mmap(addr, page_aligned_size, prot, flags, fd.get(), 0)); if (actual == MAP_FAILED) { PLOG(ERROR) << "mmap(" << reinterpret_cast<void*>(addr) << ", " << page_aligned_size << ", " << prot << ", " << flags << ", " << fd.get() << ", 0) failed for " << name; return NULL; } return new MemMap(actual, length, actual, page_aligned_size); } MemMap* MemMap::MapFileAtAddress(byte* addr, size_t length, int prot, int flags, int fd, off_t start) { CHECK_NE(0U, length); CHECK_NE(0, prot); CHECK_NE(0, flags & (MAP_SHARED | MAP_PRIVATE)); // adjust to be page-aligned int page_offset = start % kPageSize; off_t page_aligned_offset = start - page_offset; size_t page_aligned_size = RoundUp(length + page_offset, kPageSize); CheckMapRequest(addr, page_aligned_size); byte* actual = reinterpret_cast<byte*>(mmap(addr, page_aligned_size, prot, flags, fd, page_aligned_offset)); if (actual == MAP_FAILED) { PLOG(ERROR) << "mmap failed"; return NULL; } return new MemMap(actual + page_offset, length, actual, page_aligned_size); } MemMap::~MemMap() { if (base_begin_ == NULL && base_size_ == 0) { return; } int result = munmap(base_begin_, base_size_); if (result == -1) { PLOG(FATAL) << "munmap failed"; } } MemMap::MemMap(byte* begin, size_t size, void* base_begin, size_t base_size) : begin_(begin), size_(size), base_begin_(base_begin), base_size_(base_size) { CHECK(begin_ != NULL); CHECK_NE(size_, 0U); CHECK(base_begin_ != NULL); CHECK_NE(base_size_, 0U); }; } // namespace art <|endoftext|>
<commit_before>/* ** © 2014 by Philipp Dunkel <pip@pipobscure.com> ** Licensed under MIT License. */ void FSEvents::emitEvent(const char *path, UInt32 flags, UInt64 id) { if (!handler) return; NanScope(); v8::Local<v8::Value> argv[] = { NanNew<v8::String>(path), NanNew<v8::Number>(flags), NanNew<v8::Number>(id) }; handler->Call(3, argv); } NAN_METHOD(FSEvents::New) { NanScope(); char* path = static_cast<char *>(*NanUtf8String(args[0])); NanCallback *callback = new NanCallback(args[1].As<v8::Function>()); FSEvents *fse = new FSEvents(path, callback); fse->Wrap(args.This()); NanReturnValue(args.This()); } NAN_METHOD(FSEvents::Stop) { NanScope(); FSEvents* fse = node::ObjectWrap::Unwrap<FSEvents>(args.This()); fse->threadStop(); fse->asyncStop(); NanReturnValue(args.This()); } NAN_METHOD(FSEvents::Start) { NanScope(); FSEvents* fse = node::ObjectWrap::Unwrap<FSEvents>(args.This()); fse->asyncStart(); fse->threadStart(); NanReturnValue(args.This()); } <commit_msg>Fix NanUtf8String implementation<commit_after>/* ** © 2014 by Philipp Dunkel <pip@pipobscure.com> ** Licensed under MIT License. */ void FSEvents::emitEvent(const char *path, UInt32 flags, UInt64 id) { if (!handler) return; NanScope(); v8::Local<v8::Value> argv[] = { NanNew<v8::String>(path), NanNew<v8::Number>(flags), NanNew<v8::Number>(id) }; handler->Call(3, argv); } NAN_METHOD(FSEvents::New) { NanScope(); NanUtf8String *path = new NanUtf8String(args[0]); NanCallback *callback = new NanCallback(args[1].As<v8::Function>()); FSEvents *fse = new FSEvents(**path, callback); fse->Wrap(args.This()); NanReturnValue(args.This()); } NAN_METHOD(FSEvents::Stop) { NanScope(); FSEvents* fse = node::ObjectWrap::Unwrap<FSEvents>(args.This()); fse->threadStop(); fse->asyncStop(); NanReturnValue(args.This()); } NAN_METHOD(FSEvents::Start) { NanScope(); FSEvents* fse = node::ObjectWrap::Unwrap<FSEvents>(args.This()); fse->asyncStart(); fse->threadStart(); NanReturnValue(args.This()); } <|endoftext|>
<commit_before>#ifndef __MINEAR_HPP__ #define __MINEAR_HPP__ #include <memory> #include <iostream> namespace minear { template <class T> class Matrix { public: unsigned int n_rows; unsigned int n_cols; /* constructors and destructors */ Matrix<T>() : n_rows(0), n_cols(0), data(nullptr), insertion_index(0) {} Matrix<T>(const unsigned int n, const unsigned int m) : n_rows(n), n_cols(m), data(new T[n*m]), insertion_index(0) {}; Matrix<T>(const unsigned int n, const unsigned int m, const T value); Matrix<T>(const Matrix<T>&); Matrix<T>& operator=(const Matrix<T>&); Matrix<T>(Matrix<T>&&); Matrix<T>& operator=(Matrix<T>&&); ~Matrix<T>() { delete[] data; } /* data insertion */ Matrix<T>& operator<<(const T value); void reset_index() { insertion_index = 0; } /* data accessors */ inline T& operator()(const unsigned int i, const unsigned int j) { return data[i*n_cols + j]; } inline const T& operator() (const unsigned int i, const unsigned int j) const { return data[i*n_cols + j]; } /* printing */ friend std::ostream& operator<< (std::ostream& stream, const Matrix& a) { for (unsigned int i = 0; i < a.n_rows; i++) { for (unsigned int j = 0; j < a.n_cols; j++) stream << " " << a(i,j); stream << std::endl; } return stream; } /* memory management */ void resize(const unsigned int, const unsigned int); private: T* data; unsigned int insertion_index; }; template <class T> Matrix<T>::Matrix(const unsigned int n, const unsigned int m, const T value) : Matrix<T>(n,m) { for (unsigned int i = 0; i < n; i++) for (unsigned int j = 0; j < m; j++) (*this)(i,j) = value; } template <class T> Matrix<T>::Matrix(const Matrix<T>& a) : n_rows(a.n_rows), n_cols(a.n_cols) { data = new T[n_rows*n_cols]; for (unsigned int i = 0; i < n_rows; i++) for (unsigned int j = 0; j < n_cols; j++) (*this)(i,j) = a(i,j); } template <class T> Matrix<T>& Matrix<T>::operator=(const Matrix<T>& a) { resize(a.n_rows, a.n_cols); insertion_index = 0; for (unsigned int i = 0; i < n_rows; i++) for (unsigned int j = 0; j < n_cols; j++) (*this)(i,j) = a(i,j); return *this; } template <class T> Matrix<T>::Matrix(Matrix<T>&& a) : n_rows(a.n_rows), n_cols(a.n_cols), data(a.data), insertion_index(0) { a.data = nullptr; /* ensure nothing funny happens when a is deleted */ } template <class T> Matrix<T>& Matrix<T>::operator=(Matrix<T>&& a) { insertion_index = 0; /* delete old memory, move rvalue memory in */ T* p = data; data = a.data; delete[] p; n_rows = a.n_rows; n_cols = a.n_cols; a.data = nullptr; return *this; } template <class T> Matrix<T>& Matrix<T>::operator<<(const T value) { data[insertion_index] = value; insertion_index++; if (insertion_index == n_rows*n_cols) insertion_index = 0; return *this; } template <class T> Matrix<T> operator+(const Matrix<T>& a, const Matrix<T>& b) { /* TODO: make sure matrices are the same size */ Matrix<T> result(a.n_rows,a.n_cols); for (unsigned int i = 0; i < a.n_rows; i++) for (unsigned int j = 0; j < a.n_cols; j++) result(i,j) = a(i,j) + b(i,j); return result; } template <class T> Matrix<T> operator-(const Matrix<T>& a, const Matrix<T>& b) { /* TODO: make sure matrices are the same size */ Matrix<T> result(a.n_rows,a.n_cols); for (unsigned int i = 0; i < a.n_rows; i++) for (unsigned int j = 0; j < a.n_cols; j++) result(i,j) = a(i,j) - b(i,j); return result; } template <class T> Matrix<T> operator-(const Matrix<T>& a) { /* TODO: make sure matrices are the same size */ Matrix<T> result(a.n_rows,a.n_cols); for (unsigned int i = 0; i < a.n_rows; i++) for (unsigned int j = 0; j < a.n_cols; j++) result(i,j) = -a(i,j); return result; } template <class T> Matrix<T> operator*(const Matrix<T>& a, const Matrix<T>& b) { Matrix<T> result(a.n_rows,b.n_cols,0); for (unsigned int i = 0; i < a.n_rows; i++) { for (unsigned int j = 0; j < b.n_cols; j++) for (unsigned int k = 0; k < b.n_rows; k++) result(i,j) += a(i,k)*b(k,j); } return result; } template <class T> void Matrix<T>::resize(const unsigned int n, const unsigned int m) { if (sizeof(data)/sizeof(T) < n*m) { T* p = data; data = new T[n*m]; delete[] p; insertion_index = 0; } n_rows = n; n_cols = m; } } #endif /* __MINEAR_HPP__ */ <commit_msg>changed i++ to ++i just because<commit_after>#ifndef __MINEAR_HPP__ #define __MINEAR_HPP__ #include <memory> #include <iostream> namespace minear { template <class T> class Matrix { public: unsigned int n_rows; unsigned int n_cols; /* constructors and destructors */ Matrix<T>() : n_rows(0), n_cols(0), data(nullptr), insertion_index(0) {} Matrix<T>(const unsigned int n, const unsigned int m) : n_rows(n), n_cols(m), data(new T[n*m]), insertion_index(0) {}; Matrix<T>(const unsigned int n, const unsigned int m, const T value); Matrix<T>(const Matrix<T>&); Matrix<T>& operator=(const Matrix<T>&); Matrix<T>(Matrix<T>&&); Matrix<T>& operator=(Matrix<T>&&); ~Matrix<T>() { delete[] data; } /* data insertion */ Matrix<T>& operator<<(const T value); void reset_index() { insertion_index = 0; } /* data accessors */ inline T& operator()(const unsigned int i, const unsigned int j) { return data[i*n_cols + j]; } inline const T& operator() (const unsigned int i, const unsigned int j) const { return data[i*n_cols + j]; } /* printing */ friend std::ostream& operator<< (std::ostream& stream, const Matrix& a) { for (unsigned int i = 0; i < a.n_rows; ++i) { for (unsigned int j = 0; j < a.n_cols; ++j) stream << " " << a(i,j); stream << std::endl; } return stream; } /* memory management */ void resize(const unsigned int, const unsigned int); private: T* data; unsigned int insertion_index; }; template <class T> Matrix<T>::Matrix(const unsigned int n, const unsigned int m, const T value) : Matrix<T>(n,m) { for (unsigned int i = 0; i < n; ++i) for (unsigned int j = 0; j < m; ++j) (*this)(i,j) = value; } template <class T> Matrix<T>::Matrix(const Matrix<T>& a) : n_rows(a.n_rows), n_cols(a.n_cols) { data = new T[n_rows*n_cols]; for (unsigned int i = 0; i < n_rows; ++i) for (unsigned int j = 0; j < n_cols; ++j) (*this)(i,j) = a(i,j); } template <class T> Matrix<T>& Matrix<T>::operator=(const Matrix<T>& a) { resize(a.n_rows, a.n_cols); insertion_index = 0; for (unsigned int i = 0; i < n_rows; ++i) for (unsigned int j = 0; j < n_cols; ++j) (*this)(i,j) = a(i,j); return *this; } template <class T> Matrix<T>::Matrix(Matrix<T>&& a) : n_rows(a.n_rows), n_cols(a.n_cols), data(a.data), insertion_index(0) { a.data = nullptr; /* ensure nothing funny happens when a is deleted */ } template <class T> Matrix<T>& Matrix<T>::operator=(Matrix<T>&& a) { insertion_index = 0; /* delete old memory, move rvalue memory in */ T* p = data; data = a.data; delete[] p; n_rows = a.n_rows; n_cols = a.n_cols; a.data = nullptr; return *this; } template <class T> Matrix<T>& Matrix<T>::operator<<(const T value) { data[insertion_index] = value; insertion_index++; if (insertion_index == n_rows*n_cols) insertion_index = 0; return *this; } template <class T> Matrix<T> operator+(const Matrix<T>& a, const Matrix<T>& b) { /* TODO: make sure matrices are the same size */ Matrix<T> result(a.n_rows,a.n_cols); for (unsigned int i = 0; i < a.n_rows; ++i) for (unsigned int j = 0; j < a.n_cols; ++j) result(i,j) = a(i,j) + b(i,j); return result; } template <class T> Matrix<T> operator-(const Matrix<T>& a, const Matrix<T>& b) { /* TODO: make sure matrices are the same size */ Matrix<T> result(a.n_rows,a.n_cols); for (unsigned int i = 0; i < a.n_rows; ++i) for (unsigned int j = 0; j < a.n_cols; ++j) result(i,j) = a(i,j) - b(i,j); return result; } template <class T> Matrix<T> operator-(const Matrix<T>& a) { /* TODO: make sure matrices are the same size */ Matrix<T> result(a.n_rows,a.n_cols); for (unsigned int i = 0; i < a.n_rows; ++i) for (unsigned int j = 0; j < a.n_cols; ++j) result(i,j) = -a(i,j); return result; } template <class T> Matrix<T> operator*(const Matrix<T>& a, const Matrix<T>& b) { Matrix<T> result(a.n_rows,b.n_cols,0); for (unsigned int i = 0; i < a.n_rows; ++i) { for (unsigned int j = 0; j < b.n_cols; ++j) for (unsigned int k = 0; k < b.n_rows; ++k) result(i,j) += a(i,k)*b(k,j); } return result; } template <class T> void Matrix<T>::resize(const unsigned int n, const unsigned int m) { if (sizeof(data)/sizeof(T) < n*m) { T* p = data; data = new T[n*m]; delete[] p; insertion_index = 0; } n_rows = n; n_cols = m; } } #endif /* __MINEAR_HPP__ */ <|endoftext|>
<commit_before>#include "nixfile.h" #include "mex.h" #include <nix.hpp> #include "handle.h" #include "arguments.h" #include "struct.h" namespace nixfile { void open(const extractor &input, infusor &output) { std::string name = input.str(1); uint8_t omode = input.num<uint8_t>(2); nix::FileMode mode; switch (omode) { case 0: mode = nix::FileMode::ReadOnly; break; case 1: mode = nix::FileMode::ReadWrite; break; case 2: mode = nix::FileMode::Overwrite; break; default: throw std::invalid_argument("unkown open mode"); } nix::File fn = nix::File::open(name, mode); handle h = handle(fn); output.set(0, h); } void describe(const extractor &input, infusor &output) { nix::File fd = input.entity<nix::File>(1); struct_builder sb({ 1 }, { "blockCount", "sectionCount" }); sb.set(fd.blockCount()); sb.set(fd.sectionCount()); output.set(0, sb.array()); } void list_blocks(const extractor &input, infusor &output) { nix::File fd = input.entity<nix::File>(1); std::vector<nix::Block> blocks = fd.blocks(); struct_builder sb({ blocks.size() }, { "name", "id", "type" }); for (const auto &b : blocks) { sb.set(b.name()); sb.set(b.id()); sb.set(b.type()); sb.next(); } output.set(0, sb.array()); } void open_block(const extractor &input, infusor &output) { nix::File nf = input.entity<nix::File>(1); nix::Block block = nf.getBlock(input.str(2)); handle bb = handle(block); output.set(0, bb); } void blocks(const extractor &input, infusor &output) { nix::File nf = input.entity<nix::File>(1); std::vector<nix::Block> blocks = nf.blocks(); const mwSize size = static_cast<mwSize>(blocks.size()); mxArray *lst = mxCreateCellArray(1, &size); for (int i = 0; i < blocks.size(); i++) { mxSetCell(lst, i, make_mx_array(handle(blocks[i]))); } output.set(0, lst); } void list_sections(const extractor &input, infusor &output) { nix::File fd = input.entity<nix::File>(1); std::vector<nix::Section> secs = fd.sections(); struct_builder sb({ secs.size() }, { "name", "id", "type" }); for (const auto &b : secs) { sb.set(b.name()); sb.set(b.id()); sb.set(b.type()); sb.next(); } output.set(0, sb.array()); } void open_section(const extractor &input, infusor &output) { nix::File nf = input.entity<nix::File>(1); nix::Section sec = nf.getSection(input.str(2)); handle bb = handle(sec); output.set(0, bb); } void sections(const extractor &input, infusor &output) { nix::File nf = input.entity<nix::File>(1); std::vector<nix::Section> sections = nf.sections(); const mwSize size = static_cast<mwSize>(sections.size()); mxArray *lst = mxCreateCellArray(1, &size); for (int i = 0; i < sections.size(); i++) { mxSetCell(lst, i, make_mx_array(handle(sections[i]))); } output.set(0, lst); } } // namespace nixfile<commit_msg>[nixfile] use size_t in loops to avoid warning<commit_after>#include "nixfile.h" #include "mex.h" #include <nix.hpp> #include "handle.h" #include "arguments.h" #include "struct.h" namespace nixfile { void open(const extractor &input, infusor &output) { std::string name = input.str(1); uint8_t omode = input.num<uint8_t>(2); nix::FileMode mode; switch (omode) { case 0: mode = nix::FileMode::ReadOnly; break; case 1: mode = nix::FileMode::ReadWrite; break; case 2: mode = nix::FileMode::Overwrite; break; default: throw std::invalid_argument("unkown open mode"); } nix::File fn = nix::File::open(name, mode); handle h = handle(fn); output.set(0, h); } void describe(const extractor &input, infusor &output) { nix::File fd = input.entity<nix::File>(1); struct_builder sb({ 1 }, { "blockCount", "sectionCount" }); sb.set(fd.blockCount()); sb.set(fd.sectionCount()); output.set(0, sb.array()); } void list_blocks(const extractor &input, infusor &output) { nix::File fd = input.entity<nix::File>(1); std::vector<nix::Block> blocks = fd.blocks(); struct_builder sb({ blocks.size() }, { "name", "id", "type" }); for (const auto &b : blocks) { sb.set(b.name()); sb.set(b.id()); sb.set(b.type()); sb.next(); } output.set(0, sb.array()); } void open_block(const extractor &input, infusor &output) { nix::File nf = input.entity<nix::File>(1); nix::Block block = nf.getBlock(input.str(2)); handle bb = handle(block); output.set(0, bb); } void blocks(const extractor &input, infusor &output) { nix::File nf = input.entity<nix::File>(1); std::vector<nix::Block> blocks = nf.blocks(); const mwSize size = static_cast<mwSize>(blocks.size()); mxArray *lst = mxCreateCellArray(1, &size); for (size_t i = 0; i < blocks.size(); i++) { mxSetCell(lst, i, make_mx_array(handle(blocks[i]))); } output.set(0, lst); } void list_sections(const extractor &input, infusor &output) { nix::File fd = input.entity<nix::File>(1); std::vector<nix::Section> secs = fd.sections(); struct_builder sb({ secs.size() }, { "name", "id", "type" }); for (const auto &b : secs) { sb.set(b.name()); sb.set(b.id()); sb.set(b.type()); sb.next(); } output.set(0, sb.array()); } void open_section(const extractor &input, infusor &output) { nix::File nf = input.entity<nix::File>(1); nix::Section sec = nf.getSection(input.str(2)); handle bb = handle(sec); output.set(0, bb); } void sections(const extractor &input, infusor &output) { nix::File nf = input.entity<nix::File>(1); std::vector<nix::Section> sections = nf.sections(); const mwSize size = static_cast<mwSize>(sections.size()); mxArray *lst = mxCreateCellArray(1, &size); for (size_t i = 0; i < sections.size(); i++) { mxSetCell(lst, i, make_mx_array(handle(sections[i]))); } output.set(0, lst); } } // namespace nixfile <|endoftext|>
<commit_before>/* * Send notifications from a worker thread to the main thread. * * author: Max Kellermann <mk@cm4all.com> */ #include "notify.hxx" #include "gerrno.h" #include <inline/compiler.h> #include <event.h> #include <atomic> #include <assert.h> #include <unistd.h> #include <sys/eventfd.h> class Notify { public: notify_callback_t callback; void *callback_ctx; int fd; struct event event; std::atomic_bool pending; Notify() :pending(false) {} }; static void notify_event_callback(int fd, gcc_unused short event, void *ctx) { Notify *notify = (Notify *)ctx; uint64_t value; (void)read(fd, &value, sizeof(value)); if (notify->pending.exchange(false)) notify->callback(notify->callback_ctx); } Notify * notify_new(notify_callback_t callback, void *ctx, GError **error_r) { auto notify = new Notify(); notify->callback = callback; notify->callback_ctx = ctx; notify->fd = eventfd(0, EFD_NONBLOCK|EFD_CLOEXEC); if (notify->fd < 0) { set_error_errno_msg(error_r, "eventfd() failed"); return nullptr; } event_set(&notify->event, notify->fd, EV_READ|EV_PERSIST, notify_event_callback, notify); event_add(&notify->event, nullptr); return notify; } void notify_free(Notify *notify) { event_del(&notify->event); close(notify->fd); delete notify; } void notify_signal(Notify *notify) { if (!notify->pending.exchange(true)) { static constexpr uint64_t value = 1; (void)write(notify->fd, &value, sizeof(value)); } } void notify_enable(Notify *notify) { event_add(&notify->event, nullptr); } void notify_disable(Notify *notify) { event_del(&notify->event); } <commit_msg>notify: use class Event<commit_after>/* * Send notifications from a worker thread to the main thread. * * author: Max Kellermann <mk@cm4all.com> */ #include "notify.hxx" #include "gerrno.h" #include "event/Event.hxx" #include <inline/compiler.h> #include <atomic> #include <unistd.h> #include <sys/eventfd.h> class Notify { public: notify_callback_t callback; void *callback_ctx; int fd; Event event; std::atomic_bool pending; Notify() :pending(false) {} }; static void notify_event_callback(int fd, gcc_unused short event, void *ctx) { Notify *notify = (Notify *)ctx; uint64_t value; (void)read(fd, &value, sizeof(value)); if (notify->pending.exchange(false)) notify->callback(notify->callback_ctx); } Notify * notify_new(notify_callback_t callback, void *ctx, GError **error_r) { auto notify = new Notify(); notify->callback = callback; notify->callback_ctx = ctx; notify->fd = eventfd(0, EFD_NONBLOCK|EFD_CLOEXEC); if (notify->fd < 0) { set_error_errno_msg(error_r, "eventfd() failed"); return nullptr; } notify->event.Set(notify->fd, EV_READ|EV_PERSIST, notify_event_callback, notify); notify->event.Add(); return notify; } void notify_free(Notify *notify) { notify->event.Delete(); close(notify->fd); delete notify; } void notify_signal(Notify *notify) { if (!notify->pending.exchange(true)) { static constexpr uint64_t value = 1; (void)write(notify->fd, &value, sizeof(value)); } } void notify_enable(Notify *notify) { notify->event.Add(); } void notify_disable(Notify *notify) { notify->event.Delete(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: MDatabaseMetaDataHelper.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hjs $ $Date: 2004-06-25 18:31:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_ #define _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_ /* #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATASUPPLIER_HPP_ #include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XCLOSEABLE_HPP_ #include <com/sun/star/sdbc/XCloseable.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XCOLUMNLOCATE_HPP_ #include <com/sun/star/sdbc/XColumnLocate.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XCANCELLABLE_HPP_ #include <com/sun/star/util/XCancellable.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XWARNINGSSUPPLIER_HPP_ #include <com/sun/star/sdbc/XWarningsSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSETUPDATE_HPP_ #include <com/sun/star/sdbc/XResultSetUpdate.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XROWUPDATE_HPP_ #include <com/sun/star/sdbc/XRowUpdate.hpp> #endif #ifndef _CPPUHELPER_COMPBASE7_HXX_ #include <cppuhelper/compbase7.hxx> #endif */ #ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_ #include <comphelper/proparrhlp.hxx> #endif /* #ifndef _CONNECTIVITY_FILE_ASTATEMENT_HXX_ #include "file/FStatement.hxx" #endif #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #include "connectivity/CommonTools.hxx" #endif */ #ifndef _COMPHELPER_PROPERTYCONTAINER_HXX_ #include <comphelper/propertycontainer.hxx> #endif #ifndef _CONNECTIVITY_FDATABASEMETADATARESULTSET_HXX_ #include "FDatabaseMetaDataResultSet.hxx" #endif #ifndef _CONNECTIVITY_MAB_CONNECTION_HXX_ #include <MConnection.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif namespace connectivity { namespace mozab { class MDatabaseMetaDataHelper { public: MDatabaseMetaDataHelper( ); ~MDatabaseMetaDataHelper(); //PROXIED_FUNCTION sal_Bool getTableStrings( OConnection* _pCon, ::std::vector< ::rtl::OUString >& _rStrings, ::std::vector< ::rtl::OUString >& _rTypes); sal_Bool getTables( OConnection* _pCon, const ::rtl::OUString& tableNamePattern, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& types, ODatabaseMetaDataResultSet::ORows& _rRows); const ::rtl::OUString& getErrorString() { return m_aErrorString; } sal_Bool testLDAPConnection( OConnection* _pCon ); sal_Bool NewAddressBook( OConnection* _pCon,const ::rtl::OUString & aTableName); private: sal_Bool m_bProfileExists ; ::std::vector< ::rtl::OUString > m_aTableNames; ::std::vector< ::rtl::OUString > m_aTableTypes; ::rtl::OUString m_aErrorString; void setAbSpecificError( OConnection* _pCon, sal_Bool bGivenURI ); }; } } #endif // _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_ <commit_msg>INTEGRATION: CWS mozab05 (1.5.46); FILE MERGED 2005/01/27 11:30:11 windly 1.5.46.2: #i41444# mozab crash on solaris sparc 2005/01/17 05:30:54 windly 1.5.46.1: #i20088# Detect Mozilla Thunderbird Address Book: patchs for connectivity<commit_after>/************************************************************************* * * $RCSfile: MDatabaseMetaDataHelper.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2005-02-21 12:30:29 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_ #define _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_ /* #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATASUPPLIER_HPP_ #include <com/sun/star/sdbc/XResultSetMetaDataSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XCLOSEABLE_HPP_ #include <com/sun/star/sdbc/XCloseable.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XCOLUMNLOCATE_HPP_ #include <com/sun/star/sdbc/XColumnLocate.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XCANCELLABLE_HPP_ #include <com/sun/star/util/XCancellable.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XWARNINGSSUPPLIER_HPP_ #include <com/sun/star/sdbc/XWarningsSupplier.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSETUPDATE_HPP_ #include <com/sun/star/sdbc/XResultSetUpdate.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XROWUPDATE_HPP_ #include <com/sun/star/sdbc/XRowUpdate.hpp> #endif #ifndef _CPPUHELPER_COMPBASE7_HXX_ #include <cppuhelper/compbase7.hxx> #endif */ #ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_ #include <comphelper/proparrhlp.hxx> #endif /* #ifndef _CONNECTIVITY_FILE_ASTATEMENT_HXX_ #include "file/FStatement.hxx" #endif #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #include "connectivity/CommonTools.hxx" #endif */ #ifndef _COMPHELPER_PROPERTYCONTAINER_HXX_ #include <comphelper/propertycontainer.hxx> #endif #ifndef _CONNECTIVITY_FDATABASEMETADATARESULTSET_HXX_ #include "FDatabaseMetaDataResultSet.hxx" #endif #ifndef _CONNECTIVITY_MAB_CONNECTION_HXX_ #include <MConnection.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _COM_SUN_STAR_MOZILLA_MOZILLPRODUCTTYPE_HPP_ #include <com/sun/star/mozilla/MozillaProductType.hpp> #endif namespace connectivity { namespace mozab { class MDatabaseMetaDataHelper { public: MDatabaseMetaDataHelper( ); ~MDatabaseMetaDataHelper(); // sal_Bool getTableStrings( OConnection* _pCon, ::std::vector< ::rtl::OUString >& _rStrings, ::std::vector< ::rtl::OUString >& _rTypes); sal_Bool getTables( OConnection* _pCon, const ::rtl::OUString& tableNamePattern, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& types, ODatabaseMetaDataResultSet::ORows& _rRows); const ::rtl::OUString& getErrorString() { return m_aErrorString; } sal_Bool testLDAPConnection( OConnection* _pCon ); sal_Bool NewAddressBook( OConnection* _pCon,const ::rtl::OUString & aTableName); private: sal_Bool m_bProfileExists ; ::std::vector< ::rtl::OUString > m_aTableNames; ::std::vector< ::rtl::OUString > m_aTableTypes; ::rtl::OUString m_aErrorString; void setAbSpecificError( OConnection* _pCon, sal_Bool bGivenURI ); ::com::sun::star::mozilla::MozillaProductType m_ProductType; ::rtl::OUString m_ProfileName; }; } } #endif // _CONNECTIVITY_MAB_DATABASEMETADATAHELPER_HXX_ <|endoftext|>
<commit_before>#include "output.hpp" #include <cmath> #include <cstdint> #include <vector> #include <ctime> #include <cstdio> #include "math/vec.hpp" #include "stb_image_write.h" #include "util.hpp" #include "./srgb.hpp" namespace yks { static std::vector<uint8_t> encode_srgb(const std::vector<yks::vec3> fdata) { std::vector<uint8_t> bdata(fdata.size() * 3); for (size_t i = 0; i < fdata.size(); ++i) { bdata[i*3 + 0] = byte_from_linear(clamp(0.0f, fdata[i][0], 1.0f)); bdata[i*3 + 1] = byte_from_linear(clamp(0.0f, fdata[i][1], 1.0f)); bdata[i*3 + 2] = byte_from_linear(clamp(0.0f, fdata[i][2], 1.0f)); } return bdata; } void save_srgb_image(const std::vector<yks::vec3>& pixels, int width, int height) { std::vector<uint8_t> image_byte_data = encode_srgb(pixels); std::time_t t = std::time(nullptr); std::tm* tm = std::localtime(&t); char buffer[64]; std::sprintf(buffer, "%04d-%02d-%02d_%02d-%02d_output.png", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min); stbi_write_png(buffer, width, height, 3, image_byte_data.data(), 0); } } <commit_msg>Add second to the file timestamp too.<commit_after>#include "output.hpp" #include <cmath> #include <cstdint> #include <vector> #include <ctime> #include <cstdio> #include "math/vec.hpp" #include "stb_image_write.h" #include "util.hpp" #include "./srgb.hpp" namespace yks { static std::vector<uint8_t> encode_srgb(const std::vector<yks::vec3> fdata) { std::vector<uint8_t> bdata(fdata.size() * 3); for (size_t i = 0; i < fdata.size(); ++i) { bdata[i*3 + 0] = byte_from_linear(clamp(0.0f, fdata[i][0], 1.0f)); bdata[i*3 + 1] = byte_from_linear(clamp(0.0f, fdata[i][1], 1.0f)); bdata[i*3 + 2] = byte_from_linear(clamp(0.0f, fdata[i][2], 1.0f)); } return bdata; } void save_srgb_image(const std::vector<yks::vec3>& pixels, int width, int height) { std::vector<uint8_t> image_byte_data = encode_srgb(pixels); std::time_t t = std::time(nullptr); std::tm* tm = std::localtime(&t); char buffer[64]; std::sprintf(buffer, "%04d-%02d-%02d_%02d-%02d-%02d_output.png", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); stbi_write_png(buffer, width, height, 3, image_byte_data.data(), 0); } } <|endoftext|>
<commit_before> #include "util.hpp" #include "DiscoveryVisitor.hpp" #include "Export.hpp" #include <clang/Frontend/FrontendPluginRegistry.h> using namespace autobind; class AutobindPluginAction: public clang::PluginASTAction { protected: clang::ASTConsumer *CreateASTConsumer(clang::CompilerInstance &ci, llvm::StringRef path) { return newASTConsumer([path, &ci](clang::ASTContext &ctx) { ModuleManager mgr; discoverTranslationUnit(mgr, *ctx.getTranslationUnitDecl(), ci); for(const auto &item : mgr.moduleStream()) { mgr.module(item.first).setSourceTUPath(path); } mgr.codegen(std::cout); }); } bool ParseArgs(const clang::CompilerInstance &ci, const std::vector<std::string> &args) { return true; } }; static clang::FrontendPluginRegistry::Add<AutobindPluginAction> registration("autobind", "automatically generate " "Python bindings"); <commit_msg>Make the plugin, which can now be loaded, somewhat functional.<commit_after> #include <string> #include <fstream> #include "util.hpp" #include "DiscoveryVisitor.hpp" #include "Export.hpp" #include <clang/Frontend/FrontendPluginRegistry.h> using namespace autobind; class AutobindPluginAction: public clang::PluginASTAction { protected: clang::ASTConsumer *CreateASTConsumer(clang::CompilerInstance &ci, llvm::StringRef path) { // return nullptr; std::string pathString = path; return newASTConsumer([pathString, &ci](clang::ASTContext &ctx) { ModuleManager mgr; discoverTranslationUnit(mgr, *ctx.getTranslationUnitDecl(), ci); for(const auto &item : mgr.moduleStream()) { mgr.module(item.first).setSourceTUPath(pathString); } std::ofstream outStream("/tmp/output.cpp"); mgr.codegen(outStream); // mgr.codegen(std::cout); }); } bool ParseArgs(const clang::CompilerInstance &ci, const std::vector<std::string> &args) { return true; } }; static clang::FrontendPluginRegistry::Add<AutobindPluginAction> registration("autobind", "automatically generate " "Python bindings"); <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <tackat@kde.org> // Copyright 2007 Inge Wallin <ingwa@kde.org> // #include <QtGui/QApplication> #include <QtCore/QFile> #include <QtCore/QDir> #include <QtCore/QLocale> #include <QtCore/QSettings> #include <QtCore/QTranslator> #include <QtCore/QProcessEnvironment> #include "QtMainWindow.h" #include "MarbleDirs.h" #include "MarbleDebug.h" #include "MarbleTest.h" #include "MarbleLocale.h" #ifdef STATIC_BUILD #include <QtCore/QtPlugin> Q_IMPORT_PLUGIN(qjpeg) Q_IMPORT_PLUGIN(qsvg) #endif #ifdef Q_OS_MACX //for getting app bundle path #include <ApplicationServices/ApplicationServices.h> #endif using namespace Marble; int main(int argc, char *argv[]) { // The GraphicsSystem needs to be set before the instantiation of the // QApplication. Therefore we need to parse the current setting // in this unusual place :-/ QSettings * graphicsSettings = new QSettings("kde.org", "Marble Desktop Globe"); QString graphicsString = graphicsSettings->value("View/graphicsSystem", "raster").toString(); delete graphicsSettings; QApplication::setGraphicsSystem( graphicsString ); QApplication app(argc, argv); // Widget translation #ifdef Q_WS_MAEMO_5 // Work around http://bugreports.qt.nokia.com/browse/QTBUG-1313 QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); QString lang( "C" ); QStringList const locales = QStringList() << "LC_ALL" << "LC_MESSAGES" << "LANG" << "LANGUAGE"; foreach( const QString &locale, locales ) { if ( env.contains( locale ) && !env.value( locale ).isEmpty() ) { lang = env.value( locale, "C" ); break; } } lang = lang.section( '_', 0, 0 ); #else QString lang = QLocale::system().name().section('_', 0, 0); #endif QTranslator translator; translator.load( "marble-" + lang, MarbleDirs::path(QString("lang") ) ); app.installTranslator(&translator); // For non static builds on mac and win // we need to be sure we can find the qt image // plugins. In mac be sure to look in the // application bundle... #ifdef Q_WS_WIN QApplication::addLibraryPath( QApplication::applicationDirPath() + QDir::separator() + "plugins" ); #endif #ifdef Q_OS_MACX QApplication::instance()->setAttribute(Qt::AA_DontShowIconsInMenus); qDebug("Adding qt image plugins to plugin search path..."); CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle()); CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle); const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding()); CFRelease(myBundleRef); CFRelease(myMacPath); QString myPath(mypPathPtr); // if we are not in a bundle assume that the app is built // as a non bundle app and that image plugins will be // in system Qt frameworks. If the app is a bundle // lets try to set the qt plugin search path... if (myPath.contains(".app")) { myPath += "/Contents/plugins"; QApplication::addLibraryPath( myPath ); qDebug( "Added %s to plugin search path", qPrintable( myPath ) ); } #endif QString marbleDataPath; int dataPathIndex=0; MarbleGlobal::Profiles profiles = MarbleGlobal::detectProfiles(); QStringList args = QApplication::arguments(); for ( int i = 1; i < args.count(); ++i ) { const QString arg = args.at(i); if ( arg == "--debug-info" ) { MarbleDebug::enable = true; } else if ( arg.startsWith( "--marbledatapath=", Qt::CaseInsensitive ) ) { marbleDataPath = args.at(i).mid(17); } else if ( arg.compare( "--marbledatapath", Qt::CaseInsensitive ) == 0 ) { dataPathIndex = i + 1; marbleDataPath = args.value( dataPathIndex ); ++i; } else if ( arg == "--smallscreen" ) { profiles |= MarbleGlobal::SmallScreen; } else if ( arg == "--nosmallscreen" ) { profiles &= ~MarbleGlobal::SmallScreen; } else if ( arg == "--highresolution" ) { profiles |= MarbleGlobal::HighResolution; } else if ( arg == "--nohighresolution" ) { profiles &= ~MarbleGlobal::HighResolution; } } MarbleGlobal::getInstance()->setProfiles( profiles ); QLocale::MeasurementSystem const measurement = QLocale::system().measurementSystem(); Marble::MeasureSystem const marbleMeasurement = measurement == QLocale::ImperialSystem ? Marble::Imperial : Marble::Metric; MarbleGlobal::getInstance()->locale()->setMeasureSystem( marbleMeasurement ); MainWindow *window = new MainWindow( marbleDataPath ); window->setAttribute( Qt::WA_DeleteOnClose, true ); MarbleTest *marbleTest = new MarbleTest( window->marbleWidget() ); // window->marbleWidget()->rotateTo( 0, 0, -90 ); // window->show(); for ( int i = 1; i < args.count(); ++i ) { const QString arg = args.at(i); if ( arg == "--timedemo" ) { window->resize(900, 640); marbleTest->timeDemo(); return 0; } else if( arg == "--gpsdemo" ) { window->resize( 900, 640 ); marbleTest->gpsDemo(); return 0; } else if( arg == "--fps" ) { window->marbleControl()->marbleWidget()->setShowFrameRate( true ); } else if( arg == "--enableCurrentLocation" ) { window->marbleControl()->setCurrentLocationTabShown(true); } else if( arg == "--enableFileView" ) { window->marbleControl()->setFileViewTabShown(true); } else if ( arg == "--tile-id" ) { window->marbleControl()->marbleWidget()->setShowTileId(true); } else if ( i != dataPathIndex && QFile::exists( arg ) ) ( window->marbleControl() )->addGeoDataFile( arg ); } delete marbleTest; return app.exec(); } <commit_msg>Implement -h/--help.<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <tackat@kde.org> // Copyright 2007 Inge Wallin <ingwa@kde.org> // #include <QtGui/QApplication> #include <QtCore/QFile> #include <QtCore/QDir> #include <QtCore/QLocale> #include <QtCore/QSettings> #include <QtCore/QTranslator> #include <QtCore/QProcessEnvironment> #include "QtMainWindow.h" #include "MarbleDirs.h" #include "MarbleDebug.h" #include "MarbleTest.h" #include "MarbleLocale.h" #ifdef STATIC_BUILD #include <QtCore/QtPlugin> Q_IMPORT_PLUGIN(qjpeg) Q_IMPORT_PLUGIN(qsvg) #endif #ifdef Q_OS_MACX //for getting app bundle path #include <ApplicationServices/ApplicationServices.h> #endif using namespace Marble; int main(int argc, char *argv[]) { // The GraphicsSystem needs to be set before the instantiation of the // QApplication. Therefore we need to parse the current setting // in this unusual place :-/ QSettings * graphicsSettings = new QSettings("kde.org", "Marble Desktop Globe"); QString graphicsString = graphicsSettings->value("View/graphicsSystem", "raster").toString(); delete graphicsSettings; QApplication::setGraphicsSystem( graphicsString ); QApplication app(argc, argv); // Widget translation #ifdef Q_WS_MAEMO_5 // Work around http://bugreports.qt.nokia.com/browse/QTBUG-1313 QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); QString lang( "C" ); QStringList const locales = QStringList() << "LC_ALL" << "LC_MESSAGES" << "LANG" << "LANGUAGE"; foreach( const QString &locale, locales ) { if ( env.contains( locale ) && !env.value( locale ).isEmpty() ) { lang = env.value( locale, "C" ); break; } } lang = lang.section( '_', 0, 0 ); #else QString lang = QLocale::system().name().section('_', 0, 0); #endif QTranslator translator; translator.load( "marble-" + lang, MarbleDirs::path(QString("lang") ) ); app.installTranslator(&translator); // For non static builds on mac and win // we need to be sure we can find the qt image // plugins. In mac be sure to look in the // application bundle... #ifdef Q_WS_WIN QApplication::addLibraryPath( QApplication::applicationDirPath() + QDir::separator() + "plugins" ); #endif #ifdef Q_OS_MACX QApplication::instance()->setAttribute(Qt::AA_DontShowIconsInMenus); qDebug("Adding qt image plugins to plugin search path..."); CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle()); CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle); const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding()); CFRelease(myBundleRef); CFRelease(myMacPath); QString myPath(mypPathPtr); // if we are not in a bundle assume that the app is built // as a non bundle app and that image plugins will be // in system Qt frameworks. If the app is a bundle // lets try to set the qt plugin search path... if (myPath.contains(".app")) { myPath += "/Contents/plugins"; QApplication::addLibraryPath( myPath ); qDebug( "Added %s to plugin search path", qPrintable( myPath ) ); } #endif QString marbleDataPath; int dataPathIndex=0; MarbleGlobal::Profiles profiles = MarbleGlobal::detectProfiles(); QStringList args = QApplication::arguments(); if ( args.contains( "-h" ) || args.contains( "--help" ) ) { qWarning() << "Usage: marble [options] [files]"; qWarning(); qWarning() << "[files] can be zero, one or more .kml and/or .gpx files to load and show."; qWarning(); qWarning() << "general options:"; qWarning() << " --marbledatapath=<path> .... Overwrite the compile-time path to map themes and other data"; qWarning() << " --enableFileView ........... Add a tab on the left showing detailed information about loaded files"; qWarning(); qWarning() << "debug options:"; qWarning() << " --debug-info ............... write (more) debugging information to the console"; qWarning() << " --fps ...................... Show the paint performance (paint rate) in the top left corner"; qWarning() << " --tile-id................... Write the identifier of texture tiles on top of them"; qWarning() << " --timedemo ................. Measure the paint performance while moving the map and quit"; qWarning(); qWarning() << "profile options (note that marble should automatically detect which profile to use. Override that with the options below):"; qWarning() << " --smallscreen .............. Enforce the profile for devices with small screens (e.g. smartphones)"; qWarning() << " --highresolution ........... Enforce the profile for devices with high resolution (e.g. desktop computers)"; qWarning() << " --nosmallscreen ............ Deactivate the profile for devices with small screens (e.g. smartphones)"; qWarning() << " --nohighresolution ......... Deactivate the profile for devices with high resolution (e.g. desktop computers)"; return 0; } for ( int i = 1; i < args.count(); ++i ) { const QString arg = args.at(i); if ( arg == "--debug-info" ) { MarbleDebug::enable = true; } else if ( arg.startsWith( "--marbledatapath=", Qt::CaseInsensitive ) ) { marbleDataPath = args.at(i).mid(17); } else if ( arg.compare( "--marbledatapath", Qt::CaseInsensitive ) == 0 ) { dataPathIndex = i + 1; marbleDataPath = args.value( dataPathIndex ); ++i; } else if ( arg == "--smallscreen" ) { profiles |= MarbleGlobal::SmallScreen; } else if ( arg == "--nosmallscreen" ) { profiles &= ~MarbleGlobal::SmallScreen; } else if ( arg == "--highresolution" ) { profiles |= MarbleGlobal::HighResolution; } else if ( arg == "--nohighresolution" ) { profiles &= ~MarbleGlobal::HighResolution; } } MarbleGlobal::getInstance()->setProfiles( profiles ); QLocale::MeasurementSystem const measurement = QLocale::system().measurementSystem(); Marble::MeasureSystem const marbleMeasurement = measurement == QLocale::ImperialSystem ? Marble::Imperial : Marble::Metric; MarbleGlobal::getInstance()->locale()->setMeasureSystem( marbleMeasurement ); MainWindow *window = new MainWindow( marbleDataPath ); window->setAttribute( Qt::WA_DeleteOnClose, true ); MarbleTest *marbleTest = new MarbleTest( window->marbleWidget() ); // window->marbleWidget()->rotateTo( 0, 0, -90 ); // window->show(); for ( int i = 1; i < args.count(); ++i ) { const QString arg = args.at(i); if ( arg == "--timedemo" ) { window->resize(900, 640); marbleTest->timeDemo(); return 0; } else if( arg == "--gpsdemo" ) { window->resize( 900, 640 ); marbleTest->gpsDemo(); return 0; } else if( arg == "--fps" ) { window->marbleControl()->marbleWidget()->setShowFrameRate( true ); } else if( arg == "--enableCurrentLocation" ) { window->marbleControl()->setCurrentLocationTabShown(true); } else if( arg == "--enableFileView" ) { window->marbleControl()->setFileViewTabShown(true); } else if ( arg == "--tile-id" ) { window->marbleControl()->marbleWidget()->setShowTileId(true); } else if ( i != dataPathIndex && QFile::exists( arg ) ) ( window->marbleControl() )->addGeoDataFile( arg ); } delete marbleTest; return app.exec(); } <|endoftext|>
<commit_before>#include <iostream> /* allows to perform standard input and output operations */ #include <fstream> #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <ctype.h> /* isxxx() */ #include <ros/ros.h> /* ROS */ #include <geometry_msgs/Twist.h> /* ROS Twist message */ #include <base_controller/encoders.h> /* Custom message /encoders */ #include <base_controller/md49data.h> /* Custom message /encoders */ #include <serialport/serialport.h> #define REPLY_SIZE 18 #define TIMEOUT 1000 int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ char reply[REPLY_SIZE]; unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ unsigned char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */ double vr = 0.0; double vl = 0.0; double max_vr = 0.2; double max_vl = 0.2; double min_vr = 0.2; double min_vl = 0.2; double base_width = 0.4; /* Base width in meters */ //unsigned char serialBuffer[18]; /* Serial buffer to store uart data */ void read_MD49_Data (void); void set_MD49_speed (unsigned char speed_l, unsigned char speed_r); char* itoa(int value, char* result, int base); using namespace std; cereal::CerealPort device; base_controller::encoders encoders; base_controller::md49data md49data; void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){ if (vel_cmd.linear.x>0){ speed_l = 255; speed_r = 255; } if (vel_cmd.linear.x<0){ speed_l = 0; speed_r = 0; } if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){ speed_l = 128; speed_r = 128; } if (vel_cmd.angular.z>0){ speed_l = 0; speed_r = 255; } if (vel_cmd.angular.z<0){ speed_l = 255; speed_r = 0; } if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){ //set_MD49_speed(speed_l,speed_r); last_speed_l=speed_l; last_speed_r=speed_r; } /* //ANFANG Alternative if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;} else if(vel_cmd.linear.x == 0){ // turning vr = vel_cmd.angular.z * base_width / 2.0; vl = (-1) * vr; } else if(vel_cmd.angular.z == 0){ // forward / backward vl = vr = vel_cmd.linear.x; } else{ // moving doing arcs vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0; if (vl > max_vl) {vl=max_vl;} if (vl < min_vl) {vl=min_vl;} vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0; if (vr > max_vr) {vr=max_vr;} if (vr < min_vr) {vr=min_vr;} } //ENDE Alternative */ } int main( int argc, char* argv[] ){ ros::init(argc, argv, "base_controller" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback); ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10); ros::Publisher md49data_pub = n.advertise<base_controller::md49data>("md49data",10); // Init node // ********* ros::Rate loop_rate(10); ROS_INFO("base_controller running..."); ROS_INFO("============================="); ROS_INFO("Subscribing to topic /cmd_vel"); ROS_INFO("Publishing to topic /encoders"); ROS_INFO("Publishing to topic /md49data"); sleep(2); // Open serial port // **************** try{ device.open("/dev/ttyAMA0", 38400); } catch(cereal::Exception& e) { ROS_FATAL("Failed to open the serial port!!!"); ROS_BREAK(); } ROS_INFO("The serial port is opened."); while(n.ok()) { // Read encoder and other data from MD49 // (data is read from serial_controller_node // and avaiable through md49_data.txt) // ***************************************** read_MD49_Data(); // Publish encoder values to topic /encoders (custom message) // ********************************************************** encoders.encoder_l=EncoderL; encoders.encoder_r=EncoderR; encoders_pub.publish(encoders); // Publish MD49 data to topic /md49data (custom message) // ***************************************************** md49data.speed_l = reply[8]; md49data.speed_r = reply[9]; md49data.volt = reply[10]; md49data.current_l = reply[11]; md49data.current_r = reply[12]; md49data.error = reply[13]; md49data.acceleration = reply[14]; md49data.mode = reply[15]; md49data.regulator = reply[16]; md49data.timeout = reply[17]; md49data_pub.publish(md49data); // **** ros::spinOnce(); loop_rate.sleep(); }// end.mainloop return 1; } // end.main void read_MD49_Data (void){ // Send 'R' over the serial port device.write("R"); // Get the reply, the last value is the timeout in ms try{ device.read(reply, REPLY_SIZE, TIMEOUT); } catch(cereal::TimeoutException& e) { ROS_ERROR("Timeout on serialport! No data read"); } //ROS_INFO("Received MD49 data"); // Put toghether new encodervalues // ******************************* EncoderL = reply[0] << 24; // Put together first encoder value EncoderL |= (reply[1] << 16); EncoderL |= (reply[2] << 8); EncoderL |= (reply[3]); EncoderR = reply[4] << 24; // Put together second encoder value EncoderR |= (reply[5] << 16); EncoderR |= (reply[6] << 8); EncoderR |= (reply[7]); /* // Output MD49 data on screen // ************************** printf("\033[2J"); // clear the screen printf("\033[H"); // position cursor at top-left corner printf ("MD49-Data read from AVR-Master: \n"); printf("========================================\n"); printf("Encoder1 Byte1: %i ",reply[0]); printf("Byte2: %i ",reply[1]); printf("Byte3: % i ",reply[2]); printf("Byte4: %i \n",reply[3]); printf("Encoder2 Byte1: %i ",reply[4]); printf("Byte2: %i ",reply[5]); printf("Byte3: %i ",reply[6]); printf("Byte4: %i \n",reply[7]); printf("EncoderL: %i ",EncoderL); printf("EncoderR: %i \n",EncoderR); printf("========================================\n"); printf("Speed1: %i ",reply[8]); printf("Speed2: %i \n",reply[9]); printf("Volts: %i \n",reply[10]); printf("Current1: %i ",reply[11]); printf("Current2: %i \n",reply[12]); printf("Error: %i \n",reply[13]); printf("Acceleration: %i \n",reply[14]); printf("Mode: %i \n",reply[15]); printf("Regulator: %i \n",reply[16]); printf("Timeout: %i \n",reply[17]); */ } void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){ /* char buffer[33]; ofstream myfile; myfile.open ("md49_commands.txt"); //myfile << "Writing this to a file.\n"; if (speed_l==0){ myfile << "000"; myfile << "\n"; } else if (speed_l<10){ myfile << "00"; myfile << itoa(speed_l,buffer,10); myfile << "\n"; } else if (speed_l<100){ myfile << "0"; myfile << itoa(speed_l,buffer,10); myfile << "\n"; } else{ myfile << itoa(speed_l,buffer,10); myfile << "\n"; } if (speed_r==0){ myfile << "000"; myfile << "\n"; } else if (speed_r<10){ myfile << "00"; myfile << itoa(speed_r,buffer,10); myfile << "\n"; } else if (speed_r<100){ myfile << "0"; myfile << itoa(speed_r,buffer,10); myfile << "\n"; } else{ myfile << itoa(speed_r,buffer,10); myfile << "\n"; } myfile.close(); */ } char* itoa(int value, char* result, int base) { // check that the base if valid if (base < 2 || base > 36) { *result = '\0'; return result; } char* ptr = result, *ptr1 = result, tmp_char; int tmp_value; do { tmp_value = value; value /= base; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)]; } while ( value ); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while(ptr1 < ptr) { tmp_char = *ptr; *ptr--= *ptr1; *ptr1++ = tmp_char; } return result; } <commit_msg>Update code<commit_after>#include <iostream> /* allows to perform standard input and output operations */ #include <fstream> #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <ctype.h> /* isxxx() */ #include <ros/ros.h> /* ROS */ #include <geometry_msgs/Twist.h> /* ROS Twist message */ #include <base_controller/encoders.h> /* Custom message /encoders */ #include <base_controller/md49data.h> /* Custom message /encoders */ #include <serialport/serialport.h> #define REPLY_SIZE 18 #define TIMEOUT 1000 int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ char reply[REPLY_SIZE]; unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ unsigned char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */ double vr = 0.0; double vl = 0.0; double max_vr = 0.2; double max_vl = 0.2; double min_vr = 0.2; double min_vl = 0.2; double base_width = 0.4; /* Base width in meters */ //unsigned char serialBuffer[18]; /* Serial buffer to store uart data */ void read_MD49_Data (void); void set_MD49_speed (unsigned char speed_l, unsigned char speed_r); char* itoa(int value, char* result, int base); using namespace std; cereal::CerealPort device; base_controller::encoders encoders; base_controller::md49data md49data; void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){ if (vel_cmd.linear.x>0){ speed_l = 255; speed_r = 255; } if (vel_cmd.linear.x<0){ speed_l = 0; speed_r = 0; } if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){ speed_l = 128; speed_r = 128; } if (vel_cmd.angular.z>0){ speed_l = 0; speed_r = 255; } if (vel_cmd.angular.z<0){ speed_l = 255; speed_r = 0; } if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){ //set_MD49_speed(speed_l,speed_r); last_speed_l=speed_l; last_speed_r=speed_r; } /* //ANFANG Alternative if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;} else if(vel_cmd.linear.x == 0){ // turning vr = vel_cmd.angular.z * base_width / 2.0; vl = (-1) * vr; } else if(vel_cmd.angular.z == 0){ // forward / backward vl = vr = vel_cmd.linear.x; } else{ // moving doing arcs vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0; if (vl > max_vl) {vl=max_vl;} if (vl < min_vl) {vl=min_vl;} vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0; if (vr > max_vr) {vr=max_vr;} if (vr < min_vr) {vr=min_vr;} } //ENDE Alternative */ } int main( int argc, char* argv[] ){ ros::init(argc, argv, "base_controller" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback); ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10); ros::Publisher md49data_pub = n.advertise<base_controller::md49data>("md49data",10); // Init node // ********* ros::Rate loop_rate(10); ROS_INFO("base_controller running..."); ROS_INFO("============================="); ROS_INFO("Subscribing to topic /cmd_vel"); ROS_INFO("Publishing to topic /encoders"); ROS_INFO("Publishing to topic /md49data"); // Open serial port // **************** try{ device.open("/dev/ttyAMA0", 38400); } catch(cereal::Exception& e) { ROS_FATAL("Failed to open the serial port!!!"); ROS_BREAK(); } ROS_INFO("The serial port is opened."); while(n.ok()) { // Read encoder and other data from MD49 // (data is read from serial_controller_node // and avaiable through md49_data.txt) // ***************************************** read_MD49_Data(); // Publish encoder values to topic /encoders (custom message) // ********************************************************** encoders.encoder_l=EncoderL; encoders.encoder_r=EncoderR; encoders_pub.publish(encoders); // Publish MD49 data to topic /md49data (custom message) // ***************************************************** md49data.speed_l = reply[8]; md49data.speed_r = reply[9]; md49data.volt = reply[10]; md49data.current_l = reply[11]; md49data.current_r = reply[12]; md49data.error = reply[13]; md49data.acceleration = reply[14]; md49data.mode = reply[15]; md49data.regulator = reply[16]; md49data.timeout = reply[17]; md49data_pub.publish(md49data); // **** ros::spinOnce(); loop_rate.sleep(); }// end.mainloop return 1; } // end.main void read_MD49_Data (void){ // Send 'R' over the serial port device.write("R"); // Get the reply, the last value is the timeout in ms try{ device.read(reply, REPLY_SIZE, TIMEOUT); } catch(cereal::TimeoutException& e) { ROS_ERROR("Timeout on serialport! No data read"); } //ROS_INFO("Received MD49 data"); // Put toghether new encodervalues // ******************************* EncoderL = reply[0] << 24; // Put together first encoder value EncoderL |= (reply[1] << 16); EncoderL |= (reply[2] << 8); EncoderL |= (reply[3]); EncoderR = reply[4] << 24; // Put together second encoder value EncoderR |= (reply[5] << 16); EncoderR |= (reply[6] << 8); EncoderR |= (reply[7]); /* // Output MD49 data on screen // ************************** printf("\033[2J"); // clear the screen printf("\033[H"); // position cursor at top-left corner printf ("MD49-Data read from AVR-Master: \n"); printf("========================================\n"); printf("Encoder1 Byte1: %i ",reply[0]); printf("Byte2: %i ",reply[1]); printf("Byte3: % i ",reply[2]); printf("Byte4: %i \n",reply[3]); printf("Encoder2 Byte1: %i ",reply[4]); printf("Byte2: %i ",reply[5]); printf("Byte3: %i ",reply[6]); printf("Byte4: %i \n",reply[7]); printf("EncoderL: %i ",EncoderL); printf("EncoderR: %i \n",EncoderR); printf("========================================\n"); printf("Speed1: %i ",reply[8]); printf("Speed2: %i \n",reply[9]); printf("Volts: %i \n",reply[10]); printf("Current1: %i ",reply[11]); printf("Current2: %i \n",reply[12]); printf("Error: %i \n",reply[13]); printf("Acceleration: %i \n",reply[14]); printf("Mode: %i \n",reply[15]); printf("Regulator: %i \n",reply[16]); printf("Timeout: %i \n",reply[17]); */ } void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){ /* char buffer[33]; ofstream myfile; myfile.open ("md49_commands.txt"); //myfile << "Writing this to a file.\n"; if (speed_l==0){ myfile << "000"; myfile << "\n"; } else if (speed_l<10){ myfile << "00"; myfile << itoa(speed_l,buffer,10); myfile << "\n"; } else if (speed_l<100){ myfile << "0"; myfile << itoa(speed_l,buffer,10); myfile << "\n"; } else{ myfile << itoa(speed_l,buffer,10); myfile << "\n"; } if (speed_r==0){ myfile << "000"; myfile << "\n"; } else if (speed_r<10){ myfile << "00"; myfile << itoa(speed_r,buffer,10); myfile << "\n"; } else if (speed_r<100){ myfile << "0"; myfile << itoa(speed_r,buffer,10); myfile << "\n"; } else{ myfile << itoa(speed_r,buffer,10); myfile << "\n"; } myfile.close(); */ } char* itoa(int value, char* result, int base) { // check that the base if valid if (base < 2 || base > 36) { *result = '\0'; return result; } char* ptr = result, *ptr1 = result, tmp_char; int tmp_value; do { tmp_value = value; value /= base; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)]; } while ( value ); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while(ptr1 < ptr) { tmp_char = *ptr; *ptr--= *ptr1; *ptr1++ = tmp_char; } return result; } <|endoftext|>
<commit_before>/* * This file is part of the UnTech Editor Suite. * Copyright (c) 2016 - 2019, Marcus Rowe <undisbeliever@gmail.com>. * Distributed under The MIT License: https://opensource.org/licenses/MIT */ #include "cartridge.h" #include <array> #include <cassert> #include <climits> #include <fstream> #include <stdexcept> using namespace UnTech::Snes; using namespace UnTech::Snes::Cartridge; constexpr size_t HEADER_ADDR = 0xffb0; constexpr size_t CHECKSUM_COMPLEMENT_ADDR = 0xffdc; constexpr size_t CHECKSUM_ADDR = 0xffde; constexpr unsigned MIN_ROM_SIZE = 64 * 1024; constexpr unsigned MAX_ROM_SIZE = 4 * 1024 * 1024; #define MIN_ROM_STRING "64 KiB" #define MAX_ROM_STRING "4 MiB" size_t Cartridge::headerAddress(MemoryMap memoryMap) { switch (memoryMap) { case MemoryMap::LOROM: return HEADER_ADDR - 0x8000; case MemoryMap::HIROM: return HEADER_ADDR; } throw std::invalid_argument("invalid MemoryMap"); } static inline size_t checksumCompelementAddress(MemoryMap memoryMap) { constexpr size_t offset = CHECKSUM_COMPLEMENT_ADDR - HEADER_ADDR; return headerAddress(memoryMap) + offset; } static inline size_t checksumAddress(MemoryMap memoryMap) { constexpr size_t offset = CHECKSUM_ADDR - HEADER_ADDR; return headerAddress(memoryMap) + offset; } bool Cartridge::isHeaderValid(const std::vector<uint8_t>& rom, MemoryMap memoryMap) { static const std::array<uint8_t, 2 + 4 + 7> EXPECTED( { { 'F', 'F', 'S', 'N', 'E', 'S', 0, 0, 0, 0, 0, 0, 0 } }); // addresses of blank words in the interrupt vector static const std::array<size_t, 6> BLANK_INTERRUPT_VECTORS( { { 0xffe0, 0xffe2, 0xffec, 0xfff0, 0xfff2, 0xfff6 } }); if (rom.size() < MIN_ROM_SIZE) { return false; } size_t addr = headerAddress(memoryMap); if (!std::equal(EXPECTED.begin(), EXPECTED.end(), rom.begin() + addr)) { return false; } for (size_t v : BLANK_INTERRUPT_VECTORS) { size_t a = addr + v - HEADER_ADDR; if (rom[a] != 0 || rom[a + 1] != 0) { return false; } } return true; } uint16_t Cartridge::readChecksum(const std::vector<uint8_t>& rom, MemoryMap memoryMap) { unsigned addr = checksumAddress(memoryMap); return rom.at(addr) | rom.at(addr + 1) << 8; } uint16_t Cartridge::calculateChecksum(const std::vector<uint8_t>& rom, MemoryMap memoryMap) { static_assert(sizeof(int) > sizeof(uint16_t) + 1, "int too small"); static_assert(INT_MAX > MAX_ROM_SIZE * 256, "int too small"); if (rom.size() < MIN_ROM_SIZE) { throw std::runtime_error("ROM is to small (minimum " MIN_ROM_STRING ")."); } if (rom.size() > MAX_ROM_SIZE) { throw std::runtime_error("ROM is to large (maximum " MAX_ROM_STRING ")."); } unsigned part1Size = 1; while (part1Size <= rom.size()) { part1Size <<= 1; } part1Size >>= 1; int part1 = 0; assert(part1Size <= rom.size()); for (unsigned i = 0; i < part1Size; i++) { part1 += rom[i]; } int part2 = 0; unsigned part2Count = 0; if (part1Size != rom.size()) { unsigned part2Size = rom.size() - part1Size; part2Count = part1Size / part2Size; if (part1Size % part2Size != 0) { throw std::runtime_error("Invalid ROM size."); } for (unsigned i = part1Size; i < rom.size(); i++) { part2 += rom[i]; } } int oldSum = 0; static_assert(CHECKSUM_ADDR == CHECKSUM_COMPLEMENT_ADDR + 2, "assumption failed"); unsigned ccAddr = checksumCompelementAddress(memoryMap); for (unsigned i = 0; i < 4; i++) { oldSum += rom[i + ccAddr]; } int checkSum = part1 + part2 * part2Count - oldSum + 0xff * 2; while (checkSum < 0) { checkSum += 0x10000; } return checkSum & 0xffff; } void Cartridge::writeChecksum(const std::string& filename, uint16_t checksum, MemoryMap memoryMap) { unsigned checksumAddr = checksumAddress(memoryMap); unsigned complementAddr = checksumCompelementAddress(memoryMap); uint16_t complement = 0xffff ^ checksum; std::ofstream out(filename, std::ios::out | std::ios::in | std::ios::binary); if (!out) { throw std::runtime_error("Error opening file: " + filename); } out.exceptions(std::ios::failbit | std::ios::badbit); out.seekp(complementAddr); out.put(complement & 0xff); out.put(complement >> 8 & 0xff); assert(checksumAddr == complementAddr + 2); out.put(checksum & 0xff); out.put(checksum >> 8 & 0xff); out.close(); } <commit_msg>Remove Maker Code and Game Code from the SNES header<commit_after>/* * This file is part of the UnTech Editor Suite. * Copyright (c) 2016 - 2019, Marcus Rowe <undisbeliever@gmail.com>. * Distributed under The MIT License: https://opensource.org/licenses/MIT */ #include "cartridge.h" #include <array> #include <cassert> #include <climits> #include <fstream> #include <stdexcept> using namespace UnTech::Snes; using namespace UnTech::Snes::Cartridge; constexpr size_t HEADER_ADDR = 0xffb0; constexpr size_t CHECKSUM_COMPLEMENT_ADDR = 0xffdc; constexpr size_t CHECKSUM_ADDR = 0xffde; constexpr unsigned MIN_ROM_SIZE = 64 * 1024; constexpr unsigned MAX_ROM_SIZE = 4 * 1024 * 1024; #define MIN_ROM_STRING "64 KiB" #define MAX_ROM_STRING "4 MiB" size_t Cartridge::headerAddress(MemoryMap memoryMap) { switch (memoryMap) { case MemoryMap::LOROM: return HEADER_ADDR - 0x8000; case MemoryMap::HIROM: return HEADER_ADDR; } throw std::invalid_argument("invalid MemoryMap"); } static inline size_t checksumCompelementAddress(MemoryMap memoryMap) { constexpr size_t offset = CHECKSUM_COMPLEMENT_ADDR - HEADER_ADDR; return headerAddress(memoryMap) + offset; } static inline size_t checksumAddress(MemoryMap memoryMap) { constexpr size_t offset = CHECKSUM_ADDR - HEADER_ADDR; return headerAddress(memoryMap) + offset; } bool Cartridge::isHeaderValid(const std::vector<uint8_t>& rom, MemoryMap memoryMap) { // Blank Maker Code and Game Code as my homebrew stuff is unlicensed. static const std::array<uint8_t, 2 + 4 + 7> EXPECTED( { { ' ', ' ', ' ', ' ', ' ', ' ', 0, 0, 0, 0, 0, 0, 0 } }); // addresses of blank words in the interrupt vector static const std::array<size_t, 6> BLANK_INTERRUPT_VECTORS( { { 0xffe0, 0xffe2, 0xffec, 0xfff0, 0xfff2, 0xfff6 } }); if (rom.size() < MIN_ROM_SIZE) { return false; } size_t addr = headerAddress(memoryMap); if (!std::equal(EXPECTED.begin(), EXPECTED.end(), rom.begin() + addr)) { return false; } for (size_t v : BLANK_INTERRUPT_VECTORS) { size_t a = addr + v - HEADER_ADDR; if (rom[a] != 0 || rom[a + 1] != 0) { return false; } } return true; } uint16_t Cartridge::readChecksum(const std::vector<uint8_t>& rom, MemoryMap memoryMap) { unsigned addr = checksumAddress(memoryMap); return rom.at(addr) | rom.at(addr + 1) << 8; } uint16_t Cartridge::calculateChecksum(const std::vector<uint8_t>& rom, MemoryMap memoryMap) { static_assert(sizeof(int) > sizeof(uint16_t) + 1, "int too small"); static_assert(INT_MAX > MAX_ROM_SIZE * 256, "int too small"); if (rom.size() < MIN_ROM_SIZE) { throw std::runtime_error("ROM is to small (minimum " MIN_ROM_STRING ")."); } if (rom.size() > MAX_ROM_SIZE) { throw std::runtime_error("ROM is to large (maximum " MAX_ROM_STRING ")."); } unsigned part1Size = 1; while (part1Size <= rom.size()) { part1Size <<= 1; } part1Size >>= 1; int part1 = 0; assert(part1Size <= rom.size()); for (unsigned i = 0; i < part1Size; i++) { part1 += rom[i]; } int part2 = 0; unsigned part2Count = 0; if (part1Size != rom.size()) { unsigned part2Size = rom.size() - part1Size; part2Count = part1Size / part2Size; if (part1Size % part2Size != 0) { throw std::runtime_error("Invalid ROM size."); } for (unsigned i = part1Size; i < rom.size(); i++) { part2 += rom[i]; } } int oldSum = 0; static_assert(CHECKSUM_ADDR == CHECKSUM_COMPLEMENT_ADDR + 2, "assumption failed"); unsigned ccAddr = checksumCompelementAddress(memoryMap); for (unsigned i = 0; i < 4; i++) { oldSum += rom[i + ccAddr]; } int checkSum = part1 + part2 * part2Count - oldSum + 0xff * 2; while (checkSum < 0) { checkSum += 0x10000; } return checkSum & 0xffff; } void Cartridge::writeChecksum(const std::string& filename, uint16_t checksum, MemoryMap memoryMap) { unsigned checksumAddr = checksumAddress(memoryMap); unsigned complementAddr = checksumCompelementAddress(memoryMap); uint16_t complement = 0xffff ^ checksum; std::ofstream out(filename, std::ios::out | std::ios::in | std::ios::binary); if (!out) { throw std::runtime_error("Error opening file: " + filename); } out.exceptions(std::ios::failbit | std::ios::badbit); out.seekp(complementAddr); out.put(complement & 0xff); out.put(complement >> 8 & 0xff); assert(checksumAddr == complementAddr + 2); out.put(checksum & 0xff); out.put(checksum >> 8 & 0xff); out.close(); } <|endoftext|>
<commit_before>/* * LinearAverageProbe.cpp * * Created on: Apr 22, 2009 * Author: rasmussn */ #include "LinearAverageProbe.hpp" #include "io.h" #include <assert.h> #include <string.h> // strdup namespace PV { /** * @hc * @dim * @f * @gifFile */ LinearAverageProbe::LinearAverageProbe(HyPerCol * hc, PVDimType dim, int f, const char * gifFile) : LinearActivityProbe(hc, dim, 0, f) { this->gifFile = strdup(gifFile); this->fpGif = NULL; } /** * @filename * @hc * @dim * @f * @char */ LinearAverageProbe::LinearAverageProbe(const char * filename, HyPerCol * hc, PVDimType dim, int f, const char * gifFile) : LinearActivityProbe(filename, hc, dim, 0, f) { this->gifFile = strdup(gifFile); this->fpGif = NULL; } LinearAverageProbe::~LinearAverageProbe() { if (fpGif != NULL) { fclose(fpGif); } } /** * @time * @l */ int LinearAverageProbe::outputState(float time, PVLayer * l) { int nk, sk; float * line; if (fpGif == NULL) { int numOnLines = 0; char path[PV_PATH_MAX]; sprintf(path, "%s%s", OUTPUT_PATH, gifFile); // fpGif = fopen(path, "r"); int nx = l->loc.nxGlobal; int ny = l->loc.nyGlobal; int nf = l->numFeatures; int sx = strideX(nx, ny, nf); int sy = strideY(nx, ny, nf); float * buf = (float *) malloc(nx * ny * sizeof(float)); assert(buf != NULL); int err = readFile(path, buf, &nx, &ny); if (err == 0) { assert(nx <= l->loc.nxGlobal); assert(ny <= l->loc.nyGlobal); if (nx < l->loc.nxGlobal || ny < l->loc.nyGlobal) { err = pv_center_image(buf, nx, ny, l->loc.nxGlobal, l->loc.nyGlobal); } } nx = l->loc.nxGlobal; ny = l->loc.nyGlobal; if (dim == DimX) { nk = nx; sk = nf; for (int j = 0; j < ny; j++) { for (int i = 0; i < nx; i++) { if (buf[i*sx + j*sy] > 0.0) { numOnLines += 1; break; } } } line = l->activity->data + nf * nk * loc; } else { nk = l->activity->loc.ny; sk = nf * l->activity->loc.nx; line = l->activity->data + nf * loc; } // get list of locations } float dt = parent->getDeltaTime(); int nf = l->numFeatures; if (dim == DimX) { nk = l->activity->loc.nx; sk = nf; line = l->activity->data + nf * nk * loc; } else { nk = l->activity->loc.ny; sk = nf * l->activity->loc.nx; line = l->activity->data + nf * loc; } double sum = 0.0; for (int k = 0; k < nk; k++) { float a = line[f + k * sk]; sum += a; } float freq = sum / (nk * dt * 0.001); fprintf(fp, "t=%4d sum=%3d f=%6.1f Hz :", (int)time, (int)sum, freq); for (int k = 0; k < nk; k++) { float a = line[f + k * sk]; if (a > 0.0) fprintf(fp, "*"); else fprintf(fp, " "); } fprintf(fp, ":\n"); fflush(fp); return 0; } } <commit_msg>Marian and Craig's fixes for extended activity buffers and STDP.<commit_after>/* * LinearAverageProbe.cpp * * Created on: Apr 22, 2009 * Author: rasmussn */ #include "LinearAverageProbe.hpp" #include "io.h" #include <assert.h> #include <string.h> // strdup namespace PV { /** * @hc * @dim * @f * @gifFile */ LinearAverageProbe::LinearAverageProbe(HyPerCol * hc, PVDimType dim, int f, const char * gifFile) : LinearActivityProbe(hc, dim, 0, f) { this->gifFile = strdup(gifFile); this->fpGif = NULL; } /** * @filename * @hc * @dim * @f * @char */ LinearAverageProbe::LinearAverageProbe(const char * filename, HyPerCol * hc, PVDimType dim, int f, const char * gifFile) : LinearActivityProbe(filename, hc, dim, 0, f) { this->gifFile = strdup(gifFile); this->fpGif = NULL; } LinearAverageProbe::~LinearAverageProbe() { if (fpGif != NULL) { fclose(fpGif); } } /** * @time * @l */ int LinearAverageProbe::outputState(float time, PVLayer * l) { int nk, sk; float * line; if (fpGif == NULL) { int numOnLines = 0; char path[PV_PATH_MAX]; sprintf(path, "%s%s", OUTPUT_PATH, gifFile); // fpGif = fopen(path, "r"); int nx = l->loc.nxGlobal; int ny = l->loc.nyGlobal; int nf = l->numFeatures; int sx = strideX(nx, ny, nf); int sy = strideY(nx, ny, nf); float * buf = (float *) malloc(nx * ny * sizeof(float)); assert(buf != NULL); int err = readFile(path, buf, &nx, &ny); if (err == 0) { assert(nx <= l->loc.nxGlobal); assert(ny <= l->loc.nyGlobal); if (nx < l->loc.nxGlobal || ny < l->loc.nyGlobal) { err = pv_center_image(buf, nx, ny, l->loc.nxGlobal, l->loc.nyGlobal); } } nx = l->loc.nxGlobal; ny = l->loc.nyGlobal; if (dim == DimX) { nk = nx; sk = nf; for (int j = 0; j < ny; j++) { for (int i = 0; i < nx; i++) { if (buf[i*sx + j*sy] > 0.0) { numOnLines += 1; break; } } } line = l->activity->data + nf * nk * linePos; } else { nk = l->activity->loc.ny; sk = nf * l->activity->loc.nx; line = l->activity->data + nf * linePos; } // get list of locations } float dt = parent->getDeltaTime(); int nf = l->numFeatures; if (dim == DimX) { nk = l->activity->loc.nx; sk = nf; line = l->activity->data + nf * nk * linePos; } else { nk = l->activity->loc.ny; sk = nf * l->activity->loc.nx; line = l->activity->data + nf * linePos; } double sum = 0.0; for (int k = 0; k < nk; k++) { float a = line[f + k * sk]; sum += a; } float freq = sum / (nk * dt * 0.001); fprintf(fp, "t=%4d sum=%3d f=%6.1f Hz :", (int)time, (int)sum, freq); for (int k = 0; k < nk; k++) { float a = line[f + k * sk]; if (a > 0.0) fprintf(fp, "*"); else fprintf(fp, " "); } fprintf(fp, ":\n"); fflush(fp); return 0; } } <|endoftext|>
<commit_before>#include "HSBoundarySpecifiedTemperature.h" #include "HeatConductionModel.h" registerMooseObject("THMApp", HSBoundarySpecifiedTemperature); InputParameters HSBoundarySpecifiedTemperature::validParams() { InputParameters params = HSBoundary::validParams(); params.addRequiredParam<FunctionName>("T", "Prescribed temperature [K]"); return params; } HSBoundarySpecifiedTemperature::HSBoundarySpecifiedTemperature(const InputParameters & params) : HSBoundary(params), _T_func(getParam<FunctionName>("T")) { } void HSBoundarySpecifiedTemperature::addMooseObjects() { { std::string class_name = "FunctionDirichletBC"; InputParameters pars = _factory.getValidParams(class_name); pars.set<NonlinearVariableName>("variable") = HeatConductionModel::TEMPERATURE; pars.set<std::vector<BoundaryName>>("boundary") = _boundary; pars.set<FunctionName>("function") = _T_func; _sim.addBoundaryCondition(class_name, genName(name(), "bc"), pars); makeFunctionControllableIfConstant(_T_func, "T"); } } <commit_msg>Converting HSBoundarySpecifiedTemperature to AD<commit_after>#include "HSBoundarySpecifiedTemperature.h" #include "HeatConductionModel.h" registerMooseObject("THMApp", HSBoundarySpecifiedTemperature); InputParameters HSBoundarySpecifiedTemperature::validParams() { InputParameters params = HSBoundary::validParams(); params.addRequiredParam<FunctionName>("T", "Prescribed temperature [K]"); return params; } HSBoundarySpecifiedTemperature::HSBoundarySpecifiedTemperature(const InputParameters & params) : HSBoundary(params), _T_func(getParam<FunctionName>("T")) { } void HSBoundarySpecifiedTemperature::addMooseObjects() { { std::string class_name = "ADFunctionDirichletBC"; InputParameters pars = _factory.getValidParams(class_name); pars.set<NonlinearVariableName>("variable") = HeatConductionModel::TEMPERATURE; pars.set<std::vector<BoundaryName>>("boundary") = _boundary; pars.set<FunctionName>("function") = _T_func; _sim.addBoundaryCondition(class_name, genName(name(), "bc"), pars); makeFunctionControllableIfConstant(_T_func, "T"); } } <|endoftext|>
<commit_before>// // Created by Sam on 11/18/2017. // #include "../../../build/catch-src/include/catch.hpp" #include "../../../include/Game/Python/Factory.h" TEST_CASE("Create factory") { auto* factory = new Factory(); delete factory; // // SECTION("Verify creation") // { // REQUIRE_FALSE(factory == nullptr); // } // // SECTION("Verify minimum python version") // { // std::string minimumVersion = "2.7"; // bool versionCheck = Version(minimumVersion) < factory->version; // REQUIRE(versionCheck); // } // // SECTION("Verify expected python version") // { // std::string expectedVersion = "3.6.3"; // bool versionCheck = Version(expectedVersion) == factory->version; // // if (!versionCheck) // { // FAIL_CHECK("Unexpected python version, expected " + expectedVersion + // " but factory's interpreter is running " + factory->version.toString()); // } // } }<commit_msg>Use a shared ptr and uncomment unit tests<commit_after>// // Created by Sam on 11/18/2017. // #include "../../../build/catch-src/include/catch.hpp" #include "../../../include/Game/Python/Factory.h" TEST_CASE("Create factory") { std::shared_ptr<Factory> factory = std::make_shared<Factory>(); SECTION("Verify creation") { REQUIRE_FALSE(factory == nullptr); } SECTION("Verify minimum python version") { std::string minimumVersion = "2.7"; bool versionCheck = Version(minimumVersion) < factory->version; REQUIRE(versionCheck); } SECTION("Verify expected python version") { std::string expectedVersion = "3.6.3"; bool versionCheck = Version(expectedVersion) == factory->version; if (!versionCheck) { FAIL_CHECK("Unexpected python version, expected " + expectedVersion + " but factory's interpreter is running " + factory->version.toString()); } } }<|endoftext|>
<commit_before>/** * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 Affero 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, see <http://www.gnu.org/licenses/>. */ #include <bitcoin/bitcoin/network/protocol_seed.hpp> #include <functional> #include <bitcoin/bitcoin/config/authority.hpp> #include <bitcoin/bitcoin/error.hpp> #include <bitcoin/bitcoin/message/address.hpp> #include <bitcoin/bitcoin/message/get_address.hpp> #include <bitcoin/bitcoin/message/network_address.hpp> #include <bitcoin/bitcoin/network/channel.hpp> #include <bitcoin/bitcoin/network/protocol_base.hpp> #include <bitcoin/bitcoin/utility/assert.hpp> #include <bitcoin/bitcoin/utility/deadline.hpp> #include <bitcoin/bitcoin/utility/dispatcher.hpp> #include <bitcoin/bitcoin/utility/synchronizer.hpp> #include <bitcoin/bitcoin/utility/threadpool.hpp> INITIALIZE_TRACK(bc::network::protocol_seed); namespace libbitcoin { namespace network { using namespace bc::message; using std::placeholders::_1; using std::placeholders::_2; #define CLASS protocol_seed // Require three callbacks (or any error) before calling complete. protocol_seed::protocol_seed(channel::ptr peer, threadpool& pool, const asio::duration& timeout, handler complete, hosts& hosts, const config::authority& self) : hosts_(hosts), self_(self), protocol_base(peer, pool, timeout, synchronize(complete, 3, "seed")), track<protocol_seed>("protocol_seed", LOG_NETWORK) { } void protocol_seed::start() { protocol_base::start(); if (self_.port() == 0) { callback(error::success); } else { address self({ { self_.to_network_address() } }); SEND1(self, handle_send_address, _1); } if (hosts_.capacity() == 0) { // Error return ends synchronized completion callback. callback(error::not_found); return; } SUBSCRIBE2(address, handle_receive_address, _1, _2); SEND1(get_address(), handle_send_get_address, _1); } void protocol_seed::handle_receive_address(const code& ec, const address& message) { if (stopped()) return; if (ec) { log_debug(LOG_PROTOCOL) << "Failure receiving addresses from seed [" << authority() << "] " << ec.message(); callback(error::bad_stream); return; } log_debug(LOG_PROTOCOL) << "Storing addresses from seed [" << authority() << "] (" << message.addresses.size() << ")"; // TODO: manage timestamps (active peers are connected < 3 hours ago). hosts_.store(message.addresses, BIND1(handle_store_addresses, _1)); } void protocol_seed::handle_send_address(const code& ec) const { if (stopped()) return; if (ec) log_debug(LOG_PROTOCOL) << "Failure sending address to seed [" << authority() << "] " << ec.message(); // 1 of 3 callback(ec); } void protocol_seed::handle_send_get_address(const code& ec) const { if (stopped()) return; if (ec) log_debug(LOG_PROTOCOL) << "Failure sending get_address to seed [" << authority() << "] " << ec.message(); // 2 of 3 callback(ec); } void protocol_seed::handle_store_addresses(const code& ec) const { if (stopped()) return; if (ec) log_error(LOG_PROTOCOL) << "Failure storing addresses from seed [" << authority() << "] " << ec.message(); // 3 of 3 callback(ec); } #undef CLASS } // namespace network } // namespace libbitcoin <commit_msg>Comment and correct returned error code.<commit_after>/** * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * 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 Affero 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, see <http://www.gnu.org/licenses/>. */ #include <bitcoin/bitcoin/network/protocol_seed.hpp> #include <functional> #include <bitcoin/bitcoin/config/authority.hpp> #include <bitcoin/bitcoin/error.hpp> #include <bitcoin/bitcoin/message/address.hpp> #include <bitcoin/bitcoin/message/get_address.hpp> #include <bitcoin/bitcoin/message/network_address.hpp> #include <bitcoin/bitcoin/network/channel.hpp> #include <bitcoin/bitcoin/network/protocol_base.hpp> #include <bitcoin/bitcoin/utility/assert.hpp> #include <bitcoin/bitcoin/utility/deadline.hpp> #include <bitcoin/bitcoin/utility/dispatcher.hpp> #include <bitcoin/bitcoin/utility/synchronizer.hpp> #include <bitcoin/bitcoin/utility/threadpool.hpp> INITIALIZE_TRACK(bc::network::protocol_seed); namespace libbitcoin { namespace network { using namespace bc::message; using std::placeholders::_1; using std::placeholders::_2; #define CLASS protocol_seed // Require three callbacks (or any error) before calling complete. protocol_seed::protocol_seed(channel::ptr peer, threadpool& pool, const asio::duration& timeout, handler complete, hosts& hosts, const config::authority& self) : hosts_(hosts), self_(self), protocol_base(peer, pool, timeout, synchronize(complete, 3, "seed")), track<protocol_seed>("protocol_seed", LOG_NETWORK) { } void protocol_seed::start() { protocol_base::start(); if (self_.port() == 0) { callback(error::success); } else { address self({ { self_.to_network_address() } }); SEND1(self, handle_send_address, _1); } if (hosts_.capacity() == 0) { // Error return ends synchronized completion callback. callback(error::not_found); return; } SUBSCRIBE2(address, handle_receive_address, _1, _2); SEND1(get_address(), handle_send_get_address, _1); } void protocol_seed::handle_receive_address(const code& ec, const address& message) { if (stopped()) return; if (ec) { // We are getting here with channel stopped because this session // doesn't register a stop handler. We may be getting stopped due to // failure to handle ping on this session. log_debug(LOG_PROTOCOL) << "Failure receiving addresses from seed [" << authority() << "] " << ec.message(); callback(ec); return; } log_debug(LOG_PROTOCOL) << "Storing addresses from seed [" << authority() << "] (" << message.addresses.size() << ")"; // TODO: manage timestamps (active peers are connected < 3 hours ago). hosts_.store(message.addresses, BIND1(handle_store_addresses, _1)); } void protocol_seed::handle_send_address(const code& ec) const { if (stopped()) return; if (ec) log_debug(LOG_PROTOCOL) << "Failure sending address to seed [" << authority() << "] " << ec.message(); // 1 of 3 callback(ec); } void protocol_seed::handle_send_get_address(const code& ec) const { if (stopped()) return; if (ec) log_debug(LOG_PROTOCOL) << "Failure sending get_address to seed [" << authority() << "] " << ec.message(); // 2 of 3 callback(ec); } void protocol_seed::handle_store_addresses(const code& ec) const { if (stopped()) return; if (ec) log_error(LOG_PROTOCOL) << "Failure storing addresses from seed [" << authority() << "] " << ec.message(); // 3 of 3 callback(ec); } #undef CLASS } // namespace network } // namespace libbitcoin <|endoftext|>
<commit_before>#include "NodeAlbum.h" #include "NodeTrack.h" #include "NodeArtist.h" #include "../spotify/Track.h" NodeAlbum::NodeAlbum(std::unique_ptr<Album> _album) : album(std::move(_album)) { album->nodeObject = this; }; NodeAlbum::~NodeAlbum() { if(album->nodeObject == this) { album->nodeObject = nullptr; } } NAN_GETTER(NodeAlbum::getName) { NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This()); NanReturnValue(Nan::New<String>(nodeAlbum->album->name().c_str()).ToLocalChecked()); } NAN_GETTER(NodeAlbum::getLink) { NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This()); NanReturnValue(Nan::New<String>(nodeAlbum->album->link().c_str()).ToLocalChecked()); } NAN_METHOD(NodeAlbum::getCoverBase64) { NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This()); NanReturnValue(Nan::New<String>(nodeAlbum->album->coverBase64().c_str()).ToLocalChecked()); } NAN_METHOD(NodeAlbum::browse) { NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This()); if(nodeAlbum->album->albumBrowse == nullptr) { nodeAlbum->makePersistent(); nodeAlbum->browseCompleteCallback.SetFunction(args[0].As<Function>()); //Mutate the V8 object. Handle<Object> nodeAlbumV8 = NanObjectWrapHandle(nodeAlbum); nodeAlbumV8->SetAccessor(Nan::New<String>("tracks").ToLocalChecked(), getTracks); nodeAlbumV8->SetAccessor(Nan::New<String>("review").ToLocalChecked(), getReview); nodeAlbumV8->SetAccessor(Nan::New<String>("copyrights").ToLocalChecked(), getCopyrights); nodeAlbumV8->SetAccessor(Nan::New<String>("artist").ToLocalChecked(), getArtist); nodeAlbum->album->browse(); } else { nodeAlbum->callBrowseComplete(); } NanReturnUndefined(); } NAN_GETTER(NodeAlbum::getTracks) { NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This()); std::vector<std::shared_ptr<Track>> tracks = nodeAlbum->album->tracks(); Handle<Array> nodeTracks = NanNew<Array>(tracks.size()); for(int i = 0; i < (int)tracks.size(); i++) { NodeTrack* nodeTrack = new NodeTrack(tracks[i]); nodeTracks->Set(Nan::New<Number>(i), nodeTrack->createInstance()); } NanReturnValue(nodeTracks); } NAN_GETTER(NodeAlbum::getReview) { NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This()); NanReturnValue(Nan::New<String>(nodeAlbum->album->review().c_str()).ToLocalChecked()); } NAN_GETTER(NodeAlbum::getCopyrights) { NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This()); std::vector<std::string> copyrights = nodeAlbum->album->copyrights(); Handle<Array> nodeCopyrights = NanNew<Array>(copyrights.size()); for(int i = 0; i < (int)copyrights.size(); i++) { nodeCopyrights->Set(Nan::New<Number>(i), Nan::New<String>(copyrights[i].c_str()).ToLocalChecked()); } NanReturnValue(nodeCopyrights); } NAN_GETTER(NodeAlbum::getArtist) { NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This()); NodeArtist* nodeArtist = new NodeArtist(nodeAlbum->album->artist()); NanReturnValue(nodeArtist->createInstance()); } NAN_GETTER(NodeAlbum::isLoaded) { NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This()); NanReturnValue(NanNew<Boolean>(nodeAlbum->album->isLoaded())); } void NodeAlbum::init() { NanScope(); Handle<FunctionTemplate> constructorTemplate = NodeWrapped::init("Album"); constructorTemplate->InstanceTemplate()->SetAccessor(Nan::New<String>("name").ToLocalChecked(), getName); constructorTemplate->InstanceTemplate()->SetAccessor(Nan::New<String>("link").ToLocalChecked(), getLink); constructorTemplate->InstanceTemplate()->SetAccessor(Nan::New<String>("isLoaded").ToLocalChecked(), isLoaded); NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "getCoverBase64", getCoverBase64); NODE_SET_PROTOTYPE_METHOD(constructorTemplate, "browse", browse); NanAssignPersistent(NodeAlbum::constructorTemplate, constructorTemplate); } <commit_msg>Fix NodeAlbum return values and init method.<commit_after>#include "NodeAlbum.h" #include "NodeTrack.h" #include "NodeArtist.h" #include "../spotify/Track.h" NodeAlbum::NodeAlbum(std::unique_ptr<Album> _album) : album(std::move(_album)) { album->nodeObject = this; }; NodeAlbum::~NodeAlbum() { if(album->nodeObject == this) { album->nodeObject = nullptr; } } NAN_GETTER(NodeAlbum::getName) { NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This()); info.GetReturnValue().Set(Nan::New<String>(nodeAlbum->album->name().c_str()).ToLocalChecked()); } NAN_GETTER(NodeAlbum::getLink) { NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This()); info.GetReturnValue().Set(Nan::New<String>(nodeAlbum->album->link().c_str()).ToLocalChecked()); } NAN_METHOD(NodeAlbum::getCoverBase64) { NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This()); info.GetReturnValue().Set(Nan::New<String>(nodeAlbum->album->coverBase64().c_str()).ToLocalChecked()); } NAN_METHOD(NodeAlbum::browse) { NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This()); if(nodeAlbum->album->albumBrowse == nullptr) { nodeAlbum->makePersistent(); nodeAlbum->browseCompleteCallback.SetFunction(info[0].As<Function>()); //Mutate the V8 object. Handle<Object> nodeAlbumV8 = nodeAlbum->handle(); Nan::SetAccessor(nodeAlbumV8, Nan::New<String>("tracks").ToLocalChecked(), getTracks); Nan::SetAccessor(nodeAlbumV8, Nan::New<String>("review").ToLocalChecked(), getReview); Nan::SetAccessor(nodeAlbumV8, Nan::New<String>("copyrights").ToLocalChecked(), getCopyrights); Nan::SetAccessor(nodeAlbumV8, Nan::New<String>("artist").ToLocalChecked(), getArtist); nodeAlbum->album->browse(); } else { nodeAlbum->callBrowseComplete(); } info.GetReturnValue().SetUndefined(); } NAN_GETTER(NodeAlbum::getTracks) { NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This()); std::vector<std::shared_ptr<Track>> tracks = nodeAlbum->album->tracks(); Handle<Array> nodeTracks = Nan::New<Array>(tracks.size()); for(int i = 0; i < (int)tracks.size(); i++) { NodeTrack* nodeTrack = new NodeTrack(tracks[i]); nodeTracks->Set(Nan::New<Number>(i), nodeTrack->createInstance()); } info.GetReturnValue().Set(nodeTracks); } NAN_GETTER(NodeAlbum::getReview) { NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This()); info.GetReturnValue().Set(Nan::New<String>(nodeAlbum->album->review().c_str()).ToLocalChecked()); } NAN_GETTER(NodeAlbum::getCopyrights) { NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This()); std::vector<std::string> copyrights = nodeAlbum->album->copyrights(); Handle<Array> nodeCopyrights = Nan::New<Array>(copyrights.size()); for(int i = 0; i < (int)copyrights.size(); i++) { nodeCopyrights->Set(Nan::New<Number>(i), Nan::New<String>(copyrights[i].c_str()).ToLocalChecked()); } info.GetReturnValue().Set(nodeCopyrights); } NAN_GETTER(NodeAlbum::getArtist) { NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This()); NodeArtist* nodeArtist = new NodeArtist(nodeAlbum->album->artist()); info.GetReturnValue().Set(nodeArtist->createInstance()); } NAN_GETTER(NodeAlbum::isLoaded) { NodeAlbum* nodeAlbum = node::ObjectWrap::Unwrap<NodeAlbum>(info.This()); info.GetReturnValue().Set(Nan::New<Boolean>(nodeAlbum->album->isLoaded())); } void NodeAlbum::init() { Handle<FunctionTemplate> constructorTemplate = NodeWrapped::init("Album"); Nan::SetAccessor(constructorTemplate->InstanceTemplate(), Nan::New<String>("name").ToLocalChecked(), getName); Nan::SetAccessor(constructorTemplate->InstanceTemplate(), Nan::New<String>("link").ToLocalChecked(), getLink); Nan::SetAccessor(constructorTemplate->InstanceTemplate(), Nan::New<String>("isLoaded").ToLocalChecked(), isLoaded); Nan::SetMethod(constructorTemplate, "getCoverBase64", getCoverBase64); Nan::SetMethod(constructorTemplate, "browse", browse); NodeAlbum::constructorTemplate.Reset(constructorTemplate); } <|endoftext|>
<commit_before>#include <hop_bits/optimisationAlgorithm.hpp> #include <limits> namespace hop { OptimisationAlgorithm::OptimisationAlgorithm(const std::shared_ptr<OptimisationProblem> optimisationProblem) : optimisationProblem_(optimisationProblem) { setMaximalNumberOfIterations(1000); } void OptimisationAlgorithm::optimise() { bestObjectiveValue_ = std::numeric_limits<double>::infinity(); bestSolution_ = arma::Col<double>({}); numberOfIterations_ = 0; optimisationProblem_->reset(); return optimiseImplementation(); } double OptimisationAlgorithm::getBestObjectiveValue() const { return bestObjectiveValue_; } arma::Col<double> OptimisationAlgorithm::getBestSolution() const { return bestSolution_; } bool OptimisationAlgorithm::isFinished() const { return (bestObjectiveValue_ <= optimisationProblem_->getAcceptableObjectiveValue()); } bool OptimisationAlgorithm::isTerminated() const { return (numberOfIterations_ >= maximalNumberOfIterations_); } unsigned int OptimisationAlgorithm::getNumberOfIterations() const { return numberOfIterations_; } void OptimisationAlgorithm::setMaximalNumberOfIterations(const unsigned int& maximalNumberOfIterations) { maximalNumberOfIterations_ = maximalNumberOfIterations; } } <commit_msg>feat: Added reset function<commit_after>#include <hop_bits/optimisationAlgorithm.hpp> // C++ STL #include <limits> namespace hop { OptimisationAlgorithm::OptimisationAlgorithm(const std::shared_ptr<OptimisationProblem> optimisationProblem) : optimisationProblem_(optimisationProblem) { setMaximalNumberOfIterations(1000); reset(); } void OptimisationAlgorithm::optimise() { reset(); return optimiseImplementation(); } double OptimisationAlgorithm::getBestObjectiveValue() const { return bestObjectiveValue_; } arma::Col<double> OptimisationAlgorithm::getBestSolution() const { return bestSolution_; } bool OptimisationAlgorithm::isFinished() const { return (bestObjectiveValue_ <= optimisationProblem_->getAcceptableObjectiveValue()); } bool OptimisationAlgorithm::isTerminated() const { return (numberOfIterations_ >= maximalNumberOfIterations_); } unsigned int OptimisationAlgorithm::getNumberOfIterations() const { return numberOfIterations_; } void OptimisationAlgorithm::setMaximalNumberOfIterations(const unsigned int& maximalNumberOfIterations) { maximalNumberOfIterations_ = maximalNumberOfIterations; } void OptimisationAlgorithm::reset() { bestObjectiveValue_ = std::numeric_limits<double>::infinity(); bestSolution_.fill(arma::datum::nan); numberOfIterations_ = 0; optimisationProblem_->reset(); } } <|endoftext|>