text
stringlengths
54
60.6k
<commit_before>/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License") * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // Third party includes #include <boost/interprocess/sync/file_lock.hpp> // VOTCA includes #include <votca/tools/filesystem.h> // Local VOTCA includes #include "votca/xtp/statesaver.h" #include "votca/xtp/topology.h" namespace votca { namespace xtp { std::vector<Index> StateSaver::getFrames() const { CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::READ); CheckpointReader r = cpf.getReader(); std::vector<Index> frames = std::vector<Index>{}; try { r(frames, "frames"); } catch (std::runtime_error&) { ; } return frames; } void StateSaver::WriteFrame(const Topology& top) { if (!tools::filesystem::FileExists(_hdf5file)) { std::cout << "Creating statefile " << _hdf5file << std::endl; CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::CREATE); } boost::interprocess::file_lock flock(_hdf5file.c_str()); flock.lock(); if (!TopStepisinFrames(top.getStep())) { std::vector<Index> frames = this->getFrames(); frames.push_back(top.getStep()); CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::MODIFY); CheckpointWriter w = cpf.getWriter(); w(frames, "frames"); std::cout << "Frame with id " << top.getStep() << " was not in statefile " << _hdf5file << " ,adding it now." << std::endl; } CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::MODIFY); CheckpointWriter w = cpf.getWriter("/frame_" + std::to_string(top.getStep())); top.WriteToCpt(w); flock.unlock(); std::cout << "Writing MD topology (step = " << top.getStep() << ", time = " << top.getTime() << ") to " << _hdf5file << std::endl; std::cout << "... "; std::cout << ". " << std::endl; return; } Topology StateSaver::ReadFrame(Index frameid) const { if (!tools::filesystem::FileExists(_hdf5file)) { throw std::runtime_error("Statefile " + _hdf5file + " does not exist."); } std::cout << "Import MD Topology (i.e. frame " << frameid << ")" << " from " << _hdf5file << std::endl; std::cout << "..."; boost::interprocess::file_lock flock(_hdf5file.c_str()); flock.lock(); if (!TopStepisinFrames(frameid)) { throw std::runtime_error("Frame with id " + std::to_string(frameid) + " is not in statefile."); } CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::READ); CheckpointReader r = cpf.getReader("/frame_" + std::to_string(frameid)); Topology top; top.ReadFromCpt(r); flock.unlock(); std::cout << ". " << std::endl; return top; } bool StateSaver::TopStepisinFrames(Index frameid) const { std::vector<Index> frames = this->getFrames(); return std::find(frames.begin(), frames.end(), frameid) != frames.end(); } } // namespace xtp } // namespace votca <commit_msg>changed output a bit<commit_after>/* * Copyright 2009-2020 The VOTCA Development Team * (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License") * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // Third party includes #include <boost/interprocess/sync/file_lock.hpp> // VOTCA includes #include <votca/tools/filesystem.h> // Local VOTCA includes #include "votca/xtp/statesaver.h" #include "votca/xtp/topology.h" namespace votca { namespace xtp { std::vector<Index> StateSaver::getFrames() const { CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::READ); CheckpointReader r = cpf.getReader(); std::vector<Index> frames = std::vector<Index>{}; try { r(frames, "frames"); } catch (std::runtime_error&) { ; } return frames; } void StateSaver::WriteFrame(const Topology& top) { if (!tools::filesystem::FileExists(_hdf5file)) { std::cout << "Creating statefile " << _hdf5file << std::endl; CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::CREATE); } boost::interprocess::file_lock flock(_hdf5file.c_str()); flock.lock(); if (!TopStepisinFrames(top.getStep())) { std::vector<Index> frames = this->getFrames(); frames.push_back(top.getStep()); CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::MODIFY); CheckpointWriter w = cpf.getWriter(); w(frames, "frames"); std::cout << "Frame with id " << top.getStep() << " was not in statefile " << _hdf5file << " ,adding it now." << std::endl; } CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::MODIFY); CheckpointWriter w = cpf.getWriter("/frame_" + std::to_string(top.getStep())); top.WriteToCpt(w); flock.unlock(); std::cout << "Wrote MD topology (step = " << top.getStep() << ", time = " << top.getTime() << ") to " << _hdf5file << std::endl; std::cout << "... "; std::cout << ". " << std::endl; return; } Topology StateSaver::ReadFrame(Index frameid) const { if (!tools::filesystem::FileExists(_hdf5file)) { throw std::runtime_error("Statefile " + _hdf5file + " does not exist."); } std::cout << "Import MD Topology (i.e. frame " << frameid << ")" << " from " << _hdf5file << std::endl; std::cout << "..."; boost::interprocess::file_lock flock(_hdf5file.c_str()); flock.lock(); if (!TopStepisinFrames(frameid)) { throw std::runtime_error("Frame with id " + std::to_string(frameid) + " is not in statefile."); } CheckpointFile cpf(_hdf5file, CheckpointAccessLevel::READ); CheckpointReader r = cpf.getReader("/frame_" + std::to_string(frameid)); Topology top; top.ReadFromCpt(r); flock.unlock(); std::cout << ". " << std::endl; return top; } bool StateSaver::TopStepisinFrames(Index frameid) const { std::vector<Index> frames = this->getFrames(); return std::find(frames.begin(), frames.end(), frameid) != frames.end(); } } // namespace xtp } // namespace votca <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2016, Johan Mabille and Sylvain Corlay * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XTENSOR_JULIA_HPP #define XTENSOR_JULIA_HPP #include <cstddef> #include <array> #include <algorithm> #include <exception> #include "xtensor/xsemantic.hpp" #include "type_conversion.hpp" #include "jlbuffer_adaptor.hpp" #include "jlcontainer.hpp" namespace xt { /************************ * jltensor declaration * ************************/ template <class T, std::size_t N> class jltensor; template <class T, std::size_t N> struct xiterable_inner_types<jltensor<T, N>> : xcontainer_iterable_types<jltensor<T, N>> { }; template <class T, std::size_t N> struct xcontainer_inner_types<jltensor<T, N>> { using container_type = jlbuffer_adaptor<cxx_wrap::mapped_julia_type<T>>; using shape_type = std::array<std::size_t, N>; using strides_type = shape_type; using backstrides_type = shape_type; using inner_shape_type = shape_type; using inner_strides_type = strides_type; using inner_backstrides_type = backstrides_type; using temporary_type = jltensor<T, N>; }; template <class T, std::size_t N> class jltensor : public jlcontainer<jltensor<T, N>>, public xcontainer_semantic<jltensor<T, N>> { public: using self_type = jltensor<T, N>; using semantic_base = xcontainer_semantic<self_type>; using base_type = jlcontainer<self_type>; using container_type = typename base_type::container_type; using value_type = typename base_type::value_type; using reference = typename base_type::reference; using const_reference = typename base_type::const_reference; using pointer = typename base_type::pointer; using size_type = typename base_type::size_type; using shape_type = typename base_type::shape_type; using strides_type = typename base_type::strides_type; using backstrides_type = typename base_type::backstrides_type; using inner_shape_type = typename base_type::inner_shape_type; using inner_strides_type = typename base_type::inner_strides_type; using inner_backstrides_type = typename base_type::inner_backstrides_type; jltensor(); jltensor(const self_type&); jltensor(self_type&&) = default; jltensor(nested_initializer_list_t<T, N> t); explicit jltensor(const shape_type& shape); explicit jltensor(const shape_type& shape, const_reference value); explicit jltensor(jl_array_t* jl); self_type& operator=(const self_type&); self_type& operator=(self_type&&) = default; template <class E> jltensor(const xexpression<E>& e); template <class E> self_type& operator=(const xexpression<E>& e); using base_type::begin; using base_type::end; private: inner_shape_type m_shape; inner_strides_type m_strides; inner_backstrides_type m_backstrides; container_type m_data; void init_tensor(const shape_type& shape); void init_from_julia(); inner_shape_type& shape_impl() noexcept; const inner_shape_type& shape_impl() const noexcept; inner_strides_type& strides_impl() noexcept; const inner_strides_type& strides_impl() const noexcept; inner_backstrides_type& backstrides_impl() noexcept; const inner_backstrides_type& backstrides_impl() const noexcept; container_type& data_impl() noexcept; const container_type& data_impl() const noexcept; friend class xcontainer<jltensor<T, N>>; }; /*************************** * jltensor implementation * ***************************/ /** * @name Constructors */ //@{ /** * Allocates a jltensor that holds 1 element. */ template <class T, std::size_t N> inline jltensor<T, N>::jltensor() : base_type() { m_shape = make_sequence<shape_type>(N, size_type(1)); compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides); init_tensor(m_shape); m_data[0] = T(); } /** * Allocates a jltensor with a nested initializer list. */ template <class T, std::size_t N> inline jltensor<T, N>::jltensor(nested_initializer_list_t<T, N> t) : base_type() { base_type::reshape(xt::shape<shape_type>(t)); nested_copy(this->xbegin(), t); } /** * Allocates an uninitialized jltensor with the specified shape and * layout. * @param shape the shape of the jltensor */ template <class T, std::size_t N> inline jltensor<T, N>::jltensor(const shape_type& shape) : m_shape(shape) { compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides); init_tensor(m_shape); } /** * Allocates a jltensor with the specified shape and layout. Elements * are initialized to the specified value. * @param shape the shape of the jltensor * @param value the value of the elements */ template <class T, std::size_t N> inline jltensor<T, N>::jltensor(const shape_type& shape, const_reference value) : m_shape(shape) { compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides); init_tensor(m_shape); std::fill(m_data.begin(), m_data.end(), value); } /** * Allocates a jltensor that holds 1 element. */ template <class T, std::size_t N> inline jltensor<T, N>::jltensor(jl_array_t* jl) : base_type(jl) { init_from_julia(); } //@} /** * @name Copy semantic */ //@{ /** * The copy constructor. */ template <class T, std::size_t N> inline jltensor<T, N>::jltensor(const self_type& rhs) : base_type(), m_shape(rhs.shape()) { compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides); init_tensor(m_shape); std::copy(rhs.data().begin(), rhs.data().end(), this->data().begin()); } /** * The assignment operator. */ template <class T, std::size_t N> inline auto jltensor<T, N>::operator=(const self_type& rhs) -> self_type& { self_type tmp(rhs); *this = std::move(tmp); return *this; } //@} /** * @name Extended copy semantic */ //@{ /** * The extended copy constructor. */ template <class T, std::size_t N> template <class E> inline jltensor<T, N>::jltensor(const xexpression<E>& e) : base_type() { m_shape = forward_sequence<shape_type>(e.derived_cast().shape()); compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides); init_tensor(m_shape); semantic_base::assign(e); } /** * The extended assignment operator. */ template <class T, std::size_t N> template <class E> inline auto jltensor<T, N>::operator=(const xexpression<E>& e) -> self_type& { return semantic_base::operator=(e); } //@} template <class T, std::size_t N> inline void jltensor<T, N>::init_tensor(const shape_type& shape) { jl_value_t* array_type = cxx_wrap::apply_array_type(cxx_wrap::static_type_mapping<value_type>::julia_type(), N); // make tuple_type for shape jl_svec_t* jtypes = jl_alloc_svec(N); for (std::size_t i = 0; i < N; ++i) { jl_svecset(jtypes, i, cxx_wrap::julia_type<typename shape_type::value_type>()); } jl_datatype_t* tuple_type = jl_apply_tuple_type(jtypes); // allocate array jl_value_t* dims = jl_new_bits((jl_value_t*)tuple_type, const_cast<void*>(reinterpret_cast<const void*>(shape.data()))); this->p_array = jl_new_array((jl_value_t*)array_type, dims); // setup buffer adaptor m_data = container_type(reinterpret_cast<pointer>(this->p_array->data), static_cast<size_type>(jl_array_len(this->p_array))); } template <class T, std::size_t N> inline void jltensor<T, N>::init_from_julia() { if (this->p_array->flags.ndims != N) { throw std::runtime_error("Julia array has incorrect number of dimensions"); } std::copy(&(this->p_array->nrows), &(this->p_array->nrows) + N, m_shape.begin()); compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides); m_data = container_type(reinterpret_cast<pointer>(this->p_array->data), static_cast<size_type>(jl_array_len(this->p_array))); } template <class T, std::size_t N> inline auto jltensor<T, N>::shape_impl() noexcept -> inner_shape_type& { return m_shape; } template <class T, std::size_t N> inline auto jltensor<T, N>::shape_impl() const noexcept -> const inner_shape_type& { return m_shape; } template <class T, std::size_t N> inline auto jltensor<T, N>::strides_impl() noexcept -> inner_strides_type& { return m_strides; } template <class T, std::size_t N> inline auto jltensor<T, N>::strides_impl() const noexcept -> const inner_strides_type& { return m_strides; } template <class T, std::size_t N> inline auto jltensor<T, N>::backstrides_impl() noexcept -> inner_backstrides_type& { return m_backstrides; } template <class T, std::size_t N> inline auto jltensor<T, N>::backstrides_impl() const noexcept -> const inner_backstrides_type& { return m_backstrides; } template <class T, std::size_t N> inline auto jltensor<T, N>::data_impl() noexcept -> container_type& { return m_data; } template <class T, std::size_t N> inline auto jltensor<T, N>::data_impl() const noexcept -> const container_type& { return m_data; } } namespace cxx_wrap { /**************************************************************** * Template specializations for ConvertToJulia and ConvertToCpp * ****************************************************************/ template <class T, std::size_t N> struct ConvertToJulia<xt::jltensor<T, N>, false, false, false> { template <class U> jl_array_t* operator()(U&& arr) const { return arr.wrapped(); } }; template <class T, std::size_t N> struct ConvertToCpp<xt::jltensor<T, N>, false, false, false> { xt::jltensor<T, N> operator()(jl_array_t* arr) const { return xt::jltensor<T, N>(arr); } }; // Conversions template<class T, std::size_t N> struct static_type_mapping<xt::jltensor<T, N>> { using type = jl_array_t*; static constexpr bool is_dynamic = false; static jl_datatype_t* julia_type() { return (jl_datatype_t*)apply_array_type(static_type_mapping<T>::julia_type(), N); } }; } #endif <commit_msg>Static Julia types<commit_after>/*************************************************************************** * Copyright (c) 2016, Johan Mabille and Sylvain Corlay * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #ifndef XTENSOR_JULIA_HPP #define XTENSOR_JULIA_HPP #include <cstddef> #include <array> #include <algorithm> #include <exception> #include "xtensor/xsemantic.hpp" #include "type_conversion.hpp" #include "jlbuffer_adaptor.hpp" #include "jlcontainer.hpp" namespace xt { /************************ * jltensor declaration * ************************/ template <class T, std::size_t N> class jltensor; template <class T, std::size_t N> struct xiterable_inner_types<jltensor<T, N>> : xcontainer_iterable_types<jltensor<T, N>> { }; template <class T, std::size_t N> struct xcontainer_inner_types<jltensor<T, N>> { using container_type = jlbuffer_adaptor<cxx_wrap::mapped_julia_type<T>>; using shape_type = std::array<std::size_t, N>; using strides_type = shape_type; using backstrides_type = shape_type; using inner_shape_type = shape_type; using inner_strides_type = strides_type; using inner_backstrides_type = backstrides_type; using temporary_type = jltensor<T, N>; }; template <class T, std::size_t N> class jltensor : public jlcontainer<jltensor<T, N>>, public xcontainer_semantic<jltensor<T, N>> { public: using self_type = jltensor<T, N>; using semantic_base = xcontainer_semantic<self_type>; using base_type = jlcontainer<self_type>; using container_type = typename base_type::container_type; using value_type = typename base_type::value_type; using reference = typename base_type::reference; using const_reference = typename base_type::const_reference; using pointer = typename base_type::pointer; using size_type = typename base_type::size_type; using shape_type = typename base_type::shape_type; using strides_type = typename base_type::strides_type; using backstrides_type = typename base_type::backstrides_type; using inner_shape_type = typename base_type::inner_shape_type; using inner_strides_type = typename base_type::inner_strides_type; using inner_backstrides_type = typename base_type::inner_backstrides_type; jltensor(); jltensor(const self_type&); jltensor(self_type&&) = default; jltensor(nested_initializer_list_t<T, N> t); explicit jltensor(const shape_type& shape); explicit jltensor(const shape_type& shape, const_reference value); explicit jltensor(jl_array_t* jl); self_type& operator=(const self_type&); self_type& operator=(self_type&&) = default; template <class E> jltensor(const xexpression<E>& e); template <class E> self_type& operator=(const xexpression<E>& e); using base_type::begin; using base_type::end; private: inner_shape_type m_shape; inner_strides_type m_strides; inner_backstrides_type m_backstrides; container_type m_data; void init_tensor(const shape_type& shape); void init_from_julia(); inner_shape_type& shape_impl() noexcept; const inner_shape_type& shape_impl() const noexcept; inner_strides_type& strides_impl() noexcept; const inner_strides_type& strides_impl() const noexcept; inner_backstrides_type& backstrides_impl() noexcept; const inner_backstrides_type& backstrides_impl() const noexcept; container_type& data_impl() noexcept; const container_type& data_impl() const noexcept; static jl_datatype_t* make_julia_shape_type(); static jl_value_t* make_julia_array_type(); friend class xcontainer<jltensor<T, N>>; }; /*************************** * jltensor implementation * ***************************/ /** * @name Constructors */ //@{ /** * Allocates a jltensor that holds 1 element. */ template <class T, std::size_t N> inline jltensor<T, N>::jltensor() : base_type() { m_shape = make_sequence<shape_type>(N, size_type(1)); compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides); init_tensor(m_shape); m_data[0] = T(); } /** * Allocates a jltensor with a nested initializer list. */ template <class T, std::size_t N> inline jltensor<T, N>::jltensor(nested_initializer_list_t<T, N> t) : base_type() { base_type::reshape(xt::shape<shape_type>(t)); nested_copy(this->xbegin(), t); } /** * Allocates an uninitialized jltensor with the specified shape and * layout. * @param shape the shape of the jltensor */ template <class T, std::size_t N> inline jltensor<T, N>::jltensor(const shape_type& shape) : m_shape(shape) { compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides); init_tensor(m_shape); } /** * Allocates a jltensor with the specified shape and layout. Elements * are initialized to the specified value. * @param shape the shape of the jltensor * @param value the value of the elements */ template <class T, std::size_t N> inline jltensor<T, N>::jltensor(const shape_type& shape, const_reference value) : m_shape(shape) { compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides); init_tensor(m_shape); std::fill(m_data.begin(), m_data.end(), value); } /** * Allocates a jltensor that holds 1 element. */ template <class T, std::size_t N> inline jltensor<T, N>::jltensor(jl_array_t* jl) : base_type(jl) { init_from_julia(); } //@} /** * @name Copy semantic */ //@{ /** * The copy constructor. */ template <class T, std::size_t N> inline jltensor<T, N>::jltensor(const self_type& rhs) : base_type(), m_shape(rhs.shape()) { compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides); init_tensor(m_shape); std::copy(rhs.data().begin(), rhs.data().end(), this->data().begin()); } /** * The assignment operator. */ template <class T, std::size_t N> inline auto jltensor<T, N>::operator=(const self_type& rhs) -> self_type& { self_type tmp(rhs); *this = std::move(tmp); return *this; } //@} /** * @name Extended copy semantic */ //@{ /** * The extended copy constructor. */ template <class T, std::size_t N> template <class E> inline jltensor<T, N>::jltensor(const xexpression<E>& e) : base_type() { m_shape = forward_sequence<shape_type>(e.derived_cast().shape()); compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides); init_tensor(m_shape); semantic_base::assign(e); } /** * The extended assignment operator. */ template <class T, std::size_t N> template <class E> inline auto jltensor<T, N>::operator=(const xexpression<E>& e) -> self_type& { return semantic_base::operator=(e); } //@} template <class T, std::size_t N> inline void jltensor<T, N>::init_tensor(const shape_type& shape) { static jl_value_t* array_type = make_julia_array_type(); static jl_datatype_t* tuple_type = make_julia_shape_type(); // allocate array jl_value_t* dims = jl_new_bits((jl_value_t*)tuple_type, const_cast<void*>(reinterpret_cast<const void*>(shape.data()))); this->p_array = jl_new_array((jl_value_t*)array_type, dims); // setup buffer adaptor m_data = container_type(reinterpret_cast<pointer>(this->p_array->data), static_cast<size_type>(jl_array_len(this->p_array))); } template <class T, std::size_t N> inline void jltensor<T, N>::init_from_julia() { if (this->p_array->flags.ndims != N) { throw std::runtime_error("Julia array has incorrect number of dimensions"); } std::copy(&(this->p_array->nrows), &(this->p_array->nrows) + N, m_shape.begin()); compute_strides(m_shape, layout_type::column_major, m_strides, m_backstrides); m_data = container_type(reinterpret_cast<pointer>(this->p_array->data), static_cast<size_type>(jl_array_len(this->p_array))); } template <class T, std::size_t N> inline auto jltensor<T, N>::shape_impl() noexcept -> inner_shape_type& { return m_shape; } template <class T, std::size_t N> inline auto jltensor<T, N>::shape_impl() const noexcept -> const inner_shape_type& { return m_shape; } template <class T, std::size_t N> inline auto jltensor<T, N>::strides_impl() noexcept -> inner_strides_type& { return m_strides; } template <class T, std::size_t N> inline auto jltensor<T, N>::strides_impl() const noexcept -> const inner_strides_type& { return m_strides; } template <class T, std::size_t N> inline auto jltensor<T, N>::backstrides_impl() noexcept -> inner_backstrides_type& { return m_backstrides; } template <class T, std::size_t N> inline auto jltensor<T, N>::backstrides_impl() const noexcept -> const inner_backstrides_type& { return m_backstrides; } template <class T, std::size_t N> inline auto jltensor<T, N>::data_impl() noexcept -> container_type& { return m_data; } template <class T, std::size_t N> inline auto jltensor<T, N>::data_impl() const noexcept -> const container_type& { return m_data; } template <class T, std::size_t N> inline jl_datatype_t* jltensor<T, N>::make_julia_shape_type() { jl_svec_t* jtypes = jl_alloc_svec(N); for (std::size_t i = 0; i < N; ++i) { jl_svecset(jtypes, i, cxx_wrap::julia_type<typename shape_type::value_type>()); } return jl_apply_tuple_type(jtypes); } template <class T, std::size_t N> inline jl_value_t* jltensor<T, N>::make_julia_array_type() { return cxx_wrap::apply_array_type(cxx_wrap::static_type_mapping<value_type>::julia_type(), N); } } namespace cxx_wrap { /**************************************************************** * Template specializations for ConvertToJulia and ConvertToCpp * ****************************************************************/ template <class T, std::size_t N> struct ConvertToJulia<xt::jltensor<T, N>, false, false, false> { template <class U> jl_array_t* operator()(U&& arr) const { return arr.wrapped(); } }; template <class T, std::size_t N> struct ConvertToCpp<xt::jltensor<T, N>, false, false, false> { xt::jltensor<T, N> operator()(jl_array_t* arr) const { return xt::jltensor<T, N>(arr); } }; // Conversions template<class T, std::size_t N> struct static_type_mapping<xt::jltensor<T, N>> { using type = jl_array_t*; static constexpr bool is_dynamic = false; static jl_datatype_t* julia_type() { return (jl_datatype_t*)apply_array_type(static_type_mapping<T>::julia_type(), N); } }; } #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tkthrobber.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2008-04-04 10:55: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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_toolkit.hxx" #ifndef TOOLKIT_CONTROLS_TKTHROBBER_HXX #include "toolkit/controls/tkthrobber.hxx" #endif #ifndef _TOOLKIT_HELPER_PROPERTY_HXX_ #include "toolkit/helper/property.hxx" #endif #ifndef _TOOLKIT_HELPER_UNOPROPERTYARRAYHELPER_HXX_ #include "toolkit/helper/unopropertyarrayhelper.hxx" #endif #ifndef _CPPUHELPER_TYPEPROVIDER_HXX_ #include <cppuhelper/typeprovider.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif //........................................................................ namespace toolkit { //........................................................................ using namespace ::com::sun::star; //==================================================================== //= UnoThrobberControlModel //==================================================================== //-------------------------------------------------------------------- UnoThrobberControlModel::UnoThrobberControlModel() { ImplRegisterProperty( BASEPROPERTY_DEFAULTCONTROL ); ImplRegisterProperty( BASEPROPERTY_BACKGROUNDCOLOR ); } //-------------------------------------------------------------------- ::rtl::OUString UnoThrobberControlModel::getServiceName( ) throw ( uno::RuntimeException ) { return ::rtl::OUString::createFromAscii( szServiceName_UnoThrobberControlModel ); } //-------------------------------------------------------------------- uno::Any UnoThrobberControlModel::ImplGetDefaultValue( sal_uInt16 nPropId ) const { switch ( nPropId ) { case BASEPROPERTY_DEFAULTCONTROL: return uno::makeAny( ::rtl::OUString::createFromAscii( szServiceName_UnoThrobberControl ) ); default: return UnoControlModel::ImplGetDefaultValue( nPropId ); } } //-------------------------------------------------------------------- ::cppu::IPropertyArrayHelper& UnoThrobberControlModel::getInfoHelper() { static UnoPropertyArrayHelper* pHelper = NULL; if ( !pHelper ) { uno::Sequence< sal_Int32 > aIDs = ImplGetPropertyIds(); pHelper = new UnoPropertyArrayHelper( aIDs ); } return *pHelper; } //-------------------------------------------------------------------- uno::Reference< beans::XPropertySetInfo > UnoThrobberControlModel::getPropertySetInfo() throw( uno::RuntimeException ) { static uno::Reference< beans::XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } //-------------------------------------------------------------------- ::rtl::OUString SAL_CALL UnoThrobberControlModel::getImplementationName() throw( uno::RuntimeException ) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.toolkit.UnoThrobberControlModel" ) ); } //-------------------------------------------------------------------- uno::Sequence< ::rtl::OUString > SAL_CALL UnoThrobberControlModel::getSupportedServiceNames() throw( uno::RuntimeException ) { uno::Sequence< ::rtl::OUString > aServices( UnoControlModel::getSupportedServiceNames() ); aServices.realloc( aServices.getLength() + 1 ); aServices[ aServices.getLength() - 1 ] = ::rtl::OUString::createFromAscii( szServiceName_UnoThrobberControlModel ); return aServices; } //==================================================================== //= UnoThrobberControl //==================================================================== //-------------------------------------------------------------------- UnoThrobberControl::UnoThrobberControl() { } //-------------------------------------------------------------------- ::rtl::OUString UnoThrobberControl::GetComponentServiceName() { return ::rtl::OUString::createFromAscii( "Throbber" ); } //-------------------------------------------------------------------- uno::Any UnoThrobberControl::queryAggregation( const uno::Type & rType ) throw( uno::RuntimeException ) { uno::Any aRet = UnoControlBase::queryAggregation( rType ); if ( !aRet.hasValue() ) aRet = UnoThrobberControl_Base::queryInterface( rType ); return aRet; } //-------------------------------------------------------------------- IMPLEMENT_FORWARD_XTYPEPROVIDER2( UnoThrobberControl, UnoControlBase, UnoThrobberControl_Base ) //-------------------------------------------------------------------- void UnoThrobberControl::dispose() throw( uno::RuntimeException ) { ::osl::ClearableMutexGuard aGuard( GetMutex() ); UnoControl::dispose(); } //-------------------------------------------------------------------- ::rtl::OUString SAL_CALL UnoThrobberControl::getImplementationName() throw( uno::RuntimeException ) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.toolkit.UnoThrobberControl" ) ); } //-------------------------------------------------------------------- uno::Sequence< ::rtl::OUString > SAL_CALL UnoThrobberControl::getSupportedServiceNames() throw( uno::RuntimeException ) { uno::Sequence< ::rtl::OUString > aServices( UnoControlBase::getSupportedServiceNames() ); aServices.realloc( aServices.getLength() + 1 ); aServices[ aServices.getLength() - 1 ] = ::rtl::OUString::createFromAscii( szServiceName_UnoThrobberControl ); return aServices; } //-------------------------------------------------------------------- void UnoThrobberControl::createPeer( const uno::Reference< awt::XToolkit > & rxToolkit, const uno::Reference< awt::XWindowPeer > & rParentPeer ) throw( uno::RuntimeException ) { UnoControl::createPeer( rxToolkit, rParentPeer ); } //-------------------------------------------------------------------- void SAL_CALL UnoThrobberControl::start() throw ( uno::RuntimeException ) { ::osl::MutexGuard aGuard( GetMutex() ); uno::Reference< XThrobber > xAnimation( getPeer(), uno::UNO_QUERY ); if ( xAnimation.is() ) xAnimation->start(); } //-------------------------------------------------------------------- void SAL_CALL UnoThrobberControl::stop() throw ( uno::RuntimeException ) { ::osl::MutexGuard aGuard( GetMutex() ); uno::Reference< XThrobber > xAnimation( getPeer(), uno::UNO_QUERY ); if ( xAnimation.is() ) xAnimation->stop(); } //........................................................................ } // namespace toolkit //........................................................................ <commit_msg>INTEGRATION: CWS changefileheader (1.3.148); FILE MERGED 2008/04/01 16:00:59 thb 1.3.148.3: #i85898# Stripping all external header guards 2008/04/01 12:56:52 thb 1.3.148.2: #i85898# Stripping all external header guards 2008/03/28 15:40:17 rt 1.3.148.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tkthrobber.cxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_toolkit.hxx" #include "toolkit/controls/tkthrobber.hxx" #include "toolkit/helper/property.hxx" #include "toolkit/helper/unopropertyarrayhelper.hxx" #include <cppuhelper/typeprovider.hxx> #include <tools/debug.hxx> //........................................................................ namespace toolkit { //........................................................................ using namespace ::com::sun::star; //==================================================================== //= UnoThrobberControlModel //==================================================================== //-------------------------------------------------------------------- UnoThrobberControlModel::UnoThrobberControlModel() { ImplRegisterProperty( BASEPROPERTY_DEFAULTCONTROL ); ImplRegisterProperty( BASEPROPERTY_BACKGROUNDCOLOR ); } //-------------------------------------------------------------------- ::rtl::OUString UnoThrobberControlModel::getServiceName( ) throw ( uno::RuntimeException ) { return ::rtl::OUString::createFromAscii( szServiceName_UnoThrobberControlModel ); } //-------------------------------------------------------------------- uno::Any UnoThrobberControlModel::ImplGetDefaultValue( sal_uInt16 nPropId ) const { switch ( nPropId ) { case BASEPROPERTY_DEFAULTCONTROL: return uno::makeAny( ::rtl::OUString::createFromAscii( szServiceName_UnoThrobberControl ) ); default: return UnoControlModel::ImplGetDefaultValue( nPropId ); } } //-------------------------------------------------------------------- ::cppu::IPropertyArrayHelper& UnoThrobberControlModel::getInfoHelper() { static UnoPropertyArrayHelper* pHelper = NULL; if ( !pHelper ) { uno::Sequence< sal_Int32 > aIDs = ImplGetPropertyIds(); pHelper = new UnoPropertyArrayHelper( aIDs ); } return *pHelper; } //-------------------------------------------------------------------- uno::Reference< beans::XPropertySetInfo > UnoThrobberControlModel::getPropertySetInfo() throw( uno::RuntimeException ) { static uno::Reference< beans::XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) ); return xInfo; } //-------------------------------------------------------------------- ::rtl::OUString SAL_CALL UnoThrobberControlModel::getImplementationName() throw( uno::RuntimeException ) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.toolkit.UnoThrobberControlModel" ) ); } //-------------------------------------------------------------------- uno::Sequence< ::rtl::OUString > SAL_CALL UnoThrobberControlModel::getSupportedServiceNames() throw( uno::RuntimeException ) { uno::Sequence< ::rtl::OUString > aServices( UnoControlModel::getSupportedServiceNames() ); aServices.realloc( aServices.getLength() + 1 ); aServices[ aServices.getLength() - 1 ] = ::rtl::OUString::createFromAscii( szServiceName_UnoThrobberControlModel ); return aServices; } //==================================================================== //= UnoThrobberControl //==================================================================== //-------------------------------------------------------------------- UnoThrobberControl::UnoThrobberControl() { } //-------------------------------------------------------------------- ::rtl::OUString UnoThrobberControl::GetComponentServiceName() { return ::rtl::OUString::createFromAscii( "Throbber" ); } //-------------------------------------------------------------------- uno::Any UnoThrobberControl::queryAggregation( const uno::Type & rType ) throw( uno::RuntimeException ) { uno::Any aRet = UnoControlBase::queryAggregation( rType ); if ( !aRet.hasValue() ) aRet = UnoThrobberControl_Base::queryInterface( rType ); return aRet; } //-------------------------------------------------------------------- IMPLEMENT_FORWARD_XTYPEPROVIDER2( UnoThrobberControl, UnoControlBase, UnoThrobberControl_Base ) //-------------------------------------------------------------------- void UnoThrobberControl::dispose() throw( uno::RuntimeException ) { ::osl::ClearableMutexGuard aGuard( GetMutex() ); UnoControl::dispose(); } //-------------------------------------------------------------------- ::rtl::OUString SAL_CALL UnoThrobberControl::getImplementationName() throw( uno::RuntimeException ) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.toolkit.UnoThrobberControl" ) ); } //-------------------------------------------------------------------- uno::Sequence< ::rtl::OUString > SAL_CALL UnoThrobberControl::getSupportedServiceNames() throw( uno::RuntimeException ) { uno::Sequence< ::rtl::OUString > aServices( UnoControlBase::getSupportedServiceNames() ); aServices.realloc( aServices.getLength() + 1 ); aServices[ aServices.getLength() - 1 ] = ::rtl::OUString::createFromAscii( szServiceName_UnoThrobberControl ); return aServices; } //-------------------------------------------------------------------- void UnoThrobberControl::createPeer( const uno::Reference< awt::XToolkit > & rxToolkit, const uno::Reference< awt::XWindowPeer > & rParentPeer ) throw( uno::RuntimeException ) { UnoControl::createPeer( rxToolkit, rParentPeer ); } //-------------------------------------------------------------------- void SAL_CALL UnoThrobberControl::start() throw ( uno::RuntimeException ) { ::osl::MutexGuard aGuard( GetMutex() ); uno::Reference< XThrobber > xAnimation( getPeer(), uno::UNO_QUERY ); if ( xAnimation.is() ) xAnimation->start(); } //-------------------------------------------------------------------- void SAL_CALL UnoThrobberControl::stop() throw ( uno::RuntimeException ) { ::osl::MutexGuard aGuard( GetMutex() ); uno::Reference< XThrobber > xAnimation( getPeer(), uno::UNO_QUERY ); if ( xAnimation.is() ) xAnimation->stop(); } //........................................................................ } // namespace toolkit //........................................................................ <|endoftext|>
<commit_before>//===-- Clustering.cpp ------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Clustering.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallVector.h" #include <string> namespace llvm { namespace exegesis { // The clustering problem has the following characteristics: // (A) - Low dimension (dimensions are typically proc resource units, // typically < 10). // (B) - Number of points : ~thousands (points are measurements of an MCInst) // (C) - Number of clusters: ~tens. // (D) - The number of clusters is not known /a priory/. // (E) - The amount of noise is relatively small. // The problem is rather small. In terms of algorithms, (D) disqualifies // k-means and makes algorithms such as DBSCAN[1] or OPTICS[2] more applicable. // // We've used DBSCAN here because it's simple to implement. This is a pretty // straightforward and inefficient implementation of the pseudocode in [2]. // // [1] https://en.wikipedia.org/wiki/DBSCAN // [2] https://en.wikipedia.org/wiki/OPTICS_algorithm // Finds the points at distance less than sqrt(EpsilonSquared) of Q (not // including Q). void InstructionBenchmarkClustering::rangeQuery( const size_t Q, std::vector<size_t> &Neighbors) const { Neighbors.clear(); Neighbors.reserve(Points_.size() - 1); // The Q itself isn't a neighbor. const auto &QMeasurements = Points_[Q].Measurements; for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) { if (P == Q) continue; const auto &PMeasurements = Points_[P].Measurements; if (PMeasurements.empty()) // Error point. continue; if (isNeighbour(PMeasurements, QMeasurements)) { Neighbors.push_back(P); } } } InstructionBenchmarkClustering::InstructionBenchmarkClustering( const std::vector<InstructionBenchmark> &Points, const double EpsilonSquared) : Points_(Points), EpsilonSquared_(EpsilonSquared), NoiseCluster_(ClusterId::noise()), ErrorCluster_(ClusterId::error()) {} llvm::Error InstructionBenchmarkClustering::validateAndSetup() { ClusterIdForPoint_.resize(Points_.size()); // Mark erroneous measurements out. // All points must have the same number of dimensions, in the same order. const std::vector<BenchmarkMeasure> *LastMeasurement = nullptr; for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) { const auto &Point = Points_[P]; if (!Point.Error.empty()) { ClusterIdForPoint_[P] = ClusterId::error(); ErrorCluster_.PointIndices.push_back(P); continue; } const auto *CurMeasurement = &Point.Measurements; if (LastMeasurement) { if (LastMeasurement->size() != CurMeasurement->size()) { return llvm::make_error<llvm::StringError>( "inconsistent measurement dimensions", llvm::inconvertibleErrorCode()); } for (size_t I = 0, E = LastMeasurement->size(); I < E; ++I) { if (LastMeasurement->at(I).Key != CurMeasurement->at(I).Key) { return llvm::make_error<llvm::StringError>( "inconsistent measurement dimensions keys", llvm::inconvertibleErrorCode()); } } } LastMeasurement = CurMeasurement; } if (LastMeasurement) { NumDimensions_ = LastMeasurement->size(); } return llvm::Error::success(); } void InstructionBenchmarkClustering::dbScan(const size_t MinPts) { std::vector<size_t> Neighbors; // Persistent buffer to avoid allocs. for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) { if (!ClusterIdForPoint_[P].isUndef()) continue; // Previously processed in inner loop. rangeQuery(P, Neighbors); if (Neighbors.size() + 1 < MinPts) { // Density check. // The region around P is not dense enough to create a new cluster, mark // as noise for now. ClusterIdForPoint_[P] = ClusterId::noise(); continue; } // Create a new cluster, add P. Clusters_.emplace_back(ClusterId::makeValid(Clusters_.size())); Cluster &CurrentCluster = Clusters_.back(); ClusterIdForPoint_[P] = CurrentCluster.Id; /* Label initial point */ CurrentCluster.PointIndices.push_back(P); // Process P's neighbors. llvm::SetVector<size_t, std::deque<size_t>> ToProcess; ToProcess.insert(Neighbors.begin(), Neighbors.end()); while (!ToProcess.empty()) { // Retrieve a point from the set. const size_t Q = *ToProcess.begin(); ToProcess.erase(ToProcess.begin()); if (ClusterIdForPoint_[Q].isNoise()) { // Change noise point to border point. ClusterIdForPoint_[Q] = CurrentCluster.Id; CurrentCluster.PointIndices.push_back(Q); continue; } if (!ClusterIdForPoint_[Q].isUndef()) { continue; // Previously processed. } // Add Q to the current custer. ClusterIdForPoint_[Q] = CurrentCluster.Id; CurrentCluster.PointIndices.push_back(Q); // And extend to the neighbors of Q if the region is dense enough. rangeQuery(Q, Neighbors); if (Neighbors.size() + 1 >= MinPts) { ToProcess.insert(Neighbors.begin(), Neighbors.end()); } } } // assert(Neighbors.capacity() == (Points_.size() - 1)); // ^ True, but it is not quaranteed to be true in all the cases. // Add noisy points to noise cluster. for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) { if (ClusterIdForPoint_[P].isNoise()) { NoiseCluster_.PointIndices.push_back(P); } } } llvm::Expected<InstructionBenchmarkClustering> InstructionBenchmarkClustering::create( const std::vector<InstructionBenchmark> &Points, const size_t MinPts, const double Epsilon) { InstructionBenchmarkClustering Clustering(Points, Epsilon * Epsilon); if (auto Error = Clustering.validateAndSetup()) { return std::move(Error); } if (Clustering.ErrorCluster_.PointIndices.size() == Points.size()) { return Clustering; // Nothing to cluster. } Clustering.dbScan(MinPts); return Clustering; } } // namespace exegesis } // namespace llvm <commit_msg>[llvm-exegesis] Optimize ToProcess in dbScan<commit_after>//===-- Clustering.cpp ------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Clustering.h" #include "llvm/ADT/SmallVector.h" #include <string> namespace llvm { namespace exegesis { // The clustering problem has the following characteristics: // (A) - Low dimension (dimensions are typically proc resource units, // typically < 10). // (B) - Number of points : ~thousands (points are measurements of an MCInst) // (C) - Number of clusters: ~tens. // (D) - The number of clusters is not known /a priory/. // (E) - The amount of noise is relatively small. // The problem is rather small. In terms of algorithms, (D) disqualifies // k-means and makes algorithms such as DBSCAN[1] or OPTICS[2] more applicable. // // We've used DBSCAN here because it's simple to implement. This is a pretty // straightforward and inefficient implementation of the pseudocode in [2]. // // [1] https://en.wikipedia.org/wiki/DBSCAN // [2] https://en.wikipedia.org/wiki/OPTICS_algorithm // Finds the points at distance less than sqrt(EpsilonSquared) of Q (not // including Q). void InstructionBenchmarkClustering::rangeQuery( const size_t Q, std::vector<size_t> &Neighbors) const { Neighbors.clear(); Neighbors.reserve(Points_.size() - 1); // The Q itself isn't a neighbor. const auto &QMeasurements = Points_[Q].Measurements; for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) { if (P == Q) continue; const auto &PMeasurements = Points_[P].Measurements; if (PMeasurements.empty()) // Error point. continue; if (isNeighbour(PMeasurements, QMeasurements)) { Neighbors.push_back(P); } } } InstructionBenchmarkClustering::InstructionBenchmarkClustering( const std::vector<InstructionBenchmark> &Points, const double EpsilonSquared) : Points_(Points), EpsilonSquared_(EpsilonSquared), NoiseCluster_(ClusterId::noise()), ErrorCluster_(ClusterId::error()) {} llvm::Error InstructionBenchmarkClustering::validateAndSetup() { ClusterIdForPoint_.resize(Points_.size()); // Mark erroneous measurements out. // All points must have the same number of dimensions, in the same order. const std::vector<BenchmarkMeasure> *LastMeasurement = nullptr; for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) { const auto &Point = Points_[P]; if (!Point.Error.empty()) { ClusterIdForPoint_[P] = ClusterId::error(); ErrorCluster_.PointIndices.push_back(P); continue; } const auto *CurMeasurement = &Point.Measurements; if (LastMeasurement) { if (LastMeasurement->size() != CurMeasurement->size()) { return llvm::make_error<llvm::StringError>( "inconsistent measurement dimensions", llvm::inconvertibleErrorCode()); } for (size_t I = 0, E = LastMeasurement->size(); I < E; ++I) { if (LastMeasurement->at(I).Key != CurMeasurement->at(I).Key) { return llvm::make_error<llvm::StringError>( "inconsistent measurement dimensions keys", llvm::inconvertibleErrorCode()); } } } LastMeasurement = CurMeasurement; } if (LastMeasurement) { NumDimensions_ = LastMeasurement->size(); } return llvm::Error::success(); } void InstructionBenchmarkClustering::dbScan(const size_t MinPts) { const size_t NumPoints = Points_.size(); // Persistent buffers to avoid allocs. std::vector<size_t> Neighbors; std::vector<size_t> ToProcess(NumPoints); std::vector<char> Added(NumPoints); for (size_t P = 0; P < NumPoints; ++P) { if (!ClusterIdForPoint_[P].isUndef()) continue; // Previously processed in inner loop. rangeQuery(P, Neighbors); if (Neighbors.size() + 1 < MinPts) { // Density check. // The region around P is not dense enough to create a new cluster, mark // as noise for now. ClusterIdForPoint_[P] = ClusterId::noise(); continue; } // Create a new cluster, add P. Clusters_.emplace_back(ClusterId::makeValid(Clusters_.size())); Cluster &CurrentCluster = Clusters_.back(); ClusterIdForPoint_[P] = CurrentCluster.Id; /* Label initial point */ CurrentCluster.PointIndices.push_back(P); Added[P] = 1; // Process P's neighbors. size_t Tail = 0; for (size_t Q : Neighbors) if (!Added[Q]) { ToProcess[Tail++] = P; Added[Q] = 1; } for (size_t Head = 0; Head < Tail; ++Head) { // Retrieve a point from the set. size_t Q = ToProcess[Head]; if (ClusterIdForPoint_[Q].isNoise()) { // Change noise point to border point. ClusterIdForPoint_[Q] = CurrentCluster.Id; CurrentCluster.PointIndices.push_back(Q); continue; } assert(ClusterIdForPoint_[Q].isUndef()); // Add Q to the current custer. ClusterIdForPoint_[Q] = CurrentCluster.Id; CurrentCluster.PointIndices.push_back(Q); // And extend to the neighbors of Q if the region is dense enough. rangeQuery(Q, Neighbors); if (Neighbors.size() + 1 >= MinPts) for (size_t P : Neighbors) if (!Added[P]) { ToProcess[Tail++] = P; Added[P] = 1; } } } // assert(Neighbors.capacity() == (Points_.size() - 1)); // ^ True, but it is not quaranteed to be true in all the cases. // Add noisy points to noise cluster. for (size_t P = 0, NumPoints = Points_.size(); P < NumPoints; ++P) { if (ClusterIdForPoint_[P].isNoise()) { NoiseCluster_.PointIndices.push_back(P); } } } llvm::Expected<InstructionBenchmarkClustering> InstructionBenchmarkClustering::create( const std::vector<InstructionBenchmark> &Points, const size_t MinPts, const double Epsilon) { InstructionBenchmarkClustering Clustering(Points, Epsilon * Epsilon); if (auto Error = Clustering.validateAndSetup()) { return std::move(Error); } if (Clustering.ErrorCluster_.PointIndices.size() == Points.size()) { return Clustering; // Nothing to cluster. } Clustering.dbScan(MinPts); return Clustering; } } // namespace exegesis } // namespace llvm <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2011-2012 Jose Fonseca * 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 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. * **************************************************************************/ /** * Window system helpers for glretrace. */ #include <string.h> #include <algorithm> #include <map> #include "os_thread.hpp" #include "retrace.hpp" #include "glproc.hpp" #include "glstate.hpp" #include "glretrace.hpp" namespace glretrace { static std::map<glfeatures::Profile, glws::Visual *> visuals; inline glws::Visual * getVisual(glfeatures::Profile profile) { std::map<glfeatures::Profile, glws::Visual *>::iterator it = visuals.find(profile); if (it == visuals.end()) { glws::Visual *visual = NULL; unsigned samples = retrace::samples; /* The requested number of samples might not be available, try fewer until we succeed */ while (!visual && samples > 0) { visual = glws::createVisual(retrace::doubleBuffer, samples, profile); if (!visual) { samples--; } } if (!visual) { std::cerr << "error: failed to create OpenGL visual\n"; exit(1); } if (samples != retrace::samples) { std::cerr << "warning: Using " << samples << " samples instead of the requested " << retrace::samples << "\n"; } visuals[profile] = visual; return visual; } return it->second; } static glws::Drawable * createDrawableHelper(glfeatures::Profile profile, int width = 32, int height = 32, const glws::pbuffer_info *pbInfo = NULL) { glws::Visual *visual = getVisual(profile); glws::Drawable *draw = glws::createDrawable(visual, width, height, pbInfo); if (!draw) { std::cerr << "error: failed to create OpenGL drawable\n"; exit(1); } if (pbInfo) draw->pbInfo = *pbInfo; return draw; } glws::Drawable * createDrawable(glfeatures::Profile profile) { return createDrawableHelper(profile); } glws::Drawable * createDrawable(void) { return createDrawable(defaultProfile); } glws::Drawable * createPbuffer(int width, int height, const glws::pbuffer_info *pbInfo) { // Zero area pbuffers are often accepted, but given we create window // drawables instead, they should have non-zero area. width = std::max(width, 1); height = std::max(height, 1); return createDrawableHelper(defaultProfile, width, height, pbInfo); } Context * createContext(Context *shareContext, glfeatures::Profile profile) { glws::Visual *visual = getVisual(profile); glws::Context *shareWsContext = shareContext ? shareContext->wsContext : NULL; glws::Context *ctx = glws::createContext(visual, shareWsContext, retrace::debug); if (!ctx) { std::cerr << "error: failed to create " << profile << " context.\n"; exit(1); } return new Context(ctx); } Context * createContext(Context *shareContext) { return createContext(shareContext, defaultProfile); } Context::~Context() { //assert(this != getCurrentContext()); if (this != getCurrentContext()) { delete wsContext; } } OS_THREAD_LOCAL Context * currentContextPtr; bool makeCurrent(trace::Call &call, glws::Drawable *drawable, Context *context) { return makeCurrent(call, drawable, drawable, context); } bool makeCurrent(trace::Call &call, glws::Drawable *drawable, glws::Drawable *readable, Context *context) { Context *currentContext = currentContextPtr; glws::Drawable *currentDrawable = currentContext ? currentContext->drawable : NULL; glws::Drawable *currentReadable = currentContext ? currentContext->readable : NULL; if (drawable == currentDrawable && readable == currentReadable && context == currentContext) { return true; } if (currentContext) { glFlush(); currentContext->needsFlush = false; if (!retrace::doubleBuffer) { frame_complete(call); } } flushQueries(); beforeContextSwitch(); bool success = glws::makeCurrent(drawable, readable, context ? context->wsContext : NULL); if (!success) { std::cerr << "error: failed to make current OpenGL context and drawable\n"; exit(1); } if (context != currentContext) { if (context) { context->aquire(); } currentContextPtr = context; if (currentContext) { currentContext->release(); } } if (drawable && context) { context->drawable = drawable; context->readable = readable; if (!context->used) { initContext(); context->used = true; } } afterContextSwitch(); return true; } /** * Grow the current drawble. * * We need to infer the drawable size from GL calls because the drawable sizes * are specified by OS specific calls which we do not trace. */ void updateDrawable(int width, int height) { Context *currentContext = getCurrentContext(); if (!currentContext) { return; } glws::Drawable *currentDrawable = currentContext->drawable; if (!currentDrawable) { return; } if (currentDrawable->pbuffer) { return; } if (currentDrawable->visible && width <= currentDrawable->width && height <= currentDrawable->height) { return; } // Ignore zero area viewports if (width == 0 || height == 0) { return; } width = std::max(width, currentDrawable->width); height = std::max(height, currentDrawable->height); // Check for bound framebuffer last, as this may have a performance impact. if (currentContext->features().framebuffer_object) { GLint framebuffer = 0; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &framebuffer); if (framebuffer != 0) { return; } } currentDrawable->resize(width, height); currentDrawable->show(); // Ensure the drawable dimensions, as perceived by glstate match. if (retrace::debug) { GLint newWidth = 0; GLint newHeight = 0; if (glstate::getDrawableBounds(&newWidth, &newHeight) && (newWidth != width || newHeight != height)) { std::cerr << "error: drawable failed to resize: " << "expected " << width << "x" << height << ", " << "got " << newWidth << "x" << newHeight << "\n"; } } glScissor(0, 0, width, height); } int parseAttrib(const trace::Value *attribs, int param, int default_, int terminator) { const trace::Array *attribs_ = attribs ? attribs->toArray() : NULL; if (attribs_) { for (size_t i = 0; i + 1 < attribs_->values.size(); i += 2) { int param_i = attribs_->values[i]->toSInt(); if (param_i == terminator) { break; } if (param_i == param) { int value = attribs_->values[i + 1]->toSInt(); return value; } } } return default_; } /** * Parse GLX/WGL_ARB_create_context attribute list. */ glfeatures::Profile parseContextAttribList(const trace::Value *attribs) { // {GLX,WGL}_CONTEXT_MAJOR_VERSION_ARB int major_version = parseAttrib(attribs, 0x2091, 1); // {GLX,WGL}_CONTEXT_MINOR_VERSION_ARB int minor_version = parseAttrib(attribs, 0x2092, 0); int profile_mask = parseAttrib(attribs, GL_CONTEXT_PROFILE_MASK, GL_CONTEXT_CORE_PROFILE_BIT); bool core_profile = profile_mask & GL_CONTEXT_CORE_PROFILE_BIT; if (major_version < 3 || (major_version == 3 && minor_version < 2)) { core_profile = false; } int context_flags = parseAttrib(attribs, GL_CONTEXT_FLAGS, 0); bool forward_compatible = context_flags & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT; if (major_version < 3) { forward_compatible = false; } // {GLX,WGL}_CONTEXT_ES_PROFILE_BIT_EXT bool es_profile = profile_mask & 0x0004; glfeatures::Profile profile; if (es_profile) { profile.api = glfeatures::API_GLES; } else { profile.api = glfeatures::API_GL; profile.core = core_profile; profile.forwardCompatible = forward_compatible; } profile.major = major_version; profile.minor = minor_version; return profile; } // WGL_ARB_render_texture / wglBindTexImageARB() bool bindTexImage(glws::Drawable *pBuffer, int iBuffer) { return glws::bindTexImage(pBuffer, iBuffer); } // WGL_ARB_render_texture / wglReleaseTexImageARB() bool releaseTexImage(glws::Drawable *pBuffer, int iBuffer) { return glws::releaseTexImage(pBuffer, iBuffer); } // WGL_ARB_render_texture / wglSetPbufferAttribARB() bool setPbufferAttrib(glws::Drawable *pBuffer, const int *attribs) { return glws::setPbufferAttrib(pBuffer, attribs); } } /* namespace glretrace */ <commit_msg>glretrace: fix a comment typo<commit_after>/************************************************************************** * * Copyright 2011-2012 Jose Fonseca * 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 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. * **************************************************************************/ /** * Window system helpers for glretrace. */ #include <string.h> #include <algorithm> #include <map> #include "os_thread.hpp" #include "retrace.hpp" #include "glproc.hpp" #include "glstate.hpp" #include "glretrace.hpp" namespace glretrace { static std::map<glfeatures::Profile, glws::Visual *> visuals; inline glws::Visual * getVisual(glfeatures::Profile profile) { std::map<glfeatures::Profile, glws::Visual *>::iterator it = visuals.find(profile); if (it == visuals.end()) { glws::Visual *visual = NULL; unsigned samples = retrace::samples; /* The requested number of samples might not be available, try fewer until we succeed */ while (!visual && samples > 0) { visual = glws::createVisual(retrace::doubleBuffer, samples, profile); if (!visual) { samples--; } } if (!visual) { std::cerr << "error: failed to create OpenGL visual\n"; exit(1); } if (samples != retrace::samples) { std::cerr << "warning: Using " << samples << " samples instead of the requested " << retrace::samples << "\n"; } visuals[profile] = visual; return visual; } return it->second; } static glws::Drawable * createDrawableHelper(glfeatures::Profile profile, int width = 32, int height = 32, const glws::pbuffer_info *pbInfo = NULL) { glws::Visual *visual = getVisual(profile); glws::Drawable *draw = glws::createDrawable(visual, width, height, pbInfo); if (!draw) { std::cerr << "error: failed to create OpenGL drawable\n"; exit(1); } if (pbInfo) draw->pbInfo = *pbInfo; return draw; } glws::Drawable * createDrawable(glfeatures::Profile profile) { return createDrawableHelper(profile); } glws::Drawable * createDrawable(void) { return createDrawable(defaultProfile); } glws::Drawable * createPbuffer(int width, int height, const glws::pbuffer_info *pbInfo) { // Zero area pbuffers are often accepted, but given we create window // drawables instead, they should have non-zero area. width = std::max(width, 1); height = std::max(height, 1); return createDrawableHelper(defaultProfile, width, height, pbInfo); } Context * createContext(Context *shareContext, glfeatures::Profile profile) { glws::Visual *visual = getVisual(profile); glws::Context *shareWsContext = shareContext ? shareContext->wsContext : NULL; glws::Context *ctx = glws::createContext(visual, shareWsContext, retrace::debug); if (!ctx) { std::cerr << "error: failed to create " << profile << " context.\n"; exit(1); } return new Context(ctx); } Context * createContext(Context *shareContext) { return createContext(shareContext, defaultProfile); } Context::~Context() { //assert(this != getCurrentContext()); if (this != getCurrentContext()) { delete wsContext; } } OS_THREAD_LOCAL Context * currentContextPtr; bool makeCurrent(trace::Call &call, glws::Drawable *drawable, Context *context) { return makeCurrent(call, drawable, drawable, context); } bool makeCurrent(trace::Call &call, glws::Drawable *drawable, glws::Drawable *readable, Context *context) { Context *currentContext = currentContextPtr; glws::Drawable *currentDrawable = currentContext ? currentContext->drawable : NULL; glws::Drawable *currentReadable = currentContext ? currentContext->readable : NULL; if (drawable == currentDrawable && readable == currentReadable && context == currentContext) { return true; } if (currentContext) { glFlush(); currentContext->needsFlush = false; if (!retrace::doubleBuffer) { frame_complete(call); } } flushQueries(); beforeContextSwitch(); bool success = glws::makeCurrent(drawable, readable, context ? context->wsContext : NULL); if (!success) { std::cerr << "error: failed to make current OpenGL context and drawable\n"; exit(1); } if (context != currentContext) { if (context) { context->aquire(); } currentContextPtr = context; if (currentContext) { currentContext->release(); } } if (drawable && context) { context->drawable = drawable; context->readable = readable; if (!context->used) { initContext(); context->used = true; } } afterContextSwitch(); return true; } /** * Grow the current drawable. * * We need to infer the drawable size from GL calls because the drawable sizes * are specified by OS specific calls which we do not trace. */ void updateDrawable(int width, int height) { Context *currentContext = getCurrentContext(); if (!currentContext) { return; } glws::Drawable *currentDrawable = currentContext->drawable; if (!currentDrawable) { return; } if (currentDrawable->pbuffer) { return; } if (currentDrawable->visible && width <= currentDrawable->width && height <= currentDrawable->height) { return; } // Ignore zero area viewports if (width == 0 || height == 0) { return; } width = std::max(width, currentDrawable->width); height = std::max(height, currentDrawable->height); // Check for bound framebuffer last, as this may have a performance impact. if (currentContext->features().framebuffer_object) { GLint framebuffer = 0; glGetIntegerv(GL_FRAMEBUFFER_BINDING, &framebuffer); if (framebuffer != 0) { return; } } currentDrawable->resize(width, height); currentDrawable->show(); // Ensure the drawable dimensions, as perceived by glstate match. if (retrace::debug) { GLint newWidth = 0; GLint newHeight = 0; if (glstate::getDrawableBounds(&newWidth, &newHeight) && (newWidth != width || newHeight != height)) { std::cerr << "error: drawable failed to resize: " << "expected " << width << "x" << height << ", " << "got " << newWidth << "x" << newHeight << "\n"; } } glScissor(0, 0, width, height); } int parseAttrib(const trace::Value *attribs, int param, int default_, int terminator) { const trace::Array *attribs_ = attribs ? attribs->toArray() : NULL; if (attribs_) { for (size_t i = 0; i + 1 < attribs_->values.size(); i += 2) { int param_i = attribs_->values[i]->toSInt(); if (param_i == terminator) { break; } if (param_i == param) { int value = attribs_->values[i + 1]->toSInt(); return value; } } } return default_; } /** * Parse GLX/WGL_ARB_create_context attribute list. */ glfeatures::Profile parseContextAttribList(const trace::Value *attribs) { // {GLX,WGL}_CONTEXT_MAJOR_VERSION_ARB int major_version = parseAttrib(attribs, 0x2091, 1); // {GLX,WGL}_CONTEXT_MINOR_VERSION_ARB int minor_version = parseAttrib(attribs, 0x2092, 0); int profile_mask = parseAttrib(attribs, GL_CONTEXT_PROFILE_MASK, GL_CONTEXT_CORE_PROFILE_BIT); bool core_profile = profile_mask & GL_CONTEXT_CORE_PROFILE_BIT; if (major_version < 3 || (major_version == 3 && minor_version < 2)) { core_profile = false; } int context_flags = parseAttrib(attribs, GL_CONTEXT_FLAGS, 0); bool forward_compatible = context_flags & GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT; if (major_version < 3) { forward_compatible = false; } // {GLX,WGL}_CONTEXT_ES_PROFILE_BIT_EXT bool es_profile = profile_mask & 0x0004; glfeatures::Profile profile; if (es_profile) { profile.api = glfeatures::API_GLES; } else { profile.api = glfeatures::API_GL; profile.core = core_profile; profile.forwardCompatible = forward_compatible; } profile.major = major_version; profile.minor = minor_version; return profile; } // WGL_ARB_render_texture / wglBindTexImageARB() bool bindTexImage(glws::Drawable *pBuffer, int iBuffer) { return glws::bindTexImage(pBuffer, iBuffer); } // WGL_ARB_render_texture / wglReleaseTexImageARB() bool releaseTexImage(glws::Drawable *pBuffer, int iBuffer) { return glws::releaseTexImage(pBuffer, iBuffer); } // WGL_ARB_render_texture / wglSetPbufferAttribARB() bool setPbufferAttrib(glws::Drawable *pBuffer, const int *attribs) { return glws::setPbufferAttrib(pBuffer, attribs); } } /* namespace glretrace */ <|endoftext|>
<commit_before>/* -*- indent-tabs-mode: nil -*- */ #include <gflags/gflags.h> #include <glog/logging.h> #include <gtest/gtest.h> #include <set> #include <string> #include "database.h" #include "file_db.h" #include "file_storage.h" #include "sqlite_db.h" #include "test_db.h" #include "test_signer.h" #include "util.h" namespace { using ct::DigitallySigned; using ct::LogEntry; using ct::LoggedCertificate; using ct::PrecertChainEntry; using ct::SignedTreeHead; using ct::X509ChainEntry; using std::string; // A slightly shorter notation for constructing hex strings from binary blobs. string H(const string &byte_string) { return util::HexString(byte_string); } template <class T> class DBTest : public ::testing::Test { protected: DBTest() : test_db_(), test_signer_() { } ~DBTest() {} T *db() const { return test_db_.db(); } TestDB<T> test_db_; TestSigner test_signer_; }; typedef testing::Types<FileDB, SQLiteDB> Databases; TYPED_TEST_CASE(DBTest, Databases); TYPED_TEST(DBTest, CreatePending) { LoggedCertificate logged_cert, lookup_cert; this->test_signer_.CreateUnique(&logged_cert); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert)); EXPECT_EQ(Database::LOOKUP_OK, this->db()->LookupCertificateByHash( logged_cert.certificate_sha256_hash(), &lookup_cert)); TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert); string similar_hash = logged_cert.certificate_sha256_hash(); similar_hash[similar_hash.size() - 1] ^= 1; EXPECT_EQ(Database::NOT_FOUND, this->db()->LookupCertificateByHash(similar_hash, &lookup_cert)); EXPECT_EQ(Database::NOT_FOUND, this->db()->LookupCertificateByHash(this->test_signer_.UniqueHash(), &lookup_cert)); } TYPED_TEST(DBTest, GetPendingHashes) { LoggedCertificate logged_cert, logged_cert2; this->test_signer_.CreateUnique(&logged_cert); this->test_signer_.CreateUnique(&logged_cert2); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert)); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert2)); std::set<string> hashes; hashes.insert(logged_cert.certificate_sha256_hash()); hashes.insert(logged_cert2.certificate_sha256_hash()); std::set<string> pending_hashes = this->db()->PendingHashes(); EXPECT_EQ(hashes, pending_hashes); } TYPED_TEST(DBTest, CreatePendingDuplicate) { LoggedCertificate logged_cert, duplicate_cert, lookup_cert; this->test_signer_.CreateUnique(&logged_cert); duplicate_cert.CopyFrom(logged_cert); // Change the timestamp so that we can check that we get the right thing back. duplicate_cert.mutable_sct()->set_timestamp( logged_cert.sct().timestamp() + 1000); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert)); EXPECT_EQ(Database::DUPLICATE_CERTIFICATE_HASH, this->db()->CreatePendingCertificateEntry(duplicate_cert)); EXPECT_EQ(Database::LOOKUP_OK, this->db()->LookupCertificateByHash( logged_cert.certificate_sha256_hash(), &lookup_cert)); // Check that we get the original entry back. TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert); } TYPED_TEST(DBTest, AssignSequenceNumber) { LoggedCertificate logged_cert, lookup_cert; this->test_signer_.CreateUnique(&logged_cert); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert)); EXPECT_EQ(Database::OK, this->db()->AssignCertificateSequenceNumber( logged_cert.certificate_sha256_hash(), 42)); EXPECT_EQ(Database::LOOKUP_OK, this->db()->LookupCertificateByHash( logged_cert.certificate_sha256_hash(), &lookup_cert)); EXPECT_EQ(42U, lookup_cert.sequence_number()); lookup_cert.clear_sequence_number(); TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert); } TYPED_TEST(DBTest, AssignSequenceNumberNotPending) { LoggedCertificate logged_cert; this->test_signer_.CreateUnique(&logged_cert); EXPECT_EQ(Database::ENTRY_NOT_FOUND, this->db()->AssignCertificateSequenceNumber( logged_cert.certificate_sha256_hash(), 0)); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert)); EXPECT_EQ(Database::OK, this->db()->AssignCertificateSequenceNumber( logged_cert.certificate_sha256_hash(), 42)); EXPECT_EQ(Database::ENTRY_ALREADY_LOGGED, this->db()->AssignCertificateSequenceNumber( logged_cert.certificate_sha256_hash(), 42)); } TYPED_TEST(DBTest, AssignSequenceNumberTwice) { LoggedCertificate logged_cert, logged_cert2; this->test_signer_.CreateUnique(&logged_cert); this->test_signer_.CreateUnique(&logged_cert2); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert)); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert2)); EXPECT_EQ(Database::OK, this->db()->AssignCertificateSequenceNumber( logged_cert.certificate_sha256_hash(), 42)); EXPECT_EQ(Database::SEQUENCE_NUMBER_ALREADY_IN_USE, this->db()->AssignCertificateSequenceNumber( logged_cert2.certificate_sha256_hash(), 42)); } TYPED_TEST(DBTest, LookupBySequenceNumber) { LoggedCertificate logged_cert, logged_cert2, lookup_cert, lookup_cert2; this->test_signer_.CreateUnique(&logged_cert); this->test_signer_.CreateUnique(&logged_cert2); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert)); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert2)); EXPECT_EQ(Database::OK, this->db()->AssignCertificateSequenceNumber( logged_cert.certificate_sha256_hash(), 42)); EXPECT_EQ(Database::OK, this->db()->AssignCertificateSequenceNumber( logged_cert2.certificate_sha256_hash(), 22)); EXPECT_EQ(Database::NOT_FOUND, this->db()->LookupCertificateByIndex(23, &lookup_cert)); EXPECT_EQ(Database::LOOKUP_OK, this->db()->LookupCertificateByIndex(42, &lookup_cert)); EXPECT_EQ(42U, lookup_cert.sequence_number()); lookup_cert.clear_sequence_number(); TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert); EXPECT_EQ(Database::LOOKUP_OK, this->db()->LookupCertificateByIndex(22, &lookup_cert2)); EXPECT_EQ(22U, lookup_cert2.sequence_number()); lookup_cert2.clear_sequence_number(); TestSigner::TestEqualLoggedCerts(logged_cert2, lookup_cert2); } TYPED_TEST(DBTest, WriteTreeHead) { SignedTreeHead sth, lookup_sth; this->test_signer_.CreateUnique(&sth); EXPECT_EQ(Database::NOT_FOUND, this->db()->LatestTreeHead(&lookup_sth)); EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth)); EXPECT_EQ(Database::LOOKUP_OK, this->db()->LatestTreeHead(&lookup_sth)); TestSigner::TestEqualTreeHeads(sth, lookup_sth); } TYPED_TEST(DBTest, WriteTreeHeadDuplicateTimestamp) { SignedTreeHead sth, sth2, lookup_sth; this->test_signer_.CreateUnique(&sth); EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth)); sth2.CopyFrom(sth); sth2.set_tree_size(sth.tree_size() + 1); EXPECT_EQ(Database::DUPLICATE_TREE_HEAD_TIMESTAMP, this->db()->WriteTreeHead(sth2)); EXPECT_EQ(Database::LOOKUP_OK, this->db()->LatestTreeHead(&lookup_sth)); TestSigner::TestEqualTreeHeads(sth, lookup_sth); } TYPED_TEST(DBTest, WriteTreeHeadNewerTimestamp) { SignedTreeHead sth, sth2, lookup_sth; this->test_signer_.CreateUnique(&sth); this->test_signer_.CreateUnique(&sth2); // Should be newer already but don't rely on this. sth2.set_timestamp(sth.timestamp() + 1000); EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth)); EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth2)); EXPECT_EQ(Database::LOOKUP_OK, this->db()->LatestTreeHead(&lookup_sth)); TestSigner::TestEqualTreeHeads(sth2, lookup_sth); } TYPED_TEST(DBTest, WriteTreeHeadOlderTimestamp) { SignedTreeHead sth, sth2, lookup_sth; this->test_signer_.CreateUnique(&sth); this->test_signer_.CreateUnique(&sth2); // Should be newer already but don't rely on this. sth2.set_timestamp(sth.timestamp() - 1000); EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth)); EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth2)); EXPECT_EQ(Database::LOOKUP_OK, this->db()->LatestTreeHead(&lookup_sth)); TestSigner::TestEqualTreeHeads(sth, lookup_sth); } TYPED_TEST(DBTest, Resume) { LoggedCertificate logged_cert, logged_cert2, lookup_cert, lookup_cert2; this->test_signer_.CreateUnique(&logged_cert); this->test_signer_.CreateUnique(&logged_cert2); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert)); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert2)); EXPECT_EQ(Database::OK, this->db()->AssignCertificateSequenceNumber( logged_cert.certificate_sha256_hash(), 42)); SignedTreeHead sth, sth2, lookup_sth; this->test_signer_.CreateUnique(&sth); this->test_signer_.CreateUnique(&sth2); sth2.set_timestamp(sth.timestamp() - 1000); EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth)); EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth2)); Database *db2 = this->test_db_.SecondDB(); EXPECT_EQ(Database::LOOKUP_OK, db2->LookupCertificateByHash( logged_cert.certificate_sha256_hash(), &lookup_cert)); EXPECT_EQ(42U, lookup_cert.sequence_number()); lookup_cert.clear_sequence_number(); TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert); EXPECT_EQ(Database::LOOKUP_OK, db2->LookupCertificateByHash( logged_cert2.certificate_sha256_hash(), &lookup_cert2)); TestSigner::TestEqualLoggedCerts(logged_cert2, lookup_cert2); EXPECT_EQ(Database::LOOKUP_OK, db2->LatestTreeHead(&lookup_sth)); TestSigner::TestEqualTreeHeads(sth, lookup_sth); std::set<string> pending_hashes; pending_hashes.insert(logged_cert2.certificate_sha256_hash()); EXPECT_EQ(pending_hashes, db2->PendingHashes()); delete db2; } TYPED_TEST(DBTest, ResumeEmpty) { Database *db2 = this->test_db_.SecondDB(); LoggedCertificate lookup_cert; EXPECT_EQ(Database::NOT_FOUND, db2->LookupCertificateByIndex(0, &lookup_cert)); SignedTreeHead lookup_sth; EXPECT_EQ(Database::NOT_FOUND, db2->LatestTreeHead(&lookup_sth)); EXPECT_TRUE(db2->PendingHashes().empty()); delete db2; } } // namespace int main(int argc, char **argv) { // Change the defaults. Can be overridden on command line. // Log to stderr instead of log files. FLAGS_logtostderr = true; // Only log fatal messages by default. FLAGS_minloglevel = 3; google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Refactor protobufs (leftovers from previous CL)<commit_after>/* -*- indent-tabs-mode: nil -*- */ #include <gflags/gflags.h> #include <glog/logging.h> #include <gtest/gtest.h> #include <set> #include <string> #include "database.h" #include "file_db.h" #include "file_storage.h" #include "sqlite_db.h" #include "test_db.h" #include "test_signer.h" #include "util.h" namespace { using ct::LoggedCertificate; using ct::SignedTreeHead; using std::string; // A slightly shorter notation for constructing hex strings from binary blobs. string H(const string &byte_string) { return util::HexString(byte_string); } template <class T> class DBTest : public ::testing::Test { protected: DBTest() : test_db_(), test_signer_() { } ~DBTest() {} T *db() const { return test_db_.db(); } TestDB<T> test_db_; TestSigner test_signer_; }; typedef testing::Types<FileDB, SQLiteDB> Databases; TYPED_TEST_CASE(DBTest, Databases); TYPED_TEST(DBTest, CreatePending) { LoggedCertificate logged_cert, lookup_cert; this->test_signer_.CreateUnique(&logged_cert); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert)); EXPECT_EQ(Database::LOOKUP_OK, this->db()->LookupCertificateByHash( logged_cert.certificate_sha256_hash(), &lookup_cert)); TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert); string similar_hash = logged_cert.certificate_sha256_hash(); similar_hash[similar_hash.size() - 1] ^= 1; EXPECT_EQ(Database::NOT_FOUND, this->db()->LookupCertificateByHash(similar_hash, &lookup_cert)); EXPECT_EQ(Database::NOT_FOUND, this->db()->LookupCertificateByHash(this->test_signer_.UniqueHash(), &lookup_cert)); } TYPED_TEST(DBTest, GetPendingHashes) { LoggedCertificate logged_cert, logged_cert2; this->test_signer_.CreateUnique(&logged_cert); this->test_signer_.CreateUnique(&logged_cert2); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert)); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert2)); std::set<string> hashes; hashes.insert(logged_cert.certificate_sha256_hash()); hashes.insert(logged_cert2.certificate_sha256_hash()); std::set<string> pending_hashes = this->db()->PendingHashes(); EXPECT_EQ(hashes, pending_hashes); } TYPED_TEST(DBTest, CreatePendingDuplicate) { LoggedCertificate logged_cert, duplicate_cert, lookup_cert; this->test_signer_.CreateUnique(&logged_cert); duplicate_cert.CopyFrom(logged_cert); // Change the timestamp so that we can check that we get the right thing back. duplicate_cert.mutable_sct()->set_timestamp( logged_cert.sct().timestamp() + 1000); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert)); EXPECT_EQ(Database::DUPLICATE_CERTIFICATE_HASH, this->db()->CreatePendingCertificateEntry(duplicate_cert)); EXPECT_EQ(Database::LOOKUP_OK, this->db()->LookupCertificateByHash( logged_cert.certificate_sha256_hash(), &lookup_cert)); // Check that we get the original entry back. TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert); } TYPED_TEST(DBTest, AssignSequenceNumber) { LoggedCertificate logged_cert, lookup_cert; this->test_signer_.CreateUnique(&logged_cert); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert)); EXPECT_EQ(Database::OK, this->db()->AssignCertificateSequenceNumber( logged_cert.certificate_sha256_hash(), 42)); EXPECT_EQ(Database::LOOKUP_OK, this->db()->LookupCertificateByHash( logged_cert.certificate_sha256_hash(), &lookup_cert)); EXPECT_EQ(42U, lookup_cert.sequence_number()); lookup_cert.clear_sequence_number(); TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert); } TYPED_TEST(DBTest, AssignSequenceNumberNotPending) { LoggedCertificate logged_cert; this->test_signer_.CreateUnique(&logged_cert); EXPECT_EQ(Database::ENTRY_NOT_FOUND, this->db()->AssignCertificateSequenceNumber( logged_cert.certificate_sha256_hash(), 0)); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert)); EXPECT_EQ(Database::OK, this->db()->AssignCertificateSequenceNumber( logged_cert.certificate_sha256_hash(), 42)); EXPECT_EQ(Database::ENTRY_ALREADY_LOGGED, this->db()->AssignCertificateSequenceNumber( logged_cert.certificate_sha256_hash(), 42)); } TYPED_TEST(DBTest, AssignSequenceNumberTwice) { LoggedCertificate logged_cert, logged_cert2; this->test_signer_.CreateUnique(&logged_cert); this->test_signer_.CreateUnique(&logged_cert2); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert)); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert2)); EXPECT_EQ(Database::OK, this->db()->AssignCertificateSequenceNumber( logged_cert.certificate_sha256_hash(), 42)); EXPECT_EQ(Database::SEQUENCE_NUMBER_ALREADY_IN_USE, this->db()->AssignCertificateSequenceNumber( logged_cert2.certificate_sha256_hash(), 42)); } TYPED_TEST(DBTest, LookupBySequenceNumber) { LoggedCertificate logged_cert, logged_cert2, lookup_cert, lookup_cert2; this->test_signer_.CreateUnique(&logged_cert); this->test_signer_.CreateUnique(&logged_cert2); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert)); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert2)); EXPECT_EQ(Database::OK, this->db()->AssignCertificateSequenceNumber( logged_cert.certificate_sha256_hash(), 42)); EXPECT_EQ(Database::OK, this->db()->AssignCertificateSequenceNumber( logged_cert2.certificate_sha256_hash(), 22)); EXPECT_EQ(Database::NOT_FOUND, this->db()->LookupCertificateByIndex(23, &lookup_cert)); EXPECT_EQ(Database::LOOKUP_OK, this->db()->LookupCertificateByIndex(42, &lookup_cert)); EXPECT_EQ(42U, lookup_cert.sequence_number()); lookup_cert.clear_sequence_number(); TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert); EXPECT_EQ(Database::LOOKUP_OK, this->db()->LookupCertificateByIndex(22, &lookup_cert2)); EXPECT_EQ(22U, lookup_cert2.sequence_number()); lookup_cert2.clear_sequence_number(); TestSigner::TestEqualLoggedCerts(logged_cert2, lookup_cert2); } TYPED_TEST(DBTest, WriteTreeHead) { SignedTreeHead sth, lookup_sth; this->test_signer_.CreateUnique(&sth); EXPECT_EQ(Database::NOT_FOUND, this->db()->LatestTreeHead(&lookup_sth)); EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth)); EXPECT_EQ(Database::LOOKUP_OK, this->db()->LatestTreeHead(&lookup_sth)); TestSigner::TestEqualTreeHeads(sth, lookup_sth); } TYPED_TEST(DBTest, WriteTreeHeadDuplicateTimestamp) { SignedTreeHead sth, sth2, lookup_sth; this->test_signer_.CreateUnique(&sth); EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth)); sth2.CopyFrom(sth); sth2.set_tree_size(sth.tree_size() + 1); EXPECT_EQ(Database::DUPLICATE_TREE_HEAD_TIMESTAMP, this->db()->WriteTreeHead(sth2)); EXPECT_EQ(Database::LOOKUP_OK, this->db()->LatestTreeHead(&lookup_sth)); TestSigner::TestEqualTreeHeads(sth, lookup_sth); } TYPED_TEST(DBTest, WriteTreeHeadNewerTimestamp) { SignedTreeHead sth, sth2, lookup_sth; this->test_signer_.CreateUnique(&sth); this->test_signer_.CreateUnique(&sth2); // Should be newer already but don't rely on this. sth2.set_timestamp(sth.timestamp() + 1000); EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth)); EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth2)); EXPECT_EQ(Database::LOOKUP_OK, this->db()->LatestTreeHead(&lookup_sth)); TestSigner::TestEqualTreeHeads(sth2, lookup_sth); } TYPED_TEST(DBTest, WriteTreeHeadOlderTimestamp) { SignedTreeHead sth, sth2, lookup_sth; this->test_signer_.CreateUnique(&sth); this->test_signer_.CreateUnique(&sth2); // Should be newer already but don't rely on this. sth2.set_timestamp(sth.timestamp() - 1000); EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth)); EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth2)); EXPECT_EQ(Database::LOOKUP_OK, this->db()->LatestTreeHead(&lookup_sth)); TestSigner::TestEqualTreeHeads(sth, lookup_sth); } TYPED_TEST(DBTest, Resume) { LoggedCertificate logged_cert, logged_cert2, lookup_cert, lookup_cert2; this->test_signer_.CreateUnique(&logged_cert); this->test_signer_.CreateUnique(&logged_cert2); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert)); EXPECT_EQ(Database::OK, this->db()->CreatePendingCertificateEntry(logged_cert2)); EXPECT_EQ(Database::OK, this->db()->AssignCertificateSequenceNumber( logged_cert.certificate_sha256_hash(), 42)); SignedTreeHead sth, sth2, lookup_sth; this->test_signer_.CreateUnique(&sth); this->test_signer_.CreateUnique(&sth2); sth2.set_timestamp(sth.timestamp() - 1000); EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth)); EXPECT_EQ(Database::OK, this->db()->WriteTreeHead(sth2)); Database *db2 = this->test_db_.SecondDB(); EXPECT_EQ(Database::LOOKUP_OK, db2->LookupCertificateByHash( logged_cert.certificate_sha256_hash(), &lookup_cert)); EXPECT_EQ(42U, lookup_cert.sequence_number()); lookup_cert.clear_sequence_number(); TestSigner::TestEqualLoggedCerts(logged_cert, lookup_cert); EXPECT_EQ(Database::LOOKUP_OK, db2->LookupCertificateByHash( logged_cert2.certificate_sha256_hash(), &lookup_cert2)); TestSigner::TestEqualLoggedCerts(logged_cert2, lookup_cert2); EXPECT_EQ(Database::LOOKUP_OK, db2->LatestTreeHead(&lookup_sth)); TestSigner::TestEqualTreeHeads(sth, lookup_sth); std::set<string> pending_hashes; pending_hashes.insert(logged_cert2.certificate_sha256_hash()); EXPECT_EQ(pending_hashes, db2->PendingHashes()); delete db2; } TYPED_TEST(DBTest, ResumeEmpty) { Database *db2 = this->test_db_.SecondDB(); LoggedCertificate lookup_cert; EXPECT_EQ(Database::NOT_FOUND, db2->LookupCertificateByIndex(0, &lookup_cert)); SignedTreeHead lookup_sth; EXPECT_EQ(Database::NOT_FOUND, db2->LatestTreeHead(&lookup_sth)); EXPECT_TRUE(db2->PendingHashes().empty()); delete db2; } } // namespace int main(int argc, char **argv) { // Change the defaults. Can be overridden on command line. // Log to stderr instead of log files. FLAGS_logtostderr = true; // Only log fatal messages by default. FLAGS_minloglevel = 3; google::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include <string> #include <sstream> #include <time.h> #include <sys/time.h> #include "log_service_impl.h" using namespace rpc; using namespace std; using namespace rlog; void RLogServiceImpl::log(const i32& level, const std::string& source, const i64& msg_id, const std::string& message) { log_piece piece; piece.msg_id = msg_id; piece.level = level; piece.message = message; const int tm_str_len = 80; char tm_str[tm_str_len]; time_t now = time(NULL); struct tm tm_val; localtime_r(&now, &tm_val); strftime(tm_str, tm_str_len - 1, "%F %T", &tm_val); timeval tv; gettimeofday(&tv, NULL); l_.lock(); set<log_piece>& buffer = buffer_[source]; buffer.insert(piece); i64& done = done_[source]; while (!buffer.empty() && buffer.begin()->msg_id <= done + 1) { Log::log(buffer.begin()->level, 0, "remote", "%s.%03d %s: %s", tm_str, tv.tv_usec / 1000, source.c_str(), buffer.begin()->message.c_str()); done = max(done, buffer.begin()->msg_id); buffer.erase(buffer.begin()); } l_.unlock(); } void RLogServiceImpl::aggregate_qps(const std::string& metric_name, const rpc::i32& increment) { agg_qps_l_.lock(); list<agg_qps_record>& records = agg_qps_[metric_name]; agg_qps_record new_rec; timeval tv; gettimeofday(&tv, NULL); double now = tv.tv_sec + tv.tv_usec / 1000.0 / 1000.0; new_rec.tm = now; if (records.empty()) { new_rec.agg_count = increment; } else { new_rec.agg_count = records.back().agg_count + increment; } records.push_back(new_rec); // only keep 5min qps info while (now - records.front().tm > 5 * 60) { records.erase(records.begin()); } // report aggregate qps every 1sec if (now - last_qps_report_tm_ > 1) { const int report_intervals[] = {1, 5, 15, 30, 60}; ostringstream qps_ostr; for (size_t i = 0; i < sizeof(report_intervals) / sizeof(report_intervals[0]); i++) { double increment = -1; const int report_interval = report_intervals[i]; for (list<agg_qps_record>::reverse_iterator it = records.rbegin(); it != records.rend(); ++it) { if (now - it->tm < report_interval) { increment = records.back().agg_count - it->agg_count; } else { break; } } if (increment > 0) { double qps = increment / report_interval; qps_ostr << " " << report_interval << ":" << qps; } } last_qps_report_tm_ = now; if (qps_ostr.str().length() > 0) { Log_info("qps '%s':%s", metric_name.c_str(), qps_ostr.str().c_str()); } } agg_qps_l_.unlock(); } <commit_msg>minor update<commit_after>#include <string> #include <sstream> #include <time.h> #include <sys/time.h> #include "log_service_impl.h" using namespace rpc; using namespace std; using namespace rlog; void RLogServiceImpl::log(const i32& level, const std::string& source, const i64& msg_id, const std::string& message) { log_piece piece; piece.msg_id = msg_id; piece.level = level; piece.message = message; const int tm_str_len = 80; char tm_str[tm_str_len]; time_t now = time(NULL); struct tm tm_val; localtime_r(&now, &tm_val); strftime(tm_str, tm_str_len - 1, "%F %T", &tm_val); timeval tv; gettimeofday(&tv, NULL); l_.lock(); set<log_piece>& buffer = buffer_[source]; buffer.insert(piece); i64& done = done_[source]; while (!buffer.empty() && buffer.begin()->msg_id <= done + 1) { Log::log(buffer.begin()->level, 0, "remote", "%s.%03d %s: %s", tm_str, tv.tv_usec / 1000, source.c_str(), buffer.begin()->message.c_str()); done = max(done, buffer.begin()->msg_id); buffer.erase(buffer.begin()); } l_.unlock(); } void RLogServiceImpl::aggregate_qps(const std::string& metric_name, const rpc::i32& increment) { agg_qps_l_.lock(); list<agg_qps_record>& records = agg_qps_[metric_name]; agg_qps_record new_rec; timeval tv; gettimeofday(&tv, NULL); double now = tv.tv_sec + tv.tv_usec / 1000.0 / 1000.0; new_rec.tm = now; if (records.empty()) { new_rec.agg_count = increment; } else { new_rec.agg_count = records.back().agg_count + increment; } records.push_back(new_rec); // only keep 5min qps info while (now - records.front().tm > 5 * 60) { records.erase(records.begin()); } // report aggregate qps every 1sec if (now - last_qps_report_tm_ > 1) { const int report_intervals[] = {1, 5, 15, 30, 60}; ostringstream qps_ostr; for (size_t i = 0; i < arraysize(report_intervals); i++) { double increment = -1; const int report_interval = report_intervals[i]; for (list<agg_qps_record>::reverse_iterator it = records.rbegin(); it != records.rend(); ++it) { if (now - it->tm < report_interval) { increment = records.back().agg_count - it->agg_count; } else { break; } } if (increment > 0) { double qps = increment / report_interval; qps_ostr << " " << report_interval << ":" << qps; } } last_qps_report_tm_ = now; if (qps_ostr.str().length() > 0) { Log_info("qps '%s':%s", metric_name.c_str(), qps_ostr.str().c_str()); } } agg_qps_l_.unlock(); } <|endoftext|>
<commit_before>#pragma once #include "boost_defs.hpp" #include "gcd_utility.hpp" #include "session.hpp" #include <boost/optional.hpp> #include <boost/signals2.hpp> #include <memory> namespace krbn { class console_user_id_monitor final { public: boost::signals2::signal<void(boost::optional<uid_t>)> console_user_id_changed; console_user_id_monitor(const console_user_id_monitor&) = delete; console_user_id_monitor(void) { timer_ = std::make_unique<gcd_utility::main_queue_timer>( dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), 1 * NSEC_PER_SEC, 0, ^{ auto u = session::get_current_console_user_id(); if (uid_ && *uid_ == u) { return; } console_user_id_changed(u); uid_ = std::make_unique<boost::optional<uid_t>>(u); }); } ~console_user_id_monitor(void) { timer_ = nullptr; } private: std::unique_ptr<gcd_utility::main_queue_timer> timer_; std::unique_ptr<boost::optional<uid_t>> uid_; }; } // namespace krbn <commit_msg>add console_user_id_monitor::start<commit_after>#pragma once #include "boost_defs.hpp" #include "gcd_utility.hpp" #include "session.hpp" #include <boost/optional.hpp> #include <boost/signals2.hpp> #include <memory> namespace krbn { class console_user_id_monitor final { public: boost::signals2::signal<void(boost::optional<uid_t>)> console_user_id_changed; console_user_id_monitor(const console_user_id_monitor&) = delete; console_user_id_monitor(void) { } ~console_user_id_monitor(void) { stop(); } void start(void) { stop(); timer_ = std::make_unique<gcd_utility::main_queue_timer>( DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0, ^{ auto u = session::get_current_console_user_id(); if (uid_ && *uid_ == u) { return; } console_user_id_changed(u); uid_ = std::make_unique<boost::optional<uid_t>>(u); }); } void stop(void) { timer_ = nullptr; } private: std::unique_ptr<gcd_utility::main_queue_timer> timer_; std::unique_ptr<boost::optional<uid_t>> uid_; }; } // namespace krbn <|endoftext|>
<commit_before>#include "GUI_ObjectSettings.hpp" #include "GUI_ObjectList.hpp" #include "OptionsGroup.hpp" #include "wxExtensions.hpp" #include "PresetBundle.hpp" #include "libslic3r/Model.hpp" #include <boost/algorithm/string.hpp> #include "I18N.hpp" #include "ConfigManipulation.hpp" #include <wx/wupdlock.h> namespace Slic3r { namespace GUI { OG_Settings::OG_Settings(wxWindow* parent, const bool staticbox) : m_parent(parent) { wxString title = staticbox ? " " : ""; // temporary workaround - #ys_FIXME m_og = std::make_shared<ConfigOptionsGroup>(parent, title); } bool OG_Settings::IsShown() { return m_og->sizer->IsEmpty() ? false : m_og->sizer->IsShown(size_t(0)); } void OG_Settings::Show(const bool show) { m_og->Show(show); } void OG_Settings::Hide() { Show(false); } void OG_Settings::UpdateAndShow(const bool show) { Show(show); // m_parent->Layout(); } wxSizer* OG_Settings::get_sizer() { return m_og->sizer; } ObjectSettings::ObjectSettings(wxWindow* parent) : OG_Settings(parent, true) { m_og->set_name(_(L("Additional Settings"))); m_settings_list_sizer = new wxBoxSizer(wxVERTICAL); m_og->sizer->Add(m_settings_list_sizer, 1, wxEXPAND | wxLEFT, 5); m_bmp_delete = ScalableBitmap(parent, "cross"); m_bmp_delete_focus = ScalableBitmap(parent, "cross_focus"); } bool ObjectSettings::update_settings_list() { m_settings_list_sizer->Clear(true); m_og_settings.resize(0); auto objects_ctrl = wxGetApp().obj_list(); auto objects_model = wxGetApp().obj_list()->GetModel(); auto config = wxGetApp().obj_list()->config(); const auto item = objects_ctrl->GetSelection(); if (!item || !objects_model->IsSettingsItem(item) || !config || objects_ctrl->multiple_selection()) return false; const bool is_object_settings = objects_model->GetItemType(objects_model->GetParent(item)) == itObject; SettingsBundle cat_options = objects_ctrl->get_item_settings_bundle(config, is_object_settings); if (!cat_options.empty()) { std::vector<std::string> categories; categories.reserve(cat_options.size()); auto extra_column = [config, this](wxWindow* parent, const Line& line) { auto opt_key = (line.get_options())[0].opt_id; //we assume that we have one option per line auto btn = new ScalableButton(parent, wxID_ANY, m_bmp_delete); btn->SetToolTip(_(L("Remove parameter"))); btn->SetBitmapFocus(m_bmp_delete_focus.bmp()); btn->SetBitmapHover(m_bmp_delete_focus.bmp()); btn->Bind(wxEVT_BUTTON, [opt_key, config, this](wxEvent &event) { wxGetApp().plater()->take_snapshot(wxString::Format(_(L("Delete Option %s")), opt_key)); config->erase(opt_key); wxGetApp().obj_list()->changed_object(); wxTheApp->CallAfter([this]() { wxWindowUpdateLocker noUpdates(m_parent); update_settings_list(); m_parent->Layout(); }); }); return btn; }; for (auto& cat : cat_options) { categories.push_back(cat.first); auto optgroup = std::make_shared<ConfigOptionsGroup>(m_og->ctrl_parent(), _(cat.first), config, false, extra_column); optgroup->label_width = 15; optgroup->sidetext_width = 5.5; optgroup->m_on_change = [this, config](const t_config_option_key& opt_id, const boost::any& value) { this->update_config_values(config); wxGetApp().obj_list()->changed_object(); }; // call back for rescaling of the extracolumn control optgroup->rescale_extra_column_item = [this](wxWindow* win) { auto *ctrl = dynamic_cast<ScalableButton*>(win); if (ctrl == nullptr) return; ctrl->SetBitmap_(m_bmp_delete); ctrl->SetBitmapFocus(m_bmp_delete_focus.bmp()); ctrl->SetBitmapHover(m_bmp_delete_focus.bmp()); }; const bool is_extruders_cat = cat.first == "Extruders"; for (auto& opt : cat.second) { Option option = optgroup->get_option(opt); option.opt.width = 12; if (is_extruders_cat) option.opt.max = wxGetApp().extruders_edited_cnt(); optgroup->append_single_option_line(option); optgroup->get_field(opt)->m_on_change = [optgroup](const std::string& opt_id, const boost::any& value) { // first of all take a snapshot and then change value in configuration wxGetApp().plater()->take_snapshot(wxString::Format(_(L("Change Option %s")), opt_id)); optgroup->on_change_OG(opt_id, value); }; } optgroup->reload_config(); m_settings_list_sizer->Add(optgroup->sizer, 0, wxEXPAND | wxALL, 0); m_og_settings.push_back(optgroup); } if (!categories.empty()) { objects_model->UpdateSettingsDigest(item, categories); update_config_values(config); } } else { objects_ctrl->select_item(objects_model->Delete(item)); return false; } return true; } void ObjectSettings::update_config_values(DynamicPrintConfig* config) { const auto objects_model = wxGetApp().obj_list()->GetModel(); const auto item = wxGetApp().obj_list()->GetSelection(); const auto printer_technology = wxGetApp().plater()->printer_technology(); const bool is_object_settings = objects_model->GetItemType(objects_model->GetParent(item)) == itObject; // update config values according to configuration hierarchy DynamicPrintConfig main_config = printer_technology == ptFFF ? wxGetApp().preset_bundle->prints.get_edited_preset().config : wxGetApp().preset_bundle->sla_prints.get_edited_preset().config; auto load_config = [this, config, &main_config]() { // load checked values from main_config to config config->apply_only(main_config, config->keys(), true); // Initialize UI components with the config values. for (auto og : m_og_settings) og->reload_config(); // next config check update_config_values(config); }; auto get_field = [this](const t_config_option_key & opt_key, int opt_index) { Field* field = nullptr; for (auto og : m_og_settings) { field = og->get_fieldc(opt_key, opt_index); if (field != nullptr) return field; } return field; }; ConfigManipulation config_manipulation(load_config, get_field, nullptr, config); if (!is_object_settings) { const int obj_idx = objects_model->GetObjectIdByItem(item); assert(obj_idx >= 0); DynamicPrintConfig* obj_config = &wxGetApp().model().objects[obj_idx]->config; main_config.apply(*obj_config, true); printer_technology == ptFFF ? config_manipulation.update_print_fff_config(&main_config) : config_manipulation.update_print_sla_config(&main_config) ; } main_config.apply(*config, true); printer_technology == ptFFF ? config_manipulation.update_print_fff_config(&main_config) : config_manipulation.update_print_sla_config(&main_config) ; printer_technology == ptFFF ? config_manipulation.toggle_print_fff_options(&main_config) : config_manipulation.toggle_print_sla_options(&main_config) ; } void ObjectSettings::UpdateAndShow(const bool show) { OG_Settings::UpdateAndShow(show ? update_settings_list() : false); } void ObjectSettings::msw_rescale() { m_bmp_delete.msw_rescale(); m_bmp_delete_focus.msw_rescale(); for (auto group : m_og_settings) group->msw_rescale(); } } //namespace GUI } //namespace Slic3r <commit_msg>Fixed application crash, when change focus from overridden option to empty space in ObjectList.<commit_after>#include "GUI_ObjectSettings.hpp" #include "GUI_ObjectList.hpp" #include "OptionsGroup.hpp" #include "wxExtensions.hpp" #include "PresetBundle.hpp" #include "libslic3r/Model.hpp" #include <boost/algorithm/string.hpp> #include "I18N.hpp" #include "ConfigManipulation.hpp" #include <wx/wupdlock.h> namespace Slic3r { namespace GUI { OG_Settings::OG_Settings(wxWindow* parent, const bool staticbox) : m_parent(parent) { wxString title = staticbox ? " " : ""; // temporary workaround - #ys_FIXME m_og = std::make_shared<ConfigOptionsGroup>(parent, title); } bool OG_Settings::IsShown() { return m_og->sizer->IsEmpty() ? false : m_og->sizer->IsShown(size_t(0)); } void OG_Settings::Show(const bool show) { m_og->Show(show); } void OG_Settings::Hide() { Show(false); } void OG_Settings::UpdateAndShow(const bool show) { Show(show); // m_parent->Layout(); } wxSizer* OG_Settings::get_sizer() { return m_og->sizer; } ObjectSettings::ObjectSettings(wxWindow* parent) : OG_Settings(parent, true) { m_og->set_name(_(L("Additional Settings"))); m_settings_list_sizer = new wxBoxSizer(wxVERTICAL); m_og->sizer->Add(m_settings_list_sizer, 1, wxEXPAND | wxLEFT, 5); m_bmp_delete = ScalableBitmap(parent, "cross"); m_bmp_delete_focus = ScalableBitmap(parent, "cross_focus"); } bool ObjectSettings::update_settings_list() { m_settings_list_sizer->Clear(true); m_og_settings.resize(0); auto objects_ctrl = wxGetApp().obj_list(); auto objects_model = wxGetApp().obj_list()->GetModel(); auto config = wxGetApp().obj_list()->config(); const auto item = objects_ctrl->GetSelection(); if (!item || !objects_model->IsSettingsItem(item) || !config || objects_ctrl->multiple_selection()) return false; const bool is_object_settings = objects_model->GetItemType(objects_model->GetParent(item)) == itObject; SettingsBundle cat_options = objects_ctrl->get_item_settings_bundle(config, is_object_settings); if (!cat_options.empty()) { std::vector<std::string> categories; categories.reserve(cat_options.size()); auto extra_column = [config, this](wxWindow* parent, const Line& line) { auto opt_key = (line.get_options())[0].opt_id; //we assume that we have one option per line auto btn = new ScalableButton(parent, wxID_ANY, m_bmp_delete); btn->SetToolTip(_(L("Remove parameter"))); btn->SetBitmapFocus(m_bmp_delete_focus.bmp()); btn->SetBitmapHover(m_bmp_delete_focus.bmp()); btn->Bind(wxEVT_BUTTON, [opt_key, config, this](wxEvent &event) { wxGetApp().plater()->take_snapshot(wxString::Format(_(L("Delete Option %s")), opt_key)); config->erase(opt_key); wxGetApp().obj_list()->changed_object(); wxTheApp->CallAfter([this]() { wxWindowUpdateLocker noUpdates(m_parent); update_settings_list(); m_parent->Layout(); }); }); return btn; }; for (auto& cat : cat_options) { categories.push_back(cat.first); auto optgroup = std::make_shared<ConfigOptionsGroup>(m_og->ctrl_parent(), _(cat.first), config, false, extra_column); optgroup->label_width = 15; optgroup->sidetext_width = 5.5; optgroup->m_on_change = [this, config](const t_config_option_key& opt_id, const boost::any& value) { this->update_config_values(config); wxGetApp().obj_list()->changed_object(); }; // call back for rescaling of the extracolumn control optgroup->rescale_extra_column_item = [this](wxWindow* win) { auto *ctrl = dynamic_cast<ScalableButton*>(win); if (ctrl == nullptr) return; ctrl->SetBitmap_(m_bmp_delete); ctrl->SetBitmapFocus(m_bmp_delete_focus.bmp()); ctrl->SetBitmapHover(m_bmp_delete_focus.bmp()); }; const bool is_extruders_cat = cat.first == "Extruders"; for (auto& opt : cat.second) { Option option = optgroup->get_option(opt); option.opt.width = 12; if (is_extruders_cat) option.opt.max = wxGetApp().extruders_edited_cnt(); optgroup->append_single_option_line(option); optgroup->get_field(opt)->m_on_change = [optgroup](const std::string& opt_id, const boost::any& value) { // first of all take a snapshot and then change value in configuration wxGetApp().plater()->take_snapshot(wxString::Format(_(L("Change Option %s")), opt_id)); optgroup->on_change_OG(opt_id, value); }; } optgroup->reload_config(); m_settings_list_sizer->Add(optgroup->sizer, 0, wxEXPAND | wxALL, 0); m_og_settings.push_back(optgroup); } if (!categories.empty()) { objects_model->UpdateSettingsDigest(item, categories); update_config_values(config); } } else { objects_ctrl->select_item(objects_model->Delete(item)); return false; } return true; } void ObjectSettings::update_config_values(DynamicPrintConfig* config) { const auto objects_model = wxGetApp().obj_list()->GetModel(); const auto item = wxGetApp().obj_list()->GetSelection(); const auto printer_technology = wxGetApp().plater()->printer_technology(); const bool is_object_settings = objects_model->GetItemType(objects_model->GetParent(item)) == itObject; if (!item || !objects_model->IsSettingsItem(item) || !config) return; // update config values according to configuration hierarchy DynamicPrintConfig main_config = printer_technology == ptFFF ? wxGetApp().preset_bundle->prints.get_edited_preset().config : wxGetApp().preset_bundle->sla_prints.get_edited_preset().config; auto load_config = [this, config, &main_config]() { // load checked values from main_config to config config->apply_only(main_config, config->keys(), true); // Initialize UI components with the config values. for (auto og : m_og_settings) og->reload_config(); // next config check update_config_values(config); }; auto get_field = [this](const t_config_option_key & opt_key, int opt_index) { Field* field = nullptr; for (auto og : m_og_settings) { field = og->get_fieldc(opt_key, opt_index); if (field != nullptr) return field; } return field; }; ConfigManipulation config_manipulation(load_config, get_field, nullptr, config); if (!is_object_settings) { const int obj_idx = objects_model->GetObjectIdByItem(item); assert(obj_idx >= 0); DynamicPrintConfig* obj_config = &wxGetApp().model().objects[obj_idx]->config; main_config.apply(*obj_config, true); printer_technology == ptFFF ? config_manipulation.update_print_fff_config(&main_config) : config_manipulation.update_print_sla_config(&main_config) ; } main_config.apply(*config, true); printer_technology == ptFFF ? config_manipulation.update_print_fff_config(&main_config) : config_manipulation.update_print_sla_config(&main_config) ; printer_technology == ptFFF ? config_manipulation.toggle_print_fff_options(&main_config) : config_manipulation.toggle_print_sla_options(&main_config) ; } void ObjectSettings::UpdateAndShow(const bool show) { OG_Settings::UpdateAndShow(show ? update_settings_list() : false); } void ObjectSettings::msw_rescale() { m_bmp_delete.msw_rescale(); m_bmp_delete_focus.msw_rescale(); for (auto group : m_og_settings) group->msw_rescale(); } } //namespace GUI } //namespace Slic3r <|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 2015 Cloudius Systems */ #include <seastar/http/routes.hh> #include <seastar/http/reply.hh> #include <seastar/http/exception.hh> #include <seastar/http/json_path.hh> namespace seastar { namespace httpd { using namespace std; void verify_param(const request& req, const sstring& param) { if (req.get_query_param(param) == "") { throw missing_param_exception(param); } } routes::routes() : _general_handler([this](std::exception_ptr eptr) mutable { return exception_reply(eptr); }) {} routes::~routes() { for (int i = 0; i < NUM_OPERATION; i++) { for (auto kv : _map[i]) { delete kv.second; } } for (int i = 0; i < NUM_OPERATION; i++) { for (auto r : _rules[i]) { delete r.second; } } } std::unique_ptr<reply> routes::exception_reply(std::exception_ptr eptr) { auto rep = std::make_unique<reply>(); try { // go over the register exception handler // if one of them handle the exception, return. for (auto e: _exceptions) { try { return e.second(eptr); } catch (...) { // this is needed if there are more then one register exception handler // so if the exception handler throw a new exception, they would // get the new exception and not the original one. eptr = std::current_exception(); } } std::rethrow_exception(eptr); } catch (const base_exception& e) { rep->set_status(e.status(), json_exception(e).to_json()); } catch (...) { rep->set_status(reply::status_type::internal_server_error, json_exception(std::current_exception()).to_json()); } rep->done("json"); return rep; } future<std::unique_ptr<reply> > routes::handle(const sstring& path, std::unique_ptr<request> req, std::unique_ptr<reply> rep) { handler_base* handler = get_handler(str2type(req->_method), normalize_url(path), req->param); if (handler != nullptr) { try { for (auto& i : handler->_mandatory_param) { verify_param(*req.get(), i); } auto r = handler->handle(path, std::move(req), std::move(rep)); return r.handle_exception(_general_handler); } catch (const redirect_exception& _e) { rep.reset(new reply()); rep->add_header("Location", _e.url).set_status(_e.status()).done( "json"); } catch (...) { rep = exception_reply(std::current_exception()); } } else { rep.reset(new reply()); json_exception ex(not_found_exception("Not found")); rep->set_status(reply::status_type::not_found, ex.to_json()).done( "json"); } return make_ready_future<std::unique_ptr<reply>>(std::move(rep)); } sstring routes::normalize_url(const sstring& url) { if (url.length() < 2 || url.at(url.length() - 1) != '/') { return url; } return url.substr(0, url.length() - 1); } handler_base* routes::get_handler(operation_type type, const sstring& url, parameters& params) { handler_base* handler = get_exact_match(type, url); if (handler != nullptr) { return handler; } for (auto&& rule : _rules[type]) { handler = rule.second->get(url, params); if (handler != nullptr) { return handler; } params.clear(); } return nullptr; } routes& routes::add(operation_type type, const url& url, handler_base* handler) { match_rule* rule = new match_rule(handler); rule->add_str(url._path); if (url._param != "") { rule->add_param(url._param, true); } return add(rule, type); } template <typename Map, typename Key> static auto delete_rule_from(operation_type type, Key& key, Map& map) { auto& bucket = map[type]; auto ret = bucket.find(key); if (ret != bucket.end()) { bucket.erase(ret); } return ret == bucket.end() ? nullptr : ret->second; } handler_base* routes::drop(operation_type type, const sstring& url) { return delete_rule_from(type, url, _map); } match_rule* routes::del_cookie(rule_cookie cookie, operation_type type) { return delete_rule_from(type, cookie, _rules); } void routes::add_alias(const path_description& old_path, const path_description& new_path) { httpd::parameters p; stringstream path; path << old_path.path; for (const auto& p : old_path.params) { // the path_description path does not contains the path parameters // so just add a fake parameter to the path for each of the parameters, // and add the string for each fixed string part. if (p.type == path_description::url_component_type::FIXED_STRING) { path << p.name; } else { path << "/k"; } } auto a = get_handler(old_path.operations.method, path.str(), p); if (!a) { throw std::runtime_error("routes::add_alias path_description not found: " + old_path.path); } // if a handler is found then it must be a function_handler new_path.set(*this, new function_handler(*static_cast<function_handler*>(a))); } rule_registration::rule_registration(routes& rs, match_rule& rule, operation_type op) : _routes(rs) , _op(op) , _cookie(_routes.add_cookie(&rule, _op)) {} rule_registration::~rule_registration() { _routes.del_cookie(_cookie, _op); } handler_registration::handler_registration(routes& rs, handler_base& h, const sstring& url, operation_type op) : _routes(rs), _url(url), _op(op) { _routes.put(_op, _url, &h); } handler_registration::~handler_registration() { _routes.drop(_op, _url); } } } <commit_msg>http: Fix use after free<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 2015 Cloudius Systems */ #include <seastar/http/routes.hh> #include <seastar/http/reply.hh> #include <seastar/http/exception.hh> #include <seastar/http/json_path.hh> namespace seastar { namespace httpd { using namespace std; void verify_param(const request& req, const sstring& param) { if (req.get_query_param(param) == "") { throw missing_param_exception(param); } } routes::routes() : _general_handler([this](std::exception_ptr eptr) mutable { return exception_reply(eptr); }) {} routes::~routes() { for (int i = 0; i < NUM_OPERATION; i++) { for (auto kv : _map[i]) { delete kv.second; } } for (int i = 0; i < NUM_OPERATION; i++) { for (auto r : _rules[i]) { delete r.second; } } } std::unique_ptr<reply> routes::exception_reply(std::exception_ptr eptr) { auto rep = std::make_unique<reply>(); try { // go over the register exception handler // if one of them handle the exception, return. for (auto e: _exceptions) { try { return e.second(eptr); } catch (...) { // this is needed if there are more then one register exception handler // so if the exception handler throw a new exception, they would // get the new exception and not the original one. eptr = std::current_exception(); } } std::rethrow_exception(eptr); } catch (const base_exception& e) { rep->set_status(e.status(), json_exception(e).to_json()); } catch (...) { rep->set_status(reply::status_type::internal_server_error, json_exception(std::current_exception()).to_json()); } rep->done("json"); return rep; } future<std::unique_ptr<reply> > routes::handle(const sstring& path, std::unique_ptr<request> req, std::unique_ptr<reply> rep) { handler_base* handler = get_handler(str2type(req->_method), normalize_url(path), req->param); if (handler != nullptr) { try { for (auto& i : handler->_mandatory_param) { verify_param(*req.get(), i); } auto r = handler->handle(path, std::move(req), std::move(rep)); return r.handle_exception(_general_handler); } catch (const redirect_exception& _e) { rep.reset(new reply()); rep->add_header("Location", _e.url).set_status(_e.status()).done( "json"); } catch (...) { rep = exception_reply(std::current_exception()); } } else { rep.reset(new reply()); json_exception ex(not_found_exception("Not found")); rep->set_status(reply::status_type::not_found, ex.to_json()).done( "json"); } return make_ready_future<std::unique_ptr<reply>>(std::move(rep)); } sstring routes::normalize_url(const sstring& url) { if (url.length() < 2 || url.at(url.length() - 1) != '/') { return url; } return url.substr(0, url.length() - 1); } handler_base* routes::get_handler(operation_type type, const sstring& url, parameters& params) { handler_base* handler = get_exact_match(type, url); if (handler != nullptr) { return handler; } for (auto&& rule : _rules[type]) { handler = rule.second->get(url, params); if (handler != nullptr) { return handler; } params.clear(); } return nullptr; } routes& routes::add(operation_type type, const url& url, handler_base* handler) { match_rule* rule = new match_rule(handler); rule->add_str(url._path); if (url._param != "") { rule->add_param(url._param, true); } return add(rule, type); } template <typename Map, typename Key> static auto delete_rule_from(operation_type type, Key& key, Map& map) { auto& bucket = map[type]; auto ret = bucket.find(key); using ret_type = decltype(ret->second); if (ret != bucket.end()) { ret_type v = ret->second; bucket.erase(ret); return v; } return static_cast<ret_type>(nullptr); } handler_base* routes::drop(operation_type type, const sstring& url) { return delete_rule_from(type, url, _map); } match_rule* routes::del_cookie(rule_cookie cookie, operation_type type) { return delete_rule_from(type, cookie, _rules); } void routes::add_alias(const path_description& old_path, const path_description& new_path) { httpd::parameters p; stringstream path; path << old_path.path; for (const auto& p : old_path.params) { // the path_description path does not contains the path parameters // so just add a fake parameter to the path for each of the parameters, // and add the string for each fixed string part. if (p.type == path_description::url_component_type::FIXED_STRING) { path << p.name; } else { path << "/k"; } } auto a = get_handler(old_path.operations.method, path.str(), p); if (!a) { throw std::runtime_error("routes::add_alias path_description not found: " + old_path.path); } // if a handler is found then it must be a function_handler new_path.set(*this, new function_handler(*static_cast<function_handler*>(a))); } rule_registration::rule_registration(routes& rs, match_rule& rule, operation_type op) : _routes(rs) , _op(op) , _cookie(_routes.add_cookie(&rule, _op)) {} rule_registration::~rule_registration() { _routes.del_cookie(_cookie, _op); } handler_registration::handler_registration(routes& rs, handler_base& h, const sstring& url, operation_type op) : _routes(rs), _url(url), _op(op) { _routes.put(_op, _url, &h); } handler_registration::~handler_registration() { _routes.drop(_op, _url); } } } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "../libjsapi.h" rs::jsapi::Runtime rt_; class ScriptExceptionTests : public ::testing::Test { protected: virtual void SetUp() { } virtual void TearDown() { } }; TEST_F(ScriptExceptionTests, test1) { ASSERT_THROW({ rs::jsapi::Script script(rt_, "!)(*\")(!*\"!"); script.Compile(); }, rs::jsapi::ScriptException); } TEST_F(ScriptExceptionTests, test2) { ASSERT_THROW({ rs::jsapi::Script script(rt_, "var xyz = abc;"); script.Compile(); script.Execute(); }, rs::jsapi::ScriptException); } TEST_F(ScriptExceptionTests, test3) { ASSERT_THROW({ rs::jsapi::Script script(rt_, "(function(){return abc;})()"); script.Compile(); rs::jsapi::Value result(rt_); script.Execute(result); }, rs::jsapi::ScriptException); }<commit_msg>Added more exception tests<commit_after>#include <gtest/gtest.h> #include "../libjsapi.h" rs::jsapi::Runtime rt_; class ScriptExceptionTests : public ::testing::Test { protected: virtual void SetUp() { } virtual void TearDown() { } }; TEST_F(ScriptExceptionTests, test1) { ASSERT_THROW({ rs::jsapi::Script script(rt_, "!)(*\")(!*\"!"); script.Compile(); }, rs::jsapi::ScriptException); } TEST_F(ScriptExceptionTests, test2) { ASSERT_THROW({ rs::jsapi::Script script(rt_, "var xyz = abc;"); script.Compile(); script.Execute(); }, rs::jsapi::ScriptException); } TEST_F(ScriptExceptionTests, test3) { ASSERT_THROW({ rs::jsapi::Script script(rt_, "(function(){return abc;})()"); script.Compile(); rs::jsapi::Value result(rt_); script.Execute(result); }, rs::jsapi::ScriptException); } TEST_F(ScriptExceptionTests, test4) { ASSERT_THROW({ rs::jsapi::Script script(rt_, "!)(*\")(!*\"!"); script.Compile(); }, rs::jsapi::ScriptException); rs::jsapi::Script script(rt_, "(function(){return 42;})()"); script.Compile(); rs::jsapi::Value result(rt_); script.Execute(result); ASSERT_EQ(result().isNumber(), true); ASSERT_EQ(result().toNumber(), 42); } TEST_F(ScriptExceptionTests, test5) { ASSERT_THROW({ rs::jsapi::Script script(rt_, "var xyz = abc;"); script.Compile(); script.Execute(); }, rs::jsapi::ScriptException); rs::jsapi::Script script(rt_, "(function(){return 42;})()"); script.Compile(); rs::jsapi::Value result(rt_); script.Execute(result); ASSERT_EQ(result().isNumber(), true); ASSERT_EQ(result().toNumber(), 42); } TEST_F(ScriptExceptionTests, test6) { ASSERT_THROW({ rs::jsapi::Script script(rt_, "(function(){return abc;})()"); script.Compile(); rs::jsapi::Value result(rt_); script.Execute(result); }, rs::jsapi::ScriptException); rs::jsapi::Script script(rt_, "(function(){return 42;})()"); script.Compile(); rs::jsapi::Value result(rt_); script.Execute(result); ASSERT_EQ(result().isNumber(), true); ASSERT_EQ(result().toNumber(), 42); }<|endoftext|>
<commit_before>#include <GarrysMod/Lua/Interface.h> #include <GarrysMod/Lua/Helpers.hpp> #include <GarrysMod/FunctionPointers.hpp> #include <GarrysMod/InterfacePointers.hpp> #include <detouring/classproxy.hpp> #include <cstdint> #include <string> #include <unordered_set> #include <algorithm> #include <cctype> #include <interface.h> #include <filesystem.h> #include <eiface.h> class GModDataPack; namespace Bootil { class Buffer { public: virtual ~Buffer() = default; // For the VTable void *data; uint32_t size; uint32_t pos; uint32_t written; }; class AutoBuffer : public Buffer { public: virtual ~AutoBuffer() = default; // For the VTable }; } class LuaFile // 116 bytes { public: virtual ~LuaFile() = default; // For the VTable std::string path; std::string parent; std::string content; Bootil::AutoBuffer buffer; bool unknown1; bool unknown2; }; namespace luapack { static IFileSystem *filesystem = nullptr; static std::unordered_set<std::string> whitelist_extensions = { "lua", "txt", "dat" }; static std::unordered_set<std::string> whitelist_pathid = { "lsv", "lua", "data" }; class GModDataPackProxy : public Detouring::ClassProxy<GModDataPack, GModDataPackProxy> { private: #if defined _WIN32 typedef void( __thiscall *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force ); #elif defined __linux || defined __APPLE__ typedef void( *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force ); #endif static AddOrUpdateFile_t AddOrUpdateFile_original; static const char hook_name[]; static GarrysMod::Lua::ILuaBase *lua; public: static void Initialize( GarrysMod::Lua::ILuaBase *LUA ) { lua = LUA; AddOrUpdateFile_original = FunctionPointers::GModDataPack_AddOrUpdateFile( ); if( AddOrUpdateFile_original == nullptr ) LUA->ThrowError( "failed to find GModDataPack::AddOrUpdateFile" ); if( !Hook( AddOrUpdateFile_original, &GModDataPackProxy::AddOrUpdateFile ) ) LUA->ThrowError( "failed to hook GModDataPack::AddOrUpdateFile" ); } static void Deinitialize( GarrysMod::Lua::ILuaBase *LUA ) { UnHook( AddOrUpdateFile_original ); } void AddOrUpdateFile( LuaFile *file, bool reload ) { LuaHelpers::PushHookRun( lua, hook_name ); lua->PushString( file->path.c_str( ) ); lua->PushBool( reload ); bool shouldcall = true; if( LuaHelpers::CallHookRun( lua, 2, 1 ) ) shouldcall = !lua->IsType( -1, GarrysMod::Lua::Type::BOOL ) || lua->GetBool( -1 ); lua->Pop( 1 ); if( shouldcall ) return Call( AddOrUpdateFile_original, file, reload ); } static GModDataPackProxy Singleton; }; GModDataPackProxy::AddOrUpdateFile_t GModDataPackProxy::AddOrUpdateFile_original = nullptr; const char GModDataPackProxy::hook_name[] = "AddOrUpdateCSLuaFile"; GarrysMod::Lua::ILuaBase *GModDataPackProxy::lua = nullptr; static bool IsPathAllowed( std::string &filename ) { if( !V_RemoveDotSlashes( &filename[0], CORRECT_PATH_SEPARATOR, true ) ) return false; filename.resize( std::strlen( filename.c_str( ) ) ); const char *extension = V_GetFileExtension( filename.c_str( ) ); if( extension == nullptr ) return false; std::string ext = extension; std::transform( ext.begin( ), ext.end( ), ext.begin( ), [] ( uint8_t c ) { return static_cast<char>( std::tolower( c ) ); } ); return whitelist_extensions.find( ext ) != whitelist_extensions.end( ); } inline bool IsPathIDAllowed( std::string &pathid ) { std::transform( pathid.begin( ), pathid.end( ), pathid.begin( ), [] ( uint8_t c ) { return static_cast<char>( std::tolower( c ) ); } ); return whitelist_pathid.find( pathid ) != whitelist_pathid.end( ); } LUA_FUNCTION_STATIC( Rename ) { LUA->CheckType( 1, GarrysMod::Lua::Type::STRING ); LUA->CheckType( 2, GarrysMod::Lua::Type::STRING ); LUA->CheckType( 3, GarrysMod::Lua::Type::STRING ); std::string fname = LUA->GetString( 1 ), fnew = LUA->GetString( 2 ), pathid = LUA->GetString( 3 ); if( !IsPathAllowed( fname ) || !IsPathAllowed( fnew ) || !IsPathIDAllowed( pathid ) ) { LUA->PushBool( false ); return 1; } LUA->PushBool( filesystem->RenameFile( fname.c_str( ), fnew.c_str( ), pathid.c_str( ) ) ); return 1; } static void Initialize( GarrysMod::Lua::ILuaBase *LUA ) { filesystem = InterfacePointers::FileSystem( ); if( filesystem == nullptr ) LUA->ThrowError( "failed to initialize IFileSystem" ); GModDataPackProxy::Singleton.Initialize( LUA ); LUA->GetField( GarrysMod::Lua::INDEX_GLOBAL, "luapack" ); if( !LUA->IsType( -1, GarrysMod::Lua::Type::TABLE ) ) { GModDataPackProxy::Singleton.Deinitialize(LUA); LUA->ThrowError("luapack table not found"); } LUA->PushCFunction( Rename ); LUA->SetField( -2, "Rename" ); LUA->Pop( 1 ); } static void Deinitialize( GarrysMod::Lua::ILuaBase *LUA ) { LUA->GetField( GarrysMod::Lua::INDEX_GLOBAL, "luapack" ); if( !LUA->IsType( -1, GarrysMod::Lua::Type::TABLE ) ) LUA->ThrowError( "luapack table not found" ); LUA->PushNil( ); LUA->SetField( -2, "Rename" ); LUA->Pop( 1 ); GModDataPackProxy::Singleton.Deinitialize( LUA ); } } GMOD_MODULE_OPEN( ) { luapack::Initialize( LUA ); return 0; } GMOD_MODULE_CLOSE( ) { luapack::Deinitialize( LUA ); return 0; } <commit_msg>Removed OS dependent function definition<commit_after>#include <GarrysMod/Lua/Interface.h> #include <GarrysMod/Lua/Helpers.hpp> #include <GarrysMod/FunctionPointers.hpp> #include <GarrysMod/InterfacePointers.hpp> #include <detouring/classproxy.hpp> #include <cstdint> #include <string> #include <unordered_set> #include <algorithm> #include <cctype> #include <interface.h> #include <filesystem.h> #include <eiface.h> class GModDataPack; namespace Bootil { class Buffer { public: virtual ~Buffer() = default; // For the VTable void *data; uint32_t size; uint32_t pos; uint32_t written; }; class AutoBuffer : public Buffer { public: virtual ~AutoBuffer() = default; // For the VTable }; } class LuaFile // 116 bytes { public: virtual ~LuaFile() = default; // For the VTable std::string path; std::string parent; std::string content; Bootil::AutoBuffer buffer; bool unknown1; bool unknown2; }; namespace luapack { static IFileSystem *filesystem = nullptr; static std::unordered_set<std::string> whitelist_extensions = { "lua", "txt", "dat" }; static std::unordered_set<std::string> whitelist_pathid = { "lsv", "lua", "data" }; class GModDataPackProxy : public Detouring::ClassProxy<GModDataPack, GModDataPackProxy> { private: static FunctionPointers::GModDataPack_AddOrUpdateFile_t AddOrUpdateFile_original; static const char hook_name[]; static GarrysMod::Lua::ILuaBase *lua; public: static void Initialize( GarrysMod::Lua::ILuaBase *LUA ) { lua = LUA; AddOrUpdateFile_original = FunctionPointers::GModDataPack_AddOrUpdateFile( ); if( AddOrUpdateFile_original == nullptr ) LUA->ThrowError( "failed to find GModDataPack::AddOrUpdateFile" ); if( !Hook( AddOrUpdateFile_original, &GModDataPackProxy::AddOrUpdateFile ) ) LUA->ThrowError( "failed to hook GModDataPack::AddOrUpdateFile" ); } static void Deinitialize( GarrysMod::Lua::ILuaBase *LUA ) { UnHook( AddOrUpdateFile_original ); } void AddOrUpdateFile( LuaFile *file, bool reload ) { LuaHelpers::PushHookRun( lua, hook_name ); lua->PushString( file->path.c_str( ) ); lua->PushBool( reload ); bool shouldcall = true; if( LuaHelpers::CallHookRun( lua, 2, 1 ) ) shouldcall = !lua->IsType( -1, GarrysMod::Lua::Type::BOOL ) || lua->GetBool( -1 ); lua->Pop( 1 ); if( shouldcall ) return Call( AddOrUpdateFile_original, file, reload ); } static GModDataPackProxy Singleton; }; FunctionPointers::GModDataPack_AddOrUpdateFile_t GModDataPackProxy::AddOrUpdateFile_original = nullptr; const char GModDataPackProxy::hook_name[] = "AddOrUpdateCSLuaFile"; GarrysMod::Lua::ILuaBase *GModDataPackProxy::lua = nullptr; static bool IsPathAllowed( std::string &filename ) { if( !V_RemoveDotSlashes( &filename[0], CORRECT_PATH_SEPARATOR, true ) ) return false; filename.resize( std::strlen( filename.c_str( ) ) ); const char *extension = V_GetFileExtension( filename.c_str( ) ); if( extension == nullptr ) return false; std::string ext = extension; std::transform( ext.begin( ), ext.end( ), ext.begin( ), [] ( uint8_t c ) { return static_cast<char>( std::tolower( c ) ); } ); return whitelist_extensions.find( ext ) != whitelist_extensions.end( ); } inline bool IsPathIDAllowed( std::string &pathid ) { std::transform( pathid.begin( ), pathid.end( ), pathid.begin( ), [] ( uint8_t c ) { return static_cast<char>( std::tolower( c ) ); } ); return whitelist_pathid.find( pathid ) != whitelist_pathid.end( ); } LUA_FUNCTION_STATIC( Rename ) { LUA->CheckType( 1, GarrysMod::Lua::Type::STRING ); LUA->CheckType( 2, GarrysMod::Lua::Type::STRING ); LUA->CheckType( 3, GarrysMod::Lua::Type::STRING ); std::string fname = LUA->GetString( 1 ), fnew = LUA->GetString( 2 ), pathid = LUA->GetString( 3 ); if( !IsPathAllowed( fname ) || !IsPathAllowed( fnew ) || !IsPathIDAllowed( pathid ) ) { LUA->PushBool( false ); return 1; } LUA->PushBool( filesystem->RenameFile( fname.c_str( ), fnew.c_str( ), pathid.c_str( ) ) ); return 1; } static void Initialize( GarrysMod::Lua::ILuaBase *LUA ) { filesystem = InterfacePointers::FileSystem( ); if( filesystem == nullptr ) LUA->ThrowError( "failed to initialize IFileSystem" ); GModDataPackProxy::Singleton.Initialize( LUA ); LUA->GetField( GarrysMod::Lua::INDEX_GLOBAL, "luapack" ); if( !LUA->IsType( -1, GarrysMod::Lua::Type::TABLE ) ) { GModDataPackProxy::Singleton.Deinitialize(LUA); LUA->ThrowError("luapack table not found"); } LUA->PushCFunction( Rename ); LUA->SetField( -2, "Rename" ); LUA->Pop( 1 ); } static void Deinitialize( GarrysMod::Lua::ILuaBase *LUA ) { LUA->GetField( GarrysMod::Lua::INDEX_GLOBAL, "luapack" ); if( !LUA->IsType( -1, GarrysMod::Lua::Type::TABLE ) ) LUA->ThrowError( "luapack table not found" ); LUA->PushNil( ); LUA->SetField( -2, "Rename" ); LUA->Pop( 1 ); GModDataPackProxy::Singleton.Deinitialize( LUA ); } } GMOD_MODULE_OPEN( ) { luapack::Initialize( LUA ); return 0; } GMOD_MODULE_CLOSE( ) { luapack::Deinitialize( LUA ); return 0; } <|endoftext|>
<commit_before>#include "qmljstypedescriptionreader.h" #include "parser/qmljsparser_p.h" #include "parser/qmljslexer_p.h" #include "parser/qmljsengine_p.h" #include "parser/qmljsnodepool_p.h" #include "parser/qmljsast_p.h" #include "parser/qmljsastvisitor_p.h" #include "qmljsbind.h" #include <QtCore/QIODevice> #include <QtCore/QBuffer> using namespace QmlJS; using namespace QmlJS::AST; using namespace LanguageUtils; TypeDescriptionReader::TypeDescriptionReader(const QString &data) : _source(data) , _objects(0) { } TypeDescriptionReader::~TypeDescriptionReader() { } bool TypeDescriptionReader::operator()(QHash<QString, FakeMetaObject::Ptr> *objects) { QString fileName("typeDescription"); Engine engine; NodePool pool(fileName, &engine); Lexer lexer(&engine); Parser parser(&engine); lexer.setCode(_source, /*line = */ 1); if (!parser.parse()) { _errorMessage = QString("%1:%2: %3").arg( QString::number(parser.errorLineNumber()), QString::number(parser.errorColumnNumber()), parser.errorMessage()); return false; } _objects = objects; readDocument(parser.ast()); return _errorMessage.isEmpty(); } QString TypeDescriptionReader::errorMessage() const { return _errorMessage; } void TypeDescriptionReader::readDocument(UiProgram *ast) { if (!ast) { addError(SourceLocation(), "Could not parse document"); return; } if (!ast->imports || ast->imports->next) { addError(SourceLocation(), "Expected a single import"); return; } UiImport *import = ast->imports->import; if (Bind::toString(import->importUri) != QLatin1String("QtQuick.tooling")) { addError(import->importToken, "Expected import of QtQuick.tooling"); return; } ComponentVersion version; const QString versionString = _source.mid(import->versionToken.offset, import->versionToken.length); const int dotIdx = versionString.indexOf(QLatin1Char('.')); if (dotIdx != -1) { version = ComponentVersion(versionString.left(dotIdx).toInt(), versionString.mid(dotIdx + 1).toInt()); } if (version != ComponentVersion(1, 0)) { addError(import->versionToken, "Expected version 1.0"); return; } if (!ast->members || !ast->members->member || ast->members->next) { addError(SourceLocation(), "Expected document to contain a single object definition"); return; } UiObjectDefinition *module = dynamic_cast<UiObjectDefinition *>(ast->members->member); if (!module) { addError(SourceLocation(), "Expected document to contain a single object definition"); return; } if (Bind::toString(module->qualifiedTypeNameId) != "Module") { addError(SourceLocation(), "Expected document to contain a Module {} member"); return; } readModule(module); } void TypeDescriptionReader::readModule(UiObjectDefinition *ast) { for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) { UiObjectMember *member = it->member; UiObjectDefinition *component = dynamic_cast<UiObjectDefinition *>(member); if (!component || Bind::toString(component->qualifiedTypeNameId) != "Component") { addError(member->firstSourceLocation(), "Expected only 'Component' object definitions"); return; } readComponent(component); } } void TypeDescriptionReader::addError(const SourceLocation &loc, const QString &message) { _errorMessage += QString("%1:%2: %3\n").arg( QString::number(loc.startLine), QString::number(loc.startColumn), message); } void TypeDescriptionReader::readComponent(UiObjectDefinition *ast) { FakeMetaObject::Ptr fmo(new FakeMetaObject); for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) { UiObjectMember *member = it->member; UiObjectDefinition *component = dynamic_cast<UiObjectDefinition *>(member); UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member); if (component) { QString name = Bind::toString(component->qualifiedTypeNameId); if (name == "Property") { readProperty(component, fmo); } else if (name == "Method" || name == "Signal") { readSignalOrMethod(component, name == "Method", fmo); } else if (name == "Enum") { readEnum(component, fmo); } else { addError(component->firstSourceLocation(), "Expected only Property, Method, Signal and Enum object definitions"); return; } } else if (script) { QString name = Bind::toString(script->qualifiedId); if (name == "name") { fmo->setClassName(readStringBinding(script)); } else if (name == "prototype") { fmo->setSuperclassName(readStringBinding(script)); } else if (name == "defaultProperty") { fmo->setDefaultPropertyName(readStringBinding(script)); } else if (name == "exports") { readExports(script, fmo); } else { addError(script->firstSourceLocation(), "Expected only name, prototype, defaultProperty and exports script bindings"); return; } } else { addError(member->firstSourceLocation(), "Expected only script bindings and object definitions"); return; } } if (fmo->className().isEmpty()) { addError(ast->firstSourceLocation(), "Component definition is missing a name binding"); return; } _objects->insert(fmo->className(), fmo); } void TypeDescriptionReader::readSignalOrMethod(UiObjectDefinition *ast, bool isMethod, FakeMetaObject::Ptr fmo) { FakeMetaMethod fmm; // ### confusion between Method and Slot. Method should be removed. if (isMethod) fmm.setMethodType(FakeMetaMethod::Slot); else fmm.setMethodType(FakeMetaMethod::Signal); for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) { UiObjectMember *member = it->member; UiObjectDefinition *component = dynamic_cast<UiObjectDefinition *>(member); UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member); if (component) { QString name = Bind::toString(component->qualifiedTypeNameId); if (name == "Parameter") { readParameter(component, &fmm); } else { addError(component->firstSourceLocation(), "Expected only Parameter object definitions"); return; } } else if (script) { QString name = Bind::toString(script->qualifiedId); if (name == "name") { fmm.setMethodName(readStringBinding(script)); } else if (name == "type") { fmm.setReturnType(readStringBinding(script)); } else { addError(script->firstSourceLocation(), "Expected only name and type script bindings"); return; } } else { addError(member->firstSourceLocation(), "Expected only script bindings and object definitions"); return; } } if (fmm.methodName().isEmpty()) { addError(ast->firstSourceLocation(), "Method or Signal is missing a name script binding"); return; } fmo->addMethod(fmm); } void TypeDescriptionReader::readProperty(UiObjectDefinition *ast, FakeMetaObject::Ptr fmo) { QString name; QString type; bool isPointer = false; bool isReadonly = false; bool isList = false; for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) { UiObjectMember *member = it->member; UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member); if (!script) { addError(member->firstSourceLocation(), "Expected script binding"); return; } QString id = Bind::toString(script->qualifiedId); if (id == "name") { name = readStringBinding(script); } else if (id == "type") { type = readStringBinding(script); } else if (id == "isPointer") { isPointer = readBoolBinding(script); } else if (id == "isReadonly") { isReadonly = readBoolBinding(script); } else if (id == "isList") { isList = readBoolBinding(script); } else { addError(script->firstSourceLocation(), "Expected only type, name, isPointer, isReadonly and isList script bindings"); return; } } if (name.isEmpty() || type.isEmpty()) { addError(ast->firstSourceLocation(), "Property object is missing a name or type script binding"); return; } fmo->addProperty(FakeMetaProperty(name, type, isList, !isReadonly, isPointer)); } void TypeDescriptionReader::readEnum(UiObjectDefinition *ast, FakeMetaObject::Ptr fmo) { FakeMetaEnum fme; for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) { UiObjectMember *member = it->member; UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member); if (!script) { addError(member->firstSourceLocation(), "Expected script binding"); return; } QString name = Bind::toString(script->qualifiedId); if (name == "name") { fme.setName(readStringBinding(script)); } else if (name == "values") { readEnumValues(script, &fme); } else { addError(script->firstSourceLocation(), "Expected only name and values script bindings"); return; } } fmo->addEnum(fme); } void TypeDescriptionReader::readParameter(UiObjectDefinition *ast, FakeMetaMethod *fmm) { QString name; QString type; for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) { UiObjectMember *member = it->member; UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member); if (!script) { addError(member->firstSourceLocation(), "Expected script binding"); return; } QString id = Bind::toString(script->qualifiedId); if (id == "name") { id = readStringBinding(script); } else if (id == "type") { type = readStringBinding(script); } else if (id == "isPointer") { // ### unhandled } else if (id == "isReadonly") { // ### unhandled } else if (id == "isList") { // ### unhandled } else { addError(script->firstSourceLocation(), "Expected only name and type script bindings"); return; } } fmm->addParameter(name, type); } QString TypeDescriptionReader::readStringBinding(UiScriptBinding *ast) { if (!ast || !ast->statement) { addError(ast->colonToken, "Expected string after colon"); return QString(); } ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement); if (!expStmt) { addError(ast->statement->firstSourceLocation(), "Expected string after colon"); return QString(); } StringLiteral *stringLit = dynamic_cast<StringLiteral *>(expStmt->expression); if (!stringLit) { addError(expStmt->firstSourceLocation(), "Expected string after colon"); return QString(); } return stringLit->value->asString(); } bool TypeDescriptionReader::readBoolBinding(AST::UiScriptBinding *ast) { if (!ast || !ast->statement) { addError(ast->colonToken, "Expected boolean after colon"); return false; } ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement); if (!expStmt) { addError(ast->statement->firstSourceLocation(), "Expected boolean after colon"); return false; } TrueLiteral *trueLit = dynamic_cast<TrueLiteral *>(expStmt->expression); FalseLiteral *falseLit = dynamic_cast<FalseLiteral *>(expStmt->expression); if (!trueLit && !falseLit) { addError(expStmt->firstSourceLocation(), "Expected true or false after colon"); return false; } return trueLit; } void TypeDescriptionReader::readExports(UiScriptBinding *ast, FakeMetaObject::Ptr fmo) { if (!ast || !ast->statement) { addError(ast->colonToken, "Expected array of strings after colon"); return; } ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement); if (!expStmt) { addError(ast->statement->firstSourceLocation(), "Expected array of strings after colon"); return; } ArrayLiteral *arrayLit = dynamic_cast<ArrayLiteral *>(expStmt->expression); if (!arrayLit) { addError(expStmt->firstSourceLocation(), "Expected array of strings after colon"); return; } for (ElementList *it = arrayLit->elements; it; it = it->next) { StringLiteral *stringLit = dynamic_cast<StringLiteral *>(it->expression); if (!stringLit) { addError(arrayLit->firstSourceLocation(), "Expected array literal with only string literal members"); return; } QString exp = stringLit->value->asString(); int slashIdx = exp.indexOf(QLatin1Char('/')); int spaceIdx = exp.indexOf(QLatin1Char(' ')); ComponentVersion version(exp.mid(spaceIdx + 1)); if (spaceIdx == -1 || !version.isValid()) { addError(stringLit->firstSourceLocation(), "Expected string literal to contain 'Package/Name major.minor' or 'Name major.minor'"); continue; } QString package; if (slashIdx != -1) package = exp.left(slashIdx); QString name = exp.mid(slashIdx + 1, spaceIdx - (slashIdx+1)); // ### relocatable exports where package is empty? fmo->addExport(name, package, version); } } void TypeDescriptionReader::readEnumValues(AST::UiScriptBinding *ast, LanguageUtils::FakeMetaEnum *fme) { if (!ast || !ast->statement) { addError(ast->colonToken, "Expected object literal after colon"); return; } ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement); if (!expStmt) { addError(ast->statement->firstSourceLocation(), "Expected object literal after colon"); return; } ObjectLiteral *objectLit = dynamic_cast<ObjectLiteral *>(expStmt->expression); if (!objectLit) { addError(expStmt->firstSourceLocation(), "Expected object literal after colon"); return; } for (PropertyNameAndValueList *it = objectLit->properties; it; it = it->next) { StringLiteralPropertyName *propName = dynamic_cast<StringLiteralPropertyName *>(it->name); NumericLiteral *value = dynamic_cast<NumericLiteral *>(it->value); UnaryMinusExpression *minus = dynamic_cast<UnaryMinusExpression *>(it->value); if (minus) value = dynamic_cast<NumericLiteral *>(minus->expression); if (!propName || !value) { addError(objectLit->firstSourceLocation(), "Expected object literal to contain only 'string: number' elements"); continue; } double v = value->value; if (minus) v = -v; fme->addKey(propName->id->asString(), v); } } <commit_msg>QmlJS: Fix qml type info by reintroducing workaround exports.<commit_after>#include "qmljstypedescriptionreader.h" #include "parser/qmljsparser_p.h" #include "parser/qmljslexer_p.h" #include "parser/qmljsengine_p.h" #include "parser/qmljsnodepool_p.h" #include "parser/qmljsast_p.h" #include "parser/qmljsastvisitor_p.h" #include "qmljsbind.h" #include <QtCore/QIODevice> #include <QtCore/QBuffer> using namespace QmlJS; using namespace QmlJS::AST; using namespace LanguageUtils; TypeDescriptionReader::TypeDescriptionReader(const QString &data) : _source(data) , _objects(0) { } TypeDescriptionReader::~TypeDescriptionReader() { } bool TypeDescriptionReader::operator()(QHash<QString, FakeMetaObject::Ptr> *objects) { QString fileName("typeDescription"); Engine engine; NodePool pool(fileName, &engine); Lexer lexer(&engine); Parser parser(&engine); lexer.setCode(_source, /*line = */ 1); if (!parser.parse()) { _errorMessage = QString("%1:%2: %3").arg( QString::number(parser.errorLineNumber()), QString::number(parser.errorColumnNumber()), parser.errorMessage()); return false; } _objects = objects; readDocument(parser.ast()); return _errorMessage.isEmpty(); } QString TypeDescriptionReader::errorMessage() const { return _errorMessage; } void TypeDescriptionReader::readDocument(UiProgram *ast) { if (!ast) { addError(SourceLocation(), "Could not parse document"); return; } if (!ast->imports || ast->imports->next) { addError(SourceLocation(), "Expected a single import"); return; } UiImport *import = ast->imports->import; if (Bind::toString(import->importUri) != QLatin1String("QtQuick.tooling")) { addError(import->importToken, "Expected import of QtQuick.tooling"); return; } ComponentVersion version; const QString versionString = _source.mid(import->versionToken.offset, import->versionToken.length); const int dotIdx = versionString.indexOf(QLatin1Char('.')); if (dotIdx != -1) { version = ComponentVersion(versionString.left(dotIdx).toInt(), versionString.mid(dotIdx + 1).toInt()); } if (version != ComponentVersion(1, 0)) { addError(import->versionToken, "Expected version 1.0"); return; } if (!ast->members || !ast->members->member || ast->members->next) { addError(SourceLocation(), "Expected document to contain a single object definition"); return; } UiObjectDefinition *module = dynamic_cast<UiObjectDefinition *>(ast->members->member); if (!module) { addError(SourceLocation(), "Expected document to contain a single object definition"); return; } if (Bind::toString(module->qualifiedTypeNameId) != "Module") { addError(SourceLocation(), "Expected document to contain a Module {} member"); return; } readModule(module); } void TypeDescriptionReader::readModule(UiObjectDefinition *ast) { for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) { UiObjectMember *member = it->member; UiObjectDefinition *component = dynamic_cast<UiObjectDefinition *>(member); if (!component || Bind::toString(component->qualifiedTypeNameId) != "Component") { addError(member->firstSourceLocation(), "Expected only 'Component' object definitions"); return; } readComponent(component); } } void TypeDescriptionReader::addError(const SourceLocation &loc, const QString &message) { _errorMessage += QString("%1:%2: %3\n").arg( QString::number(loc.startLine), QString::number(loc.startColumn), message); } void TypeDescriptionReader::readComponent(UiObjectDefinition *ast) { FakeMetaObject::Ptr fmo(new FakeMetaObject); for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) { UiObjectMember *member = it->member; UiObjectDefinition *component = dynamic_cast<UiObjectDefinition *>(member); UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member); if (component) { QString name = Bind::toString(component->qualifiedTypeNameId); if (name == "Property") { readProperty(component, fmo); } else if (name == "Method" || name == "Signal") { readSignalOrMethod(component, name == "Method", fmo); } else if (name == "Enum") { readEnum(component, fmo); } else { addError(component->firstSourceLocation(), "Expected only Property, Method, Signal and Enum object definitions"); return; } } else if (script) { QString name = Bind::toString(script->qualifiedId); if (name == "name") { fmo->setClassName(readStringBinding(script)); } else if (name == "prototype") { fmo->setSuperclassName(readStringBinding(script)); } else if (name == "defaultProperty") { fmo->setDefaultPropertyName(readStringBinding(script)); } else if (name == "exports") { readExports(script, fmo); } else { addError(script->firstSourceLocation(), "Expected only name, prototype, defaultProperty and exports script bindings"); return; } } else { addError(member->firstSourceLocation(), "Expected only script bindings and object definitions"); return; } } if (fmo->className().isEmpty()) { addError(ast->firstSourceLocation(), "Component definition is missing a name binding"); return; } // ### for backwards compatibility until fixed: export by cpp name fmo->addExport(fmo->className(), "", ComponentVersion()); _objects->insert(fmo->className(), fmo); } void TypeDescriptionReader::readSignalOrMethod(UiObjectDefinition *ast, bool isMethod, FakeMetaObject::Ptr fmo) { FakeMetaMethod fmm; // ### confusion between Method and Slot. Method should be removed. if (isMethod) fmm.setMethodType(FakeMetaMethod::Slot); else fmm.setMethodType(FakeMetaMethod::Signal); for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) { UiObjectMember *member = it->member; UiObjectDefinition *component = dynamic_cast<UiObjectDefinition *>(member); UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member); if (component) { QString name = Bind::toString(component->qualifiedTypeNameId); if (name == "Parameter") { readParameter(component, &fmm); } else { addError(component->firstSourceLocation(), "Expected only Parameter object definitions"); return; } } else if (script) { QString name = Bind::toString(script->qualifiedId); if (name == "name") { fmm.setMethodName(readStringBinding(script)); } else if (name == "type") { fmm.setReturnType(readStringBinding(script)); } else { addError(script->firstSourceLocation(), "Expected only name and type script bindings"); return; } } else { addError(member->firstSourceLocation(), "Expected only script bindings and object definitions"); return; } } if (fmm.methodName().isEmpty()) { addError(ast->firstSourceLocation(), "Method or Signal is missing a name script binding"); return; } fmo->addMethod(fmm); } void TypeDescriptionReader::readProperty(UiObjectDefinition *ast, FakeMetaObject::Ptr fmo) { QString name; QString type; bool isPointer = false; bool isReadonly = false; bool isList = false; for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) { UiObjectMember *member = it->member; UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member); if (!script) { addError(member->firstSourceLocation(), "Expected script binding"); return; } QString id = Bind::toString(script->qualifiedId); if (id == "name") { name = readStringBinding(script); } else if (id == "type") { type = readStringBinding(script); } else if (id == "isPointer") { isPointer = readBoolBinding(script); } else if (id == "isReadonly") { isReadonly = readBoolBinding(script); } else if (id == "isList") { isList = readBoolBinding(script); } else { addError(script->firstSourceLocation(), "Expected only type, name, isPointer, isReadonly and isList script bindings"); return; } } if (name.isEmpty() || type.isEmpty()) { addError(ast->firstSourceLocation(), "Property object is missing a name or type script binding"); return; } fmo->addProperty(FakeMetaProperty(name, type, isList, !isReadonly, isPointer)); } void TypeDescriptionReader::readEnum(UiObjectDefinition *ast, FakeMetaObject::Ptr fmo) { FakeMetaEnum fme; for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) { UiObjectMember *member = it->member; UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member); if (!script) { addError(member->firstSourceLocation(), "Expected script binding"); return; } QString name = Bind::toString(script->qualifiedId); if (name == "name") { fme.setName(readStringBinding(script)); } else if (name == "values") { readEnumValues(script, &fme); } else { addError(script->firstSourceLocation(), "Expected only name and values script bindings"); return; } } fmo->addEnum(fme); } void TypeDescriptionReader::readParameter(UiObjectDefinition *ast, FakeMetaMethod *fmm) { QString name; QString type; for (UiObjectMemberList *it = ast->initializer->members; it; it = it->next) { UiObjectMember *member = it->member; UiScriptBinding *script = dynamic_cast<UiScriptBinding *>(member); if (!script) { addError(member->firstSourceLocation(), "Expected script binding"); return; } QString id = Bind::toString(script->qualifiedId); if (id == "name") { id = readStringBinding(script); } else if (id == "type") { type = readStringBinding(script); } else if (id == "isPointer") { // ### unhandled } else if (id == "isReadonly") { // ### unhandled } else if (id == "isList") { // ### unhandled } else { addError(script->firstSourceLocation(), "Expected only name and type script bindings"); return; } } fmm->addParameter(name, type); } QString TypeDescriptionReader::readStringBinding(UiScriptBinding *ast) { if (!ast || !ast->statement) { addError(ast->colonToken, "Expected string after colon"); return QString(); } ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement); if (!expStmt) { addError(ast->statement->firstSourceLocation(), "Expected string after colon"); return QString(); } StringLiteral *stringLit = dynamic_cast<StringLiteral *>(expStmt->expression); if (!stringLit) { addError(expStmt->firstSourceLocation(), "Expected string after colon"); return QString(); } return stringLit->value->asString(); } bool TypeDescriptionReader::readBoolBinding(AST::UiScriptBinding *ast) { if (!ast || !ast->statement) { addError(ast->colonToken, "Expected boolean after colon"); return false; } ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement); if (!expStmt) { addError(ast->statement->firstSourceLocation(), "Expected boolean after colon"); return false; } TrueLiteral *trueLit = dynamic_cast<TrueLiteral *>(expStmt->expression); FalseLiteral *falseLit = dynamic_cast<FalseLiteral *>(expStmt->expression); if (!trueLit && !falseLit) { addError(expStmt->firstSourceLocation(), "Expected true or false after colon"); return false; } return trueLit; } void TypeDescriptionReader::readExports(UiScriptBinding *ast, FakeMetaObject::Ptr fmo) { if (!ast || !ast->statement) { addError(ast->colonToken, "Expected array of strings after colon"); return; } ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement); if (!expStmt) { addError(ast->statement->firstSourceLocation(), "Expected array of strings after colon"); return; } ArrayLiteral *arrayLit = dynamic_cast<ArrayLiteral *>(expStmt->expression); if (!arrayLit) { addError(expStmt->firstSourceLocation(), "Expected array of strings after colon"); return; } for (ElementList *it = arrayLit->elements; it; it = it->next) { StringLiteral *stringLit = dynamic_cast<StringLiteral *>(it->expression); if (!stringLit) { addError(arrayLit->firstSourceLocation(), "Expected array literal with only string literal members"); return; } QString exp = stringLit->value->asString(); int slashIdx = exp.indexOf(QLatin1Char('/')); int spaceIdx = exp.indexOf(QLatin1Char(' ')); ComponentVersion version(exp.mid(spaceIdx + 1)); if (spaceIdx == -1 || !version.isValid()) { addError(stringLit->firstSourceLocation(), "Expected string literal to contain 'Package/Name major.minor' or 'Name major.minor'"); continue; } QString package; if (slashIdx != -1) package = exp.left(slashIdx); QString name = exp.mid(slashIdx + 1, spaceIdx - (slashIdx+1)); // ### relocatable exports where package is empty? fmo->addExport(name, package, version); } } void TypeDescriptionReader::readEnumValues(AST::UiScriptBinding *ast, LanguageUtils::FakeMetaEnum *fme) { if (!ast || !ast->statement) { addError(ast->colonToken, "Expected object literal after colon"); return; } ExpressionStatement *expStmt = dynamic_cast<ExpressionStatement *>(ast->statement); if (!expStmt) { addError(ast->statement->firstSourceLocation(), "Expected object literal after colon"); return; } ObjectLiteral *objectLit = dynamic_cast<ObjectLiteral *>(expStmt->expression); if (!objectLit) { addError(expStmt->firstSourceLocation(), "Expected object literal after colon"); return; } for (PropertyNameAndValueList *it = objectLit->properties; it; it = it->next) { StringLiteralPropertyName *propName = dynamic_cast<StringLiteralPropertyName *>(it->name); NumericLiteral *value = dynamic_cast<NumericLiteral *>(it->value); UnaryMinusExpression *minus = dynamic_cast<UnaryMinusExpression *>(it->value); if (minus) value = dynamic_cast<NumericLiteral *>(minus->expression); if (!propName || !value) { addError(objectLit->firstSourceLocation(), "Expected object literal to contain only 'string: number' elements"); continue; } double v = value->value; if (minus) v = -v; fme->addKey(propName->id->asString(), v); } } <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <string> #include "pixelboost/data/xml/xml.h" #include "pixelboost/file/fileHelpers.h" enum ShaderLanguage { kShaderLanguageGLSL, kShaderLanguageHLSL, }; enum ShaderType { kShaderTypeVertex, kShaderTypeFragment, }; bool ParseShaderGLSL(const std::string& input, pugi::xml_node& output) { output.append_child(pugi::node_cdata).set_value(input.c_str()); return true; } bool ParseShaderHLSL(const std::string& input, pugi::xml_node& output) { output.append_child(pugi::node_cdata).set_value(input.c_str()); return true; } bool AppendProgram(pugi::xml_node& programOutput, pugi::xml_node& programInput) { std::string language = programInput.attribute("language").value(); if (language == "glsl") { if (!ParseShaderGLSL(programInput.child_value(), programOutput)) return false; } else if (language == "hlsl") { if (!ParseShaderHLSL(programInput.child_value(), programOutput)) return false; } else { // Unknown language return false; } return true; } int main(int argc, const char * argv[]) { bool status = true; if (argc < 3) return 1; new pb::FileSystem(argv[0]); pb::FileSystem::Instance()->MountReadLocation(argv[1], "/", true); pb::FileSystem::Instance()->OverrideWriteDirectory(argv[1]); std::string vertex, fragment; const char* inputLocation = argv[2]; const char* outputLocation = argv[3]; pb::File* file = pb::FileSystem::Instance()->OpenFile(inputLocation); std::string input; if (file) { file->ReadAll(input); delete file; } pugi::xml_document inputDocument; pugi::xml_document outputDocument; inputDocument.load(input.c_str()); pugi::xml_node shaderInput = inputDocument.child("shader"); pugi::xml_node shaderOutput = outputDocument.append_child("shader"); shaderOutput.append_copy(shaderInput.attribute("name")); pugi::xml_node attributesInput = shaderInput.child("attributes"); shaderOutput.append_copy(attributesInput); pugi::xml_node subshaderInput = shaderInput.child("subshader"); while (!subshaderInput.empty()) { pugi::xml_node subshaderOutput = shaderOutput.append_child("subshader"); subshaderOutput.append_copy(subshaderInput.attribute("class")); pugi::xml_node passInput = subshaderInput.child("pass"); while (!passInput.empty()) { pugi::xml_node passOutput = subshaderOutput.append_child("pass"); pugi::xml_node programInput = passInput.child("program"); while (!programInput.empty()) { pugi::xml_node programOutput = passOutput.append_child("program"); programOutput.append_copy(programInput.attribute("language")); status &= AppendProgram(programOutput, programInput); programInput = passInput.next_sibling("program"); } passInput = passInput.next_sibling("pass"); } subshaderInput = subshaderInput.next_sibling("subshader"); } std::ostringstream output; outputDocument.save(output); file = pb::FileSystem::Instance()->OpenFile(outputLocation, pb::kFileModeWrite); if (file) { file->Write(output.str()); delete file; } else { status = false; } if (!status) return 1; return 0; } <commit_msg>Update to use new pugixml<commit_after>#include <iostream> #include <sstream> #include <string> #include "pixelboost/data/xml/pugixml.hpp" #include "pixelboost/file/fileHelpers.h" enum ShaderLanguage { kShaderLanguageGLSL, kShaderLanguageHLSL, }; enum ShaderType { kShaderTypeVertex, kShaderTypeFragment, }; bool ParseShaderGLSL(const std::string& input, pugi::xml_node& output) { output.append_child(pugi::node_cdata).set_value(input.c_str()); return true; } bool ParseShaderHLSL(const std::string& input, pugi::xml_node& output) { output.append_child(pugi::node_cdata).set_value(input.c_str()); return true; } bool AppendProgram(pugi::xml_node& programOutput, pugi::xml_node& programInput) { std::string language = programInput.attribute("language").value(); if (language == "glsl") { if (!ParseShaderGLSL(programInput.child_value(), programOutput)) return false; } else if (language == "hlsl") { if (!ParseShaderHLSL(programInput.child_value(), programOutput)) return false; } else { // Unknown language return false; } return true; } int main(int argc, const char * argv[]) { bool status = true; if (argc < 3) return 1; new pb::FileSystem(argv[0]); pb::FileSystem::Instance()->MountReadLocation(argv[1], "/", true); pb::FileSystem::Instance()->OverrideWriteDirectory(argv[1]); std::string vertex, fragment; const char* inputLocation = argv[2]; const char* outputLocation = argv[3]; pb::File* file = pb::FileSystem::Instance()->OpenFile(inputLocation); std::string input; if (file) { file->ReadAll(input); delete file; } pugi::xml_document inputDocument; pugi::xml_document outputDocument; inputDocument.load(input.c_str()); pugi::xml_node shaderInput = inputDocument.child("shader"); pugi::xml_node shaderOutput = outputDocument.append_child("shader"); shaderOutput.append_copy(shaderInput.attribute("name")); pugi::xml_node attributesInput = shaderInput.child("attributes"); shaderOutput.append_copy(attributesInput); pugi::xml_node subshaderInput = shaderInput.child("subshader"); while (!subshaderInput.empty()) { pugi::xml_node subshaderOutput = shaderOutput.append_child("subshader"); subshaderOutput.append_copy(subshaderInput.attribute("class")); pugi::xml_node passInput = subshaderInput.child("pass"); while (!passInput.empty()) { pugi::xml_node passOutput = subshaderOutput.append_child("pass"); pugi::xml_node programInput = passInput.child("program"); while (!programInput.empty()) { pugi::xml_node programOutput = passOutput.append_child("program"); programOutput.append_copy(programInput.attribute("language")); status &= AppendProgram(programOutput, programInput); programInput = passInput.next_sibling("program"); } passInput = passInput.next_sibling("pass"); } subshaderInput = subshaderInput.next_sibling("subshader"); } std::ostringstream output; outputDocument.save(output); file = pb::FileSystem::Instance()->OpenFile(outputLocation, pb::kFileModeWrite); if (file) { file->Write(output.str()); delete file; } else { status = false; } if (!status) return 1; return 0; } <|endoftext|>
<commit_before>#include <iostream> #include "moltengamepad.h" #include <getopt.h> #include <signal.h> #include <stdio.h> #include <csignal> int parse_opts(moltengamepad::mg_options &options,int argc, char* argv[]); volatile bool STOP_WORKING = true; volatile bool QUIT_APPLICATION = false; moltengamepad* app; void signal_handler(int signum) { if (!STOP_WORKING) { //A long running action is to be interrupted. STOP_WORKING = true; return; } //Otherwise, we want to interrupt everything! (And let them shut down appropriately) QUIT_APPLICATION = true; delete app; exit(0); return; } int main(int argc, char* argv[]) { STOP_WORKING = true; QUIT_APPLICATION = false; signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); //signal(SIGHUP, signal_handler); moltengamepad::mg_options options; options.look_for_devices = true; options.listen_for_devices = true; options.make_keyboard = true; options.make_mouse = false; options.make_pointer = false; options.dpad_as_hat = false; options.mimic_xpad = false; options.num_gamepads = 4; options.config_dir = ""; options.profile_dir = ""; options.gendev_dir = ""; options.fifo_path = ""; options.uinput_path = ""; int ret = parse_opts(options,argc,argv); if (ret > 0) return 0; if (ret < 0) return ret; try { moltengamepad* mg = new moltengamepad(options); app = mg; mg->init(); shell_loop(mg, std::cin); delete mg; } catch (int e) { return e; } return 0; } int print_version() { std::cout << "MoltenGamepad version " << VERSION_STRING << "\n"; return 0; } int print_usage(char* execname) { print_version(); std::cout << "USAGE:\n"; std::cout << "\t" << execname << " [OPTIONS]\n"; std::cout << "\n"; std::string help_text = ""\ "--help -h\n"\ "\tShow this message\n"\ "\n"\ "--version -v\n"\ "\tDisplay the version string\n"\ "\n"\ "--uinput-path -u\n"\ "\tSet where the uinput node is found on the system\n"\ "\n"\ "--fifo-path -f\n"\ "\tSet where the fifo command channel should be placed.\n"\ "\n"\ "--profiles-path -p\n"\ "\tSet where the profiles are located\n"\ "\n"\ "--gendev-path -g\n"\ "\tSet where the generic device descriptions are located\n"\ "\n"\ "--config-path -c\n"\ "\tSet where the general config files are located\n"\ "\n"\ "--num-gamepads -n\n"\ "\tSet how many virtual gamepads will be created\n"\ "\n"\ "--no-make-keys\n"\ "\tDisable the creation of a virtual keyboard\n"\ "\n"\ "--no-enumerate\n"\ "\tDisable the search for already connected devices\n"\ "\n"\ "--no-monitor\n"\ "\tDisable listening for future connected devices\n"\ "\n"\ "--dpad-as-hat\n"\ "\tOutput dpad events as a hat rather than separate buttons\n"\ "\n"\ "--mimic-xpad\n"\ "\tMake the virtual output devices appear as xpad-style XBox 360 devices\n"\ ; std::cout << help_text; return 0; } int parse_opts(moltengamepad::mg_options &options, int argc, char* argv[]) { char c = 0; static struct option long_options[] = { {"help", 0, 0, 'h'}, {"version", 0, 0, 'v'}, {"uinput-path", 1, 0, 'u'}, {"profiles-path", 1, 0, 'p'}, {"gendev-path", 1, 0, 'g'}, {"config-path", 1, 0, 'c'}, {"num-gamepads", 1, 0, 'n'}, {"make-fifo", 1, 0, 'm'}, {"fifo-path", 1, 0, 'f'}, {"no-make-keys", 0, 0, 0}, {"no-enumerate", 0, 0, 0}, {"no-monitor", 0, 0, 0}, {"dpad-as-hat", 0, 0, 0}, {"mimic-xpad", 0, 0, 0}, {0, 0, 0, 0}, }; int long_index; while (c != -1) { c = getopt_long(argc,argv,"u:p:g:n:c:f:mhv", long_options, &long_index); switch (c) { case 0: if (long_index == 9) {options.make_keyboard = false;}; if (long_index == 10) {options.look_for_devices = false;}; if (long_index == 11) {options.listen_for_devices = false;}; if (long_index == 12) {options.dpad_as_hat = true;}; if (long_index == 13) {options.mimic_xpad = true;}; break; case 'u': options.uinput_path = std::string(optarg); break; case 'm': options.make_fifo = true; case 'f': options.fifo_path = std::string(optarg); break; case 'p': options.profile_dir = std::string(optarg); break; case 'g': options.gendev_dir = std::string(optarg); break; case 'c': options.config_dir = std::string(optarg); break; case 'h': print_usage(argv[0]); return 10; break; case 'v': print_version(); return 10; break; case 'n': try { options.num_gamepads = std::stoi(optarg); if (options.num_gamepads < 0 ) throw -3; } catch (...) { std::cerr << "could not parse numeric value for number of gamepads." << std::endl; return -5; } break; } } return 0; } <commit_msg>Fix bugs in fifo command line arguments<commit_after>#include <iostream> #include "moltengamepad.h" #include <getopt.h> #include <signal.h> #include <stdio.h> #include <csignal> int parse_opts(moltengamepad::mg_options &options,int argc, char* argv[]); volatile bool STOP_WORKING = true; volatile bool QUIT_APPLICATION = false; moltengamepad* app; void signal_handler(int signum) { if (!STOP_WORKING) { //A long running action is to be interrupted. STOP_WORKING = true; return; } //Otherwise, we want to interrupt everything! (And let them shut down appropriately) QUIT_APPLICATION = true; delete app; exit(0); return; } int main(int argc, char* argv[]) { STOP_WORKING = true; QUIT_APPLICATION = false; signal(SIGINT, signal_handler); signal(SIGTERM, signal_handler); //signal(SIGHUP, signal_handler); moltengamepad::mg_options options; options.look_for_devices = true; options.listen_for_devices = true; options.make_keyboard = true; options.make_mouse = false; options.make_pointer = false; options.dpad_as_hat = false; options.mimic_xpad = false; options.num_gamepads = 4; options.config_dir = ""; options.profile_dir = ""; options.gendev_dir = ""; options.fifo_path = ""; options.uinput_path = ""; int ret = parse_opts(options,argc,argv); if (ret > 0) return 0; if (ret < 0) return ret; try { moltengamepad* mg = new moltengamepad(options); app = mg; mg->init(); shell_loop(mg, std::cin); delete mg; } catch (int e) { return e; } return 0; } int print_version() { std::cout << "MoltenGamepad version " << VERSION_STRING << "\n"; return 0; } int print_usage(char* execname) { print_version(); std::cout << "USAGE:\n"; std::cout << "\t" << execname << " [OPTIONS]\n"; std::cout << "\n"; std::string help_text = ""\ "--help -h\n"\ "\tShow this message\n"\ "\n"\ "--version -v\n"\ "\tDisplay the version string\n"\ "\n"\ "--uinput-path -u\n"\ "\tSet where the uinput node is found on the system\n"\ "\n"\ "--make-fifo -f\n"\ "\tCreate a fifo command channel, and exit if it can't be made.\n"\ "\n"\ "--fifo-path -f\n"\ "\tSet where the fifo command channel should be placed.\n"\ "\n"\ "--profiles-path -p\n"\ "\tSet where the profiles are located\n"\ "\n"\ "--gendev-path -g\n"\ "\tSet where the generic device descriptions are located\n"\ "\n"\ "--config-path -c\n"\ "\tSet where the general config files are located\n"\ "\n"\ "--num-gamepads -n\n"\ "\tSet how many virtual gamepads will be created\n"\ "\n"\ "--no-make-keys\n"\ "\tDisable the creation of a virtual keyboard\n"\ "\n"\ "--no-enumerate\n"\ "\tDisable the search for already connected devices\n"\ "\n"\ "--no-monitor\n"\ "\tDisable listening for future connected devices\n"\ "\n"\ "--dpad-as-hat\n"\ "\tOutput dpad events as a hat rather than separate buttons\n"\ "\n"\ "--mimic-xpad\n"\ "\tMake the virtual output devices appear as xpad-style XBox 360 devices\n"\ ; std::cout << help_text; return 0; } int parse_opts(moltengamepad::mg_options &options, int argc, char* argv[]) { char c = 0; static struct option long_options[] = { {"help", 0, 0, 'h'}, {"version", 0, 0, 'v'}, {"uinput-path", 1, 0, 'u'}, {"profiles-path", 1, 0, 'p'}, {"gendev-path", 1, 0, 'g'}, {"config-path", 1, 0, 'c'}, {"num-gamepads", 1, 0, 'n'}, {"make-fifo", 0, 0, 'm'}, {"fifo-path", 1, 0, 'f'}, {"no-make-keys", 0, 0, 0}, {"no-enumerate", 0, 0, 0}, {"no-monitor", 0, 0, 0}, {"dpad-as-hat", 0, 0, 0}, {"mimic-xpad", 0, 0, 0}, {0, 0, 0, 0}, }; int long_index; while (c != -1) { c = getopt_long(argc,argv,"u:p:g:n:c:f:mhv", long_options, &long_index); switch (c) { case 0: if (long_index == 9) {options.make_keyboard = false;}; if (long_index == 10) {options.look_for_devices = false;}; if (long_index == 11) {options.listen_for_devices = false;}; if (long_index == 12) {options.dpad_as_hat = true;}; if (long_index == 13) {options.mimic_xpad = true;}; break; case 'u': options.uinput_path = std::string(optarg); break; case 'm': options.make_fifo = true; break; case 'f': options.fifo_path = std::string(optarg); break; case 'p': options.profile_dir = std::string(optarg); break; case 'g': options.gendev_dir = std::string(optarg); break; case 'c': options.config_dir = std::string(optarg); break; case 'h': print_usage(argv[0]); return 10; break; case 'v': print_version(); return 10; break; case 'n': try { options.num_gamepads = std::stoi(optarg); if (options.num_gamepads < 0 ) throw -3; } catch (...) { std::cerr << "could not parse numeric value for number of gamepads." << std::endl; return -5; } break; } } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2017-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <index/base.h> #include <shutdown.h> #include <tinyformat.h> #include <ui_interface.h> #include <util/system.h> #include <validation.h> #include <warnings.h> constexpr char DB_BEST_BLOCK = 'B'; constexpr int64_t SYNC_LOG_INTERVAL = 30; // seconds constexpr int64_t SYNC_LOCATOR_WRITE_INTERVAL = 30; // seconds template<typename... Args> static void FatalError(const char* fmt, const Args&... args) { std::string strMessage = tfm::format(fmt, args...); SetMiscWarning(strMessage); LogPrintf("*** %s\n", strMessage); uiInterface.ThreadSafeMessageBox( "Error: A fatal internal error occurred, see debug.log for details", "", CClientUIInterface::MSG_ERROR); StartShutdown(); } BaseIndex::DB::DB(const fs::path& path, size_t n_cache_size, bool f_memory, bool f_wipe, bool f_obfuscate) : CDBWrapper(path, n_cache_size, f_memory, f_wipe, f_obfuscate) {} bool BaseIndex::DB::ReadBestBlock(CBlockLocator& locator) const { bool success = Read(DB_BEST_BLOCK, locator); if (!success) { locator.SetNull(); } return success; } void BaseIndex::DB::WriteBestBlock(CDBBatch& batch, const CBlockLocator& locator) { batch.Write(DB_BEST_BLOCK, locator); } BaseIndex::~BaseIndex() { Interrupt(); Stop(); } bool BaseIndex::Init() { CBlockLocator locator; if (!GetDB().ReadBestBlock(locator)) { locator.SetNull(); } LOCK(cs_main); if (locator.IsNull()) { m_best_block_index = nullptr; } else { m_best_block_index = FindForkInGlobalIndex(::ChainActive(), locator); } m_synced = m_best_block_index.load() == ::ChainActive().Tip(); return true; } static const CBlockIndex* NextSyncBlock(const CBlockIndex* pindex_prev) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { AssertLockHeld(cs_main); if (!pindex_prev) { return ::ChainActive().Genesis(); } const CBlockIndex* pindex = ::ChainActive().Next(pindex_prev); if (pindex) { return pindex; } return ::ChainActive().Next(::ChainActive().FindFork(pindex_prev)); } void BaseIndex::ThreadSync() { const CBlockIndex* pindex = m_best_block_index.load(); if (!m_synced) { auto& consensus_params = Params().GetConsensus(); int64_t last_log_time = 0; int64_t last_locator_write_time = 0; while (true) { if (m_interrupt) { m_best_block_index = pindex; // No need to handle errors in Commit. If it fails, the error will be already be // logged. The best way to recover is to continue, as index cannot be corrupted by // a missed commit to disk for an advanced index state. Commit(); return; } { LOCK(cs_main); const CBlockIndex* pindex_next = NextSyncBlock(pindex); if (!pindex_next) { m_best_block_index = pindex; m_synced = true; // No need to handle errors in Commit. See rationale above. Commit(); break; } if (pindex_next->pprev != pindex && !Rewind(pindex, pindex_next->pprev)) { FatalError("%s: Failed to rewind index %s to a previous chain tip", __func__, GetName()); return; } pindex = pindex_next; } int64_t current_time = GetTime(); if (last_log_time + SYNC_LOG_INTERVAL < current_time) { LogPrintf("Syncing %s with block chain from height %d\n", GetName(), pindex->nHeight); last_log_time = current_time; } if (last_locator_write_time + SYNC_LOCATOR_WRITE_INTERVAL < current_time) { m_best_block_index = pindex; last_locator_write_time = current_time; // No need to handle errors in Commit. See rationale above. Commit(); } CBlock block; if (!ReadBlockFromDisk(block, pindex, consensus_params)) { FatalError("%s: Failed to read block %s from disk", __func__, pindex->GetBlockHash().ToString()); return; } if (!WriteBlock(block, pindex)) { FatalError("%s: Failed to write block %s to index database", __func__, pindex->GetBlockHash().ToString()); return; } } } if (pindex) { LogPrintf("%s is enabled at height %d\n", GetName(), pindex->nHeight); } else { LogPrintf("%s is enabled\n", GetName()); } } bool BaseIndex::Commit() { CDBBatch batch(GetDB()); if (!CommitInternal(batch) || !GetDB().WriteBatch(batch)) { return error("%s: Failed to commit latest %s state", __func__, GetName()); } return true; } bool BaseIndex::CommitInternal(CDBBatch& batch) { LOCK(cs_main); GetDB().WriteBestBlock(batch, ::ChainActive().GetLocator(m_best_block_index)); return true; } bool BaseIndex::Rewind(const CBlockIndex* current_tip, const CBlockIndex* new_tip) { assert(current_tip == m_best_block_index); assert(current_tip->GetAncestor(new_tip->nHeight) == new_tip); // In the case of a reorg, ensure persisted block locator is not stale. m_best_block_index = new_tip; if (!Commit()) { // If commit fails, revert the best block index to avoid corruption. m_best_block_index = current_tip; return false; } return true; } void BaseIndex::BlockConnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex, const std::vector<CTransactionRef>& txn_conflicted) { if (!m_synced) { return; } const CBlockIndex* best_block_index = m_best_block_index.load(); if (!best_block_index) { if (pindex->nHeight != 0) { FatalError("%s: First block connected is not the genesis block (height=%d)", __func__, pindex->nHeight); return; } } else { // Ensure block connects to an ancestor of the current best block. This should be the case // most of the time, but may not be immediately after the sync thread catches up and sets // m_synced. Consider the case where there is a reorg and the blocks on the stale branch are // in the ValidationInterface queue backlog even after the sync thread has caught up to the // new chain tip. In this unlikely event, log a warning and let the queue clear. if (best_block_index->GetAncestor(pindex->nHeight - 1) != pindex->pprev) { LogPrintf("%s: WARNING: Block %s does not connect to an ancestor of " /* Continued */ "known best chain (tip=%s); not updating index\n", __func__, pindex->GetBlockHash().ToString(), best_block_index->GetBlockHash().ToString()); return; } if (best_block_index != pindex->pprev && !Rewind(best_block_index, pindex->pprev)) { FatalError("%s: Failed to rewind index %s to a previous chain tip", __func__, GetName()); return; } } if (WriteBlock(*block, pindex)) { m_best_block_index = pindex; } else { FatalError("%s: Failed to write block %s to index", __func__, pindex->GetBlockHash().ToString()); return; } } void BaseIndex::ChainStateFlushed(const CBlockLocator& locator) { if (!m_synced) { return; } const uint256& locator_tip_hash = locator.vHave.front(); const CBlockIndex* locator_tip_index; { LOCK(cs_main); locator_tip_index = LookupBlockIndex(locator_tip_hash); } if (!locator_tip_index) { FatalError("%s: First block (hash=%s) in locator was not found", __func__, locator_tip_hash.ToString()); return; } // This checks that ChainStateFlushed callbacks are received after BlockConnected. The check may fail // immediately after the sync thread catches up and sets m_synced. Consider the case where // there is a reorg and the blocks on the stale branch are in the ValidationInterface queue // backlog even after the sync thread has caught up to the new chain tip. In this unlikely // event, log a warning and let the queue clear. const CBlockIndex* best_block_index = m_best_block_index.load(); if (best_block_index->GetAncestor(locator_tip_index->nHeight) != locator_tip_index) { LogPrintf("%s: WARNING: Locator contains block (hash=%s) not on known best " /* Continued */ "chain (tip=%s); not writing index locator\n", __func__, locator_tip_hash.ToString(), best_block_index->GetBlockHash().ToString()); return; } // No need to handle errors in Commit. If it fails, the error will be already be logged. The // best way to recover is to continue, as index cannot be corrupted by a missed commit to disk // for an advanced index state. Commit(); } bool BaseIndex::BlockUntilSyncedToCurrentChain() { AssertLockNotHeld(cs_main); if (!m_synced) { return false; } { // Skip the queue-draining stuff if we know we're caught up with // ::ChainActive().Tip(). LOCK(cs_main); const CBlockIndex* chain_tip = ::ChainActive().Tip(); const CBlockIndex* best_block_index = m_best_block_index.load(); if (best_block_index->GetAncestor(chain_tip->nHeight) == chain_tip) { return true; } } LogPrintf("%s: %s is catching up on block notifications\n", __func__, GetName()); SyncWithValidationInterfaceQueue(); return true; } void BaseIndex::Interrupt() { m_interrupt(); } void BaseIndex::Start() { // Need to register this ValidationInterface before running Init(), so that // callbacks are not missed if Init sets m_synced to true. RegisterValidationInterface(this); if (!Init()) { FatalError("%s: %s failed to initialize", __func__, GetName()); return; } m_thread_sync = std::thread(&TraceThread<std::function<void()>>, GetName(), std::bind(&BaseIndex::ThreadSync, this)); } void BaseIndex::Stop() { UnregisterValidationInterface(this); if (m_thread_sync.joinable()) { m_thread_sync.join(); } } <commit_msg>index: Don't commit a best block before indexing it during sync<commit_after>// Copyright (c) 2017-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <index/base.h> #include <shutdown.h> #include <tinyformat.h> #include <ui_interface.h> #include <util/system.h> #include <validation.h> #include <warnings.h> constexpr char DB_BEST_BLOCK = 'B'; constexpr int64_t SYNC_LOG_INTERVAL = 30; // seconds constexpr int64_t SYNC_LOCATOR_WRITE_INTERVAL = 30; // seconds template<typename... Args> static void FatalError(const char* fmt, const Args&... args) { std::string strMessage = tfm::format(fmt, args...); SetMiscWarning(strMessage); LogPrintf("*** %s\n", strMessage); uiInterface.ThreadSafeMessageBox( "Error: A fatal internal error occurred, see debug.log for details", "", CClientUIInterface::MSG_ERROR); StartShutdown(); } BaseIndex::DB::DB(const fs::path& path, size_t n_cache_size, bool f_memory, bool f_wipe, bool f_obfuscate) : CDBWrapper(path, n_cache_size, f_memory, f_wipe, f_obfuscate) {} bool BaseIndex::DB::ReadBestBlock(CBlockLocator& locator) const { bool success = Read(DB_BEST_BLOCK, locator); if (!success) { locator.SetNull(); } return success; } void BaseIndex::DB::WriteBestBlock(CDBBatch& batch, const CBlockLocator& locator) { batch.Write(DB_BEST_BLOCK, locator); } BaseIndex::~BaseIndex() { Interrupt(); Stop(); } bool BaseIndex::Init() { CBlockLocator locator; if (!GetDB().ReadBestBlock(locator)) { locator.SetNull(); } LOCK(cs_main); if (locator.IsNull()) { m_best_block_index = nullptr; } else { m_best_block_index = FindForkInGlobalIndex(::ChainActive(), locator); } m_synced = m_best_block_index.load() == ::ChainActive().Tip(); return true; } static const CBlockIndex* NextSyncBlock(const CBlockIndex* pindex_prev) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { AssertLockHeld(cs_main); if (!pindex_prev) { return ::ChainActive().Genesis(); } const CBlockIndex* pindex = ::ChainActive().Next(pindex_prev); if (pindex) { return pindex; } return ::ChainActive().Next(::ChainActive().FindFork(pindex_prev)); } void BaseIndex::ThreadSync() { const CBlockIndex* pindex = m_best_block_index.load(); if (!m_synced) { auto& consensus_params = Params().GetConsensus(); int64_t last_log_time = 0; int64_t last_locator_write_time = 0; while (true) { if (m_interrupt) { m_best_block_index = pindex; // No need to handle errors in Commit. If it fails, the error will be already be // logged. The best way to recover is to continue, as index cannot be corrupted by // a missed commit to disk for an advanced index state. Commit(); return; } { LOCK(cs_main); const CBlockIndex* pindex_next = NextSyncBlock(pindex); if (!pindex_next) { m_best_block_index = pindex; m_synced = true; // No need to handle errors in Commit. See rationale above. Commit(); break; } if (pindex_next->pprev != pindex && !Rewind(pindex, pindex_next->pprev)) { FatalError("%s: Failed to rewind index %s to a previous chain tip", __func__, GetName()); return; } pindex = pindex_next; } int64_t current_time = GetTime(); if (last_log_time + SYNC_LOG_INTERVAL < current_time) { LogPrintf("Syncing %s with block chain from height %d\n", GetName(), pindex->nHeight); last_log_time = current_time; } if (last_locator_write_time + SYNC_LOCATOR_WRITE_INTERVAL < current_time) { m_best_block_index = pindex->pprev; last_locator_write_time = current_time; // No need to handle errors in Commit. See rationale above. Commit(); } CBlock block; if (!ReadBlockFromDisk(block, pindex, consensus_params)) { FatalError("%s: Failed to read block %s from disk", __func__, pindex->GetBlockHash().ToString()); return; } if (!WriteBlock(block, pindex)) { FatalError("%s: Failed to write block %s to index database", __func__, pindex->GetBlockHash().ToString()); return; } } } if (pindex) { LogPrintf("%s is enabled at height %d\n", GetName(), pindex->nHeight); } else { LogPrintf("%s is enabled\n", GetName()); } } bool BaseIndex::Commit() { CDBBatch batch(GetDB()); if (!CommitInternal(batch) || !GetDB().WriteBatch(batch)) { return error("%s: Failed to commit latest %s state", __func__, GetName()); } return true; } bool BaseIndex::CommitInternal(CDBBatch& batch) { LOCK(cs_main); GetDB().WriteBestBlock(batch, ::ChainActive().GetLocator(m_best_block_index)); return true; } bool BaseIndex::Rewind(const CBlockIndex* current_tip, const CBlockIndex* new_tip) { assert(current_tip == m_best_block_index); assert(current_tip->GetAncestor(new_tip->nHeight) == new_tip); // In the case of a reorg, ensure persisted block locator is not stale. m_best_block_index = new_tip; if (!Commit()) { // If commit fails, revert the best block index to avoid corruption. m_best_block_index = current_tip; return false; } return true; } void BaseIndex::BlockConnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex, const std::vector<CTransactionRef>& txn_conflicted) { if (!m_synced) { return; } const CBlockIndex* best_block_index = m_best_block_index.load(); if (!best_block_index) { if (pindex->nHeight != 0) { FatalError("%s: First block connected is not the genesis block (height=%d)", __func__, pindex->nHeight); return; } } else { // Ensure block connects to an ancestor of the current best block. This should be the case // most of the time, but may not be immediately after the sync thread catches up and sets // m_synced. Consider the case where there is a reorg and the blocks on the stale branch are // in the ValidationInterface queue backlog even after the sync thread has caught up to the // new chain tip. In this unlikely event, log a warning and let the queue clear. if (best_block_index->GetAncestor(pindex->nHeight - 1) != pindex->pprev) { LogPrintf("%s: WARNING: Block %s does not connect to an ancestor of " /* Continued */ "known best chain (tip=%s); not updating index\n", __func__, pindex->GetBlockHash().ToString(), best_block_index->GetBlockHash().ToString()); return; } if (best_block_index != pindex->pprev && !Rewind(best_block_index, pindex->pprev)) { FatalError("%s: Failed to rewind index %s to a previous chain tip", __func__, GetName()); return; } } if (WriteBlock(*block, pindex)) { m_best_block_index = pindex; } else { FatalError("%s: Failed to write block %s to index", __func__, pindex->GetBlockHash().ToString()); return; } } void BaseIndex::ChainStateFlushed(const CBlockLocator& locator) { if (!m_synced) { return; } const uint256& locator_tip_hash = locator.vHave.front(); const CBlockIndex* locator_tip_index; { LOCK(cs_main); locator_tip_index = LookupBlockIndex(locator_tip_hash); } if (!locator_tip_index) { FatalError("%s: First block (hash=%s) in locator was not found", __func__, locator_tip_hash.ToString()); return; } // This checks that ChainStateFlushed callbacks are received after BlockConnected. The check may fail // immediately after the sync thread catches up and sets m_synced. Consider the case where // there is a reorg and the blocks on the stale branch are in the ValidationInterface queue // backlog even after the sync thread has caught up to the new chain tip. In this unlikely // event, log a warning and let the queue clear. const CBlockIndex* best_block_index = m_best_block_index.load(); if (best_block_index->GetAncestor(locator_tip_index->nHeight) != locator_tip_index) { LogPrintf("%s: WARNING: Locator contains block (hash=%s) not on known best " /* Continued */ "chain (tip=%s); not writing index locator\n", __func__, locator_tip_hash.ToString(), best_block_index->GetBlockHash().ToString()); return; } // No need to handle errors in Commit. If it fails, the error will be already be logged. The // best way to recover is to continue, as index cannot be corrupted by a missed commit to disk // for an advanced index state. Commit(); } bool BaseIndex::BlockUntilSyncedToCurrentChain() { AssertLockNotHeld(cs_main); if (!m_synced) { return false; } { // Skip the queue-draining stuff if we know we're caught up with // ::ChainActive().Tip(). LOCK(cs_main); const CBlockIndex* chain_tip = ::ChainActive().Tip(); const CBlockIndex* best_block_index = m_best_block_index.load(); if (best_block_index->GetAncestor(chain_tip->nHeight) == chain_tip) { return true; } } LogPrintf("%s: %s is catching up on block notifications\n", __func__, GetName()); SyncWithValidationInterfaceQueue(); return true; } void BaseIndex::Interrupt() { m_interrupt(); } void BaseIndex::Start() { // Need to register this ValidationInterface before running Init(), so that // callbacks are not missed if Init sets m_synced to true. RegisterValidationInterface(this); if (!Init()) { FatalError("%s: %s failed to initialize", __func__, GetName()); return; } m_thread_sync = std::thread(&TraceThread<std::function<void()>>, GetName(), std::bind(&BaseIndex::ThreadSync, this)); } void BaseIndex::Stop() { UnregisterValidationInterface(this); if (m_thread_sync.joinable()) { m_thread_sync.join(); } } <|endoftext|>
<commit_before>//individual.cpp #include <vector> #include <cstdlib> #include "individual.hpp" #include "utils.hpp" Individual::Individual(){ expression = new Node(); } Individual::~Individual(){ delete expression; } Node *Individual::crossover(double crossover_rate, Individual parent){ } void Individual::mutation(double mutation_rate){ double rate = mutation_rate*100; if (random()%100<rate){ //aqui eu sorteio um novo tipo de nó, e com isso um novo valor de C //também int tipo_anterior = expression->get_type(); int new_tipo = random() %utils::SIZETYPE; if (tipo_anterior==new_tipo) { //caso continue igual, sorteia outro valor } else { //caso mude, verifica se é func1 ou 2 e toma as devidas ações //ou seja -> ou cria um novo filho ou deleta um para que a árvore //não tenha pedaços que não sejam utilizados ou tenha pedaços //faltando. } } } double Individual::fitness(vector< vector<double> > points){ double mse = 0.0; for(int i=0; i<points.size(); i++){ mse += utils::uPow((expression->eval(points[0][i])-points[1][i] ), 2); } this->mse_value = utils::uSqrt(mse/(double)points.size()); return this->mse_value; } void Individual::print_expression_d(){ expression->print_node_d(); } <commit_msg>1.1 Implementado fitness<commit_after>//individual.cpp #include <vector> #include <cstdlib> #include <iostream> #include "individual.hpp" #include "utils.hpp" Individual::Individual(){ expression = new Node(); } Individual::~Individual(){ delete expression; } Node *Individual::crossover(double crossover_rate, Individual parent){ } void Individual::mutation(double mutation_rate){ double rate = mutation_rate*100; if (random()%100<rate){ int new_tipo = random() %utils::SIZETYPE; std::cout << "new tipo: " << new_tipo << std::endl; switch (new_tipo){ case utils::VAR: expression->set_C(utils::VAR, random()%2); break; case utils::CTE: expression->set_C(utils::CTE, random()%10); break; case utils::FUN1: expression->set_C(utils::FUN1, random()%utils::SIZEFUNC1); break; case utils::FUN2: expression->set_C(utils::FUN2, random()%utils::SIZEFUNC2); break; } } } double Individual::fitness(std::vector<utils::DataPoint> points){ double mse = 0.0; for(int i=0; i<points.size(); i++){ mse += utils::uPow((expression->eval(points[i])-points[i].y ), 2); } this->mse_value = utils::uSqrt(mse/(double)points.size()); return this->mse_value; } void Individual::print_expression_d(){ expression->print_node_d(); } <|endoftext|>
<commit_before>/*! * FrameRecevierConfigTest.cpp * * Created on: Feb 4, 2015 * Author: Tim Nicholls, STFC Application Engineering Group */ #include <boost/test/unit_test.hpp> #include "FrameReceiverConfig.h" namespace FrameReceiver { // This class, which is a friend of FrameReceiverConfig, allows testing of the // correct initialization of FrameReceiverConfig class FrameReceiverConfigTestProxy { public: FrameReceiverConfigTestProxy(FrameReceiver::FrameReceiverConfig& config) : mConfig(config) { } void test_config(void) { BOOST_CHECK_EQUAL(mConfig.max_buffer_mem_, FrameReceiver::Defaults::default_max_buffer_mem); BOOST_CHECK_EQUAL(mConfig.sensor_type_, FrameReceiver::Defaults::SensorTypeIllegal); std::vector<uint16_t> port_list; mConfig.tokenize_port_list(port_list, FrameReceiver::Defaults::default_rx_port_list); BOOST_CHECK_EQUAL(mConfig.rx_ports_.size(), port_list.size()); for (int i = 0; i < mConfig.rx_ports_.size(); i++) { BOOST_CHECK_EQUAL(mConfig.rx_ports_[i], port_list[i]); } BOOST_CHECK_EQUAL(mConfig.rx_address_, FrameReceiver::Defaults::default_rx_address); } private: FrameReceiver::FrameReceiverConfig& mConfig; }; } BOOST_AUTO_TEST_SUITE(FrameReceiverConfigUnitTest); BOOST_AUTO_TEST_CASE( ValidConfigWithDefaults ) { // Instantiate a configuration and a test proxy FrameReceiver::FrameReceiverConfig theConfig; FrameReceiver::FrameReceiverConfigTestProxy testProxy(theConfig); // Use the test proxy to test that the configuration object has the correct default // private configuration variables testProxy.test_config(); } BOOST_AUTO_TEST_CASE( ValidSensorNameToTypeMapping ) { FrameReceiver::FrameReceiverConfig theConfig; std::string p2mName = "percival2m"; std::string p13mName = "percival13m"; std::string excalibur3mName = "excalibur"; std::string badName = "foo"; // Check that the sensor name mapping to type works for all known values, and returns illegal for a bad name BOOST_CHECK_EQUAL(theConfig.map_sensor_name_to_type(p2mName), FrameReceiver::Defaults::SensorTypePercival2M); BOOST_CHECK_EQUAL(theConfig.map_sensor_name_to_type(p13mName), FrameReceiver::Defaults::SensorTypePercival13M); BOOST_CHECK_EQUAL(theConfig.map_sensor_name_to_type(excalibur3mName), FrameReceiver::Defaults::SensorTypeExcalibur); BOOST_CHECK_EQUAL(theConfig.map_sensor_name_to_type(badName), FrameReceiver::Defaults::SensorTypeIllegal); } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>Removed reference to 3M in EXCALIBUR sensor names<commit_after>/*! * FrameRecevierConfigTest.cpp * * Created on: Feb 4, 2015 * Author: Tim Nicholls, STFC Application Engineering Group */ #include <boost/test/unit_test.hpp> #include "FrameReceiverConfig.h" namespace FrameReceiver { // This class, which is a friend of FrameReceiverConfig, allows testing of the // correct initialization of FrameReceiverConfig class FrameReceiverConfigTestProxy { public: FrameReceiverConfigTestProxy(FrameReceiver::FrameReceiverConfig& config) : mConfig(config) { } void test_config(void) { BOOST_CHECK_EQUAL(mConfig.max_buffer_mem_, FrameReceiver::Defaults::default_max_buffer_mem); BOOST_CHECK_EQUAL(mConfig.sensor_type_, FrameReceiver::Defaults::SensorTypeIllegal); std::vector<uint16_t> port_list; mConfig.tokenize_port_list(port_list, FrameReceiver::Defaults::default_rx_port_list); BOOST_CHECK_EQUAL(mConfig.rx_ports_.size(), port_list.size()); for (int i = 0; i < mConfig.rx_ports_.size(); i++) { BOOST_CHECK_EQUAL(mConfig.rx_ports_[i], port_list[i]); } BOOST_CHECK_EQUAL(mConfig.rx_address_, FrameReceiver::Defaults::default_rx_address); } private: FrameReceiver::FrameReceiverConfig& mConfig; }; } BOOST_AUTO_TEST_SUITE(FrameReceiverConfigUnitTest); BOOST_AUTO_TEST_CASE( ValidConfigWithDefaults ) { // Instantiate a configuration and a test proxy FrameReceiver::FrameReceiverConfig theConfig; FrameReceiver::FrameReceiverConfigTestProxy testProxy(theConfig); // Use the test proxy to test that the configuration object has the correct default // private configuration variables testProxy.test_config(); } BOOST_AUTO_TEST_CASE( ValidSensorNameToTypeMapping ) { FrameReceiver::FrameReceiverConfig theConfig; std::string p2mName = "percival2m"; std::string p13mName = "percival13m"; std::string excaliburName = "excalibur"; std::string badName = "foo"; // Check that the sensor name mapping to type works for all known values, and returns illegal for a bad name BOOST_CHECK_EQUAL(theConfig.map_sensor_name_to_type(p2mName), FrameReceiver::Defaults::SensorTypePercival2M); BOOST_CHECK_EQUAL(theConfig.map_sensor_name_to_type(p13mName), FrameReceiver::Defaults::SensorTypePercival13M); BOOST_CHECK_EQUAL(theConfig.map_sensor_name_to_type(excaliburName), FrameReceiver::Defaults::SensorTypeExcalibur); BOOST_CHECK_EQUAL(theConfig.map_sensor_name_to_type(badName), FrameReceiver::Defaults::SensorTypeIllegal); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/tracing/core/trace_writer_impl.h" #include <string.h> #include <algorithm> #include <type_traits> #include <utility> #include "perfetto/base/logging.h" #include "perfetto/protozero/proto_utils.h" #include "src/tracing/core/shared_memory_arbiter_impl.h" #include "perfetto/trace/trace_packet.pbzero.h" using protozero::proto_utils::kMessageLengthFieldSize; using protozero::proto_utils::WriteRedundantVarInt; using ChunkHeader = perfetto::SharedMemoryABI::ChunkHeader; namespace perfetto { namespace { constexpr size_t kPacketHeaderSize = SharedMemoryABI::kPacketHeaderSize; } // namespace TraceWriterImpl::TraceWriterImpl(SharedMemoryArbiterImpl* shmem_arbiter, WriterID id, BufferID target_buffer) : shmem_arbiter_(shmem_arbiter), id_(id), target_buffer_(target_buffer), protobuf_stream_writer_(this) { // TODO(primiano): we could handle the case of running out of TraceWriterID(s) // more gracefully and always return a no-op TracePacket in NewTracePacket(). PERFETTO_CHECK(id_ != 0); cur_packet_.reset(new protos::pbzero::TracePacket()); cur_packet_->Finalize(); // To avoid the DCHECK in NewTracePacket(). } TraceWriterImpl::~TraceWriterImpl() { if (cur_chunk_.is_valid()) { cur_packet_->Finalize(); #if !defined(PERFETTO_BUILD_WITH_CHROMIUM) // TODO(primiano) Remove this ifdef when https://crbug.com/844379 is // resolved. Flush(); #endif } shmem_arbiter_->ReleaseWriterID(id_); } void TraceWriterImpl::Flush(std::function<void()> callback) { // Flush() cannot be called in the middle of a TracePacket. PERFETTO_CHECK(cur_packet_->is_finalized()); if (cur_chunk_.is_valid()) { shmem_arbiter_->ReturnCompletedChunk(std::move(cur_chunk_), target_buffer_, &patch_list_); shmem_arbiter_->FlushPendingCommitDataRequests(callback); } else { PERFETTO_DCHECK(patch_list_.empty()); } protobuf_stream_writer_.Reset({nullptr, nullptr}); } TraceWriterImpl::TracePacketHandle TraceWriterImpl::NewTracePacket() { // If we hit this, the caller is calling NewTracePacket() without having // finalized the previous packet. PERFETTO_DCHECK(cur_packet_->is_finalized()); fragmenting_packet_ = false; // Reserve space for the size of the message. Note: this call might re-enter // into this class invoking GetNewBuffer() if there isn't enough space or if // this is the very first call to NewTracePacket(). static_assert(kPacketHeaderSize == kMessageLengthFieldSize, "The packet header must match the Message header size"); // It doesn't make sense to begin a packet that is going to fragment // immediately after (8 is just an arbitrary estimation on the minimum size of // a realistic packet). if (protobuf_stream_writer_.bytes_available() < kPacketHeaderSize + 8) protobuf_stream_writer_.Reset(GetNewBuffer()); cur_packet_->Reset(&protobuf_stream_writer_); uint8_t* header = protobuf_stream_writer_.ReserveBytes(kPacketHeaderSize); memset(header, 0, kPacketHeaderSize); cur_packet_->set_size_field(header); cur_chunk_.IncrementPacketCount(); TracePacketHandle handle(cur_packet_.get()); cur_fragment_start_ = protobuf_stream_writer_.write_ptr(); fragmenting_packet_ = true; return handle; } // Called by the Message. We can get here in two cases: // 1. In the middle of writing a Message, // when |fragmenting_packet_| == true. In this case we want to update the // chunk header with a partial packet and start a new partial packet in the // new chunk. // 2. While calling ReserveBytes() for the packet header in NewTracePacket(). // In this case |fragmenting_packet_| == false and we just want a new chunk // without creating any fragments. protozero::ContiguousMemoryRange TraceWriterImpl::GetNewBuffer() { if (fragmenting_packet_) { uint8_t* const wptr = protobuf_stream_writer_.write_ptr(); PERFETTO_DCHECK(wptr >= cur_fragment_start_); uint32_t partial_size = static_cast<uint32_t>(wptr - cur_fragment_start_); PERFETTO_DCHECK(partial_size < cur_chunk_.size()); // Backfill the packet header with the fragment size. PERFETTO_DCHECK(partial_size > 0); cur_packet_->inc_size_already_written(partial_size); cur_chunk_.SetFlag(ChunkHeader::kLastPacketContinuesOnNextChunk); WriteRedundantVarInt(partial_size, cur_packet_->size_field()); // Descend in the stack of non-finalized nested submessages (if any) and // detour their |size_field| into the |patch_list_|. At this point we have // to release the chunk and they cannot write anymore into that. // TODO(primiano): add tests to cover this logic. for (auto* nested_msg = cur_packet_->nested_message(); nested_msg; nested_msg = nested_msg->nested_message()) { uint8_t* const cur_hdr = nested_msg->size_field(); // If this is false the protozero Message has already been instructed to // write, upon Finalize(), its size into the patch list. bool size_field_points_within_chunk = cur_hdr >= cur_chunk_.payload_begin() && cur_hdr + kMessageLengthFieldSize <= cur_chunk_.end(); if (size_field_points_within_chunk) { auto offset = static_cast<uint16_t>(cur_hdr - cur_chunk_.payload_begin()); const ChunkID cur_chunk_id = cur_chunk_.header()->chunk_id.load(std::memory_order_relaxed); Patch* patch = patch_list_.emplace_back(cur_chunk_id, offset); nested_msg->set_size_field(&patch->size_field[0]); } else { #if PERFETTO_DCHECK_IS_ON() // Ensure that the size field of the message points to an element of the // patch list. auto patch_it = std::find_if( patch_list_.begin(), patch_list_.end(), [cur_hdr](const Patch& p) { return &p.size_field[0] == cur_hdr; }); PERFETTO_DCHECK(patch_it != patch_list_.end()); #endif } } // for(nested_msg } // if(fragmenting_packet) if (cur_chunk_.is_valid()) { // ReturnCompletedChunk will consume the first patched entries from // |patch_list_| and shrink it. shmem_arbiter_->ReturnCompletedChunk(std::move(cur_chunk_), target_buffer_, &patch_list_); } // Start a new chunk. ChunkHeader::Packets packets = {}; if (fragmenting_packet_) { packets.count = 1; packets.flags = ChunkHeader::kFirstPacketContinuesFromPrevChunk; } // The memory order of the stores below doesn't really matter. This |header| // is just a local temporary object. The GetNewChunk() call below will copy it // into the shared buffer with the proper barriers. ChunkHeader header = {}; header.writer_id.store(id_, std::memory_order_relaxed); header.chunk_id.store(next_chunk_id_++, std::memory_order_relaxed); header.packets.store(packets, std::memory_order_relaxed); cur_chunk_ = shmem_arbiter_->GetNewChunk(header); uint8_t* payload_begin = cur_chunk_.payload_begin(); if (fragmenting_packet_) { cur_packet_->set_size_field(payload_begin); memset(payload_begin, 0, kPacketHeaderSize); payload_begin += kPacketHeaderSize; cur_fragment_start_ = payload_begin; } return protozero::ContiguousMemoryRange{payload_begin, cur_chunk_.end()}; } WriterID TraceWriterImpl::writer_id() const { return id_; } // Base class ctor/dtor definition. TraceWriter::TraceWriter() = default; TraceWriter::~TraceWriter() = default; } // namespace perfetto <commit_msg>Re-enabled TraceWriter flushing on destruction am: 34675596d8 am: a748c6a257<commit_after>/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/tracing/core/trace_writer_impl.h" #include <string.h> #include <algorithm> #include <type_traits> #include <utility> #include "perfetto/base/logging.h" #include "perfetto/protozero/proto_utils.h" #include "src/tracing/core/shared_memory_arbiter_impl.h" #include "perfetto/trace/trace_packet.pbzero.h" using protozero::proto_utils::kMessageLengthFieldSize; using protozero::proto_utils::WriteRedundantVarInt; using ChunkHeader = perfetto::SharedMemoryABI::ChunkHeader; namespace perfetto { namespace { constexpr size_t kPacketHeaderSize = SharedMemoryABI::kPacketHeaderSize; } // namespace TraceWriterImpl::TraceWriterImpl(SharedMemoryArbiterImpl* shmem_arbiter, WriterID id, BufferID target_buffer) : shmem_arbiter_(shmem_arbiter), id_(id), target_buffer_(target_buffer), protobuf_stream_writer_(this) { // TODO(primiano): we could handle the case of running out of TraceWriterID(s) // more gracefully and always return a no-op TracePacket in NewTracePacket(). PERFETTO_CHECK(id_ != 0); cur_packet_.reset(new protos::pbzero::TracePacket()); cur_packet_->Finalize(); // To avoid the DCHECK in NewTracePacket(). } TraceWriterImpl::~TraceWriterImpl() { if (cur_chunk_.is_valid()) { cur_packet_->Finalize(); Flush(); } shmem_arbiter_->ReleaseWriterID(id_); } void TraceWriterImpl::Flush(std::function<void()> callback) { // Flush() cannot be called in the middle of a TracePacket. PERFETTO_CHECK(cur_packet_->is_finalized()); if (cur_chunk_.is_valid()) { shmem_arbiter_->ReturnCompletedChunk(std::move(cur_chunk_), target_buffer_, &patch_list_); shmem_arbiter_->FlushPendingCommitDataRequests(callback); } else { PERFETTO_DCHECK(patch_list_.empty()); } protobuf_stream_writer_.Reset({nullptr, nullptr}); } TraceWriterImpl::TracePacketHandle TraceWriterImpl::NewTracePacket() { // If we hit this, the caller is calling NewTracePacket() without having // finalized the previous packet. PERFETTO_DCHECK(cur_packet_->is_finalized()); fragmenting_packet_ = false; // Reserve space for the size of the message. Note: this call might re-enter // into this class invoking GetNewBuffer() if there isn't enough space or if // this is the very first call to NewTracePacket(). static_assert(kPacketHeaderSize == kMessageLengthFieldSize, "The packet header must match the Message header size"); // It doesn't make sense to begin a packet that is going to fragment // immediately after (8 is just an arbitrary estimation on the minimum size of // a realistic packet). if (protobuf_stream_writer_.bytes_available() < kPacketHeaderSize + 8) protobuf_stream_writer_.Reset(GetNewBuffer()); cur_packet_->Reset(&protobuf_stream_writer_); uint8_t* header = protobuf_stream_writer_.ReserveBytes(kPacketHeaderSize); memset(header, 0, kPacketHeaderSize); cur_packet_->set_size_field(header); cur_chunk_.IncrementPacketCount(); TracePacketHandle handle(cur_packet_.get()); cur_fragment_start_ = protobuf_stream_writer_.write_ptr(); fragmenting_packet_ = true; return handle; } // Called by the Message. We can get here in two cases: // 1. In the middle of writing a Message, // when |fragmenting_packet_| == true. In this case we want to update the // chunk header with a partial packet and start a new partial packet in the // new chunk. // 2. While calling ReserveBytes() for the packet header in NewTracePacket(). // In this case |fragmenting_packet_| == false and we just want a new chunk // without creating any fragments. protozero::ContiguousMemoryRange TraceWriterImpl::GetNewBuffer() { if (fragmenting_packet_) { uint8_t* const wptr = protobuf_stream_writer_.write_ptr(); PERFETTO_DCHECK(wptr >= cur_fragment_start_); uint32_t partial_size = static_cast<uint32_t>(wptr - cur_fragment_start_); PERFETTO_DCHECK(partial_size < cur_chunk_.size()); // Backfill the packet header with the fragment size. PERFETTO_DCHECK(partial_size > 0); cur_packet_->inc_size_already_written(partial_size); cur_chunk_.SetFlag(ChunkHeader::kLastPacketContinuesOnNextChunk); WriteRedundantVarInt(partial_size, cur_packet_->size_field()); // Descend in the stack of non-finalized nested submessages (if any) and // detour their |size_field| into the |patch_list_|. At this point we have // to release the chunk and they cannot write anymore into that. // TODO(primiano): add tests to cover this logic. for (auto* nested_msg = cur_packet_->nested_message(); nested_msg; nested_msg = nested_msg->nested_message()) { uint8_t* const cur_hdr = nested_msg->size_field(); // If this is false the protozero Message has already been instructed to // write, upon Finalize(), its size into the patch list. bool size_field_points_within_chunk = cur_hdr >= cur_chunk_.payload_begin() && cur_hdr + kMessageLengthFieldSize <= cur_chunk_.end(); if (size_field_points_within_chunk) { auto offset = static_cast<uint16_t>(cur_hdr - cur_chunk_.payload_begin()); const ChunkID cur_chunk_id = cur_chunk_.header()->chunk_id.load(std::memory_order_relaxed); Patch* patch = patch_list_.emplace_back(cur_chunk_id, offset); nested_msg->set_size_field(&patch->size_field[0]); } else { #if PERFETTO_DCHECK_IS_ON() // Ensure that the size field of the message points to an element of the // patch list. auto patch_it = std::find_if( patch_list_.begin(), patch_list_.end(), [cur_hdr](const Patch& p) { return &p.size_field[0] == cur_hdr; }); PERFETTO_DCHECK(patch_it != patch_list_.end()); #endif } } // for(nested_msg } // if(fragmenting_packet) if (cur_chunk_.is_valid()) { // ReturnCompletedChunk will consume the first patched entries from // |patch_list_| and shrink it. shmem_arbiter_->ReturnCompletedChunk(std::move(cur_chunk_), target_buffer_, &patch_list_); } // Start a new chunk. ChunkHeader::Packets packets = {}; if (fragmenting_packet_) { packets.count = 1; packets.flags = ChunkHeader::kFirstPacketContinuesFromPrevChunk; } // The memory order of the stores below doesn't really matter. This |header| // is just a local temporary object. The GetNewChunk() call below will copy it // into the shared buffer with the proper barriers. ChunkHeader header = {}; header.writer_id.store(id_, std::memory_order_relaxed); header.chunk_id.store(next_chunk_id_++, std::memory_order_relaxed); header.packets.store(packets, std::memory_order_relaxed); cur_chunk_ = shmem_arbiter_->GetNewChunk(header); uint8_t* payload_begin = cur_chunk_.payload_begin(); if (fragmenting_packet_) { cur_packet_->set_size_field(payload_begin); memset(payload_begin, 0, kPacketHeaderSize); payload_begin += kPacketHeaderSize; cur_fragment_start_ = payload_begin; } return protozero::ContiguousMemoryRange{payload_begin, cur_chunk_.end()}; } WriterID TraceWriterImpl::writer_id() const { return id_; } // Base class ctor/dtor definition. TraceWriter::TraceWriter() = default; TraceWriter::~TraceWriter() = default; } // namespace perfetto <|endoftext|>
<commit_before>// RUN: %clang_cl_asan -O0 %s -Fe%t // RUN: not %run %t 2>&1 | FileCheck %s #include <stdio.h> #include <string.h> #include <malloc.h> int main() { char *ptr = _strdup("Hello"); int subscript = 1; ptr[subscript] = '3'; printf("%s\n", ptr); fflush(0); // CHECK: H3llo subscript = -1; ptr[subscript] = 42; // CHECK: AddressSanitizer: heap-buffer-overflow on address [[ADDR:0x[0-9a-f]+]] // CHECK: WRITE of size 1 at [[ADDR]] thread T0 // CHECK: {{#0 .* main .*}}intercept_strdup.cc:[[@LINE-3]] // CHECK: [[ADDR]] is located 1 bytes to the left of 6-byte region // CHECK: allocated by thread T0 here: // CHECK: #0 {{.*strdup}} // CHECK: #1 {{.* main .*}}intercept_strdup.cc:[[@LINE-15]] // CHECK: #2 {{.*foobar}} // CHECK: #3 {{.*foobar}} // CHECK: #4 {{.*foobar}} // CHECK: #5 {{.*foobar}} // CHECK: #6 {{.*foobar}} // CHECK: #7 {{.*foobar}} // CHECK: #8 {{.*foobar}} // CHECK: #9 {{.*foobar}} free(ptr); } <commit_msg>Amazingly, my guess was correct for the top two frames here. Hopefully with this, the Windows sanitizer bot will go green!<commit_after>// RUN: %clang_cl_asan -O0 %s -Fe%t // RUN: not %run %t 2>&1 | FileCheck %s #include <stdio.h> #include <string.h> #include <malloc.h> int main() { char *ptr = _strdup("Hello"); int subscript = 1; ptr[subscript] = '3'; printf("%s\n", ptr); fflush(0); // CHECK: H3llo subscript = -1; ptr[subscript] = 42; // CHECK: AddressSanitizer: heap-buffer-overflow on address [[ADDR:0x[0-9a-f]+]] // CHECK: WRITE of size 1 at [[ADDR]] thread T0 // CHECK: {{#0 .* main .*}}intercept_strdup.cc:[[@LINE-3]] // CHECK: [[ADDR]] is located 1 bytes to the left of 6-byte region // CHECK: allocated by thread T0 here: // CHECK: #0 {{.*strdup}} // CHECK: #1 {{.* main .*}}intercept_strdup.cc:[[@LINE-15]] free(ptr); } <|endoftext|>
<commit_before>/*++ Copyright (c) 2006 Microsoft Corporation Module Name: bitvector.cpp Abstract: Simple bitvector implementation Author: Leonardo de Moura (leonardo) 2006-10-03. Revision History: --*/ #include<limits.h> #include"bit_vector.h" #include"trace.h" #define DEFAULT_CAPACITY 2 #define MK_MASK(_num_bits_) ((1U << _num_bits_) - 1) void bit_vector::expand_to(unsigned new_capacity) { if (m_data) { m_data = (unsigned*)memory::reallocate(m_data, new_capacity * sizeof(unsigned)); } else { m_data = alloc_svect(unsigned, new_capacity); } m_capacity = new_capacity; } void bit_vector::resize(unsigned new_size, bool val) { if (new_size <= m_num_bits) { m_num_bits = new_size; return; } TRACE("bit_vector", tout << "expanding: " << new_size << " capacity: " << m_capacity << " num words: " << num_words(new_size) << "\n";); if (num_words(new_size) > m_capacity) { expand_to((num_words(new_size) * 3 + 1) >> 1); } unsigned bwidx = m_num_bits/32; unsigned ewidx = num_words(new_size); unsigned * begin = m_data + bwidx; unsigned pos = m_num_bits % 32; unsigned mask = MK_MASK(pos); int cval; if (val) { *begin |= ~mask; cval = ~0; } else { *begin &= mask; cval = 0; } TRACE("bit_vector", tout << "num_bits: " << m_num_bits << "\n"; tout << "bwidx: " << bwidx << "\n"; tout << "ewidx: " << ewidx << "\n"; tout << "pos: " << pos << "\n"; tout << "mask: " << std::hex << mask << "\n" << std::dec; tout << "cval: " << cval << "\n";); if (bwidx < ewidx) { memset(begin + 1, cval, (ewidx - bwidx - 1) * sizeof(unsigned)); } m_num_bits = new_size; } void bit_vector::shift_right(unsigned k) { if (k == 0) return; unsigned new_num_bits = m_num_bits + k; unsigned old_num_words = num_words(m_num_bits); unsigned new_num_words = num_words(new_num_bits); resize(m_num_bits + k, false); unsigned bit_shift = k % (8 * sizeof(unsigned)); unsigned word_shift = k / (8 * sizeof(unsigned)); if (word_shift > 0) { unsigned j = old_num_words; unsigned i = old_num_words + word_shift; while (j > 0) { --j; --i; m_data[i] = m_data[j]; } while (i > 0) { --i; m_data[i] = 0; } } if (bit_shift > 0) { DEBUG_CODE({ for (unsigned i = 0; i < word_shift; i++) { SASSERT(m_data[i] == 0); } }); unsigned comp_shift = (8 * sizeof(unsigned)) - bit_shift; unsigned prev = 0; for (unsigned i = word_shift; i < new_num_words; i++) { unsigned new_prev = (m_data[i] >> comp_shift); m_data[i] <<= bit_shift; m_data[i] |= prev; prev = new_prev; } } } bool bit_vector::operator==(bit_vector const & source) const { if (m_num_bits != source.m_num_bits) return false; unsigned n = num_words(); if (n == 0) return true; unsigned i; for (i = 0; i < n - 1; i++) { if (m_data[i] != source.m_data[i]) return false; } unsigned bit_rest = source.m_num_bits % 32; unsigned mask = MK_MASK(bit_rest); if (mask == 0) mask = UINT_MAX; return (m_data[i] & mask) == (source.m_data[i] & mask); } bit_vector & bit_vector::operator|=(bit_vector const & source) { if (size() < source.size()) resize(source.size(), false); unsigned n2 = source.num_words(); SASSERT(n2 <= num_words()); unsigned bit_rest = source.m_num_bits % 32; if (bit_rest == 0) { unsigned i = 0; for (i = 0; i < n2; i++) m_data[i] |= source.m_data[i]; } else { unsigned i = 0; for (i = 0; i < n2 - 1; i++) m_data[i] |= source.m_data[i]; unsigned mask = MK_MASK(bit_rest); m_data[i] |= source.m_data[i] & mask; } return *this; } bit_vector & bit_vector::operator&=(bit_vector const & source) { unsigned n1 = num_words(); unsigned n2 = source.num_words(); if (n1 == 0) return *this; if (n2 > n1) { for (unsigned i = 0; i < n1; i++) m_data[i] &= source.m_data[i]; } else { SASSERT(n2 <= n1); unsigned bit_rest = source.m_num_bits % 32; unsigned i = 0; if (bit_rest == 0) { for (i = 0; i < n2; i++) m_data[i] &= source.m_data[i]; } else { for (i = 0; i < n2 - 1; i++) m_data[i] &= source.m_data[i]; unsigned mask = MK_MASK(bit_rest); m_data[i] &= (source.m_data[i] & mask); } for (i = n2; i < n1; i++) m_data[i] = 0; } return *this; } void bit_vector::display(std::ostream & out) const { #if 1 unsigned i = m_num_bits; while (i > 0) { --i; if (get(i)) out << "1"; else out << "0"; } #else for (unsigned i = 0; i < m_num_bits; i++) { if (get(i)) out << "1"; else out << "0"; if ((i + 1) % 32 == 0) out << "\n"; } #endif } void fr_bit_vector::reset() { unsigned sz = size(); unsigned_vector::const_iterator it = m_one_idxs.begin(); unsigned_vector::const_iterator end = m_one_idxs.end(); for (; it != end; ++it) { unsigned idx = *it; if (idx < sz) unset(idx); } m_one_idxs.reset(); } <commit_msg>fix missing memset in my previous commit<commit_after>/*++ Copyright (c) 2006 Microsoft Corporation Module Name: bitvector.cpp Abstract: Simple bitvector implementation Author: Leonardo de Moura (leonardo) 2006-10-03. Revision History: --*/ #include<limits.h> #include"bit_vector.h" #include"trace.h" #define DEFAULT_CAPACITY 2 #define MK_MASK(_num_bits_) ((1U << _num_bits_) - 1) void bit_vector::expand_to(unsigned new_capacity) { if (m_data) { m_data = (unsigned*)memory::reallocate(m_data, new_capacity * sizeof(unsigned)); } else { m_data = alloc_svect(unsigned, new_capacity); } memset(m_data + m_capacity, 0, (new_capacity - m_capacity) * sizeof(unsigned)); m_capacity = new_capacity; } void bit_vector::resize(unsigned new_size, bool val) { if (new_size <= m_num_bits) { m_num_bits = new_size; return; } TRACE("bit_vector", tout << "expanding: " << new_size << " capacity: " << m_capacity << " num words: " << num_words(new_size) << "\n";); if (num_words(new_size) > m_capacity) { expand_to((num_words(new_size) * 3 + 1) >> 1); } unsigned bwidx = m_num_bits/32; unsigned ewidx = num_words(new_size); unsigned * begin = m_data + bwidx; unsigned pos = m_num_bits % 32; unsigned mask = MK_MASK(pos); int cval; if (val) { *begin |= ~mask; cval = ~0; } else { *begin &= mask; cval = 0; } TRACE("bit_vector", tout << "num_bits: " << m_num_bits << "\n"; tout << "bwidx: " << bwidx << "\n"; tout << "ewidx: " << ewidx << "\n"; tout << "pos: " << pos << "\n"; tout << "mask: " << std::hex << mask << "\n" << std::dec; tout << "cval: " << cval << "\n";); if (bwidx < ewidx) { memset(begin + 1, cval, (ewidx - bwidx - 1) * sizeof(unsigned)); } m_num_bits = new_size; } void bit_vector::shift_right(unsigned k) { if (k == 0) return; unsigned new_num_bits = m_num_bits + k; unsigned old_num_words = num_words(m_num_bits); unsigned new_num_words = num_words(new_num_bits); resize(m_num_bits + k, false); unsigned bit_shift = k % (8 * sizeof(unsigned)); unsigned word_shift = k / (8 * sizeof(unsigned)); if (word_shift > 0) { unsigned j = old_num_words; unsigned i = old_num_words + word_shift; while (j > 0) { --j; --i; m_data[i] = m_data[j]; } while (i > 0) { --i; m_data[i] = 0; } } if (bit_shift > 0) { DEBUG_CODE({ for (unsigned i = 0; i < word_shift; i++) { SASSERT(m_data[i] == 0); } }); unsigned comp_shift = (8 * sizeof(unsigned)) - bit_shift; unsigned prev = 0; for (unsigned i = word_shift; i < new_num_words; i++) { unsigned new_prev = (m_data[i] >> comp_shift); m_data[i] <<= bit_shift; m_data[i] |= prev; prev = new_prev; } } } bool bit_vector::operator==(bit_vector const & source) const { if (m_num_bits != source.m_num_bits) return false; unsigned n = num_words(); if (n == 0) return true; unsigned i; for (i = 0; i < n - 1; i++) { if (m_data[i] != source.m_data[i]) return false; } unsigned bit_rest = source.m_num_bits % 32; unsigned mask = MK_MASK(bit_rest); if (mask == 0) mask = UINT_MAX; return (m_data[i] & mask) == (source.m_data[i] & mask); } bit_vector & bit_vector::operator|=(bit_vector const & source) { if (size() < source.size()) resize(source.size(), false); unsigned n2 = source.num_words(); SASSERT(n2 <= num_words()); unsigned bit_rest = source.m_num_bits % 32; if (bit_rest == 0) { unsigned i = 0; for (i = 0; i < n2; i++) m_data[i] |= source.m_data[i]; } else { unsigned i = 0; for (i = 0; i < n2 - 1; i++) m_data[i] |= source.m_data[i]; unsigned mask = MK_MASK(bit_rest); m_data[i] |= source.m_data[i] & mask; } return *this; } bit_vector & bit_vector::operator&=(bit_vector const & source) { unsigned n1 = num_words(); unsigned n2 = source.num_words(); if (n1 == 0) return *this; if (n2 > n1) { for (unsigned i = 0; i < n1; i++) m_data[i] &= source.m_data[i]; } else { SASSERT(n2 <= n1); unsigned bit_rest = source.m_num_bits % 32; unsigned i = 0; if (bit_rest == 0) { for (i = 0; i < n2; i++) m_data[i] &= source.m_data[i]; } else { for (i = 0; i < n2 - 1; i++) m_data[i] &= source.m_data[i]; unsigned mask = MK_MASK(bit_rest); m_data[i] &= (source.m_data[i] & mask); } for (i = n2; i < n1; i++) m_data[i] = 0; } return *this; } void bit_vector::display(std::ostream & out) const { #if 1 unsigned i = m_num_bits; while (i > 0) { --i; if (get(i)) out << "1"; else out << "0"; } #else for (unsigned i = 0; i < m_num_bits; i++) { if (get(i)) out << "1"; else out << "0"; if ((i + 1) % 32 == 0) out << "\n"; } #endif } void fr_bit_vector::reset() { unsigned sz = size(); unsigned_vector::const_iterator it = m_one_idxs.begin(); unsigned_vector::const_iterator end = m_one_idxs.end(); for (; it != end; ++it) { unsigned idx = *it; if (idx < sz) unset(idx); } m_one_idxs.reset(); } <|endoftext|>
<commit_before>#include <iostream> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> int main (int argc, char** argv) { pcl::PointCloud<pcl::PointXYZ> cloud; // Fill in the cloud data cloud.width = 5; cloud.height = 1; cloud.is_dense = false; cloud.points.resize (cloud.width * cloud.height); for (size_t i = 0; i < cloud.points.size (); ++i) { cloud.points[i].x = 1024 * rand () / (RAND_MAX + 1.0f); cloud.points[i].y = 1024 * rand () / (RAND_MAX + 1.0f); cloud.points[i].z = 1024 * rand () / (RAND_MAX + 1.0f); } pcl::io::savePCDFileASCII ("test_pcd.pcd", cloud); std::cerr << "Saved " << cloud.points.size () << " data points to test_pcd.pcd." << std::endl; for (size_t i = 0; i < cloud.points.size (); ++i) std::cerr << " " << cloud.points[i].x << " " << cloud.points[i].y << " " << cloud.points[i].z << std::endl; return (0); }<commit_msg>oops, revert pcd_write.cpp<commit_after>#include <iostream> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> int main (int argc, char** argv) { pcl::PointCloud<pcl::PointXYZ> cloud; // Fill in the cloud data cloud.width = 5; cloud.height = 1; cloud.is_dense = false; cloud.points.resize (cloud.width * cloud.height); for (size_t i = 0; i < cloud.points.size (); ++i) { cloud.points[i].x = 1024 * rand () / (RAND_MAX + 1.0f); cloud.points[i].y = 1024 * rand () / (RAND_MAX + 1.0f); cloud.points[i].z = 1024 * rand () / (RAND_MAX + 1.0f); } pcl::io::savePCDFileASCII ("test_pcd.pcd", cloud); std::cerr << "Saved " << cloud.points.size () << " data points to test_pcd.pcd." << std::endl; for (size_t i = 0; i < cloud.points.size (); ++i) std::cerr << " " << cloud.points[i].x << " " << cloud.points[i].y << " " << cloud.points[i].z << std::endl; return (0); }<|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com> Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreException.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" #include "OgreRoot.h" #include "OgreRenderSystem.h" #include "OgreEGLSupport.h" #include "OgreEGLWindow.h" #if OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN #include "OgreEGLRenderTexture.h" #endif #ifndef EGL_VERSION_1_5 #define EGL_CONTEXT_MAJOR_VERSION EGL_CONTEXT_CLIENT_VERSION #define EGL_CONTEXT_MINOR_VERSION EGL_NONE #endif #include <EGL/eglext.h> namespace Ogre { EGLSupport::EGLSupport(int profile) : GLNativeSupport(profile), mGLDisplay(0), mNativeDisplay(EGL_DEFAULT_DISPLAY), hasEGL15(false) { } EGLDisplay EGLSupport::getGLDisplay(void) { #if defined(EGL_VERSION_1_5) && OGRE_PLATFORM != OGRE_PLATFORM_ANDROID static auto eglQueryDevicesEXT = (PFNEGLQUERYDEVICESEXTPROC)eglGetProcAddress("eglQueryDevicesEXT"); static auto eglQueryDeviceStringEXT = (PFNEGLQUERYDEVICESTRINGEXTPROC)eglGetProcAddress("eglQueryDeviceStringEXT"); if(eglQueryDevicesEXT && mNativeDisplay == EGL_DEFAULT_DISPLAY) { int numDevices; eglQueryDevicesEXT(0, NULL, &numDevices); EGL_CHECK_ERROR std::vector<EGLDeviceEXT> devices(numDevices); eglQueryDevicesEXT(numDevices, devices.data(), &numDevices); EGLAttrib attribs[] = {EGL_NONE}; for(auto dev : devices) { EGLDisplay display = eglGetPlatformDisplay(EGL_PLATFORM_DEVICE_EXT, dev, attribs); EGL_CHECK_ERROR if(display != EGL_NO_DISPLAY && !mGLDisplay) { mGLDisplay = display; const char* exts = eglQueryDeviceStringEXT(dev, EGL_EXTENSIONS); LogManager::getSingleton().stream() << "EGL: using default display. Device extensions: " << exts; break; } } } else #endif { mGLDisplay = eglGetDisplay(mNativeDisplay); EGL_CHECK_ERROR } if(mGLDisplay == EGL_NO_DISPLAY) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn`t get EGLDisplay"); } if (eglInitialize(mGLDisplay, &mEGLMajor, &mEGLMinor) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn`t initialize EGLDisplay ", "EGLSupport::getGLDisplay"); } EGL_CHECK_ERROR return mGLDisplay; } EGLConfig* EGLSupport::chooseGLConfig(const EGLint *attribList, EGLint *nElements) { EGLConfig *configs; if (eglChooseConfig(mGLDisplay, attribList, NULL, 0, nElements) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config"); *nElements = 0; return 0; } EGL_CHECK_ERROR configs = (EGLConfig*) malloc(*nElements * sizeof(EGLConfig)); if (eglChooseConfig(mGLDisplay, attribList, configs, *nElements, nElements) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config"); *nElements = 0; free(configs); return 0; } EGL_CHECK_ERROR return configs; } EGLConfig* EGLSupport::getConfigs(EGLint *nElements) { EGLConfig *configs; if (eglGetConfigs(mGLDisplay, NULL, 0, nElements) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config"); *nElements = 0; return 0; } EGL_CHECK_ERROR configs = (EGLConfig*) malloc(*nElements * sizeof(EGLConfig)); if (eglGetConfigs(mGLDisplay, configs, *nElements, nElements) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config"); *nElements = 0; free(configs); return 0; } EGL_CHECK_ERROR return configs; } EGLBoolean EGLSupport::getGLConfigAttrib(EGLConfig glConfig, EGLint attribute, EGLint *value) { EGLBoolean status; status = eglGetConfigAttrib(mGLDisplay, glConfig, attribute, value); EGL_CHECK_ERROR return status; } void* EGLSupport::getProcAddress(const char* name) const { return (void*)eglGetProcAddress(name); } ::EGLConfig EGLSupport::getGLConfigFromContext(::EGLContext context) { ::EGLConfig glConfig; EGLint id = 0; ::EGLConfig *configs; EGLint numConfigs; if (eglQueryContext(mGLDisplay, context, EGL_CONFIG_ID, &id) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to get config from context"); return 0; } EGL_CHECK_ERROR configs = getConfigs(&numConfigs); glConfig = configs[id]; free(configs); return glConfig; } ::EGLConfig EGLSupport::getGLConfigFromDrawable(::EGLSurface drawable, unsigned int *w, unsigned int *h) { ::EGLConfig glConfig; EGLint id = 0; ::EGLConfig *configs; EGLint numConfigs; if (eglQuerySurface(mGLDisplay, drawable, EGL_CONFIG_ID, &id) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to get config from drawable"); return 0; } EGL_CHECK_ERROR eglQuerySurface(mGLDisplay, drawable, EGL_WIDTH, (EGLint *) w); EGL_CHECK_ERROR eglQuerySurface(mGLDisplay, drawable, EGL_HEIGHT, (EGLint *) h); EGL_CHECK_ERROR configs = getConfigs(&numConfigs); glConfig = configs[id]; free(configs); return glConfig; } //------------------------------------------------------------------------ // A helper class for the implementation of selectFBConfig //------------------------------------------------------------------------ class GLConfigAttribs { public: GLConfigAttribs(const int* attribs) { fields[EGL_CONFIG_CAVEAT] = EGL_NONE; for (int i = 0; attribs[2*i] != EGL_NONE; i++) { fields[attribs[2*i]] = attribs[2*i+1]; } } void load(EGLSupport* const glSupport, EGLConfig glConfig) { std::map<int,int>::iterator it; for (it = fields.begin(); it != fields.end(); it++) { it->second = EGL_NONE; glSupport->getGLConfigAttrib(glConfig, it->first, &it->second); } } bool operator>(GLConfigAttribs& alternative) { // Caveats are best avoided, but might be needed for anti-aliasing if (fields[EGL_CONFIG_CAVEAT] != alternative.fields[EGL_CONFIG_CAVEAT]) { if (fields[EGL_CONFIG_CAVEAT] == EGL_SLOW_CONFIG) { return false; } if (fields.find(EGL_SAMPLES) != fields.end() && fields[EGL_SAMPLES] < alternative.fields[EGL_SAMPLES]) { return false; } } std::map<int,int>::iterator it; for (it = fields.begin(); it != fields.end(); it++) { if (it->first != EGL_CONFIG_CAVEAT && fields[it->first] > alternative.fields[it->first]) { return true; } } return false; } std::map<int,int> fields; }; ::EGLConfig EGLSupport::selectGLConfig(const int* minAttribs, const int *maxAttribs) { EGLConfig *glConfigs; EGLConfig glConfig = 0; int config, nConfigs = 0; glConfigs = chooseGLConfig(minAttribs, &nConfigs); if (!nConfigs) { glConfigs = getConfigs(&nConfigs); } if (!nConfigs) { return 0; } glConfig = glConfigs[0]; if (maxAttribs) { GLConfigAttribs maximum(maxAttribs); GLConfigAttribs best(maxAttribs); GLConfigAttribs candidate(maxAttribs); best.load(this, glConfig); for (config = 1; config < nConfigs; config++) { candidate.load(this, glConfigs[config]); if (candidate > maximum) { continue; } if (candidate > best) { glConfig = glConfigs[config]; best.load(this, glConfig); } } } free(glConfigs); return glConfig; } void EGLSupport::switchMode(void) { return switchMode(mOriginalMode.width, mOriginalMode.height, mOriginalMode.refreshRate); } ::EGLContext EGLSupport::createNewContext(EGLDisplay eglDisplay, ::EGLConfig glconfig, ::EGLContext shareList) const { EGLint contextAttrs[] = { EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 2, EGL_NONE, EGL_NONE, EGL_NONE }; if(mContextProfile != CONTEXT_ES) { if (!eglBindAPI(EGL_OPENGL_API)) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Could not bind GL API"); } EGL_CHECK_ERROR contextAttrs[1] = 4; contextAttrs[3] = 6; #ifdef EGL_VERSION_1_5 contextAttrs[4] = EGL_CONTEXT_OPENGL_PROFILE_MASK; contextAttrs[5] = EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT; if(mContextProfile == CONTEXT_COMPATIBILITY) { contextAttrs[1] = 3; // MESA 20.2.6 always gives us core if we request 4.x contextAttrs[3] = 0; contextAttrs[5] = EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT; } #endif } if(!hasEGL15) { contextAttrs[2] = EGL_NONE; // skips following attributes contextAttrs[3] = 0; } ::EGLContext context = (::EGLContext)0; // find maximal supported context version while(!context && (contextAttrs[1] >= 1)) { context = eglCreateContext(eglDisplay, glconfig, shareList, contextAttrs); EGL_CHECK_ERROR contextAttrs[1] -= contextAttrs[3] == 0; // only decrement if minor == 0 if(hasEGL15) contextAttrs[3] = (contextAttrs[3] - 1 + 7) % 7; // decrement: -1 -> 6 } if (!context) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to create EGL context"); return 0; } return context; } void EGLSupport::start() { LogManager::getSingleton().logMessage( "******************************\n" "*** Starting EGL Subsystem ***\n" "******************************"); initialiseExtensions(); } void EGLSupport::stop() { eglTerminate(mGLDisplay); EGL_CHECK_ERROR } void EGLSupport::initialiseExtensions() { assert (mGLDisplay); const char* propStr = eglQueryString(mGLDisplay, EGL_VENDOR); LogManager::getSingleton().stream() << "EGL_VENDOR = " << propStr; propStr = eglQueryString(mGLDisplay, EGL_VERSION); LogManager::getSingleton().stream() << "EGL_VERSION = " << propStr; hasEGL15 = String(propStr).find("1.5") != String::npos; StringStream ext; // client extensions propStr = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS); if(propStr) // NULL = failure case ext << propStr << " "; // display extension propStr = eglQueryString(mGLDisplay, EGL_EXTENSIONS); ext << propStr; LogManager::getSingleton().stream() << "EGL_EXTENSIONS = " << ext.str(); String instr; while(ext >> instr) { extensionList.insert(instr); } } void EGLSupport::setGLDisplay( EGLDisplay val ) { mGLDisplay = val; } GLPBuffer* EGLSupport::createPBuffer( PixelComponentType format, size_t width, size_t height ) { #if OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN return nullptr; #else return new EGLPBuffer(this, format, width, height); #endif } } <commit_msg>GLSupport: EGL - fix restarting thread to GLES<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com> Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreException.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" #include "OgreRoot.h" #include "OgreRenderSystem.h" #include "OgreEGLSupport.h" #include "OgreEGLWindow.h" #if OGRE_PLATFORM != OGRE_PLATFORM_EMSCRIPTEN #include "OgreEGLRenderTexture.h" #endif #ifndef EGL_VERSION_1_5 #define EGL_CONTEXT_MAJOR_VERSION EGL_CONTEXT_CLIENT_VERSION #define EGL_CONTEXT_MINOR_VERSION EGL_NONE #endif #include <EGL/eglext.h> namespace Ogre { EGLSupport::EGLSupport(int profile) : GLNativeSupport(profile), mGLDisplay(0), mNativeDisplay(EGL_DEFAULT_DISPLAY), hasEGL15(false) { } EGLDisplay EGLSupport::getGLDisplay(void) { #if defined(EGL_VERSION_1_5) && OGRE_PLATFORM != OGRE_PLATFORM_ANDROID static auto eglQueryDevicesEXT = (PFNEGLQUERYDEVICESEXTPROC)eglGetProcAddress("eglQueryDevicesEXT"); static auto eglQueryDeviceStringEXT = (PFNEGLQUERYDEVICESTRINGEXTPROC)eglGetProcAddress("eglQueryDeviceStringEXT"); if(eglQueryDevicesEXT && mNativeDisplay == EGL_DEFAULT_DISPLAY) { int numDevices; eglQueryDevicesEXT(0, NULL, &numDevices); EGL_CHECK_ERROR std::vector<EGLDeviceEXT> devices(numDevices); eglQueryDevicesEXT(numDevices, devices.data(), &numDevices); EGLAttrib attribs[] = {EGL_NONE}; for(auto dev : devices) { EGLDisplay display = eglGetPlatformDisplay(EGL_PLATFORM_DEVICE_EXT, dev, attribs); EGL_CHECK_ERROR if(display != EGL_NO_DISPLAY && !mGLDisplay) { mGLDisplay = display; const char* exts = eglQueryDeviceStringEXT(dev, EGL_EXTENSIONS); LogManager::getSingleton().stream() << "EGL: using default display. Device extensions: " << exts; break; } } } else #endif { mGLDisplay = eglGetDisplay(mNativeDisplay); EGL_CHECK_ERROR } if(mGLDisplay == EGL_NO_DISPLAY) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn`t get EGLDisplay"); } if (eglInitialize(mGLDisplay, &mEGLMajor, &mEGLMinor) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Couldn`t initialize EGLDisplay ", "EGLSupport::getGLDisplay"); } EGL_CHECK_ERROR return mGLDisplay; } EGLConfig* EGLSupport::chooseGLConfig(const EGLint *attribList, EGLint *nElements) { EGLConfig *configs; if (eglChooseConfig(mGLDisplay, attribList, NULL, 0, nElements) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config"); *nElements = 0; return 0; } EGL_CHECK_ERROR configs = (EGLConfig*) malloc(*nElements * sizeof(EGLConfig)); if (eglChooseConfig(mGLDisplay, attribList, configs, *nElements, nElements) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config"); *nElements = 0; free(configs); return 0; } EGL_CHECK_ERROR return configs; } EGLConfig* EGLSupport::getConfigs(EGLint *nElements) { EGLConfig *configs; if (eglGetConfigs(mGLDisplay, NULL, 0, nElements) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config"); *nElements = 0; return 0; } EGL_CHECK_ERROR configs = (EGLConfig*) malloc(*nElements * sizeof(EGLConfig)); if (eglGetConfigs(mGLDisplay, configs, *nElements, nElements) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to choose config"); *nElements = 0; free(configs); return 0; } EGL_CHECK_ERROR return configs; } EGLBoolean EGLSupport::getGLConfigAttrib(EGLConfig glConfig, EGLint attribute, EGLint *value) { EGLBoolean status; status = eglGetConfigAttrib(mGLDisplay, glConfig, attribute, value); EGL_CHECK_ERROR return status; } void* EGLSupport::getProcAddress(const char* name) const { return (void*)eglGetProcAddress(name); } ::EGLConfig EGLSupport::getGLConfigFromContext(::EGLContext context) { ::EGLConfig glConfig; EGLint id = 0; ::EGLConfig *configs; EGLint numConfigs; if (eglQueryContext(mGLDisplay, context, EGL_CONFIG_ID, &id) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to get config from context"); return 0; } EGL_CHECK_ERROR configs = getConfigs(&numConfigs); glConfig = configs[id]; free(configs); return glConfig; } ::EGLConfig EGLSupport::getGLConfigFromDrawable(::EGLSurface drawable, unsigned int *w, unsigned int *h) { ::EGLConfig glConfig; EGLint id = 0; ::EGLConfig *configs; EGLint numConfigs; if (eglQuerySurface(mGLDisplay, drawable, EGL_CONFIG_ID, &id) == EGL_FALSE) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Fail to get config from drawable"); return 0; } EGL_CHECK_ERROR eglQuerySurface(mGLDisplay, drawable, EGL_WIDTH, (EGLint *) w); EGL_CHECK_ERROR eglQuerySurface(mGLDisplay, drawable, EGL_HEIGHT, (EGLint *) h); EGL_CHECK_ERROR configs = getConfigs(&numConfigs); glConfig = configs[id]; free(configs); return glConfig; } //------------------------------------------------------------------------ // A helper class for the implementation of selectFBConfig //------------------------------------------------------------------------ class GLConfigAttribs { public: GLConfigAttribs(const int* attribs) { fields[EGL_CONFIG_CAVEAT] = EGL_NONE; for (int i = 0; attribs[2*i] != EGL_NONE; i++) { fields[attribs[2*i]] = attribs[2*i+1]; } } void load(EGLSupport* const glSupport, EGLConfig glConfig) { std::map<int,int>::iterator it; for (it = fields.begin(); it != fields.end(); it++) { it->second = EGL_NONE; glSupport->getGLConfigAttrib(glConfig, it->first, &it->second); } } bool operator>(GLConfigAttribs& alternative) { // Caveats are best avoided, but might be needed for anti-aliasing if (fields[EGL_CONFIG_CAVEAT] != alternative.fields[EGL_CONFIG_CAVEAT]) { if (fields[EGL_CONFIG_CAVEAT] == EGL_SLOW_CONFIG) { return false; } if (fields.find(EGL_SAMPLES) != fields.end() && fields[EGL_SAMPLES] < alternative.fields[EGL_SAMPLES]) { return false; } } std::map<int,int>::iterator it; for (it = fields.begin(); it != fields.end(); it++) { if (it->first != EGL_CONFIG_CAVEAT && fields[it->first] > alternative.fields[it->first]) { return true; } } return false; } std::map<int,int> fields; }; ::EGLConfig EGLSupport::selectGLConfig(const int* minAttribs, const int *maxAttribs) { EGLConfig *glConfigs; EGLConfig glConfig = 0; int config, nConfigs = 0; glConfigs = chooseGLConfig(minAttribs, &nConfigs); if (!nConfigs) { glConfigs = getConfigs(&nConfigs); } if (!nConfigs) { return 0; } glConfig = glConfigs[0]; if (maxAttribs) { GLConfigAttribs maximum(maxAttribs); GLConfigAttribs best(maxAttribs); GLConfigAttribs candidate(maxAttribs); best.load(this, glConfig); for (config = 1; config < nConfigs; config++) { candidate.load(this, glConfigs[config]); if (candidate > maximum) { continue; } if (candidate > best) { glConfig = glConfigs[config]; best.load(this, glConfig); } } } free(glConfigs); return glConfig; } void EGLSupport::switchMode(void) { return switchMode(mOriginalMode.width, mOriginalMode.height, mOriginalMode.refreshRate); } ::EGLContext EGLSupport::createNewContext(EGLDisplay eglDisplay, ::EGLConfig glconfig, ::EGLContext shareList) const { EGLint contextAttrs[] = { EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 2, EGL_NONE, EGL_NONE, EGL_NONE }; if (!eglBindAPI(mContextProfile == CONTEXT_ES ? EGL_OPENGL_ES_API : EGL_OPENGL_API)) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "eglBindAPI failed"); } if(mContextProfile != CONTEXT_ES) { contextAttrs[1] = 4; contextAttrs[3] = 6; #ifdef EGL_VERSION_1_5 contextAttrs[4] = EGL_CONTEXT_OPENGL_PROFILE_MASK; contextAttrs[5] = EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT; if(mContextProfile == CONTEXT_COMPATIBILITY) { contextAttrs[1] = 3; // MESA 20.2.6 always gives us core if we request 4.x contextAttrs[3] = 0; contextAttrs[5] = EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT; } #endif } if(!hasEGL15) { contextAttrs[2] = EGL_NONE; // skips following attributes contextAttrs[3] = 0; } ::EGLContext context = (::EGLContext)0; // find maximal supported context version while(!context && (contextAttrs[1] >= 1)) { context = eglCreateContext(eglDisplay, glconfig, shareList, contextAttrs); EGL_CHECK_ERROR contextAttrs[1] -= contextAttrs[3] == 0; // only decrement if minor == 0 if(hasEGL15) contextAttrs[3] = (contextAttrs[3] - 1 + 7) % 7; // decrement: -1 -> 6 } if (!context) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Failed to create EGL context"); return 0; } return context; } void EGLSupport::start() { LogManager::getSingleton().logMessage( "******************************\n" "*** Starting EGL Subsystem ***\n" "******************************"); initialiseExtensions(); } void EGLSupport::stop() { eglTerminate(mGLDisplay); EGL_CHECK_ERROR } void EGLSupport::initialiseExtensions() { assert (mGLDisplay); const char* propStr = eglQueryString(mGLDisplay, EGL_VENDOR); LogManager::getSingleton().stream() << "EGL_VENDOR = " << propStr; propStr = eglQueryString(mGLDisplay, EGL_VERSION); LogManager::getSingleton().stream() << "EGL_VERSION = " << propStr; hasEGL15 = String(propStr).find("1.5") != String::npos; StringStream ext; // client extensions propStr = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS); if(propStr) // NULL = failure case ext << propStr << " "; // display extension propStr = eglQueryString(mGLDisplay, EGL_EXTENSIONS); ext << propStr; LogManager::getSingleton().stream() << "EGL_EXTENSIONS = " << ext.str(); String instr; while(ext >> instr) { extensionList.insert(instr); } } void EGLSupport::setGLDisplay( EGLDisplay val ) { mGLDisplay = val; } GLPBuffer* EGLSupport::createPBuffer( PixelComponentType format, size_t width, size_t height ) { #if OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN return nullptr; #else return new EGLPBuffer(this, format, width, height); #endif } } <|endoftext|>
<commit_before>#pragma once #include "VectorIndexer.hpp" #include "Mesh.h" #include "ObjectID.hpp" #include <tuple> #include <assert.h> #include "VBSortedMeshPool.h" namespace Rendering { namespace Manager { class MeshManager final { public: MeshManager() = default; DISALLOW_ASSIGN_COPY(MeshManager); public: template<class Pool> Geometry::Mesh& Acquire(Core::ObjectID objID, Pool& meshPool) { auto mesh = Geometry::Mesh(objID); return meshPool.Add(objID.Literal(), mesh); } template<class Pool> void Delete(Core::ObjectID objID, Pool& meshPool) { meshPool.Delete(objID.Literal()); } template<class Pool> bool Has(Core::ObjectID objID, Pool& meshPool) const { return meshPool.Has(objID.Literal()); } template<class Pool> Geometry::Mesh* Find(Core::ObjectID id, Pool& meshPool) { return meshPool.Find(id.Literal()); } Geometry::Mesh& Acquire(Core::ObjectID objID); void Delete(Core::ObjectID objID); bool Has(Core::ObjectID objID) const; Geometry::Mesh* Find(Core::ObjectID id); void CheckDirty(const Core::TransformPool& tfPool); void ComputeWorldSize(Math::Vector3& refWorldMin, Math::Vector3& refWorldMax, const Core::TransformPool& tfPool) const; void UpdateTransformCB(Device::DirectX& dx, const Core::TransformPool& tfPool); void ClearDirty() { _dirtyMeshes.clear(); } template <class FromPool, class ToPool> bool ChangeTrait(Core::ObjectID id, FromPool& fromPool, ToPool& toPool) { uint literlID = id.Literal(); assert(fromPool.Has(literlID)); assert(toPool.Has(literlID) == false); toPool.Add(literlID, *fromPool.Find(literlID)); fromPool.Delete(literlID); } GET_ACCESSOR(TransparentMeshPool, Geometry::TransparentMeshPool&, _transparentMeshPool); GET_ACCESSOR(OpaqueMeshPool, Geometry::OpaqueMeshPool&, _opaqueMeshPool); GET_ACCESSOR(AlphaBlendMeshPool, Geometry::OpaqueMeshPool&, _alphaBlendMeshPool); GET_CONST_ACCESSOR(TransparentMeshPool, const Geometry::TransparentMeshPool&, _transparentMeshPool); GET_CONST_ACCESSOR(OpaqueMeshPool, const Geometry::OpaqueMeshPool&, _opaqueMeshPool); GET_CONST_ACCESSOR(AlphaBlendMeshPool, const Geometry::OpaqueMeshPool&, _alphaBlendMeshPool); GET_CONST_ACCESSOR(HasDirtyMeshes, bool, _dirtyMeshes.empty() == false); private: Geometry::TransparentMeshPool _transparentMeshPool; Geometry::OpaqueMeshPool _opaqueMeshPool; Geometry::OpaqueMeshPool _alphaBlendMeshPool; std::vector<Geometry::Mesh*> _dirtyMeshes; }; } }<commit_msg>MeshManager -> Acquire -> Add로 변경, 일부 코드 정리<commit_after>#pragma once #include "VectorIndexer.hpp" #include "Mesh.h" #include "ObjectID.hpp" #include <tuple> #include <assert.h> #include "VBSortedMeshes.hpp" namespace Rendering { namespace Manager { class MeshManager final { public: MeshManager() = default; DISALLOW_ASSIGN_COPY(MeshManager); public: Geometry::Mesh& Add(Geometry::Mesh& mesh, Geometry::TransparentMeshPool& meshPool) { assert(mesh.GetVBKey() != 0); //Error, mesh does not init yet. return meshPool.Add(mesh.GetObjectID().Literal(), mesh); } Geometry::Mesh& Add(Geometry::Mesh& mesh, Geometry::OpaqueMeshPool& meshPool) // or AlphaBlendMeshPool { assert(mesh.GetVBKey() != 0); //Error, mesh does not init yet. return meshPool.Add(mesh.GetObjectID(), mesh.GetVBKey(), mesh); } template<class Pool> void Delete(Core::ObjectID objID, Pool& meshPool) { meshPool.Delete(objID.Literal()); } template<class Pool> bool Has(Core::ObjectID objID, Pool& meshPool) const { return meshPool.Has(objID.Literal()); } template<class Pool> Geometry::Mesh* Find(Core::ObjectID id, Pool& meshPool) { return meshPool.Find(id.Literal()); } template<class Pool> const Geometry::Mesh* Find(Core::ObjectID id, Pool& meshPool) const { return meshPool.Find(id.Literal()); } Geometry::Mesh& Add(Geometry::Mesh& mesh); void Delete(Core::ObjectID objID); bool Has(Core::ObjectID objID) const; Geometry::Mesh* Find(Core::ObjectID id); void CheckDirty(const Core::TransformPool& tfPool); void ComputeWorldSize(Math::Vector3& refWorldMin, Math::Vector3& refWorldMax, const Core::TransformPool& tfPool) const; void UpdateTransformCB(Device::DirectX& dx, const Core::TransformPool& tfPool); void ClearDirty() { _dirtyMeshes.clear(); } bool ChangeTrait(Core::ObjectID id, Geometry::OpaqueMeshPool& fromPool, Geometry::TransparentMeshPool& toPool) { uint literlID = id.Literal(); assert(fromPool.Has(literlID)); assert(toPool.Has(literlID) == false); toPool.Add(literlID, *fromPool.Find(literlID)); fromPool.Delete(literlID); } bool ChangeTrait(Core::ObjectID id, Geometry::TransparentMeshPool& fromPool, Geometry::OpaqueMeshPool& toPool) // or AlphaBlend { uint literlID = id.Literal(); assert(fromPool.Has(literlID)); assert(toPool.Has(literlID) == false); Mesh* mesh = fromPool.Find(literlID); toPool.Add(literlID, mesh->GetVBKey(), *mesh); fromPool.Delete(literlID); } GET_ACCESSOR(TransparentMeshPool, Geometry::TransparentMeshPool&, _transparentMeshPool); GET_ACCESSOR(OpaqueMeshPool, Geometry::OpaqueMeshPool&, _opaqueMeshPool); GET_ACCESSOR(AlphaBlendMeshPool, Geometry::AlphaBlendMeshPool&, _alphaBlendMeshPool); GET_CONST_ACCESSOR(TransparentMeshPool, const Geometry::TransparentMeshPool&, _transparentMeshPool); GET_CONST_ACCESSOR(OpaqueMeshPool, const Geometry::OpaqueMeshPool&, _opaqueMeshPool); GET_CONST_ACCESSOR(AlphaBlendMeshPool, const Geometry::AlphaBlendMeshPool&, _alphaBlendMeshPool); GET_CONST_ACCESSOR(HasDirtyMeshes, bool, _dirtyMeshes.empty() == false); private: Geometry::TransparentMeshPool _transparentMeshPool; Geometry::OpaqueMeshPool _opaqueMeshPool; Geometry::AlphaBlendMeshPool _alphaBlendMeshPool; std::vector<Geometry::Mesh*> _dirtyMeshes; }; } } <|endoftext|>
<commit_before>/* * This file is part of Poedit (http://www.poedit.net) * * Copyright (C) 2004-2006 Vaclav Slavik * * 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. * * $Id$ * * Art provider classes * */ #include <wx/log.h> #include <wx/stdpaths.h> #include "icons.h" #include "edapp.h" #ifdef __UNIX__ #include "icons/appicon/poedit.xpm" #endif #ifdef __WXGTK20__ // translates poedit item id or Tango stock item id to "legacy" GNOME id: static wxString GetGnomeStockId(const wxString& id) { #define MAP(poedit, gnome) if ( id == _T(poedit) ) return _T(gnome) MAP("document-open", "gtk-open"); MAP("document-save", "gtk-save"); MAP("view-fullscreen", "stock_fullscreen"); MAP("help-browser", "gtk-help"); MAP("document-new", "gtk-new"); MAP("document-properties", "stock_edit"); MAP("edit-delete", "gtk-delete"); #undef MAP return wxEmptyString; // no match found } #endif // __WXGTK20__ wxBitmap PoeditArtProvider::CreateBitmap(const wxArtID& id, const wxArtClient& client, const wxSize& size) { wxLogTrace(_T("poedit.icons"), _T("getting icon '%s'"), id.c_str()); #ifdef __UNIX__ if (id == _T("poedit")) return wxBitmap(appicon_xpm); #endif #ifdef __WXGTK20__ // try legacy GNOME icons: wxString gnomeId = GetGnomeStockId(id); if ( !gnomeId.empty() ) { wxLogTrace(_T("poedit.icons"), _T("-> legacy '%s'"), gnomeId.c_str()); wxBitmap gbmp(wxArtProvider::GetBitmap(gnomeId, client, size)); if ( gbmp.Ok() ) return gbmp; } #endif // __WXGTK20__ wxString iconsdir = #ifdef __WXMAC__ wxStandardPaths::Get().GetResourcesDir() + _T("/icons"); #else wxGetApp().GetAppPath() + _T("/share/poedit/icons"); #endif if ( !wxDirExists(iconsdir) ) { wxLogTrace(_T("poedit.icons"), _T("icons dir %s not found"), iconsdir.c_str()); return wxNullBitmap; } wxString icon; icon.Printf(_T("%s/%s.png"), iconsdir.c_str(), id.c_str()); if ( !wxFileExists(icon) ) return wxNullBitmap; wxLogTrace(_T("poedit.icons"), _T("loading from %s"), icon.c_str()); wxBitmap bmp; bmp.LoadFile(icon, wxBITMAP_TYPE_ANY); return bmp; } <commit_msg>clarifying comments<commit_after>/* * This file is part of Poedit (http://www.poedit.net) * * Copyright (C) 2004-2008 Vaclav Slavik * * 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. * * $Id$ * * Art provider classes * */ #include <wx/log.h> #include <wx/stdpaths.h> #include "icons.h" #include "edapp.h" #ifdef __UNIX__ #include "icons/appicon/poedit.xpm" #endif #ifdef __WXGTK20__ // translates poedit item id or Tango stock item id to "legacy" GNOME id: static wxString GetGnomeStockId(const wxString& id) { #define MAP(poedit, gnome) if ( id == _T(poedit) ) return _T(gnome) MAP("document-open", "gtk-open"); MAP("document-save", "gtk-save"); MAP("view-fullscreen", "stock_fullscreen"); MAP("help-browser", "gtk-help"); MAP("document-new", "gtk-new"); MAP("document-properties", "stock_edit"); MAP("edit-delete", "gtk-delete"); #undef MAP return wxEmptyString; // no match found } #endif // __WXGTK20__ wxBitmap PoeditArtProvider::CreateBitmap(const wxArtID& id, const wxArtClient& client, const wxSize& size) { // Note: On Unix, this code is only called as last resolt, if standard // theme provider (that uses current icon theme and files from // /usr/share/icons/<theme>) didn't find any matching icon. wxLogTrace(_T("poedit.icons"), _T("getting icon '%s'"), id.c_str()); #ifdef __UNIX__ if (id == _T("poedit")) return wxBitmap(appicon_xpm); #endif #ifdef __WXGTK20__ // try legacy GNOME icons from standard theme: wxString gnomeId = GetGnomeStockId(id); if ( !gnomeId.empty() ) { wxLogTrace(_T("poedit.icons"), _T("-> legacy '%s'"), gnomeId.c_str()); wxBitmap gbmp(wxArtProvider::GetBitmap(gnomeId, client, size)); if ( gbmp.Ok() ) return gbmp; } #endif // __WXGTK20__ wxString iconsdir = #ifdef __WXMAC__ wxStandardPaths::Get().GetResourcesDir() + _T("/icons"); #else wxGetApp().GetAppPath() + _T("/share/poedit/icons"); #endif if ( !wxDirExists(iconsdir) ) { wxLogTrace(_T("poedit.icons"), _T("icons dir %s not found"), iconsdir.c_str()); return wxNullBitmap; } wxString icon; icon.Printf(_T("%s/%s.png"), iconsdir.c_str(), id.c_str()); if ( !wxFileExists(icon) ) return wxNullBitmap; wxLogTrace(_T("poedit.icons"), _T("loading from %s"), icon.c_str()); wxBitmap bmp; bmp.LoadFile(icon, wxBITMAP_TYPE_ANY); return bmp; } <|endoftext|>
<commit_before> #include "netbase.h" #include "masternodeconfig.h" #include "util.h" #include "chainparams.h" #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> CMasternodeConfig masternodeConfig; void CMasternodeConfig::add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex) { CMasternodeEntry cme(alias, ip, privKey, txHash, outputIndex); entries.push_back(cme); } bool CMasternodeConfig::read(std::string& strErr) { int linenumber = 1; boost::filesystem::path pathMasternodeConfigFile = GetMasternodeConfigFile(); boost::filesystem::ifstream streamConfig(pathMasternodeConfigFile); if (!streamConfig.good()) { FILE* configFile = fopen(pathMasternodeConfigFile.string().c_str(), "a"); if (configFile != NULL) { std::string strHeader = "# Masternode config file\n" "# Format: alias IP:port masternodeprivkey collateral_output_txid collateral_output_index\n" "# Example: mn1 127.0.0.2:19999 93HaYBVUCYjEMeeH1Y4sBGLALQZE1Yc1K64xiqgX37tGBDQL8Xg 2bcd3c84c84f87eaa86e4e56834c92927a07f9e18718810b92e0d0324456a67c 0\n"; fwrite(strHeader.c_str(), std::strlen(strHeader.c_str()), 1, configFile); fclose(configFile); } return true; // Nothing to read, so just return } for(std::string line; std::getline(streamConfig, line); linenumber++) { if(line.empty()) continue; std::istringstream iss(line); std::string comment, alias, ip, privKey, txHash, outputIndex; if (iss >> comment) { if(comment.at(0) == '#') continue; iss.str(line); iss.clear(); } if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) { iss.str(line); iss.clear(); if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) { strErr = _("Could not parse masternode.conf") + "\n" + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\""; streamConfig.close(); return false; } } int port = 0; std::string hostname = ""; SplitHostPort(ip, port, hostname); if(port == 0 || hostname == "") { strErr = _("Failed to parse host:port string") + "\n"+ strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\""; streamConfig.close(); return false; } int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort(); if(Params().NetworkIDString() == CBaseChainParams::MAIN) { if(port != mainnetDefaultPort) { strErr = _("Invalid port detected in masternode.conf") + "\n" + strprintf(_("Port: %d"), port) + "\n" + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" + strprintf(_("(must be %d for mainnet)"), mainnetDefaultPort); streamConfig.close(); return false; } } else if(port == mainnetDefaultPort) { strErr = _("Invalid port detected in masternode.conf") + "\n" + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" + strprintf(_("(%d could be used only on mainnet)"), mainnetDefaultPort); streamConfig.close(); return false; } add(alias, ip, privKey, txHash, outputIndex); } streamConfig.close(); return true; } <commit_msg>change to trc port<commit_after> #include "netbase.h" #include "masternodeconfig.h" #include "util.h" #include "chainparams.h" #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> CMasternodeConfig masternodeConfig; void CMasternodeConfig::add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex) { CMasternodeEntry cme(alias, ip, privKey, txHash, outputIndex); entries.push_back(cme); } bool CMasternodeConfig::read(std::string& strErr) { int linenumber = 1; boost::filesystem::path pathMasternodeConfigFile = GetMasternodeConfigFile(); boost::filesystem::ifstream streamConfig(pathMasternodeConfigFile); if (!streamConfig.good()) { FILE* configFile = fopen(pathMasternodeConfigFile.string().c_str(), "a"); if (configFile != NULL) { std::string strHeader = "# Masternode config file\n" "# Format: alias IP:port masternodeprivkey collateral_output_txid collateral_output_index\n" "# Example: mn1 127.0.0.2:13333 93HaYBVUCYjEMeeH1Y4sBGLALQZE1Yc1K64xiqgX37tGBDQL8Xg 2bcd3c84c84f87eaa86e4e56834c92927a07f9e18718810b92e0d0324456a67c 0\n"; fwrite(strHeader.c_str(), std::strlen(strHeader.c_str()), 1, configFile); fclose(configFile); } return true; // Nothing to read, so just return } for(std::string line; std::getline(streamConfig, line); linenumber++) { if(line.empty()) continue; std::istringstream iss(line); std::string comment, alias, ip, privKey, txHash, outputIndex; if (iss >> comment) { if(comment.at(0) == '#') continue; iss.str(line); iss.clear(); } if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) { iss.str(line); iss.clear(); if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) { strErr = _("Could not parse masternode.conf") + "\n" + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\""; streamConfig.close(); return false; } } int port = 0; std::string hostname = ""; SplitHostPort(ip, port, hostname); if(port == 0 || hostname == "") { strErr = _("Failed to parse host:port string") + "\n"+ strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\""; streamConfig.close(); return false; } int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort(); if(Params().NetworkIDString() == CBaseChainParams::MAIN) { if(port != mainnetDefaultPort) { strErr = _("Invalid port detected in masternode.conf") + "\n" + strprintf(_("Port: %d"), port) + "\n" + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" + strprintf(_("(must be %d for mainnet)"), mainnetDefaultPort); streamConfig.close(); return false; } } else if(port == mainnetDefaultPort) { strErr = _("Invalid port detected in masternode.conf") + "\n" + strprintf(_("Line: %d"), linenumber) + "\n\"" + line + "\"" + "\n" + strprintf(_("(%d could be used only on mainnet)"), mainnetDefaultPort); streamConfig.close(); return false; } add(alias, ip, privKey, txHash, outputIndex); } streamConfig.close(); return true; } <|endoftext|>
<commit_before>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "place.h" #include <cmath> #include <iostream> #include <limits> #include <list> #include <map> #include <ostream> #include <queue> #include <set> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <vector> #include <random> #include <algorithm> #include "arch_place.h" #include "log.h" NEXTPNR_NAMESPACE_BEGIN void place_design(Design *design) { std::set<IdString> types_used; std::set<IdString>::iterator not_found, element; std::set<BelType> used_bels; log_info("Placing..\n"); // Initial constraints placer for (auto cell_entry : design->cells) { CellInfo *cell = cell_entry.second; auto loc = cell->attrs.find("BEL"); if (loc != cell->attrs.end()) { std::string loc_name = loc->second; BelId bel = design->chip.getBelByName(IdString(loc_name)); if (bel == BelId()) { log_error("No Bel named \'%s\' located for " "this chip (processing BEL attribute on \'%s\')\n", loc_name.c_str(), cell->name.c_str()); } BelType bel_type = design->chip.getBelType(bel); if (bel_type != belTypeFromId(cell->type)) { log_error("Bel \'%s\' of type \'%s\' does not match cell " "\'%s\' of type \'%s\'", loc_name.c_str(), belTypeToId(bel_type).c_str(), cell->name.c_str(), cell->type.c_str()); } cell->bel = bel; design->chip.bindBel(bel, cell->name); } } for (auto cell_entry : design->cells) { CellInfo *cell = cell_entry.second; // Ignore already placed cells if (cell->bel != BelId()) continue; BelType bel_type; element = types_used.find(cell->type); if (element != types_used.end()) { continue; } bel_type = belTypeFromId(cell->type); if (bel_type == BelType()) { log_error("No Bel of type \'%s\' defined for " "this chip\n", cell->type.c_str()); } types_used.insert(cell->type); } for (auto bel_type_name : types_used) { auto blist = design->chip.getBels(); BelType bel_type = belTypeFromId(bel_type_name); auto bi = blist.begin(); for (auto cell_entry : design->cells) { CellInfo *cell = cell_entry.second; // Ignore already placed cells if (cell->bel != BelId()) continue; // Only place one type of Bel at a time if (cell->type != bel_type_name) continue; while ((bi != blist.end()) && ((design->chip.getBelType(*bi) != bel_type || !design->chip.checkBelAvail(*bi)) || !isValidBelForCell(design, cell, *bi))) bi++; if (bi == blist.end()) log_error("Too many \'%s\' used in design\n", cell->type.c_str()); cell->bel = *bi++; design->chip.bindBel(cell->bel, cell->name); // Back annotate location cell->attrs["BEL"] = design->chip.getBelName(cell->bel).str(); } } } static void place_cell(Design *design, CellInfo *cell, std::mt19937 &rnd) { std::uniform_real_distribution<float> random_wirelength(0.0, 30.0); float best_distance = std::numeric_limits<float>::infinity(); BelId best_bel = BelId(); Chip &chip = design->chip; if(cell->bel != BelId()) { chip.unbindBel(cell->bel); cell->bel = BelId(); } BelType targetType = belTypeFromId(cell->type); for (auto bel : chip.getBels()) { if (chip.getBelType(bel) == targetType && chip.checkBelAvail(bel) && isValidBelForCell(design, cell, bel)) { float distance = 0; float belx, bely; bool has_conns = false; chip.estimatePosition(bel, belx, bely); for (auto port : cell->ports) { const PortInfo &pi = port.second; if (pi.net != nullptr) { CellInfo *drv = pi.net->driver.cell; float pin_wirelength = std::numeric_limits<float>::infinity(); if (drv != nullptr && drv->bel != BelId()) { float otherx, othery; chip.estimatePosition(drv->bel, otherx, othery); float local_wl = std::abs(belx - otherx) + std::abs(bely - othery); if (local_wl < pin_wirelength) pin_wirelength = local_wl; has_conns = true; } if (pi.net->users.size() < 5) { for (auto user : pi.net->users) { CellInfo *uc = user.cell; if (uc != nullptr && uc->bel != BelId()) { float otherx, othery; chip.estimatePosition(uc->bel, otherx, othery); float local_wl = std::abs(belx - otherx) + std::abs(bely - othery); if (local_wl < pin_wirelength) pin_wirelength = local_wl; has_conns = true; } } } if (!std::isinf(pin_wirelength)) distance += pin_wirelength; } } if (!has_conns) distance = random_wirelength(rnd); if (distance <= best_distance) { best_distance = distance; best_bel = bel; } } } if (best_bel == BelId()) { log_error("failed to place cell '%s' of type '%s'\n", cell->name.c_str(), cell->type.c_str()); } cell->bel = best_bel; chip.bindBel(cell->bel, cell->name); // Back annotate location cell->attrs["BEL"] = chip.getBelName(cell->bel).str(); } void place_design_heuristic(Design *design) { size_t total_cells = design->cells.size(), placed_cells = 0; std::queue<CellInfo *> visit_cells; // Initial constraints placer for (auto cell_entry : design->cells) { CellInfo *cell = cell_entry.second; auto loc = cell->attrs.find("BEL"); if (loc != cell->attrs.end()) { std::string loc_name = loc->second; BelId bel = design->chip.getBelByName(IdString(loc_name)); if (bel == BelId()) { log_error("No Bel named \'%s\' located for " "this chip (processing BEL attribute on \'%s\')\n", loc_name.c_str(), cell->name.c_str()); } BelType bel_type = design->chip.getBelType(bel); if (bel_type != belTypeFromId(cell->type)) { log_error("Bel \'%s\' of type \'%s\' does not match cell " "\'%s\' of type \'%s\'", loc_name.c_str(), belTypeToId(bel_type).c_str(), cell->name.c_str(), cell->type.c_str()); } cell->bel = bel; design->chip.bindBel(bel, cell->name); placed_cells++; visit_cells.push(cell); } } log_info("place_constraints placed %d\n", placed_cells); std::mt19937 rnd; std::vector<IdString> autoplaced; for (auto cell : design->cells) { CellInfo *ci = cell.second; if (ci->bel == BelId()) { place_cell(design, ci, rnd); autoplaced.push_back(cell.first); placed_cells++; } log_info("placed %d/%d\n", placed_cells, total_cells); } for (int i = 0 ; i < 2; i ++) { int replaced_cells = 0; std::shuffle(autoplaced.begin(), autoplaced.end(), rnd); for (auto cell : autoplaced) { CellInfo *ci = design->cells[cell]; place_cell(design, ci, rnd); replaced_cells++; log_info("replaced %d/%d\n", replaced_cells, autoplaced.size()); } } } NEXTPNR_NAMESPACE_END <commit_msg>Experimenting with more unplacing<commit_after>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 Clifford Wolf <clifford@clifford.at> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "place.h" #include <cmath> #include <iostream> #include <limits> #include <list> #include <map> #include <ostream> #include <queue> #include <set> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <vector> #include <random> #include <algorithm> #include "arch_place.h" #include "log.h" NEXTPNR_NAMESPACE_BEGIN void place_design(Design *design) { std::set<IdString> types_used; std::set<IdString>::iterator not_found, element; std::set<BelType> used_bels; log_info("Placing..\n"); // Initial constraints placer for (auto cell_entry : design->cells) { CellInfo *cell = cell_entry.second; auto loc = cell->attrs.find("BEL"); if (loc != cell->attrs.end()) { std::string loc_name = loc->second; BelId bel = design->chip.getBelByName(IdString(loc_name)); if (bel == BelId()) { log_error("No Bel named \'%s\' located for " "this chip (processing BEL attribute on \'%s\')\n", loc_name.c_str(), cell->name.c_str()); } BelType bel_type = design->chip.getBelType(bel); if (bel_type != belTypeFromId(cell->type)) { log_error("Bel \'%s\' of type \'%s\' does not match cell " "\'%s\' of type \'%s\'", loc_name.c_str(), belTypeToId(bel_type).c_str(), cell->name.c_str(), cell->type.c_str()); } cell->bel = bel; design->chip.bindBel(bel, cell->name); } } for (auto cell_entry : design->cells) { CellInfo *cell = cell_entry.second; // Ignore already placed cells if (cell->bel != BelId()) continue; BelType bel_type; element = types_used.find(cell->type); if (element != types_used.end()) { continue; } bel_type = belTypeFromId(cell->type); if (bel_type == BelType()) { log_error("No Bel of type \'%s\' defined for " "this chip\n", cell->type.c_str()); } types_used.insert(cell->type); } for (auto bel_type_name : types_used) { auto blist = design->chip.getBels(); BelType bel_type = belTypeFromId(bel_type_name); auto bi = blist.begin(); for (auto cell_entry : design->cells) { CellInfo *cell = cell_entry.second; // Ignore already placed cells if (cell->bel != BelId()) continue; // Only place one type of Bel at a time if (cell->type != bel_type_name) continue; while ((bi != blist.end()) && ((design->chip.getBelType(*bi) != bel_type || !design->chip.checkBelAvail(*bi)) || !isValidBelForCell(design, cell, *bi))) bi++; if (bi == blist.end()) log_error("Too many \'%s\' used in design\n", cell->type.c_str()); cell->bel = *bi++; design->chip.bindBel(cell->bel, cell->name); // Back annotate location cell->attrs["BEL"] = design->chip.getBelName(cell->bel).str(); } } } static void place_cell(Design *design, CellInfo *cell, std::mt19937 &rnd) { std::uniform_real_distribution<float> random_wirelength(0.0, 30.0); float best_distance = std::numeric_limits<float>::infinity(); BelId best_bel = BelId(); Chip &chip = design->chip; if(cell->bel != BelId()) { chip.unbindBel(cell->bel); cell->bel = BelId(); } BelType targetType = belTypeFromId(cell->type); for (auto bel : chip.getBels()) { if (chip.getBelType(bel) == targetType && chip.checkBelAvail(bel) && isValidBelForCell(design, cell, bel)) { float distance = 0; float belx, bely; bool has_conns = false; chip.estimatePosition(bel, belx, bely); for (auto port : cell->ports) { const PortInfo &pi = port.second; if (pi.net != nullptr) { CellInfo *drv = pi.net->driver.cell; //float pin_wirelength = std::numeric_limits<float>::infinity(); float pin_wirelength = 0; if (drv != nullptr && drv->bel != BelId()) { float otherx, othery; chip.estimatePosition(drv->bel, otherx, othery); float local_wl = std::abs(belx - otherx) + std::abs(bely - othery); //if (local_wl < pin_wirelength) pin_wirelength += local_wl; has_conns = true; } if (pi.net->users.size() < 5) { for (auto user : pi.net->users) { CellInfo *uc = user.cell; if (uc != nullptr && uc->bel != BelId()) { float otherx, othery; chip.estimatePosition(uc->bel, otherx, othery); float local_wl = std::abs(belx - otherx) + std::abs(bely - othery); //if (local_wl < pin_wirelength) pin_wirelength += local_wl; has_conns = true; } } } if (!std::isinf(pin_wirelength)) distance += pin_wirelength; } } if (!has_conns) distance = random_wirelength(rnd); if (distance <= best_distance) { best_distance = distance; best_bel = bel; } } } if (best_bel == BelId()) { log_error("failed to place cell '%s' of type '%s'\n", cell->name.c_str(), cell->type.c_str()); } cell->bel = best_bel; chip.bindBel(cell->bel, cell->name); // Back annotate location cell->attrs["BEL"] = chip.getBelName(cell->bel).str(); } void place_design_heuristic(Design *design) { size_t total_cells = design->cells.size(), placed_cells = 0; std::queue<CellInfo *> visit_cells; // Initial constraints placer for (auto cell_entry : design->cells) { CellInfo *cell = cell_entry.second; auto loc = cell->attrs.find("BEL"); if (loc != cell->attrs.end()) { std::string loc_name = loc->second; BelId bel = design->chip.getBelByName(IdString(loc_name)); if (bel == BelId()) { log_error("No Bel named \'%s\' located for " "this chip (processing BEL attribute on \'%s\')\n", loc_name.c_str(), cell->name.c_str()); } BelType bel_type = design->chip.getBelType(bel); if (bel_type != belTypeFromId(cell->type)) { log_error("Bel \'%s\' of type \'%s\' does not match cell " "\'%s\' of type \'%s\'", loc_name.c_str(), belTypeToId(bel_type).c_str(), cell->name.c_str(), cell->type.c_str()); } cell->bel = bel; design->chip.bindBel(bel, cell->name); placed_cells++; visit_cells.push(cell); } } log_info("place_constraints placed %d\n", placed_cells); std::mt19937 rnd; std::vector<IdString> autoplaced; for (auto cell : design->cells) { CellInfo *ci = cell.second; if (ci->bel == BelId()) { place_cell(design, ci, rnd); autoplaced.push_back(cell.first); placed_cells++; } log_info("placed %d/%d\n", placed_cells, total_cells); } for (int i = 0 ; i < 5; i ++) { int replaced_cells = 0; for (int j = 0; j < autoplaced.size() / 10; j++) { design->chip.unbindBel(design->cells.at(autoplaced.at(j))->bel); design->cells.at(autoplaced.at(j))->bel = BelId(); } std::shuffle(autoplaced.begin(), autoplaced.end(), rnd); for (auto cell : autoplaced) { CellInfo *ci = design->cells[cell]; place_cell(design, ci, rnd); replaced_cells++; log_info("replaced %d/%d\n", replaced_cells, autoplaced.size()); } } } NEXTPNR_NAMESPACE_END <|endoftext|>
<commit_before><commit_msg>Increased scale for ARM<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2016, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include <climits> #include "third_party/googletest/src/include/gtest/gtest.h" #include "test/codec_factory.h" #include "test/encode_test_driver.h" #include "test/i420_video_source.h" #include "test/util.h" namespace { const int kTestMode = 0; const int kSuperframeSyntax = 1; const int kTileCols = 2; const int kTileRows = 3; typedef std::tr1::tuple<libaom_test::TestMode, int, int, int> SuperframeTestParam; class SuperframeTest : public ::libaom_test::EncoderTest, public ::libaom_test::CodecTestWithParam<SuperframeTestParam> { protected: SuperframeTest() : EncoderTest(GET_PARAM(0)), modified_buf_(NULL), last_sf_pts_(0) {} virtual ~SuperframeTest() {} virtual void SetUp() { InitializeConfig(); const SuperframeTestParam input = GET_PARAM(1); const libaom_test::TestMode mode = std::tr1::get<kTestMode>(input); const int syntax = std::tr1::get<kSuperframeSyntax>(input); SetMode(mode); sf_count_ = 0; sf_count_max_ = INT_MAX; is_av1_style_superframe_ = syntax; n_tile_cols_ = std::tr1::get<kTileCols>(input); n_tile_rows_ = std::tr1::get<kTileRows>(input); } virtual void TearDown() { delete[] modified_buf_; } virtual void PreEncodeFrameHook(libaom_test::VideoSource *video, libaom_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(AOME_SET_ENABLEAUTOALTREF, 1); encoder->Control(AOME_SET_CPUUSED, 2); encoder->Control(AV1E_SET_TILE_COLUMNS, n_tile_cols_); encoder->Control(AV1E_SET_TILE_ROWS, n_tile_rows_); } } virtual const aom_codec_cx_pkt_t *MutateEncoderOutputHook( const aom_codec_cx_pkt_t *pkt) { if (pkt->kind != AOM_CODEC_CX_FRAME_PKT) return pkt; const uint8_t *buffer = reinterpret_cast<uint8_t *>(pkt->data.frame.buf); const uint8_t marker = buffer[pkt->data.frame.sz - 1]; const int frames = (marker & 0x7) + 1; const int mag = ((marker >> 3) & 3) + 1; const unsigned int index_sz = 2 + mag * (frames - is_av1_style_superframe_); if ((marker & 0xe0) == 0xc0 && pkt->data.frame.sz >= index_sz && buffer[pkt->data.frame.sz - index_sz] == marker) { // frame is a superframe. strip off the index. if (modified_buf_) delete[] modified_buf_; modified_buf_ = new uint8_t[pkt->data.frame.sz - index_sz]; memcpy(modified_buf_, pkt->data.frame.buf, pkt->data.frame.sz - index_sz); modified_pkt_ = *pkt; modified_pkt_.data.frame.buf = modified_buf_; modified_pkt_.data.frame.sz -= index_sz; sf_count_++; last_sf_pts_ = pkt->data.frame.pts; return &modified_pkt_; } // Make sure we do a few frames after the last SF abort_ |= sf_count_ > sf_count_max_ && pkt->data.frame.pts - last_sf_pts_ >= 5; return pkt; } int is_av1_style_superframe_; int sf_count_; int sf_count_max_; aom_codec_cx_pkt_t modified_pkt_; uint8_t *modified_buf_; aom_codec_pts_t last_sf_pts_; private: int n_tile_cols_; int n_tile_rows_; }; TEST_P(SuperframeTest, TestSuperframeIndexIsOptional) { sf_count_max_ = 0; // early exit on successful test. cfg_.g_lag_in_frames = 25; ::libaom_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288, 30, 1, 0, 40); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); #if CONFIG_EXT_REFS // NOTE: The use of BWDREF_FRAME will enable the coding of more non-show // frames besides ALTREF_FRAME. EXPECT_GE(sf_count_, 1); #else EXPECT_EQ(sf_count_, 1); #endif // CONFIG_EXT_REFS } // The superframe index is currently mandatory with ANS due to the decoder // starting at the end of the buffer. #if CONFIG_EXT_TILE // Single tile does not work with ANS (see comment above). #if CONFIG_ANS const int tile_col_values[] = { 1, 2 }; #else const int tile_col_values[] = { 1, 2, 32 }; #endif const int tile_row_values[] = { 1, 2, 32 }; AV1_INSTANTIATE_TEST_CASE( SuperframeTest, ::testing::Combine(::testing::Values(::libaom_test::kTwoPassGood), ::testing::Values(1), ::testing::ValuesIn(tile_col_values), ::testing::ValuesIn(tile_row_values))); #else #if !CONFIG_ANS && !CONFIG_DAALA_EC AV1_INSTANTIATE_TEST_CASE( SuperframeTest, ::testing::Combine(::testing::Values(::libaom_test::kTwoPassGood), ::testing::Values(1), ::testing::Values(0), ::testing::Values(0))); #endif // !CONFIG_ANS #endif // CONFIG_EXT_TILE } // namespace <commit_msg>superframe test: Remove VP9 style syntax<commit_after>/* * Copyright (c) 2016, Alliance for Open Media. All rights reserved * * This source code is subject to the terms of the BSD 2 Clause License and * the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License * was not distributed with this source code in the LICENSE file, you can * obtain it at www.aomedia.org/license/software. If the Alliance for Open * Media Patent License 1.0 was not distributed with this source code in the * PATENTS file, you can obtain it at www.aomedia.org/license/patent. */ #include <climits> #include "third_party/googletest/src/include/gtest/gtest.h" #include "test/codec_factory.h" #include "test/encode_test_driver.h" #include "test/i420_video_source.h" #include "test/util.h" namespace { const int kTestMode = 0; const int kTileCols = 1; const int kTileRows = 2; typedef std::tr1::tuple<libaom_test::TestMode, int, int> SuperframeTestParam; class SuperframeTest : public ::libaom_test::EncoderTest, public ::libaom_test::CodecTestWithParam<SuperframeTestParam> { protected: SuperframeTest() : EncoderTest(GET_PARAM(0)), modified_buf_(NULL), last_sf_pts_(0) {} virtual ~SuperframeTest() {} virtual void SetUp() { InitializeConfig(); const SuperframeTestParam input = GET_PARAM(1); const libaom_test::TestMode mode = std::tr1::get<kTestMode>(input); SetMode(mode); sf_count_ = 0; sf_count_max_ = INT_MAX; n_tile_cols_ = std::tr1::get<kTileCols>(input); n_tile_rows_ = std::tr1::get<kTileRows>(input); } virtual void TearDown() { delete[] modified_buf_; } virtual void PreEncodeFrameHook(libaom_test::VideoSource *video, libaom_test::Encoder *encoder) { if (video->frame() == 1) { encoder->Control(AOME_SET_ENABLEAUTOALTREF, 1); encoder->Control(AOME_SET_CPUUSED, 2); encoder->Control(AV1E_SET_TILE_COLUMNS, n_tile_cols_); encoder->Control(AV1E_SET_TILE_ROWS, n_tile_rows_); } } virtual const aom_codec_cx_pkt_t *MutateEncoderOutputHook( const aom_codec_cx_pkt_t *pkt) { if (pkt->kind != AOM_CODEC_CX_FRAME_PKT) return pkt; const uint8_t *buffer = reinterpret_cast<uint8_t *>(pkt->data.frame.buf); const uint8_t marker = buffer[pkt->data.frame.sz - 1]; const int frames = (marker & 0x7) + 1; const int mag = ((marker >> 3) & 3) + 1; const unsigned int index_sz = 2 + mag * (frames - 1); if ((marker & 0xe0) == 0xc0 && pkt->data.frame.sz >= index_sz && buffer[pkt->data.frame.sz - index_sz] == marker) { // frame is a superframe. strip off the index. if (modified_buf_) delete[] modified_buf_; modified_buf_ = new uint8_t[pkt->data.frame.sz - index_sz]; memcpy(modified_buf_, pkt->data.frame.buf, pkt->data.frame.sz - index_sz); modified_pkt_ = *pkt; modified_pkt_.data.frame.buf = modified_buf_; modified_pkt_.data.frame.sz -= index_sz; sf_count_++; last_sf_pts_ = pkt->data.frame.pts; return &modified_pkt_; } // Make sure we do a few frames after the last SF abort_ |= sf_count_ > sf_count_max_ && pkt->data.frame.pts - last_sf_pts_ >= 5; return pkt; } int sf_count_; int sf_count_max_; aom_codec_cx_pkt_t modified_pkt_; uint8_t *modified_buf_; aom_codec_pts_t last_sf_pts_; private: int n_tile_cols_; int n_tile_rows_; }; TEST_P(SuperframeTest, TestSuperframeIndexIsOptional) { sf_count_max_ = 0; // early exit on successful test. cfg_.g_lag_in_frames = 25; ::libaom_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288, 30, 1, 0, 40); ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); #if CONFIG_EXT_REFS // NOTE: The use of BWDREF_FRAME will enable the coding of more non-show // frames besides ALTREF_FRAME. EXPECT_GE(sf_count_, 1); #else EXPECT_EQ(sf_count_, 1); #endif // CONFIG_EXT_REFS } // The superframe index is currently mandatory with ANS due to the decoder // starting at the end of the buffer. #if CONFIG_EXT_TILE // Single tile does not work with ANS (see comment above). #if CONFIG_ANS const int tile_col_values[] = { 1, 2 }; #else const int tile_col_values[] = { 1, 2, 32 }; #endif const int tile_row_values[] = { 1, 2, 32 }; AV1_INSTANTIATE_TEST_CASE( SuperframeTest, ::testing::Combine(::testing::Values(::libaom_test::kTwoPassGood), ::testing::ValuesIn(tile_col_values), ::testing::ValuesIn(tile_row_values))); #else #if !CONFIG_ANS && !CONFIG_DAALA_EC AV1_INSTANTIATE_TEST_CASE( SuperframeTest, ::testing::Combine(::testing::Values(::libaom_test::kTwoPassGood), ::testing::Values(0), ::testing::Values(0))); #endif // !CONFIG_ANS #endif // CONFIG_EXT_TILE } // namespace <|endoftext|>
<commit_before>//============================================================================================================= /** * @file settingscontroller.cpp * @author Juan Garcia-Prieto <Juan.GarciaPrieto@uth.tmc.edu> <juangpc@gmail.com>; * Wayne Mead <wayne.mead@uth.tmc.edu> <wayne.isk@gmail.com>; * Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu>; * John C. Mosher <John.C.Mosher@uth.tmc.edu> <jcmosher@gmail.com>; * @version 1.0 * @date September, 2019 * * @section LICENSE * * Copyright (C) 2019, Juan Garcia-Prieto and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief SettingsController class definition. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "settingscontroller.h" #include "fiffanonymizer.h" //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // Eigen INCLUDES //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace FIFFANONYMIZER; //************************************************************************************************************* //============================================================================================================= // DEFINE GLOBAL METHODS //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= //SettingsController::SettingsController() //{ //} SettingsController::SettingsController(QCoreApplication * qtApp) :m_bMultipleInFiles(false), m_pQCoreApp(qtApp) { initParser(); parseInputs(); generate_anonymizer_instances(); execute(); } //************************************************************************************************************* void SettingsController::initParser() { m_pQCoreApp->setApplicationName(m_anonymizer.name); m_pQCoreApp->setApplicationVersion(m_anonymizer.versionStr); m_parser.setApplicationDescription(QCoreApplication::translate("main", m_anonymizer.description.toUtf8())); m_parser.addHelpOption(); m_parser.addVersionOption(); QCommandLineOption verboseOpt(QStringList() << "v" << "verbose", QCoreApplication::translate("main","Prints out more information.")); m_parser.addOption(verboseOpt); QCommandLineOption quietOpt("quiet",QCoreApplication::translate("main","Show no output.")); m_parser.addOption(quietOpt); QCommandLineOption deleteInFileOpt("delete_input_file_after", QCoreApplication::translate("main","Delete input fiff file after anonymization.")); m_parser.addOption(deleteInFileOpt); QCommandLineOption deleteInFileConfirmOpt("avoid_delete_confirmation", QCoreApplication::translate("main","Avoid confirming the deletion of the input fiff file.")); m_parser.addOption(deleteInFileConfirmOpt); QCommandLineOption bruteOpt("brute", QCoreApplication::translate("main","Anonymize weight, height XXX if present in the input fiff file.")); m_parser.addOption(bruteOpt); QCommandLineOption inFileOpt("in",QCoreApplication::translate("main","File to anonymize. Wildcards are allowed and seveal &lt;&lt;-in <infile>&lt;&lt; statements can be present."), QCoreApplication::translate("main","infile")); m_parser.addOption(inFileOpt); QCommandLineOption outFileOpt("out",QCoreApplication::translate("main","Output file <outfile>. Only allowed when anonymizing one single file."), QCoreApplication::translate("main","outfile")); m_parser.addOption(outFileOpt); QCommandLineOption measDateOpt("measurement_date", QCoreApplication::translate("main","Specify the measurement date. Only when anonymizing a single file. Format: YYYMMDD "), QCoreApplication::translate("main","days")); m_parser.addOption(measDateOpt); QCommandLineOption measDateOffsetOpt("measurement_date_offset", QCoreApplication::translate("main","Specify number of days to subtract to the measurement <date>. Only allowed when anonymizing a single file."), QCoreApplication::translate("main","date")); m_parser.addOption(measDateOffsetOpt); QCommandLineOption birthdayOpt("subject_birthday", QCoreApplication::translate("main","Specify the subject's birthday <date>. Only allowed when anonymizing a single file. Format: YYYMMDD "), QCoreApplication::translate("main","date")); m_parser.addOption(birthdayOpt); QCommandLineOption birthdayOffsetOpt("subject_birthday_offset", QCoreApplication::translate("main","Specify number of <days> to subtract to the subject's birthday. Only allowed when anonymizing a single file. "), QCoreApplication::translate("main","days")); m_parser.addOption(birthdayOffsetOpt); } //************************************************************************************************************* void SettingsController::parseInputs() { m_parser.process(*m_pQCoreApp); parseInputAndOutputFiles(); if(m_parser.isSet("v") || m_parser.isSet("verbose")) { m_anonymizer.setVerboseMode(true); } if(m_parser.isSet("brute")) { m_anonymizer.setBruteMode(true); } if(m_parser.isSet("quiet")) { if(m_anonymizer.getVerboseMode()) { m_anonymizer.setVerboseMode(false); } m_anonymizer.setQuietMode(true); } if(m_parser.isSet("delete_input_file_after")) { m_anonymizer.setDeleteInputFileAfter(true); } if(m_parser.isSet("avoid_delete_confirmation")) { m_anonymizer.setDeleteInputFileAfterConfirmation(false); } if(m_parser.isSet("measurement_date")) { if(m_bMultipleInFiles) { qDebug() << "Error. Multiple Input files. You cannot specify the option \"measurement_date\"."; m_parser.showHelp(); } QString d(m_parser.value("measurement_date")); m_anonymizer.setMeasurementDay(d); } if(m_parser.isSet("measurement_date_offset")) { if(m_bMultipleInFiles) { qDebug() << "Error. Multiple Input files. You cannot specify the option \"measurement_date_offset\"."; m_parser.showHelp(); } QString doffset(m_parser.value("measurement_date_offset")); m_anonymizer.setMeasurementDayOffset(doffset.toInt()); } if(m_parser.isSet("subject_birthday")) { if(m_bMultipleInFiles) { qDebug() << "Error. Multiple Input files. You cannot specify the option \"subject_birthday\"."; m_parser.showHelp(); } QString birthday(m_parser.value("subject_birthday")); m_anonymizer.setSubjectBirthday(birthday); } if(m_parser.isSet("subject_birthday_offset")) { if(m_bMultipleInFiles) { qDebug() << "Error. Multiple Input files. You cannot specify the option \"subject_birthday_offset\"."; m_parser.showHelp(); } QString bdoffset(m_parser.value("subject_birthday_offset")); m_anonymizer.setSubjectBirthdayOffset(bdoffset.toInt()); } } //************************************************************************************************************* void SettingsController::parseInputAndOutputFiles() { if(m_parser.isSet("in")) { QStringList inFilesAux(m_parser.values("in")); for(QString f: inFilesAux) { QDir d; d.setNameFilters({f}); for(QFileInfo fi: d.entryInfoList()) { if(fi.isFile() && fi.isReadable()) { fi.makeAbsolute(); m_slInFiles.append(fi.fileName()); } } } } if(m_slInFiles.size() == 0) { qDebug() << "Error. no valid input files. OMG!!"; m_parser.showHelp(); } else if(m_slInFiles.size() == 1) { m_bMultipleInFiles = false; } else { m_bMultipleInFiles = true; } if(m_bMultipleInFiles) { // QStringList opts; // opts << "out" << "measurement_date" << "measurement_date_offset" << "subject_birthday" << "subject_birthday_offset"; // for(QString opi:opts) // { // if(m_parser.isSet(opi)) // { // qDebug() << "Error. Multiple Input files. You cannot specify the option " << opi; // m_parser.showHelp(); // } // } for(QString fi:m_slInFiles) { QFileInfo fInfo(fi); QString fout = QDir(fInfo.absolutePath()).filePath( fInfo.baseName() + "_anonymized." + fInfo.completeSuffix()); m_slOutFiles.append(fout); } } else { QString fileOutName; if(m_parser.isSet("out")) { fileOutName = m_parser.value("out"); } else { QFileInfo fInfo(m_slInFiles.at(0)); fileOutName = QDir(fInfo.absolutePath()).filePath( fInfo.baseName() + "_anonymized." + fInfo.completeSuffix()); } } if(m_slInFiles.size() != m_slOutFiles.size()) { qDebug() << "Error. something went wrong while parsing the input files."; } } //************************************************************************************************************* void SettingsController::generate_anonymizer_instances() { if(m_bMultipleInFiles) { for(int i=0; i< m_slInFiles.size(); ++i) { //generate copy of m_anonymizer --> need a copy constructor QSharedPointer<FIFFANONYMIZER::FiffAnonymizer> pAnonymizerApp; m_appList.append(pAnonymizerApp); } } else { QFile fileIn(m_slInFiles.at(0)); QFile fileOut(m_slOutFiles.at(0)); m_anonymizer.setFileIn(&fileIn); m_anonymizer.setFileOut(&fileOut); } } //************************************************************************************************************* void SettingsController::execute() { if(m_bMultipleInFiles) { QtConcurrent::map(m_appList,&SettingsController::signal_execution_start); } else { m_anonymizer.anonymizeFile(); } } //************************************************************************************************************* void SettingsController::signal_execution_start(QSharedPointer<FIFFANONYMIZER::FiffAnonymizer> app) { app->anonymizeFile(); } //************************************************************************************************************* <commit_msg>update quotes in command parser<commit_after>//============================================================================================================= /** * @file settingscontroller.cpp * @author Juan Garcia-Prieto <Juan.GarciaPrieto@uth.tmc.edu> <juangpc@gmail.com>; * Wayne Mead <wayne.mead@uth.tmc.edu> <wayne.isk@gmail.com>; * Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu>; * John C. Mosher <John.C.Mosher@uth.tmc.edu> <jcmosher@gmail.com>; * @version 1.0 * @date September, 2019 * * @section LICENSE * * Copyright (C) 2019, Juan Garcia-Prieto and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief SettingsController class definition. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "settingscontroller.h" #include "fiffanonymizer.h" //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // Eigen INCLUDES //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace FIFFANONYMIZER; //************************************************************************************************************* //============================================================================================================= // DEFINE GLOBAL METHODS //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= //SettingsController::SettingsController() //{ //} SettingsController::SettingsController(QCoreApplication * qtApp) :m_bMultipleInFiles(false), m_pQCoreApp(qtApp) { initParser(); parseInputs(); generate_anonymizer_instances(); execute(); } //************************************************************************************************************* void SettingsController::initParser() { m_pQCoreApp->setApplicationName(m_anonymizer.name); m_pQCoreApp->setApplicationVersion(m_anonymizer.versionStr); m_parser.setApplicationDescription(QCoreApplication::translate("main", m_anonymizer.description.toUtf8())); m_parser.addHelpOption(); m_parser.addVersionOption(); QCommandLineOption verboseOpt(QStringList() << "v" << "verbose", QCoreApplication::translate("main","Prints out more information.")); m_parser.addOption(verboseOpt); QCommandLineOption quietOpt("quiet",QCoreApplication::translate("main","Show no output.")); m_parser.addOption(quietOpt); QCommandLineOption deleteInFileOpt("delete_input_file_after", QCoreApplication::translate("main","Delete input fiff file after anonymization.")); m_parser.addOption(deleteInFileOpt); QCommandLineOption deleteInFileConfirmOpt("avoid_delete_confirmation", QCoreApplication::translate("main","Avoid confirming the deletion of the input fiff file.")); m_parser.addOption(deleteInFileConfirmOpt); QCommandLineOption bruteOpt("brute", QCoreApplication::translate("main","Anonymize weight, height XXX if present in the input fiff file.")); m_parser.addOption(bruteOpt); QCommandLineOption inFileOpt("in",QCoreApplication::translate("main","File to anonymize. Wildcards are allowed and seveal -in <infile> statements can be present."), QCoreApplication::translate("main","infile")); m_parser.addOption(inFileOpt); QCommandLineOption outFileOpt("out",QCoreApplication::translate("main","Output file <outfile>. Only allowed when anonymizing one single file."), QCoreApplication::translate("main","outfile")); m_parser.addOption(outFileOpt); QCommandLineOption measDateOpt("measurement_date", QCoreApplication::translate("main","Specify the measurement date. Only when anonymizing a single file. Format: YYYMMDD "), QCoreApplication::translate("main","days")); m_parser.addOption(measDateOpt); QCommandLineOption measDateOffsetOpt("measurement_date_offset", QCoreApplication::translate("main","Specify number of days to subtract to the measurement <date>. Only allowed when anonymizing a single file."), QCoreApplication::translate("main","date")); m_parser.addOption(measDateOffsetOpt); QCommandLineOption birthdayOpt("subject_birthday", QCoreApplication::translate("main","Specify the subject's birthday <date>. Only allowed when anonymizing a single file. Format: YYYMMDD "), QCoreApplication::translate("main","date")); m_parser.addOption(birthdayOpt); QCommandLineOption birthdayOffsetOpt("subject_birthday_offset", QCoreApplication::translate("main","Specify number of <days> to subtract to the subject's birthday. Only allowed when anonymizing a single file. "), QCoreApplication::translate("main","days")); m_parser.addOption(birthdayOffsetOpt); } //************************************************************************************************************* void SettingsController::parseInputs() { m_parser.process(*m_pQCoreApp); parseInputAndOutputFiles(); if(m_parser.isSet("v") || m_parser.isSet("verbose")) { m_anonymizer.setVerboseMode(true); } if(m_parser.isSet("brute")) { m_anonymizer.setBruteMode(true); } if(m_parser.isSet("quiet")) { if(m_anonymizer.getVerboseMode()) { m_anonymizer.setVerboseMode(false); } m_anonymizer.setQuietMode(true); } if(m_parser.isSet("delete_input_file_after")) { m_anonymizer.setDeleteInputFileAfter(true); } if(m_parser.isSet("avoid_delete_confirmation")) { m_anonymizer.setDeleteInputFileAfterConfirmation(false); } if(m_parser.isSet("measurement_date")) { if(m_bMultipleInFiles) { qDebug() << "Error. Multiple Input files. You cannot specify the option \"measurement_date\"."; m_parser.showHelp(); } QString d(m_parser.value("measurement_date")); m_anonymizer.setMeasurementDay(d); } if(m_parser.isSet("measurement_date_offset")) { if(m_bMultipleInFiles) { qDebug() << "Error. Multiple Input files. You cannot specify the option \"measurement_date_offset\"."; m_parser.showHelp(); } QString doffset(m_parser.value("measurement_date_offset")); m_anonymizer.setMeasurementDayOffset(doffset.toInt()); } if(m_parser.isSet("subject_birthday")) { if(m_bMultipleInFiles) { qDebug() << "Error. Multiple Input files. You cannot specify the option \"subject_birthday\"."; m_parser.showHelp(); } QString birthday(m_parser.value("subject_birthday")); m_anonymizer.setSubjectBirthday(birthday); } if(m_parser.isSet("subject_birthday_offset")) { if(m_bMultipleInFiles) { qDebug() << "Error. Multiple Input files. You cannot specify the option \"subject_birthday_offset\"."; m_parser.showHelp(); } QString bdoffset(m_parser.value("subject_birthday_offset")); m_anonymizer.setSubjectBirthdayOffset(bdoffset.toInt()); } } //************************************************************************************************************* void SettingsController::parseInputAndOutputFiles() { if(m_parser.isSet("in")) { QStringList inFilesAux(m_parser.values("in")); for(QString f: inFilesAux) { QDir d; d.setNameFilters({f}); for(QFileInfo fi: d.entryInfoList()) { if(fi.isFile() && fi.isReadable()) { fi.makeAbsolute(); m_slInFiles.append(fi.fileName()); } } } } if(m_slInFiles.size() == 0) { qDebug() << "Error. no valid input files. OMG!!"; m_parser.showHelp(); } else if(m_slInFiles.size() == 1) { m_bMultipleInFiles = false; } else { m_bMultipleInFiles = true; } if(m_bMultipleInFiles) { // QStringList opts; // opts << "out" << "measurement_date" << "measurement_date_offset" << "subject_birthday" << "subject_birthday_offset"; // for(QString opi:opts) // { // if(m_parser.isSet(opi)) // { // qDebug() << "Error. Multiple Input files. You cannot specify the option " << opi; // m_parser.showHelp(); // } // } for(QString fi:m_slInFiles) { QFileInfo fInfo(fi); QString fout = QDir(fInfo.absolutePath()).filePath( fInfo.baseName() + "_anonymized." + fInfo.completeSuffix()); m_slOutFiles.append(fout); } } else { QString fileOutName; if(m_parser.isSet("out")) { fileOutName = m_parser.value("out"); } else { QFileInfo fInfo(m_slInFiles.at(0)); fileOutName = QDir(fInfo.absolutePath()).filePath( fInfo.baseName() + "_anonymized." + fInfo.completeSuffix()); } } if(m_slInFiles.size() != m_slOutFiles.size()) { qDebug() << "Error. something went wrong while parsing the input files."; } } //************************************************************************************************************* void SettingsController::generate_anonymizer_instances() { if(m_bMultipleInFiles) { for(int i=0; i< m_slInFiles.size(); ++i) { //generate copy of m_anonymizer --> need a copy constructor QSharedPointer<FIFFANONYMIZER::FiffAnonymizer> pAnonymizerApp; m_appList.append(pAnonymizerApp); } } else { QFile fileIn(m_slInFiles.at(0)); QFile fileOut(m_slOutFiles.at(0)); m_anonymizer.setFileIn(&fileIn); m_anonymizer.setFileOut(&fileOut); } } //************************************************************************************************************* void SettingsController::execute() { if(m_bMultipleInFiles) { QtConcurrent::map(m_appList,&SettingsController::signal_execution_start); } else { m_anonymizer.anonymizeFile(); } } //************************************************************************************************************* void SettingsController::signal_execution_start(QSharedPointer<FIFFANONYMIZER::FiffAnonymizer> app) { app->anonymizeFile(); } //************************************************************************************************************* <|endoftext|>
<commit_before>#include <iostream> #include <unistd.h> #include <curses.h> #include "Ncurses.hpp" using namespace Chip8; const std::map<Key, int> Ncurses::Chip8KeyToNcurses = { { Key::KEY_0, '0' }, { Key::KEY_1, '1' }, { Key::KEY_2, '2' }, { Key::KEY_3, '3' }, { Key::KEY_4, '4' }, { Key::KEY_5, '5' }, { Key::KEY_6, '6' }, { Key::KEY_7, '7' }, { Key::KEY_8, '8' }, { Key::KEY_9, '9' }, { Key::KEY_A, 'a' }, { Key::KEY_B, 'b' }, { Key::KEY_C, 'c' }, { Key::KEY_D, 'd' }, { Key::KEY_E, 'e' }, { Key::KEY_F, 'f' } }; const std::map<int, Key> Ncurses::NcursesToChip8Key = { { '0', Key::KEY_0 }, { '1', Key::KEY_1 }, { '2', Key::KEY_2 }, { '3', Key::KEY_3 }, { '4', Key::KEY_4 }, { '5', Key::KEY_5 }, { '6', Key::KEY_6 }, { '7', Key::KEY_7 }, { '8', Key::KEY_8 }, { '9', Key::KEY_9 }, { 'a', Key::KEY_A }, { 'b', Key::KEY_B }, { 'c', Key::KEY_C }, { 'd', Key::KEY_D }, { 'e', Key::KEY_E }, { 'f', Key::KEY_F } }; Ncurses::Ncurses() { initscr(); cbreak(); noecho(); curs_set(0); attrset(A_REVERSE); mvaddch(10, 10, ' '); } Ncurses::~Ncurses() { endwin(); } bool Ncurses::keyIsPressed(Chip8::Key key) { nodelay(stdscr, TRUE); const int ch = wgetch(stdscr); nodelay(stdscr, FALSE); return (ch != ERR && Chip8KeyToNcurses.count(key) != ch); } Key Ncurses::waitKey() { while (true) { const int ch = wgetch(stdscr); if (NcursesToChip8Key.count(ch) != 0) return NcursesToChip8Key.at(ch); } } bool Ncurses::quit() { if (mPlayBeep) beep(); return false; } void Ncurses::display(const Display& display) { for (auto i = 0; i < Display::WIDTH; ++i) { for (auto j = 0; j < Display::HEIGHT; ++j) { attrset((display.getPixel(i, j)) ? A_REVERSE : A_NORMAL); mvaddch(j, i, ' '); } } } void Ncurses::clearDisplay() { clear(); } void Ncurses::playBeep() { mPlayBeep = true; } void Ncurses::stopBeep() { mPlayBeep = false; } std::chrono::milliseconds Ncurses::getTicks() { return mClock.getTicks(); } void Ncurses::delay(const std::chrono::milliseconds& time) { usleep(time.count() * 1000); } <commit_msg>remove test<commit_after>#include <iostream> #include <unistd.h> #include <curses.h> #include "Ncurses.hpp" using namespace Chip8; const std::map<Key, int> Ncurses::Chip8KeyToNcurses = { { Key::KEY_0, '0' }, { Key::KEY_1, '1' }, { Key::KEY_2, '2' }, { Key::KEY_3, '3' }, { Key::KEY_4, '4' }, { Key::KEY_5, '5' }, { Key::KEY_6, '6' }, { Key::KEY_7, '7' }, { Key::KEY_8, '8' }, { Key::KEY_9, '9' }, { Key::KEY_A, 'a' }, { Key::KEY_B, 'b' }, { Key::KEY_C, 'c' }, { Key::KEY_D, 'd' }, { Key::KEY_E, 'e' }, { Key::KEY_F, 'f' } }; const std::map<int, Key> Ncurses::NcursesToChip8Key = { { '0', Key::KEY_0 }, { '1', Key::KEY_1 }, { '2', Key::KEY_2 }, { '3', Key::KEY_3 }, { '4', Key::KEY_4 }, { '5', Key::KEY_5 }, { '6', Key::KEY_6 }, { '7', Key::KEY_7 }, { '8', Key::KEY_8 }, { '9', Key::KEY_9 }, { 'a', Key::KEY_A }, { 'b', Key::KEY_B }, { 'c', Key::KEY_C }, { 'd', Key::KEY_D }, { 'e', Key::KEY_E }, { 'f', Key::KEY_F } }; Ncurses::Ncurses() { initscr(); cbreak(); noecho(); curs_set(0); } Ncurses::~Ncurses() { endwin(); } bool Ncurses::keyIsPressed(Chip8::Key key) { nodelay(stdscr, TRUE); const int ch = wgetch(stdscr); nodelay(stdscr, FALSE); return (ch != ERR && Chip8KeyToNcurses.count(key) != ch); } Key Ncurses::waitKey() { while (true) { const int ch = wgetch(stdscr); if (NcursesToChip8Key.count(ch) != 0) return NcursesToChip8Key.at(ch); } } bool Ncurses::quit() { if (mPlayBeep) beep(); return false; } void Ncurses::display(const Display& display) { for (auto i = 0; i < Display::WIDTH; ++i) { for (auto j = 0; j < Display::HEIGHT; ++j) { attrset((display.getPixel(i, j)) ? A_REVERSE : A_NORMAL); mvaddch(j, i, ' '); } } } void Ncurses::clearDisplay() { clear(); } void Ncurses::playBeep() { mPlayBeep = true; } void Ncurses::stopBeep() { mPlayBeep = false; } std::chrono::milliseconds Ncurses::getTicks() { return mClock.getTicks(); } void Ncurses::delay(const std::chrono::milliseconds& time) { usleep(time.count() * 1000); } <|endoftext|>
<commit_before>// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/bss_relocs.h" #include "vm/native_symbol.h" #include "vm/runtime_entry.h" #include "vm/thread.h" namespace dart { void BSS::InitializeBSSEntry(BSS::Relocation relocation, uword new_value, uword* bss_start) { std::atomic<uword>* slot = reinterpret_cast<std::atomic<uword>*>( &bss_start[BSS::RelocationIndex(relocation)]); uword old_value = slot->load(std::memory_order_relaxed); if (!slot->compare_exchange_strong(old_value, new_value, std::memory_order_relaxed)) { RELEASE_ASSERT(old_value == new_value); } } void BSS::Initialize(Thread* current, uword* bss_start, bool vm) { auto const instructions = reinterpret_cast<uword>( current->isolate_group()->source()->snapshot_instructions); uword dso_base; // For non-natively loaded snapshots, this is instead initialized in // LoadedElf::ResolveSymbols(). if (NativeSymbolResolver::LookupSharedObject(instructions, &dso_base)) { InitializeBSSEntry(Relocation::InstructionsRelocatedAddress, instructions - dso_base, bss_start); } if (!vm) { // Fill values at isolate-only indices. InitializeBSSEntry(Relocation::DRT_GetThreadForNativeCallback, reinterpret_cast<uword>(DLRT_GetThreadForNativeCallback), bss_start); } } } // namespace dart <commit_msg>[vm] Only exchange initial values in BSS when different.<commit_after>// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/bss_relocs.h" #include "vm/native_symbol.h" #include "vm/runtime_entry.h" #include "vm/thread.h" namespace dart { void BSS::InitializeBSSEntry(BSS::Relocation relocation, uword new_value, uword* bss_start) { std::atomic<uword>* slot = reinterpret_cast<std::atomic<uword>*>( &bss_start[BSS::RelocationIndex(relocation)]); uword old_value = slot->load(std::memory_order_relaxed); // FullSnapshotReader::ReadProgramSnapshot, and thus BSS::Initialize, can // get called multiple times for the same isolate in different threads, though // the initialized value will be consistent and thus change only once. Avoid // calling compare_exchange_strong unless we actually need to change the // value, to avoid spurious read/write races by TSAN. if (old_value == new_value) return; if (!slot->compare_exchange_strong(old_value, new_value, std::memory_order_relaxed)) { RELEASE_ASSERT(old_value == new_value); } } void BSS::Initialize(Thread* current, uword* bss_start, bool vm) { auto const instructions = reinterpret_cast<uword>( current->isolate_group()->source()->snapshot_instructions); uword dso_base; // For non-natively loaded snapshots, this is instead initialized in // LoadedElf::ResolveSymbols(). if (NativeSymbolResolver::LookupSharedObject(instructions, &dso_base)) { InitializeBSSEntry(Relocation::InstructionsRelocatedAddress, instructions - dso_base, bss_start); } if (!vm) { // Fill values at isolate-only indices. InitializeBSSEntry(Relocation::DRT_GetThreadForNativeCallback, reinterpret_cast<uword>(DLRT_GetThreadForNativeCallback), bss_start); } } } // namespace dart <|endoftext|>
<commit_before>//============================================================================================================= /** * @file settingscontroller.cpp * @author Juan Garcia-Prieto <Juan.GarciaPrieto@uth.tmc.edu> <juangpc@gmail.com>; * Wayne Mead <wayne.mead@uth.tmc.edu> <wayne.isk@gmail.com>; * Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu>; * John C. Mosher <John.C.Mosher@uth.tmc.edu> <jcmosher@gmail.com>; * @version 1.0 * @date September, 2019 * * @section LICENSE * * Copyright (C) 2019, Juan Garcia-Prieto and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief SettingsController class definition. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "settingscontroller.h" #include "fiffanonymizer.h" //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // Eigen INCLUDES //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace FIFFANONYMIZER; //************************************************************************************************************* //============================================================================================================= // DEFINE GLOBAL METHODS //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= //SettingsController::SettingsController() //{ //} SettingsController::SettingsController(QCoreApplication * qtApp) :m_bMultipleInFiles(false), m_pQCoreApp(qtApp) { m_pQCoreApp->setApplicationName(m_anonymizer.name); m_pQCoreApp->setApplicationVersion(m_anonymizer.versionStr); initParser(); parseInputs(); generate_anonymizer_instances(); execute(); } //************************************************************************************************************* void SettingsController::initParser() { m_parser.setApplicationDescription(m_anonymizer.description); m_parser.addHelpOption(); m_parser.addVersionOption(); QCommandLineOption verboseOpt(QStringList() << "v" << "verbose", QCoreApplication::translate("main","Prints out more information.")); m_parser.addOption(verboseOpt); QCommandLineOption quietOpt("quiet",QCoreApplication::translate("main","Show no output.")); m_parser.addOption(quietOpt); QCommandLineOption deleteInFileOpt("delete_input_file_after", QCoreApplication::translate("main","Delete input fiff file after anonymization.")); m_parser.addOption(deleteInFileOpt); QCommandLineOption deleteInFileConfirmOpt("avoid_delete_confirmation", QCoreApplication::translate("main","Avoid confirming the deletion of the input fiff file.")); m_parser.addOption(deleteInFileConfirmOpt); QCommandLineOption bruteOpt("brute", QCoreApplication::translate("main","Anonymize weight, height XXX if present in the input fiff file.")); m_parser.addOption(bruteOpt); QCommandLineOption inFileOpt("in",QCoreApplication::translate("main","File to anonymize. Wildcards are allowed and seveal \"-in <infile>\" statements can be present."), QCoreApplication::translate("main","infile")); m_parser.addOption(inFileOpt); QCommandLineOption outFileOpt("out",QCoreApplication::translate("main","Output file <outfile>. Only allowed when anonymizing one single file."), QCoreApplication::translate("main","outfile")); m_parser.addOption(outFileOpt); QCommandLineOption measDateOpt("measurement_date", QCoreApplication::translate("main","Specify the measurement date. Only when anonymizing a single file. Format: YYYMMDD "), QCoreApplication::translate("main","days")); m_parser.addOption(measDateOpt); QCommandLineOption measDateOffsetOpt("measurement_date_offset", QCoreApplication::translate("main","Specify number of days to subtract to the measurement <date>. Only allowed when anonymizing a single file."), QCoreApplication::translate("main","date")); m_parser.addOption(measDateOffsetOpt); QCommandLineOption birthdayOpt("subject_birthday", QCoreApplication::translate("main","Specify the subject's birthday <date>. Only allowed when anonymizing a single file. Format: YYYMMDD "), QCoreApplication::translate("main","date")); m_parser.addOption(birthdayOpt); QCommandLineOption birthdayOffsetOpt("subject_birthday_offset", QCoreApplication::translate("main","Specify number of <days> to subtract to the subject's birthday. Only allowed when anonymizing a single file. "), QCoreApplication::translate("main","days")); m_parser.addOption(birthdayOffsetOpt); } //************************************************************************************************************* void SettingsController::parseInputs() { m_parser.process(*m_pQCoreApp); parseInputAndOutputFiles(); if(m_parser.isSet("v") || m_parser.isSet("verbose")) { m_anonymizer.setVerboseMode(true); } if(m_parser.isSet("brute")) { m_anonymizer.setBruteMode(true); } if(m_parser.isSet("quiet")) { if(m_anonymizer.getVerboseMode()) { m_anonymizer.setVerboseMode(false); } m_anonymizer.setQuietMode(true); } if(m_parser.isSet("delete_input_file_after")) { m_anonymizer.setDeleteInputFileAfter(true); } if(m_parser.isSet("avoid_delete_confirmation")) { m_anonymizer.setDeleteInputFileAfterConfirmation(false); } if(m_parser.isSet("measurement_date")) { if(m_bMultipleInFiles) { qDebug() << "Error. Multiple Input files. You cannot specify the option \"measurement_date\"."; m_parser.showHelp(); } QString d(m_parser.value("measurement_date")); m_anonymizer.setMeasurementDay(d); } if(m_parser.isSet("measurement_date_offset")) { if(m_bMultipleInFiles) { qDebug() << "Error. Multiple Input files. You cannot specify the option \"measurement_date_offset\"."; m_parser.showHelp(); } QString doffset(m_parser.value("measurement_date_offset")); m_anonymizer.setMeasurementDayOffset(doffset.toInt()); } if(m_parser.isSet("subject_birthday")) { if(m_bMultipleInFiles) { qDebug() << "Error. Multiple Input files. You cannot specify the option \"subject_birthday\"."; m_parser.showHelp(); } QString birthday(m_parser.value("subject_birthday")); m_anonymizer.setSubjectBirthday(birthday); } if(m_parser.isSet("subject_birthday_offset")) { if(m_bMultipleInFiles) { qDebug() << "Error. Multiple Input files. You cannot specify the option \"subject_birthday_offset\"."; m_parser.showHelp(); } QString bdoffset(m_parser.value("subject_birthday_offset")); m_anonymizer.setSubjectBirthdayOffset(bdoffset.toInt()); } } //************************************************************************************************************* void SettingsController::parseInputAndOutputFiles() { if(m_parser.isSet("in")) { QStringList inFilesAux(m_parser.values("in")); for(QString f: inFilesAux) { QDir d; d.setNameFilters({f}); for(QFileInfo fi: d.entryInfoList()) { if(fi.isFile() && fi.isReadable()) { fi.makeAbsolute(); m_slInFiles.append(fi.fileName()); } } } } if(m_slInFiles.size() == 0) { qDebug() << "Error. no valid input files. OMG!!"; m_parser.showHelp(); } else if(m_slInFiles.size() == 1) { m_bMultipleInFiles = false; } else { m_bMultipleInFiles = true; } if(m_bMultipleInFiles) { // QStringList opts; // opts << "out" << "measurement_date" << "measurement_date_offset" << "subject_birthday" << "subject_birthday_offset"; // for(QString opi:opts) // { // if(m_parser.isSet(opi)) // { // qDebug() << "Error. Multiple Input files. You cannot specify the option " << opi; // m_parser.showHelp(); // } // } for(QString fi:m_slInFiles) { QFileInfo fInfo(fi); QString fout = QDir(fInfo.absolutePath()).filePath( fInfo.baseName() + "_anonymized." + fInfo.completeSuffix()); m_slOutFiles.append(fout); } } else { QString fileOutName; if(m_parser.isSet("out")) { fileOutName = m_parser.value("out"); } else { QFileInfo fInfo(m_slInFiles.at(0)); fileOutName = QDir(fInfo.absolutePath()).filePath( fInfo.baseName() + "_anonymized." + fInfo.completeSuffix()); } } if(m_slInFiles.size() != m_slOutFiles.size()) { qDebug() << "Error. something went wrong while parsing the input files."; } } //************************************************************************************************************* void SettingsController::generate_anonymizer_instances() { if(m_bMultipleInFiles) { for(int i=0; i< m_slInFiles.size(); ++i) { //generate copy of m_anonymizer --> need a copy constructor QSharedPointer<FIFFANONYMIZER::FiffAnonymizer> pAnonymizerApp; m_appList.append(pAnonymizerApp); } } else { QFile fileIn(m_slInFiles.at(0)); QFile fileOut(m_slOutFiles.at(0)); m_anonymizer.setFileIn(&fileIn); m_anonymizer.setFileOut(&fileOut); } } //************************************************************************************************************* void SettingsController::execute() { if(m_bMultipleInFiles) { QtConcurrent::map(m_appList,&SettingsController::signal_execution_start); } else { m_anonymizer.anonymizeFile(); } } //************************************************************************************************************* void SettingsController::signal_execution_start(QSharedPointer<FIFFANONYMIZER::FiffAnonymizer> app) { app->anonymizeFile(); } //************************************************************************************************************* <commit_msg>update input parser<commit_after>//============================================================================================================= /** * @file settingscontroller.cpp * @author Juan Garcia-Prieto <Juan.GarciaPrieto@uth.tmc.edu> <juangpc@gmail.com>; * Wayne Mead <wayne.mead@uth.tmc.edu> <wayne.isk@gmail.com>; * Lorenz Esch <Lorenz.Esch@tu-ilmenau.de>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu>; * John C. Mosher <John.C.Mosher@uth.tmc.edu> <jcmosher@gmail.com>; * @version 1.0 * @date September, 2019 * * @section LICENSE * * Copyright (C) 2019, Juan Garcia-Prieto and Matti Hamalainen. 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 MNE-CPP authors 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. * * * @brief SettingsController class definition. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "settingscontroller.h" #include "fiffanonymizer.h" //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // Eigen INCLUDES //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace FIFFANONYMIZER; //************************************************************************************************************* //============================================================================================================= // DEFINE GLOBAL METHODS //============================================================================================================= //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= //SettingsController::SettingsController() //{ //} SettingsController::SettingsController(QCoreApplication * qtApp) :m_bMultipleInFiles(false), m_pQCoreApp(qtApp) { initParser(); parseInputs(); generate_anonymizer_instances(); execute(); } //************************************************************************************************************* void SettingsController::initParser() { m_pQCoreApp->setApplicationName(m_anonymizer.name); m_pQCoreApp->setApplicationVersion(m_anonymizer.versionStr); m_parser.setApplicationDescription(QCoreApplication::translate("main", m_anonymizer.description.toUtf8())); m_parser.addHelpOption(); m_parser.addVersionOption(); QCommandLineOption verboseOpt(QStringList() << "v" << "verbose", QCoreApplication::translate("main","Prints out more information.")); m_parser.addOption(verboseOpt); QCommandLineOption quietOpt("quiet",QCoreApplication::translate("main","Show no output.")); m_parser.addOption(quietOpt); QCommandLineOption deleteInFileOpt("delete_input_file_after", QCoreApplication::translate("main","Delete input fiff file after anonymization.")); m_parser.addOption(deleteInFileOpt); QCommandLineOption deleteInFileConfirmOpt("avoid_delete_confirmation", QCoreApplication::translate("main","Avoid confirming the deletion of the input fiff file.")); m_parser.addOption(deleteInFileConfirmOpt); QCommandLineOption bruteOpt("brute", QCoreApplication::translate("main","Anonymize weight, height XXX if present in the input fiff file.")); m_parser.addOption(bruteOpt); QCommandLineOption inFileOpt("in",QCoreApplication::translate("main","File to anonymize. Wildcards are allowed and seveal &lt;&lt;-in <infile>&lt;&lt; statements can be present."), QCoreApplication::translate("main","infile")); m_parser.addOption(inFileOpt); QCommandLineOption outFileOpt("out",QCoreApplication::translate("main","Output file <outfile>. Only allowed when anonymizing one single file."), QCoreApplication::translate("main","outfile")); m_parser.addOption(outFileOpt); QCommandLineOption measDateOpt("measurement_date", QCoreApplication::translate("main","Specify the measurement date. Only when anonymizing a single file. Format: YYYMMDD "), QCoreApplication::translate("main","days")); m_parser.addOption(measDateOpt); QCommandLineOption measDateOffsetOpt("measurement_date_offset", QCoreApplication::translate("main","Specify number of days to subtract to the measurement <date>. Only allowed when anonymizing a single file."), QCoreApplication::translate("main","date")); m_parser.addOption(measDateOffsetOpt); QCommandLineOption birthdayOpt("subject_birthday", QCoreApplication::translate("main","Specify the subject's birthday <date>. Only allowed when anonymizing a single file. Format: YYYMMDD "), QCoreApplication::translate("main","date")); m_parser.addOption(birthdayOpt); QCommandLineOption birthdayOffsetOpt("subject_birthday_offset", QCoreApplication::translate("main","Specify number of <days> to subtract to the subject's birthday. Only allowed when anonymizing a single file. "), QCoreApplication::translate("main","days")); m_parser.addOption(birthdayOffsetOpt); } //************************************************************************************************************* void SettingsController::parseInputs() { m_parser.process(*m_pQCoreApp); parseInputAndOutputFiles(); if(m_parser.isSet("v") || m_parser.isSet("verbose")) { m_anonymizer.setVerboseMode(true); } if(m_parser.isSet("brute")) { m_anonymizer.setBruteMode(true); } if(m_parser.isSet("quiet")) { if(m_anonymizer.getVerboseMode()) { m_anonymizer.setVerboseMode(false); } m_anonymizer.setQuietMode(true); } if(m_parser.isSet("delete_input_file_after")) { m_anonymizer.setDeleteInputFileAfter(true); } if(m_parser.isSet("avoid_delete_confirmation")) { m_anonymizer.setDeleteInputFileAfterConfirmation(false); } if(m_parser.isSet("measurement_date")) { if(m_bMultipleInFiles) { qDebug() << "Error. Multiple Input files. You cannot specify the option \"measurement_date\"."; m_parser.showHelp(); } QString d(m_parser.value("measurement_date")); m_anonymizer.setMeasurementDay(d); } if(m_parser.isSet("measurement_date_offset")) { if(m_bMultipleInFiles) { qDebug() << "Error. Multiple Input files. You cannot specify the option \"measurement_date_offset\"."; m_parser.showHelp(); } QString doffset(m_parser.value("measurement_date_offset")); m_anonymizer.setMeasurementDayOffset(doffset.toInt()); } if(m_parser.isSet("subject_birthday")) { if(m_bMultipleInFiles) { qDebug() << "Error. Multiple Input files. You cannot specify the option \"subject_birthday\"."; m_parser.showHelp(); } QString birthday(m_parser.value("subject_birthday")); m_anonymizer.setSubjectBirthday(birthday); } if(m_parser.isSet("subject_birthday_offset")) { if(m_bMultipleInFiles) { qDebug() << "Error. Multiple Input files. You cannot specify the option \"subject_birthday_offset\"."; m_parser.showHelp(); } QString bdoffset(m_parser.value("subject_birthday_offset")); m_anonymizer.setSubjectBirthdayOffset(bdoffset.toInt()); } } //************************************************************************************************************* void SettingsController::parseInputAndOutputFiles() { if(m_parser.isSet("in")) { QStringList inFilesAux(m_parser.values("in")); for(QString f: inFilesAux) { QDir d; d.setNameFilters({f}); for(QFileInfo fi: d.entryInfoList()) { if(fi.isFile() && fi.isReadable()) { fi.makeAbsolute(); m_slInFiles.append(fi.fileName()); } } } } if(m_slInFiles.size() == 0) { qDebug() << "Error. no valid input files. OMG!!"; m_parser.showHelp(); } else if(m_slInFiles.size() == 1) { m_bMultipleInFiles = false; } else { m_bMultipleInFiles = true; } if(m_bMultipleInFiles) { // QStringList opts; // opts << "out" << "measurement_date" << "measurement_date_offset" << "subject_birthday" << "subject_birthday_offset"; // for(QString opi:opts) // { // if(m_parser.isSet(opi)) // { // qDebug() << "Error. Multiple Input files. You cannot specify the option " << opi; // m_parser.showHelp(); // } // } for(QString fi:m_slInFiles) { QFileInfo fInfo(fi); QString fout = QDir(fInfo.absolutePath()).filePath( fInfo.baseName() + "_anonymized." + fInfo.completeSuffix()); m_slOutFiles.append(fout); } } else { QString fileOutName; if(m_parser.isSet("out")) { fileOutName = m_parser.value("out"); } else { QFileInfo fInfo(m_slInFiles.at(0)); fileOutName = QDir(fInfo.absolutePath()).filePath( fInfo.baseName() + "_anonymized." + fInfo.completeSuffix()); } } if(m_slInFiles.size() != m_slOutFiles.size()) { qDebug() << "Error. something went wrong while parsing the input files."; } } //************************************************************************************************************* void SettingsController::generate_anonymizer_instances() { if(m_bMultipleInFiles) { for(int i=0; i< m_slInFiles.size(); ++i) { //generate copy of m_anonymizer --> need a copy constructor QSharedPointer<FIFFANONYMIZER::FiffAnonymizer> pAnonymizerApp; m_appList.append(pAnonymizerApp); } } else { QFile fileIn(m_slInFiles.at(0)); QFile fileOut(m_slOutFiles.at(0)); m_anonymizer.setFileIn(&fileIn); m_anonymizer.setFileOut(&fileOut); } } //************************************************************************************************************* void SettingsController::execute() { if(m_bMultipleInFiles) { QtConcurrent::map(m_appList,&SettingsController::signal_execution_start); } else { m_anonymizer.anonymizeFile(); } } //************************************************************************************************************* void SettingsController::signal_execution_start(QSharedPointer<FIFFANONYMIZER::FiffAnonymizer> app) { app->anonymizeFile(); } //************************************************************************************************************* <|endoftext|>
<commit_before>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015 Vladimír Vondruš <mosra@centrum.cz> 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 <sstream> #include <Corrade/Utility/Resource.h> #include "Magnum/AbstractShaderProgram.h" #include "Magnum/Context.h" #include "Magnum/Extensions.h" #include "Magnum/Shader.h" #include "Magnum/Math/Matrix.h" #include "Magnum/Math/Vector4.h" #include "Magnum/Test/AbstractOpenGLTester.h" namespace Magnum { namespace Test { struct AbstractShaderProgramGLTest: AbstractOpenGLTester { explicit AbstractShaderProgramGLTest(); void construct(); void constructCopy(); void constructMove(); void label(); void create(); void createMultipleOutputs(); #ifndef MAGNUM_TARGET_GLES void createMultipleOutputsIndexed(); #endif void uniformLocationOptimizedOut(); void uniform(); void uniformVector(); void uniformMatrix(); void uniformArray(); }; AbstractShaderProgramGLTest::AbstractShaderProgramGLTest() { addTests({&AbstractShaderProgramGLTest::construct, &AbstractShaderProgramGLTest::constructCopy, &AbstractShaderProgramGLTest::constructMove, &AbstractShaderProgramGLTest::label, &AbstractShaderProgramGLTest::create, &AbstractShaderProgramGLTest::createMultipleOutputs, #ifndef MAGNUM_TARGET_GLES &AbstractShaderProgramGLTest::createMultipleOutputsIndexed, #endif &AbstractShaderProgramGLTest::uniformLocationOptimizedOut, &AbstractShaderProgramGLTest::uniform, &AbstractShaderProgramGLTest::uniformVector, &AbstractShaderProgramGLTest::uniformMatrix, &AbstractShaderProgramGLTest::uniformArray}); } namespace { class DummyShader: public AbstractShaderProgram { public: explicit DummyShader() {} }; } void AbstractShaderProgramGLTest::construct() { { const DummyShader shader; MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(shader.id() > 0); } MAGNUM_VERIFY_NO_ERROR(); } void AbstractShaderProgramGLTest::constructCopy() { CORRADE_VERIFY(!(std::is_constructible<DummyShader, const DummyShader&>{})); CORRADE_VERIFY(!(std::is_assignable<DummyShader, const DummyShader&>{})); } void AbstractShaderProgramGLTest::constructMove() { DummyShader a; const Int id = a.id(); MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(id > 0); DummyShader b(std::move(a)); CORRADE_COMPARE(a.id(), 0); CORRADE_COMPARE(b.id(), id); DummyShader c; const Int cId = c.id(); c = std::move(b); MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(cId > 0); CORRADE_COMPARE(b.id(), cId); CORRADE_COMPARE(c.id(), id); } void AbstractShaderProgramGLTest::label() { /* No-Op version is tested in AbstractObjectGLTest */ if(!Context::current()->isExtensionSupported<Extensions::GL::KHR::debug>() && !Context::current()->isExtensionSupported<Extensions::GL::EXT::debug_label>()) CORRADE_SKIP("Required extension is not available"); DummyShader shader; CORRADE_COMPARE(shader.label(), ""); shader.setLabel("DummyShader"); CORRADE_COMPARE(shader.label(), "DummyShader"); MAGNUM_VERIFY_NO_ERROR(); } namespace { struct MyPublicShader: AbstractShaderProgram { using AbstractShaderProgram::attachShaders; using AbstractShaderProgram::bindAttributeLocation; #ifndef MAGNUM_TARGET_GLES using AbstractShaderProgram::bindFragmentDataLocationIndexed; using AbstractShaderProgram::bindFragmentDataLocation; #endif using AbstractShaderProgram::link; using AbstractShaderProgram::uniformLocation; }; } void AbstractShaderProgramGLTest::create() { Utility::Resource rs("AbstractShaderProgramGLTest"); #ifndef MAGNUM_TARGET_GLES Shader vert(Version::GL210, Shader::Type::Vertex); #else Shader vert(Version::GLES200, Shader::Type::Vertex); #endif vert.addSource(rs.get("MyShader.vert")); const bool vertCompiled = vert.compile(); #ifndef MAGNUM_TARGET_GLES Shader frag(Version::GL210, Shader::Type::Fragment); #else Shader frag(Version::GLES200, Shader::Type::Fragment); #endif frag.addSource(rs.get("MyShader.frag")); const bool fragCompiled = frag.compile(); MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(vertCompiled); CORRADE_VERIFY(fragCompiled); MyPublicShader program; program.attachShaders({vert, frag}); MAGNUM_VERIFY_NO_ERROR(); program.bindAttributeLocation(0, "position"); const bool linked = program.link(); const bool valid = program.validate().first; MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(linked); CORRADE_VERIFY(valid); const Int matrixUniform = program.uniformLocation("matrix"); const Int multiplierUniform = program.uniformLocation("multiplier"); const Int colorUniform = program.uniformLocation("color"); const Int additionsUniform = program.uniformLocation("additions"); MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(matrixUniform >= 0); CORRADE_VERIFY(multiplierUniform >= 0); CORRADE_VERIFY(colorUniform >= 0); CORRADE_VERIFY(additionsUniform >= 0); } void AbstractShaderProgramGLTest::createMultipleOutputs() { #ifndef MAGNUM_TARGET_GLES Utility::Resource rs("AbstractShaderProgramGLTest"); Shader vert(Version::GL210, Shader::Type::Vertex); vert.addSource(rs.get("MyShader.vert")); const bool vertCompiled = vert.compile(); Shader frag(Version::GL300, Shader::Type::Fragment); frag.addSource(rs.get("MyShaderFragmentOutputs.frag")); const bool fragCompiled = frag.compile(); MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(vertCompiled); CORRADE_VERIFY(fragCompiled); MyPublicShader program; program.attachShaders({vert, frag}); MAGNUM_VERIFY_NO_ERROR(); program.bindAttributeLocation(0, "position"); program.bindFragmentDataLocation(0, "first"); program.bindFragmentDataLocation(1, "second"); const bool linked = program.link(); const bool valid = program.validate().first; MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(linked); CORRADE_VERIFY(valid); #elif !defined(MAGNUM_TARGET_GLES2) CORRADE_SKIP("Only explicit location specification supported in ES 3.0."); #else CORRADE_SKIP("Only gl_FragData[n] supported in ES 2.0."); #endif } #ifndef MAGNUM_TARGET_GLES void AbstractShaderProgramGLTest::createMultipleOutputsIndexed() { Utility::Resource rs("AbstractShaderProgramGLTest"); Shader vert(Version::GL210, Shader::Type::Vertex); vert.addSource(rs.get("MyShader.vert")); const bool vertCompiled = vert.compile(); Shader frag(Version::GL300, Shader::Type::Fragment); frag.addSource(rs.get("MyShaderFragmentOutputs.frag")); const bool fragCompiled = frag.compile(); MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(vertCompiled); CORRADE_VERIFY(fragCompiled); MyPublicShader program; program.attachShaders({vert, frag}); MAGNUM_VERIFY_NO_ERROR(); program.bindAttributeLocation(0, "position"); program.bindFragmentDataLocationIndexed(0, 0, "first"); program.bindFragmentDataLocationIndexed(0, 1, "second"); const bool linked = program.link(); const bool valid = program.validate().first; MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(linked); CORRADE_VERIFY(valid); } #endif void AbstractShaderProgramGLTest::uniformLocationOptimizedOut() { MyPublicShader program; #ifndef MAGNUM_TARGET_GLES Shader vert(Version::GL210, Shader::Type::Vertex); Shader frag(Version::GL210, Shader::Type::Fragment); #else Shader vert(Version::GLES200, Shader::Type::Vertex); Shader frag(Version::GLES200, Shader::Type::Fragment); #endif vert.addSource("void main() { gl_Position = vec4(0.0); }"); frag.addSource("void main() { gl_FragColor = vec4(1.0); }"); CORRADE_VERIFY(Shader::compile({vert, frag})); program.attachShaders({vert, frag}); CORRADE_VERIFY(program.link()); std::ostringstream out; Warning::setOutput(&out); program.uniformLocation("nonexistent"); program.uniformLocation(std::string{"another"}); CORRADE_COMPARE(out.str(), "AbstractShaderProgram: location of uniform 'nonexistent' cannot be retrieved!\n" "AbstractShaderProgram: location of uniform 'another' cannot be retrieved!\n"); } namespace { struct MyShader: AbstractShaderProgram { explicit MyShader(); using AbstractShaderProgram::setUniform; Int matrixUniform, multiplierUniform, colorUniform, additionsUniform; }; } #ifndef DOXYGEN_GENERATING_OUTPUT MyShader::MyShader() { Utility::Resource rs("AbstractShaderProgramGLTest"); #ifndef MAGNUM_TARGET_GLES Shader vert(Version::GL210, Shader::Type::Vertex); Shader frag(Version::GL210, Shader::Type::Fragment); #else Shader vert(Version::GLES200, Shader::Type::Vertex); Shader frag(Version::GLES200, Shader::Type::Fragment); #endif vert.addSource(rs.get("MyShader.vert")); frag.addSource(rs.get("MyShader.frag")); Shader::compile({vert, frag}); attachShaders({vert, frag}); bindAttributeLocation(0, "position"); link(); matrixUniform = uniformLocation("matrix"); multiplierUniform = uniformLocation("multiplier"); colorUniform = uniformLocation("color"); additionsUniform = uniformLocation("additions"); } #endif void AbstractShaderProgramGLTest::uniform() { MyShader shader; MAGNUM_VERIFY_NO_ERROR(); shader.setUniform(shader.multiplierUniform, 0.35f); MAGNUM_VERIFY_NO_ERROR(); } void AbstractShaderProgramGLTest::uniformVector() { MyShader shader; MAGNUM_VERIFY_NO_ERROR(); shader.setUniform(shader.colorUniform, Vector4(0.3f, 0.7f, 1.0f, 0.25f)); MAGNUM_VERIFY_NO_ERROR(); } void AbstractShaderProgramGLTest::uniformMatrix() { MyShader shader; MAGNUM_VERIFY_NO_ERROR(); shader.setUniform(shader.matrixUniform, Matrix4x4::fromDiagonal({0.3f, 0.7f, 1.0f, 0.25f})); MAGNUM_VERIFY_NO_ERROR(); } void AbstractShaderProgramGLTest::uniformArray() { MyShader shader; MAGNUM_VERIFY_NO_ERROR(); /* Testing also implicit conversion to base type (Vector4[] -> Math::Vector<4, Float>[]) */ constexpr Vector4 values[] = { {0.5f, 1.0f, 0.4f, 0.0f}, {0.0f, 0.1f, 0.7f, 0.3f}, {0.9f, 0.8f, 0.3f, 0.1f} }; shader.setUniform(shader.additionsUniform, values); MAGNUM_VERIFY_NO_ERROR(); } }} MAGNUM_GL_TEST_MAIN(Magnum::Test::AbstractShaderProgramGLTest) <commit_msg>MSVC 2015 compatibility: another compiler crash.<commit_after>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015 Vladimír Vondruš <mosra@centrum.cz> 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 <sstream> #include <Corrade/Utility/Resource.h> #include "Magnum/AbstractShaderProgram.h" #include "Magnum/Context.h" #include "Magnum/Extensions.h" #include "Magnum/Shader.h" #include "Magnum/Math/Matrix.h" #include "Magnum/Math/Vector4.h" #include "Magnum/Test/AbstractOpenGLTester.h" namespace Magnum { namespace Test { struct AbstractShaderProgramGLTest: AbstractOpenGLTester { explicit AbstractShaderProgramGLTest(); void construct(); void constructCopy(); void constructMove(); void label(); void create(); void createMultipleOutputs(); #ifndef MAGNUM_TARGET_GLES void createMultipleOutputsIndexed(); #endif void uniformLocationOptimizedOut(); void uniform(); void uniformVector(); void uniformMatrix(); void uniformArray(); }; AbstractShaderProgramGLTest::AbstractShaderProgramGLTest() { addTests({&AbstractShaderProgramGLTest::construct, &AbstractShaderProgramGLTest::constructCopy, &AbstractShaderProgramGLTest::constructMove, &AbstractShaderProgramGLTest::label, &AbstractShaderProgramGLTest::create, &AbstractShaderProgramGLTest::createMultipleOutputs, #ifndef MAGNUM_TARGET_GLES &AbstractShaderProgramGLTest::createMultipleOutputsIndexed, #endif &AbstractShaderProgramGLTest::uniformLocationOptimizedOut, &AbstractShaderProgramGLTest::uniform, &AbstractShaderProgramGLTest::uniformVector, &AbstractShaderProgramGLTest::uniformMatrix, &AbstractShaderProgramGLTest::uniformArray}); } namespace { class DummyShader: public AbstractShaderProgram { public: explicit DummyShader() {} }; } void AbstractShaderProgramGLTest::construct() { { const DummyShader shader; MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(shader.id() > 0); } MAGNUM_VERIFY_NO_ERROR(); } void AbstractShaderProgramGLTest::constructCopy() { CORRADE_VERIFY(!(std::is_constructible<DummyShader, const DummyShader&>{})); CORRADE_VERIFY(!(std::is_assignable<DummyShader, const DummyShader&>{})); } void AbstractShaderProgramGLTest::constructMove() { DummyShader a; const Int id = a.id(); MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(id > 0); DummyShader b(std::move(a)); CORRADE_COMPARE(a.id(), 0); CORRADE_COMPARE(b.id(), id); DummyShader c; const Int cId = c.id(); c = std::move(b); MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(cId > 0); CORRADE_COMPARE(b.id(), cId); CORRADE_COMPARE(c.id(), id); } void AbstractShaderProgramGLTest::label() { /* No-Op version is tested in AbstractObjectGLTest */ if(!Context::current()->isExtensionSupported<Extensions::GL::KHR::debug>() && !Context::current()->isExtensionSupported<Extensions::GL::EXT::debug_label>()) CORRADE_SKIP("Required extension is not available"); DummyShader shader; CORRADE_COMPARE(shader.label(), ""); shader.setLabel("DummyShader"); CORRADE_COMPARE(shader.label(), "DummyShader"); MAGNUM_VERIFY_NO_ERROR(); } namespace { struct MyPublicShader: AbstractShaderProgram { using AbstractShaderProgram::attachShaders; using AbstractShaderProgram::bindAttributeLocation; #ifndef MAGNUM_TARGET_GLES using AbstractShaderProgram::bindFragmentDataLocationIndexed; using AbstractShaderProgram::bindFragmentDataLocation; #endif using AbstractShaderProgram::link; using AbstractShaderProgram::uniformLocation; }; } void AbstractShaderProgramGLTest::create() { Utility::Resource rs("AbstractShaderProgramGLTest"); #ifndef MAGNUM_TARGET_GLES Shader vert(Version::GL210, Shader::Type::Vertex); #else Shader vert(Version::GLES200, Shader::Type::Vertex); #endif vert.addSource(rs.get("MyShader.vert")); const bool vertCompiled = vert.compile(); #ifndef MAGNUM_TARGET_GLES Shader frag(Version::GL210, Shader::Type::Fragment); #else Shader frag(Version::GLES200, Shader::Type::Fragment); #endif frag.addSource(rs.get("MyShader.frag")); const bool fragCompiled = frag.compile(); MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(vertCompiled); CORRADE_VERIFY(fragCompiled); MyPublicShader program; program.attachShaders({vert, frag}); MAGNUM_VERIFY_NO_ERROR(); program.bindAttributeLocation(0, "position"); const bool linked = program.link(); const bool valid = program.validate().first; MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(linked); CORRADE_VERIFY(valid); const Int matrixUniform = program.uniformLocation("matrix"); const Int multiplierUniform = program.uniformLocation("multiplier"); const Int colorUniform = program.uniformLocation("color"); const Int additionsUniform = program.uniformLocation("additions"); MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(matrixUniform >= 0); CORRADE_VERIFY(multiplierUniform >= 0); CORRADE_VERIFY(colorUniform >= 0); CORRADE_VERIFY(additionsUniform >= 0); } void AbstractShaderProgramGLTest::createMultipleOutputs() { #ifndef MAGNUM_TARGET_GLES Utility::Resource rs("AbstractShaderProgramGLTest"); Shader vert(Version::GL210, Shader::Type::Vertex); vert.addSource(rs.get("MyShader.vert")); const bool vertCompiled = vert.compile(); Shader frag(Version::GL300, Shader::Type::Fragment); frag.addSource(rs.get("MyShaderFragmentOutputs.frag")); const bool fragCompiled = frag.compile(); MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(vertCompiled); CORRADE_VERIFY(fragCompiled); MyPublicShader program; program.attachShaders({vert, frag}); MAGNUM_VERIFY_NO_ERROR(); program.bindAttributeLocation(0, "position"); program.bindFragmentDataLocation(0, "first"); program.bindFragmentDataLocation(1, "second"); const bool linked = program.link(); const bool valid = program.validate().first; MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(linked); CORRADE_VERIFY(valid); #elif !defined(MAGNUM_TARGET_GLES2) CORRADE_SKIP("Only explicit location specification supported in ES 3.0."); #else CORRADE_SKIP("Only gl_FragData[n] supported in ES 2.0."); #endif } #ifndef MAGNUM_TARGET_GLES void AbstractShaderProgramGLTest::createMultipleOutputsIndexed() { Utility::Resource rs("AbstractShaderProgramGLTest"); Shader vert(Version::GL210, Shader::Type::Vertex); vert.addSource(rs.get("MyShader.vert")); const bool vertCompiled = vert.compile(); Shader frag(Version::GL300, Shader::Type::Fragment); frag.addSource(rs.get("MyShaderFragmentOutputs.frag")); const bool fragCompiled = frag.compile(); MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(vertCompiled); CORRADE_VERIFY(fragCompiled); MyPublicShader program; program.attachShaders({vert, frag}); MAGNUM_VERIFY_NO_ERROR(); program.bindAttributeLocation(0, "position"); program.bindFragmentDataLocationIndexed(0, 0, "first"); program.bindFragmentDataLocationIndexed(0, 1, "second"); const bool linked = program.link(); const bool valid = program.validate().first; MAGNUM_VERIFY_NO_ERROR(); CORRADE_VERIFY(linked); CORRADE_VERIFY(valid); } #endif void AbstractShaderProgramGLTest::uniformLocationOptimizedOut() { MyPublicShader program; #ifndef MAGNUM_TARGET_GLES Shader vert(Version::GL210, Shader::Type::Vertex); Shader frag(Version::GL210, Shader::Type::Fragment); #else Shader vert(Version::GLES200, Shader::Type::Vertex); Shader frag(Version::GLES200, Shader::Type::Fragment); #endif vert.addSource("void main() { gl_Position = vec4(0.0); }"); frag.addSource("void main() { gl_FragColor = vec4(1.0); }"); CORRADE_VERIFY(Shader::compile({vert, frag})); program.attachShaders({vert, frag}); CORRADE_VERIFY(program.link()); std::ostringstream out; Warning::setOutput(&out); program.uniformLocation("nonexistent"); program.uniformLocation(std::string{"another"}); CORRADE_COMPARE(out.str(), "AbstractShaderProgram: location of uniform 'nonexistent' cannot be retrieved!\n" "AbstractShaderProgram: location of uniform 'another' cannot be retrieved!\n"); } namespace { struct MyShader: AbstractShaderProgram { explicit MyShader(); using AbstractShaderProgram::setUniform; Int matrixUniform, multiplierUniform, colorUniform, additionsUniform; }; } #ifndef DOXYGEN_GENERATING_OUTPUT MyShader::MyShader() { Utility::Resource rs("AbstractShaderProgramGLTest"); #ifndef MAGNUM_TARGET_GLES Shader vert(Version::GL210, Shader::Type::Vertex); Shader frag(Version::GL210, Shader::Type::Fragment); #else Shader vert(Version::GLES200, Shader::Type::Vertex); Shader frag(Version::GLES200, Shader::Type::Fragment); #endif vert.addSource(rs.get("MyShader.vert")); frag.addSource(rs.get("MyShader.frag")); Shader::compile({vert, frag}); attachShaders({vert, frag}); bindAttributeLocation(0, "position"); link(); matrixUniform = uniformLocation("matrix"); multiplierUniform = uniformLocation("multiplier"); colorUniform = uniformLocation("color"); additionsUniform = uniformLocation("additions"); } #endif void AbstractShaderProgramGLTest::uniform() { MyShader shader; MAGNUM_VERIFY_NO_ERROR(); shader.setUniform(shader.multiplierUniform, 0.35f); MAGNUM_VERIFY_NO_ERROR(); } void AbstractShaderProgramGLTest::uniformVector() { MyShader shader; MAGNUM_VERIFY_NO_ERROR(); shader.setUniform(shader.colorUniform, Vector4(0.3f, 0.7f, 1.0f, 0.25f)); MAGNUM_VERIFY_NO_ERROR(); } void AbstractShaderProgramGLTest::uniformMatrix() { MyShader shader; MAGNUM_VERIFY_NO_ERROR(); shader.setUniform(shader.matrixUniform, Matrix4x4::fromDiagonal({0.3f, 0.7f, 1.0f, 0.25f})); MAGNUM_VERIFY_NO_ERROR(); } void AbstractShaderProgramGLTest::uniformArray() { MyShader shader; MAGNUM_VERIFY_NO_ERROR(); /* Testing also implicit conversion to base type (Vector4[] -> Math::Vector<4, Float>[]) */ #ifndef CORRADE_MSVC2015_COMPATIBILITY /* Causes ICE */ constexpr #endif const Vector4 values[] = { {0.5f, 1.0f, 0.4f, 0.0f}, {0.0f, 0.1f, 0.7f, 0.3f}, {0.9f, 0.8f, 0.3f, 0.1f} }; shader.setUniform(shader.additionsUniform, values); MAGNUM_VERIFY_NO_ERROR(); } }} MAGNUM_GL_TEST_MAIN(Magnum::Test::AbstractShaderProgramGLTest) <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the 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 <qtest.h> #include <QtDeclarative/qmlengine.h> #include <QtDeclarative/qmlcomponent.h> #include <private/qmltimer_p.h> class tst_qmltimer : public QObject { Q_OBJECT public: tst_qmltimer(); private slots: void notRepeating(); void notRepeatingStart(); void repeat(); void triggeredOnStart(); void triggeredOnStartRepeat(); }; class TimerHelper : public QObject { Q_OBJECT public: TimerHelper() : QObject(), count(0) { } int count; public slots: void timeout() { ++count; } }; #if defined(Q_OS_SYMBIAN) && defined(Q_CC_NOKIAX86) // Increase wait as emulator startup can cause unexpected delays #define TIMEOUT_TIMEOUT 2000 #else #define TIMEOUT_TIMEOUT 200 #endif tst_qmltimer::tst_qmltimer() { } void tst_qmltimer::notRepeating() { QmlEngine engine; QmlComponent component(&engine, QByteArray("import Qt 4.6\nTimer { interval: 100; running: true }"), QUrl("file://")); QmlTimer *timer = qobject_cast<QmlTimer*>(component.create()); QVERIFY(timer != 0); TimerHelper helper; connect(timer, SIGNAL(triggered()), &helper, SLOT(timeout())); QTest::qWait(TIMEOUT_TIMEOUT); QCOMPARE(helper.count, 1); QTest::qWait(TIMEOUT_TIMEOUT); QCOMPARE(helper.count, 1); } void tst_qmltimer::notRepeatingStart() { QmlEngine engine; QmlComponent component(&engine, QByteArray("import Qt 4.6\nTimer { interval: 100 }"), QUrl("file://")); QmlTimer *timer = qobject_cast<QmlTimer*>(component.create()); QVERIFY(timer != 0); TimerHelper helper; connect(timer, SIGNAL(triggered()), &helper, SLOT(timeout())); QTest::qWait(TIMEOUT_TIMEOUT); QCOMPARE(helper.count, 0); timer->start(); QTest::qWait(TIMEOUT_TIMEOUT); QCOMPARE(helper.count, 1); QTest::qWait(TIMEOUT_TIMEOUT); QCOMPARE(helper.count, 1); } void tst_qmltimer::repeat() { QmlEngine engine; QmlComponent component(&engine, QByteArray("import Qt 4.6\nTimer { interval: 100; repeat: true; running: true }"), QUrl("file://")); QmlTimer *timer = qobject_cast<QmlTimer*>(component.create()); QVERIFY(timer != 0); TimerHelper helper; connect(timer, SIGNAL(triggered()), &helper, SLOT(timeout())); QCOMPARE(helper.count, 0); QTest::qWait(TIMEOUT_TIMEOUT); QVERIFY(helper.count > 0); int oldCount = helper.count; QTest::qWait(TIMEOUT_TIMEOUT); QVERIFY(helper.count > oldCount); } void tst_qmltimer::triggeredOnStart() { QmlEngine engine; QmlComponent component(&engine, QByteArray("import Qt 4.6\nTimer { interval: 100; running: true; triggeredOnStart: true }"), QUrl("file://")); QmlTimer *timer = qobject_cast<QmlTimer*>(component.create()); QVERIFY(timer != 0); TimerHelper helper; connect(timer, SIGNAL(triggered()), &helper, SLOT(timeout())); QTest::qWait(1); QCOMPARE(helper.count, 1); QTest::qWait(TIMEOUT_TIMEOUT); QCOMPARE(helper.count, 2); QTest::qWait(TIMEOUT_TIMEOUT); QCOMPARE(helper.count, 2); } void tst_qmltimer::triggeredOnStartRepeat() { QmlEngine engine; QmlComponent component(&engine, QByteArray("import Qt 4.6\nTimer { interval: 100; running: true; triggeredOnStart: true; repeat: true }"), QUrl("file://")); QmlTimer *timer = qobject_cast<QmlTimer*>(component.create()); QVERIFY(timer != 0); TimerHelper helper; connect(timer, SIGNAL(triggered()), &helper, SLOT(timeout())); QTest::qWait(1); QCOMPARE(helper.count, 1); QTest::qWait(TIMEOUT_TIMEOUT); QVERIFY(helper.count > 1); int oldCount = helper.count; QTest::qWait(TIMEOUT_TIMEOUT); QVERIFY(helper.count > oldCount); } QTEST_MAIN(tst_qmltimer) #include "tst_qmltimer.moc" <commit_msg>Check bug QT-2423<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the 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 <qtest.h> #include <QtDeclarative/qmlengine.h> #include <QtDeclarative/qmlcomponent.h> #include <private/qmltimer_p.h> class tst_qmltimer : public QObject { Q_OBJECT public: tst_qmltimer(); private slots: void notRepeating(); void notRepeatingStart(); void repeat(); void noTriggerIfNotRunning(); void triggeredOnStart(); void triggeredOnStartRepeat(); }; class TimerHelper : public QObject { Q_OBJECT public: TimerHelper() : QObject(), count(0) { } int count; public slots: void timeout() { ++count; } }; #if defined(Q_OS_SYMBIAN) && defined(Q_CC_NOKIAX86) // Increase wait as emulator startup can cause unexpected delays #define TIMEOUT_TIMEOUT 2000 #else #define TIMEOUT_TIMEOUT 200 #endif tst_qmltimer::tst_qmltimer() { } void tst_qmltimer::notRepeating() { QmlEngine engine; QmlComponent component(&engine, QByteArray("import Qt 4.6\nTimer { interval: 100; running: true }"), QUrl("file://")); QmlTimer *timer = qobject_cast<QmlTimer*>(component.create()); QVERIFY(timer != 0); TimerHelper helper; connect(timer, SIGNAL(triggered()), &helper, SLOT(timeout())); QTest::qWait(TIMEOUT_TIMEOUT); QCOMPARE(helper.count, 1); QTest::qWait(TIMEOUT_TIMEOUT); QCOMPARE(helper.count, 1); } void tst_qmltimer::notRepeatingStart() { QmlEngine engine; QmlComponent component(&engine, QByteArray("import Qt 4.6\nTimer { interval: 100 }"), QUrl("file://")); QmlTimer *timer = qobject_cast<QmlTimer*>(component.create()); QVERIFY(timer != 0); TimerHelper helper; connect(timer, SIGNAL(triggered()), &helper, SLOT(timeout())); QTest::qWait(TIMEOUT_TIMEOUT); QCOMPARE(helper.count, 0); timer->start(); QTest::qWait(TIMEOUT_TIMEOUT); QCOMPARE(helper.count, 1); QTest::qWait(TIMEOUT_TIMEOUT); QCOMPARE(helper.count, 1); } void tst_qmltimer::repeat() { QmlEngine engine; QmlComponent component(&engine, QByteArray("import Qt 4.6\nTimer { interval: 100; repeat: true; running: true }"), QUrl("file://")); QmlTimer *timer = qobject_cast<QmlTimer*>(component.create()); QVERIFY(timer != 0); TimerHelper helper; connect(timer, SIGNAL(triggered()), &helper, SLOT(timeout())); QCOMPARE(helper.count, 0); QTest::qWait(TIMEOUT_TIMEOUT); QVERIFY(helper.count > 0); int oldCount = helper.count; QTest::qWait(TIMEOUT_TIMEOUT); QVERIFY(helper.count > oldCount); } void tst_qmltimer::triggeredOnStart() { QmlEngine engine; QmlComponent component(&engine, QByteArray("import Qt 4.6\nTimer { interval: 100; running: true; triggeredOnStart: true }"), QUrl("file://")); QmlTimer *timer = qobject_cast<QmlTimer*>(component.create()); QVERIFY(timer != 0); TimerHelper helper; connect(timer, SIGNAL(triggered()), &helper, SLOT(timeout())); QTest::qWait(1); QCOMPARE(helper.count, 1); QTest::qWait(TIMEOUT_TIMEOUT); QCOMPARE(helper.count, 2); QTest::qWait(TIMEOUT_TIMEOUT); QCOMPARE(helper.count, 2); } void tst_qmltimer::triggeredOnStartRepeat() { QmlEngine engine; QmlComponent component(&engine, QByteArray("import Qt 4.6\nTimer { interval: 100; running: true; triggeredOnStart: true; repeat: true }"), QUrl("file://")); QmlTimer *timer = qobject_cast<QmlTimer*>(component.create()); QVERIFY(timer != 0); TimerHelper helper; connect(timer, SIGNAL(triggered()), &helper, SLOT(timeout())); QTest::qWait(1); QCOMPARE(helper.count, 1); QTest::qWait(TIMEOUT_TIMEOUT); QVERIFY(helper.count > 1); int oldCount = helper.count; QTest::qWait(TIMEOUT_TIMEOUT); QVERIFY(helper.count > oldCount); } void tst_qmltimer::noTriggerIfNotRunning() { QmlEngine engine; QmlComponent component(&engine, QByteArray( "import Qt 4.6\n" "Item { property bool ok: true\n" "Timer { id: t1; interval: 100; repeat: true; running: true; onTriggered: if (!running) ok=false }" "Timer { interval: 10; running: true; onTriggered: t1.running=false }" "}" ), QUrl("file://")); QObject *item = component.create(); QVERIFY(item != 0); QTest::qWait(TIMEOUT_TIMEOUT); QCOMPARE(item->property("ok").toBool(), true); } QTEST_MAIN(tst_qmltimer) #include "tst_qmltimer.moc" <|endoftext|>
<commit_before>/* * This program is just for personal experiments here on C++ mixin for * handling lifecycle of specific objects. */ // includes for the example program itself #include <fastarduino/tests/assertions.h> #include <fastarduino/uart.h> #include <fastarduino/iomanip.h> #include <fastarduino/flash.h> #include <fastarduino/move.h> #include <fastarduino/lifecycle.h> // Register vector for UART (used for debug) REGISTER_UATX_ISR(0) using namespace streams; using namespace lifecycle; // Define types that output traces on each ctor/dtor/operator= class Value { public: static void set_out(ostream& out) { out_ = &out; } Value(int val = 0) : val_{val} { trace('c'); } ~Value() { trace('d'); } Value(const Value& that) : val_{that.val_} { trace('C'); } Value(Value&& that) : val_{that.val_} { trace('M'); } Value& operator=(const Value& that) { this->val_ = that.val_; trace('='); return *this; } Value& operator=(Value&& that) { this->val_ = that.val_; trace('m'); return *this; } int val() const { return val_; } static ostream& out() { return *out_; } protected: void trace(char method) { if (out_) *out_ << method << dec << val_ << ' ' << hex << this << endl; } static ostream* out_; int val_; }; class SubValue : public Value { public: SubValue(int val = 0, int val2 = 0) : Value{val}, val2_{val2} {} ~SubValue() = default; SubValue(const SubValue& that) = default; SubValue(SubValue&& that) = default; SubValue& operator=(const SubValue& that) = default; SubValue& operator=(SubValue&& that) = default; int val2() const { return val2_; } private: int val2_; }; static constexpr const uint8_t MAX_LC_SLOTS = 32; template<typename T> static void check(ostream& out, AbstractLifeCycleManager& manager, const T& init) { { out << F("0. Instance creation") << endl; LifeCycle<T> instance{init}; assert(out, F("available_slots()"), MAX_LC_SLOTS, manager.available_()); assert(out, F("id() after construction"), 0, instance.id()); out << F("1. Registration") << endl; uint8_t id = manager.register_(instance); assert(out, F("id returned by register_()"), id); assert(out, F("id() after registration"), id, instance.id()); assert(out, F("available_slots()"), MAX_LC_SLOTS - 1, manager.available_()); out << F("2. Find") << endl; LifeCycle<T>* found = manager.find_<T>(id); assert(out, F("manager.find_(id)"), found != nullptr); assert(out, F("manager.find_(id)"), &instance, found); out << F("val=") << dec << found->val() << endl; // Check copy never compiles // LifeCycle<T> copy{instance}; out << F("3. Move constructor") << endl; LifeCycle<T> move = std::move(instance); assert(out, F("original id() after registration"), 0, instance.id()); assert(out, F("moved id() after registration"), id, move.id()); assert(out, F("available_slots()"), MAX_LC_SLOTS - 1, manager.available_()); out << F("4. Find after move") << endl; found = manager.find_<T>(id); assert(out, F("manager.find_(id)"), found != nullptr); assert(out, F("manager.find_(id)"), &move, found); out << F("val=") << dec << found->val() << endl; // Check copy never compiles // LifeCycle<T> copy2; // copy2 = move; out << F("5. Move assignment") << endl; LifeCycle<T> move2; move2 = std::move(move); assert(out, F("original id() after registration"), 0, move.id()); assert(out, F("moved id() after registration"), id, move2.id()); assert(out, F("available_slots()"), MAX_LC_SLOTS - 1, manager.available_()); } // Check destruction out << F("6. Destruction") << endl; assert(out, F("available_slots()"), MAX_LC_SLOTS, manager.available_()); } void check_proxies(ostream& out, AbstractLifeCycleManager& manager) { Value v1{10}; SubValue v2{20, 30}; Proxy<Value> p1{v1}; Proxy<Value> p2{v2}; out << F("p1->val() ") << hex << &p1 << ' ' << dec << p1->val() << endl; out << F("p2->val() ") << hex << &p2 << ' ' << dec << p2->val() << endl; LifeCycle<Value> lc1{v1}; assert(out, F("manager.register_(lc1)"), 1, manager.register_(lc1)); assert(out, F("lc1.id()"), 1, lc1.id()); LifeCycle<SubValue> lc2{v2}; assert(out, F("manager.register_(lc2)"), 2, manager.register_(lc2)); assert(out, F("lc2.id()"), 2, lc2.id()); Proxy<Value> p3{lc1}; out << F("p3.id=") << dec << p3.id() << F(" p3.manager=") << hex << p3.manager() << F(" p3.dest=") << hex << p3.destination() << endl; Proxy<Value> p4{lc2}; out << F("p4.id=") << dec << p4.id() << F(" p4.manager=") << hex << p4.manager() << F(" p4.dest=") << hex << p4.destination() << endl; out << F("p3->val() ") << hex << &p3 << ' ' << dec << p3->val() << endl; out << F("p4->val() ") << hex << &p4 << ' ' << dec << p4->val() << endl; // This shall not compile // Proxy<SubValue> p5{lc1}; } ostream* Value::out_ = nullptr; static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 128; static char output_buffer[OUTPUT_BUFFER_SIZE]; int main() __attribute__((OS_main)); int main() { board::init(); // Enable interrupts at startup time sei(); // Initialize debugging output serial::hard::UATX<board::USART::USART0> uart{output_buffer}; uart.begin(115200); ostream out = uart.out(); out << boolalpha << showbase; out << F("Starting...") << endl; Value::set_out(out); out << F("Create constant Value first") << endl; const Value VAL0 = Value{123}; // Create manager out << F("Instantiate LifeCycleManager") << endl; LifeCycleManager<MAX_LC_SLOTS> manager; // Check available slots assert(out, F("available_slots()"), MAX_LC_SLOTS, manager.available_()); // Check different types T (int, struct, with/without dtor/ctor/op=...) // check<Value>(out, manager, VAL0); check_proxies(out, manager); } <commit_msg>Cleanup comments<commit_after>/* * This program is just for personal experiments here on C++ mixin for * handling lifecycle of specific objects. */ #include <fastarduino/tests/assertions.h> #include <fastarduino/uart.h> #include <fastarduino/iomanip.h> #include <fastarduino/flash.h> #include <fastarduino/move.h> #include <fastarduino/lifecycle.h> // Register vector for UART (used for debug) REGISTER_UATX_ISR(0) using namespace streams; using namespace lifecycle; // Define types that output traces on each ctor/dtor/operator= class Value { public: static void set_out(ostream& out) { out_ = &out; } Value(int val = 0) : val_{val} { trace('c'); } ~Value() { trace('d'); } Value(const Value& that) : val_{that.val_} { trace('C'); } Value(Value&& that) : val_{that.val_} { trace('M'); } Value& operator=(const Value& that) { this->val_ = that.val_; trace('='); return *this; } Value& operator=(Value&& that) { this->val_ = that.val_; trace('m'); return *this; } int val() const { return val_; } static ostream& out() { return *out_; } protected: void trace(char method) { if (out_) *out_ << method << dec << val_ << ' ' << hex << this << endl; } static ostream* out_; int val_; }; class SubValue : public Value { public: SubValue(int val = 0, int val2 = 0) : Value{val}, val2_{val2} {} ~SubValue() = default; SubValue(const SubValue& that) = default; SubValue(SubValue&& that) = default; SubValue& operator=(const SubValue& that) = default; SubValue& operator=(SubValue&& that) = default; int val2() const { return val2_; } private: int val2_; }; static constexpr const uint8_t MAX_LC_SLOTS = 32; template<typename T> static void check(ostream& out, AbstractLifeCycleManager& manager, const T& init) { { out << F("0. Instance creation") << endl; LifeCycle<T> instance{init}; assert(out, F("available_slots()"), MAX_LC_SLOTS, manager.available_()); assert(out, F("id() after construction"), 0, instance.id()); out << F("1. Registration") << endl; uint8_t id = manager.register_(instance); assert(out, F("id returned by register_()"), id); assert(out, F("id() after registration"), id, instance.id()); assert(out, F("available_slots()"), MAX_LC_SLOTS - 1, manager.available_()); out << F("2. Find") << endl; LifeCycle<T>* found = manager.find_<T>(id); assert(out, F("manager.find_(id)"), found != nullptr); assert(out, F("manager.find_(id)"), &instance, found); out << F("val=") << dec << found->val() << endl; // Check copy never compiles // LifeCycle<T> copy{instance}; out << F("3. Move constructor") << endl; LifeCycle<T> move = std::move(instance); assert(out, F("original id() after registration"), 0, instance.id()); assert(out, F("moved id() after registration"), id, move.id()); assert(out, F("available_slots()"), MAX_LC_SLOTS - 1, manager.available_()); out << F("4. Find after move") << endl; found = manager.find_<T>(id); assert(out, F("manager.find_(id)"), found != nullptr); assert(out, F("manager.find_(id)"), &move, found); out << F("val=") << dec << found->val() << endl; // Check copy never compiles // LifeCycle<T> copy2; // copy2 = move; out << F("5. Move assignment") << endl; LifeCycle<T> move2; move2 = std::move(move); assert(out, F("original id() after registration"), 0, move.id()); assert(out, F("moved id() after registration"), id, move2.id()); assert(out, F("available_slots()"), MAX_LC_SLOTS - 1, manager.available_()); } // Check destruction out << F("6. Destruction") << endl; assert(out, F("available_slots()"), MAX_LC_SLOTS, manager.available_()); } void check_proxies(ostream& out, AbstractLifeCycleManager& manager) { Value v1{10}; SubValue v2{20, 30}; Proxy<Value> p1{v1}; Proxy<Value> p2{v2}; out << F("p1->val() ") << hex << &p1 << ' ' << dec << p1->val() << endl; out << F("p2->val() ") << hex << &p2 << ' ' << dec << p2->val() << endl; LifeCycle<Value> lc1{v1}; assert(out, F("manager.register_(lc1)"), 1, manager.register_(lc1)); assert(out, F("lc1.id()"), 1, lc1.id()); LifeCycle<SubValue> lc2{v2}; assert(out, F("manager.register_(lc2)"), 2, manager.register_(lc2)); assert(out, F("lc2.id()"), 2, lc2.id()); Proxy<Value> p3{lc1}; out << F("p3.id=") << dec << p3.id() << F(" p3.manager=") << hex << p3.manager() << F(" p3.dest=") << hex << p3.destination() << endl; Proxy<Value> p4{lc2}; out << F("p4.id=") << dec << p4.id() << F(" p4.manager=") << hex << p4.manager() << F(" p4.dest=") << hex << p4.destination() << endl; out << F("p3->val() ") << hex << &p3 << ' ' << dec << p3->val() << endl; out << F("p4->val() ") << hex << &p4 << ' ' << dec << p4->val() << endl; // This shall not compile // Proxy<SubValue> p5{lc1}; } ostream* Value::out_ = nullptr; static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 128; static char output_buffer[OUTPUT_BUFFER_SIZE]; int main() __attribute__((OS_main)); int main() { board::init(); // Enable interrupts at startup time sei(); // Initialize debugging output serial::hard::UATX<board::USART::USART0> uart{output_buffer}; uart.begin(115200); ostream out = uart.out(); out << boolalpha << showbase; out << F("Starting...") << endl; Value::set_out(out); out << F("Create constant Value first") << endl; const Value VAL0 = Value{123}; // Create manager out << F("Instantiate LifeCycleManager") << endl; LifeCycleManager<MAX_LC_SLOTS> manager; // Check available slots assert(out, F("available_slots()"), MAX_LC_SLOTS, manager.available_()); // Check different types T (int, struct, with/without dtor/ctor/op=...) // check<Value>(out, manager, VAL0); check_proxies(out, manager); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Kurt Pattyn <pattyn.kurt@gmail.com>. ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtWebSockets module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qwebsocketserver.h" #include "qwebsocketserver_p.h" #ifndef QT_NO_SSL #include "qsslserver_p.h" #endif #include "qwebsocketprotocol.h" #include "qwebsockethandshakerequest_p.h" #include "qwebsockethandshakeresponse_p.h" #include "qwebsocket.h" #include "qwebsocket_p.h" #include "qwebsocketcorsauthenticator.h" #include <QtNetwork/QTcpServer> #include <QtNetwork/QTcpSocket> #include <QtNetwork/QNetworkProxy> QT_BEGIN_NAMESPACE /*! \internal */ QWebSocketServerPrivate::QWebSocketServerPrivate(const QString &serverName, QWebSocketServerPrivate::SslMode secureMode, QWebSocketServer * const pWebSocketServer) : QObjectPrivate(), q_ptr(pWebSocketServer), m_pTcpServer(Q_NULLPTR), m_serverName(serverName), m_secureMode(secureMode), m_pendingConnections(), m_error(QWebSocketProtocol::CloseCodeNormal), m_errorString(), m_maxPendingConnections(30) { Q_ASSERT(pWebSocketServer); } /*! \internal */ void QWebSocketServerPrivate::init() { if (m_secureMode == NonSecureMode) { m_pTcpServer = new QTcpServer(); if (Q_LIKELY(m_pTcpServer)) QObjectPrivate::connect(m_pTcpServer, &QTcpServer::newConnection, this, &QWebSocketServerPrivate::onNewConnection); else qFatal("Could not allocate memory for tcp server."); } else { #ifndef QT_NO_SSL QSslServer *pSslServer = new QSslServer(); m_pTcpServer = pSslServer; if (Q_LIKELY(m_pTcpServer)) { QObjectPrivate::connect(pSslServer, &QSslServer::newEncryptedConnection, this, &QWebSocketServerPrivate::onNewConnection, Qt::QueuedConnection); QObject::connect(pSslServer, &QSslServer::peerVerifyError, q_ptr, &QWebSocketServer::peerVerifyError); QObject::connect(pSslServer, &QSslServer::sslErrors, q_ptr, &QWebSocketServer::sslErrors); } #else qFatal("SSL not supported on this platform."); #endif } QObject::connect(m_pTcpServer, &QTcpServer::acceptError, q_ptr, &QWebSocketServer::acceptError); } /*! \internal */ QWebSocketServerPrivate::~QWebSocketServerPrivate() { close(true); m_pTcpServer->deleteLater(); } /*! \internal */ void QWebSocketServerPrivate::close(bool aboutToDestroy) { Q_Q(QWebSocketServer); m_pTcpServer->close(); while (!m_pendingConnections.isEmpty()) { QWebSocket *pWebSocket = m_pendingConnections.dequeue(); pWebSocket->close(QWebSocketProtocol::CloseCodeGoingAway, QWebSocketServer::tr("Server closed.")); pWebSocket->deleteLater(); } if (!aboutToDestroy) { //emit signal via the event queue, so the server gets time //to process any hanging events, like flushing buffers aso QMetaObject::invokeMethod(q, "closed", Qt::QueuedConnection); } } /*! \internal */ QString QWebSocketServerPrivate::errorString() const { if (m_errorString.isEmpty()) return m_pTcpServer->errorString(); else return m_errorString; } /*! \internal */ bool QWebSocketServerPrivate::hasPendingConnections() const { return !m_pendingConnections.isEmpty(); } /*! \internal */ bool QWebSocketServerPrivate::isListening() const { return m_pTcpServer->isListening(); } /*! \internal */ bool QWebSocketServerPrivate::listen(const QHostAddress &address, quint16 port) { bool success = m_pTcpServer->listen(address, port); if (!success) setErrorFromSocketError(m_pTcpServer->serverError(), m_pTcpServer->errorString()); return success; } /*! \internal */ int QWebSocketServerPrivate::maxPendingConnections() const { return m_maxPendingConnections; } /*! \internal */ void QWebSocketServerPrivate::addPendingConnection(QWebSocket *pWebSocket) { if (m_pendingConnections.size() < maxPendingConnections()) m_pendingConnections.enqueue(pWebSocket); } /*! \internal */ void QWebSocketServerPrivate::setErrorFromSocketError(QAbstractSocket::SocketError error, const QString &errorDescription) { Q_UNUSED(error); setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection, errorDescription); } /*! \internal */ QWebSocket *QWebSocketServerPrivate::nextPendingConnection() { QWebSocket *pWebSocket = Q_NULLPTR; if (Q_LIKELY(!m_pendingConnections.isEmpty())) pWebSocket = m_pendingConnections.dequeue(); return pWebSocket; } /*! \internal */ void QWebSocketServerPrivate::pauseAccepting() { m_pTcpServer->pauseAccepting(); } #ifndef QT_NO_NETWORKPROXY /*! \internal */ QNetworkProxy QWebSocketServerPrivate::proxy() const { return m_pTcpServer->proxy(); } /*! \internal */ void QWebSocketServerPrivate::setProxy(const QNetworkProxy &networkProxy) { m_pTcpServer->setProxy(networkProxy); } #endif /*! \internal */ void QWebSocketServerPrivate::resumeAccepting() { m_pTcpServer->resumeAccepting(); } /*! \internal */ QHostAddress QWebSocketServerPrivate::serverAddress() const { return m_pTcpServer->serverAddress(); } /*! \internal */ QWebSocketProtocol::CloseCode QWebSocketServerPrivate::serverError() const { return m_error; } /*! \internal */ quint16 QWebSocketServerPrivate::serverPort() const { return m_pTcpServer->serverPort(); } /*! \internal */ void QWebSocketServerPrivate::setMaxPendingConnections(int numConnections) { if (m_pTcpServer->maxPendingConnections() <= numConnections) m_pTcpServer->setMaxPendingConnections(numConnections + 1); m_maxPendingConnections = numConnections; } /*! \internal */ bool QWebSocketServerPrivate::setSocketDescriptor(qintptr socketDescriptor) { return m_pTcpServer->setSocketDescriptor(socketDescriptor); } /*! \internal */ qintptr QWebSocketServerPrivate::socketDescriptor() const { return m_pTcpServer->socketDescriptor(); } /*! \internal */ QList<QWebSocketProtocol::Version> QWebSocketServerPrivate::supportedVersions() const { QList<QWebSocketProtocol::Version> supportedVersions; supportedVersions << QWebSocketProtocol::currentVersion(); //we only support V13 return supportedVersions; } /*! \internal */ QStringList QWebSocketServerPrivate::supportedProtocols() const { QStringList supportedProtocols; return supportedProtocols; //no protocols are currently supported } /*! \internal */ QStringList QWebSocketServerPrivate::supportedExtensions() const { QStringList supportedExtensions; return supportedExtensions; //no extensions are currently supported } /*! \internal */ void QWebSocketServerPrivate::setServerName(const QString &serverName) { if (m_serverName != serverName) m_serverName = serverName; } /*! \internal */ QString QWebSocketServerPrivate::serverName() const { return m_serverName; } /*! \internal */ QWebSocketServerPrivate::SslMode QWebSocketServerPrivate::secureMode() const { return m_secureMode; } #ifndef QT_NO_SSL void QWebSocketServerPrivate::setSslConfiguration(const QSslConfiguration &sslConfiguration) { if (m_secureMode == SecureMode) qobject_cast<QSslServer *>(m_pTcpServer)->setSslConfiguration(sslConfiguration); } QSslConfiguration QWebSocketServerPrivate::sslConfiguration() const { if (m_secureMode == SecureMode) return qobject_cast<QSslServer *>(m_pTcpServer)->sslConfiguration(); else return QSslConfiguration::defaultConfiguration(); } #endif void QWebSocketServerPrivate::setError(QWebSocketProtocol::CloseCode code, const QString &errorString) { if ((m_error != code) || (m_errorString != errorString)) { Q_Q(QWebSocketServer); m_error = code; m_errorString = errorString; Q_EMIT q->serverError(code); } } /*! \internal */ void QWebSocketServerPrivate::onNewConnection() { QTcpSocket *pTcpSocket = m_pTcpServer->nextPendingConnection(); //use a queued connection because a QSslSocket //needs the event loop to process incoming data //if not queued, data is incomplete when handshakeReceived is called QObjectPrivate::connect(pTcpSocket, &QTcpSocket::readyRead, this, &QWebSocketServerPrivate::handshakeReceived, Qt::QueuedConnection); } /*! \internal */ void QWebSocketServerPrivate::onCloseConnection() { if (Q_LIKELY(currentSender)) { QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(currentSender->sender); if (Q_LIKELY(pTcpSocket)) pTcpSocket->close(); } } /*! \internal */ void QWebSocketServerPrivate::handshakeReceived() { if (Q_UNLIKELY(!currentSender)) { qWarning() << QWebSocketServer::tr("Sender is NULL. This is a Qt bug."); return; } QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(currentSender->sender); if (Q_UNLIKELY(!pTcpSocket)) { qWarning() << QWebSocketServer::tr("Sender is not a QTcpSocket. This is a Qt bug!!!"); return; } //When using Google Chrome the handshake in received in two parts. //Therefore, the readyRead signal is emitted twice. //This is a guard against the BEAST attack. //See: https://www.imperialviolet.org/2012/01/15/beastfollowup.html //For Safari, the handshake is delivered at once //FIXME: For FireFox, the readyRead signal is never emitted //This is a bug in FireFox (see https://bugzilla.mozilla.org/show_bug.cgi?id=594502) if (!pTcpSocket->canReadLine()) { return; } disconnect(pTcpSocket, &QTcpSocket::readyRead, this, &QWebSocketServerPrivate::handshakeReceived); Q_Q(QWebSocketServer); bool success = false; bool isSecure = false; if (m_pendingConnections.length() >= maxPendingConnections()) { pTcpSocket->close(); pTcpSocket->deleteLater(); qWarning() << QWebSocketServer::tr("Too many pending connections: " \ "New WebSocket connection not accepted."); setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection, QWebSocketServer::tr("Too many pending connections.")); return; } QWebSocketHandshakeRequest request(pTcpSocket->peerPort(), isSecure); QTextStream textStream(pTcpSocket); request.readHandshake(textStream); if (request.isValid()) { QWebSocketCorsAuthenticator corsAuthenticator(request.origin()); Q_EMIT q->originAuthenticationRequired(&corsAuthenticator); QWebSocketHandshakeResponse response(request, m_serverName, corsAuthenticator.allowed(), supportedVersions(), supportedProtocols(), supportedExtensions()); if (response.isValid()) { QTextStream httpStream(pTcpSocket); httpStream << response; httpStream.flush(); if (response.canUpgrade()) { QWebSocket *pWebSocket = QWebSocketPrivate::upgradeFrom(pTcpSocket, request, response); if (pWebSocket) { addPendingConnection(pWebSocket); Q_EMIT q->newConnection(); success = true; } else { setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection, QWebSocketServer::tr("Upgrade to WebSocket failed.")); } } else { setError(response.error(), response.errorString()); } } else { setError(QWebSocketProtocol::CloseCodeProtocolError, QWebSocketServer::tr("Invalid response received.")); } } if (!success) { qWarning() << QWebSocketServer::tr("Closing socket because of invalid or unsupported request."); pTcpSocket->close(); } } QT_END_NAMESPACE <commit_msg>Remove superfluous qWarning statements<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Kurt Pattyn <pattyn.kurt@gmail.com>. ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtWebSockets module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qwebsocketserver.h" #include "qwebsocketserver_p.h" #ifndef QT_NO_SSL #include "qsslserver_p.h" #endif #include "qwebsocketprotocol.h" #include "qwebsockethandshakerequest_p.h" #include "qwebsockethandshakeresponse_p.h" #include "qwebsocket.h" #include "qwebsocket_p.h" #include "qwebsocketcorsauthenticator.h" #include <QtNetwork/QTcpServer> #include <QtNetwork/QTcpSocket> #include <QtNetwork/QNetworkProxy> QT_BEGIN_NAMESPACE /*! \internal */ QWebSocketServerPrivate::QWebSocketServerPrivate(const QString &serverName, QWebSocketServerPrivate::SslMode secureMode, QWebSocketServer * const pWebSocketServer) : QObjectPrivate(), q_ptr(pWebSocketServer), m_pTcpServer(Q_NULLPTR), m_serverName(serverName), m_secureMode(secureMode), m_pendingConnections(), m_error(QWebSocketProtocol::CloseCodeNormal), m_errorString(), m_maxPendingConnections(30) { Q_ASSERT(pWebSocketServer); } /*! \internal */ void QWebSocketServerPrivate::init() { if (m_secureMode == NonSecureMode) { m_pTcpServer = new QTcpServer(); if (Q_LIKELY(m_pTcpServer)) QObjectPrivate::connect(m_pTcpServer, &QTcpServer::newConnection, this, &QWebSocketServerPrivate::onNewConnection); else qFatal("Could not allocate memory for tcp server."); } else { #ifndef QT_NO_SSL QSslServer *pSslServer = new QSslServer(); m_pTcpServer = pSslServer; if (Q_LIKELY(m_pTcpServer)) { QObjectPrivate::connect(pSslServer, &QSslServer::newEncryptedConnection, this, &QWebSocketServerPrivate::onNewConnection, Qt::QueuedConnection); QObject::connect(pSslServer, &QSslServer::peerVerifyError, q_ptr, &QWebSocketServer::peerVerifyError); QObject::connect(pSslServer, &QSslServer::sslErrors, q_ptr, &QWebSocketServer::sslErrors); } #else qFatal("SSL not supported on this platform."); #endif } QObject::connect(m_pTcpServer, &QTcpServer::acceptError, q_ptr, &QWebSocketServer::acceptError); } /*! \internal */ QWebSocketServerPrivate::~QWebSocketServerPrivate() { close(true); m_pTcpServer->deleteLater(); } /*! \internal */ void QWebSocketServerPrivate::close(bool aboutToDestroy) { Q_Q(QWebSocketServer); m_pTcpServer->close(); while (!m_pendingConnections.isEmpty()) { QWebSocket *pWebSocket = m_pendingConnections.dequeue(); pWebSocket->close(QWebSocketProtocol::CloseCodeGoingAway, QWebSocketServer::tr("Server closed.")); pWebSocket->deleteLater(); } if (!aboutToDestroy) { //emit signal via the event queue, so the server gets time //to process any hanging events, like flushing buffers aso QMetaObject::invokeMethod(q, "closed", Qt::QueuedConnection); } } /*! \internal */ QString QWebSocketServerPrivate::errorString() const { if (m_errorString.isEmpty()) return m_pTcpServer->errorString(); else return m_errorString; } /*! \internal */ bool QWebSocketServerPrivate::hasPendingConnections() const { return !m_pendingConnections.isEmpty(); } /*! \internal */ bool QWebSocketServerPrivate::isListening() const { return m_pTcpServer->isListening(); } /*! \internal */ bool QWebSocketServerPrivate::listen(const QHostAddress &address, quint16 port) { bool success = m_pTcpServer->listen(address, port); if (!success) setErrorFromSocketError(m_pTcpServer->serverError(), m_pTcpServer->errorString()); return success; } /*! \internal */ int QWebSocketServerPrivate::maxPendingConnections() const { return m_maxPendingConnections; } /*! \internal */ void QWebSocketServerPrivate::addPendingConnection(QWebSocket *pWebSocket) { if (m_pendingConnections.size() < maxPendingConnections()) m_pendingConnections.enqueue(pWebSocket); } /*! \internal */ void QWebSocketServerPrivate::setErrorFromSocketError(QAbstractSocket::SocketError error, const QString &errorDescription) { Q_UNUSED(error); setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection, errorDescription); } /*! \internal */ QWebSocket *QWebSocketServerPrivate::nextPendingConnection() { QWebSocket *pWebSocket = Q_NULLPTR; if (Q_LIKELY(!m_pendingConnections.isEmpty())) pWebSocket = m_pendingConnections.dequeue(); return pWebSocket; } /*! \internal */ void QWebSocketServerPrivate::pauseAccepting() { m_pTcpServer->pauseAccepting(); } #ifndef QT_NO_NETWORKPROXY /*! \internal */ QNetworkProxy QWebSocketServerPrivate::proxy() const { return m_pTcpServer->proxy(); } /*! \internal */ void QWebSocketServerPrivate::setProxy(const QNetworkProxy &networkProxy) { m_pTcpServer->setProxy(networkProxy); } #endif /*! \internal */ void QWebSocketServerPrivate::resumeAccepting() { m_pTcpServer->resumeAccepting(); } /*! \internal */ QHostAddress QWebSocketServerPrivate::serverAddress() const { return m_pTcpServer->serverAddress(); } /*! \internal */ QWebSocketProtocol::CloseCode QWebSocketServerPrivate::serverError() const { return m_error; } /*! \internal */ quint16 QWebSocketServerPrivate::serverPort() const { return m_pTcpServer->serverPort(); } /*! \internal */ void QWebSocketServerPrivate::setMaxPendingConnections(int numConnections) { if (m_pTcpServer->maxPendingConnections() <= numConnections) m_pTcpServer->setMaxPendingConnections(numConnections + 1); m_maxPendingConnections = numConnections; } /*! \internal */ bool QWebSocketServerPrivate::setSocketDescriptor(qintptr socketDescriptor) { return m_pTcpServer->setSocketDescriptor(socketDescriptor); } /*! \internal */ qintptr QWebSocketServerPrivate::socketDescriptor() const { return m_pTcpServer->socketDescriptor(); } /*! \internal */ QList<QWebSocketProtocol::Version> QWebSocketServerPrivate::supportedVersions() const { QList<QWebSocketProtocol::Version> supportedVersions; supportedVersions << QWebSocketProtocol::currentVersion(); //we only support V13 return supportedVersions; } /*! \internal */ QStringList QWebSocketServerPrivate::supportedProtocols() const { QStringList supportedProtocols; return supportedProtocols; //no protocols are currently supported } /*! \internal */ QStringList QWebSocketServerPrivate::supportedExtensions() const { QStringList supportedExtensions; return supportedExtensions; //no extensions are currently supported } /*! \internal */ void QWebSocketServerPrivate::setServerName(const QString &serverName) { if (m_serverName != serverName) m_serverName = serverName; } /*! \internal */ QString QWebSocketServerPrivate::serverName() const { return m_serverName; } /*! \internal */ QWebSocketServerPrivate::SslMode QWebSocketServerPrivate::secureMode() const { return m_secureMode; } #ifndef QT_NO_SSL void QWebSocketServerPrivate::setSslConfiguration(const QSslConfiguration &sslConfiguration) { if (m_secureMode == SecureMode) qobject_cast<QSslServer *>(m_pTcpServer)->setSslConfiguration(sslConfiguration); } QSslConfiguration QWebSocketServerPrivate::sslConfiguration() const { if (m_secureMode == SecureMode) return qobject_cast<QSslServer *>(m_pTcpServer)->sslConfiguration(); else return QSslConfiguration::defaultConfiguration(); } #endif void QWebSocketServerPrivate::setError(QWebSocketProtocol::CloseCode code, const QString &errorString) { if ((m_error != code) || (m_errorString != errorString)) { Q_Q(QWebSocketServer); m_error = code; m_errorString = errorString; Q_EMIT q->serverError(code); } } /*! \internal */ void QWebSocketServerPrivate::onNewConnection() { QTcpSocket *pTcpSocket = m_pTcpServer->nextPendingConnection(); //use a queued connection because a QSslSocket //needs the event loop to process incoming data //if not queued, data is incomplete when handshakeReceived is called QObjectPrivate::connect(pTcpSocket, &QTcpSocket::readyRead, this, &QWebSocketServerPrivate::handshakeReceived, Qt::QueuedConnection); } /*! \internal */ void QWebSocketServerPrivate::onCloseConnection() { if (Q_LIKELY(currentSender)) { QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(currentSender->sender); if (Q_LIKELY(pTcpSocket)) pTcpSocket->close(); } } /*! \internal */ void QWebSocketServerPrivate::handshakeReceived() { if (Q_UNLIKELY(!currentSender)) { return; } QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(currentSender->sender); if (Q_UNLIKELY(!pTcpSocket)) { return; } //When using Google Chrome the handshake in received in two parts. //Therefore, the readyRead signal is emitted twice. //This is a guard against the BEAST attack. //See: https://www.imperialviolet.org/2012/01/15/beastfollowup.html //For Safari, the handshake is delivered at once //FIXME: For FireFox, the readyRead signal is never emitted //This is a bug in FireFox (see https://bugzilla.mozilla.org/show_bug.cgi?id=594502) if (!pTcpSocket->canReadLine()) { return; } disconnect(pTcpSocket, &QTcpSocket::readyRead, this, &QWebSocketServerPrivate::handshakeReceived); Q_Q(QWebSocketServer); bool success = false; bool isSecure = false; if (m_pendingConnections.length() >= maxPendingConnections()) { pTcpSocket->close(); pTcpSocket->deleteLater(); setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection, QWebSocketServer::tr("Too many pending connections.")); return; } QWebSocketHandshakeRequest request(pTcpSocket->peerPort(), isSecure); QTextStream textStream(pTcpSocket); request.readHandshake(textStream); if (request.isValid()) { QWebSocketCorsAuthenticator corsAuthenticator(request.origin()); Q_EMIT q->originAuthenticationRequired(&corsAuthenticator); QWebSocketHandshakeResponse response(request, m_serverName, corsAuthenticator.allowed(), supportedVersions(), supportedProtocols(), supportedExtensions()); if (response.isValid()) { QTextStream httpStream(pTcpSocket); httpStream << response; httpStream.flush(); if (response.canUpgrade()) { QWebSocket *pWebSocket = QWebSocketPrivate::upgradeFrom(pTcpSocket, request, response); if (pWebSocket) { addPendingConnection(pWebSocket); Q_EMIT q->newConnection(); success = true; } else { setError(QWebSocketProtocol::CloseCodeAbnormalDisconnection, QWebSocketServer::tr("Upgrade to WebSocket failed.")); } } else { setError(response.error(), response.errorString()); } } else { setError(QWebSocketProtocol::CloseCodeProtocolError, QWebSocketServer::tr("Invalid response received.")); } } if (!success) { pTcpSocket->close(); } } QT_END_NAMESPACE <|endoftext|>
<commit_before>/* Copyright (c) 2007, Un Shyam All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <algorithm> #include <iostream> #include "libtorrent/hasher.hpp" #include "libtorrent/pe_crypto.hpp" #include "libtorrent/session.hpp" #include "setup_transfer.hpp" #include "test.hpp" #ifndef TORRENT_DISABLE_ENCRYPTION char const* pe_policy(libtorrent::pe_settings::enc_policy policy) { using namespace libtorrent; if (policy == pe_settings::disabled) return "disabled"; else if (policy == pe_settings::enabled) return "enabled"; else if (policy == pe_settings::forced) return "forced"; return "unknown"; } void display_pe_settings(libtorrent::pe_settings s) { using namespace libtorrent; fprintf(stderr, "out_enc_policy - %s\tin_enc_policy - %s\n" , pe_policy(s.out_enc_policy), pe_policy(s.in_enc_policy)); fprintf(stderr, "enc_level - %s\t\tprefer_rc4 - %s\n" , s.allowed_enc_level == pe_settings::plaintext ? "plaintext" : s.allowed_enc_level == pe_settings::rc4 ? "rc4" : s.allowed_enc_level == pe_settings::both ? "both" : "unknown" , s.prefer_rc4 ? "true": "false"); } void test_transfer(libtorrent::pe_settings::enc_policy policy, libtorrent::pe_settings::enc_level level = libtorrent::pe_settings::both, bool pref_rc4 = false) { using namespace libtorrent; // these are declared before the session objects // so that they are destructed last. This enables // the sessions to destruct in parallel session_proxy p1; session_proxy p2; session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48800, 49000), "0.0.0.0", 0); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49800, 50000), "0.0.0.0", 0); pe_settings s; s.out_enc_policy = libtorrent::pe_settings::enabled; s.in_enc_policy = libtorrent::pe_settings::enabled; s.allowed_enc_level = pe_settings::both; ses2.set_pe_settings(s); s.out_enc_policy = policy; s.in_enc_policy = policy; s.allowed_enc_level = level; s.prefer_rc4 = pref_rc4; ses1.set_pe_settings(s); s = ses1.get_pe_settings(); fprintf(stderr, " Session1 \n"); display_pe_settings(s); s = ses2.get_pe_settings(); fprintf(stderr, " Session2 \n"); display_pe_settings(s); torrent_handle tor1; torrent_handle tor2; using boost::tuples::ignore; boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0, true, false, true , "_pe", 16 * 1024, 0, false, 0, true); fprintf(stderr, "waiting for transfer to complete\n"); for (int i = 0; i < 50; ++i) { torrent_status s = tor2.status(); print_alerts(ses1, "ses1"); print_alerts(ses2, "ses2"); if (s.is_seeding) break; test_sleep(1000); } TEST_CHECK(tor2.status().is_seeding); if (tor2.status().is_seeding) fprintf(stderr, "done\n"); ses1.remove_torrent(tor1); ses2.remove_torrent(tor2); // this allows shutting down the sessions in parallel p1 = ses1.abort(); p2 = ses2.abort(); error_code ec; remove_all("tmp1_pe", ec); remove_all("tmp2_pe", ec); remove_all("tmp3_pe", ec); } void test_enc_handler(libtorrent::encryption_handler* a, libtorrent::encryption_handler* b) { int repcount = 128; for (int rep = 0; rep < repcount; ++rep) { std::size_t buf_len = rand() % (512 * 1024); char* buf = new char[buf_len]; char* cmp_buf = new char[buf_len]; std::generate(buf, buf + buf_len, &std::rand); std::memcpy(cmp_buf, buf, buf_len); a->encrypt(buf, buf_len); TEST_CHECK(!std::equal(buf, buf + buf_len, cmp_buf)); b->decrypt(buf, buf_len); TEST_CHECK(std::equal(buf, buf + buf_len, cmp_buf)); b->encrypt(buf, buf_len); TEST_CHECK(!std::equal(buf, buf + buf_len, cmp_buf)); a->decrypt(buf, buf_len); TEST_CHECK(std::equal(buf, buf + buf_len, cmp_buf)); delete[] buf; delete[] cmp_buf; } } #endif int test_main() { using namespace libtorrent; #ifndef TORRENT_DISABLE_ENCRYPTION int repcount = 128; for (int rep = 0; rep < repcount; ++rep) { dh_key_exchange DH1, DH2; DH1.compute_secret(DH2.get_local_key()); DH2.compute_secret(DH1.get_local_key()); TEST_CHECK(std::equal(DH1.get_secret(), DH1.get_secret() + 96, DH2.get_secret())); } dh_key_exchange DH1, DH2; DH1.compute_secret(DH2.get_local_key()); DH2.compute_secret(DH1.get_local_key()); TEST_CHECK(std::equal(DH1.get_secret(), DH1.get_secret() + 96, DH2.get_secret())); sha1_hash test1_key = hasher("test1_key",8).final(); sha1_hash test2_key = hasher("test2_key",8).final(); fprintf(stderr, "testing RC4 handler\n"); rc4_handler rc41; rc41.set_incoming_key(&test2_key[0], 20); rc41.set_outgoing_key(&test1_key[0], 20); rc4_handler rc42; rc42.set_incoming_key(&test1_key[0], 20); rc42.set_outgoing_key(&test2_key[0], 20); test_enc_handler(&rc41, &rc42); test_transfer(pe_settings::disabled); test_transfer(pe_settings::forced, pe_settings::plaintext); test_transfer(pe_settings::forced, pe_settings::rc4); test_transfer(pe_settings::forced, pe_settings::both, false); test_transfer(pe_settings::forced, pe_settings::both, true); test_transfer(pe_settings::enabled, pe_settings::plaintext); test_transfer(pe_settings::enabled, pe_settings::rc4); test_transfer(pe_settings::enabled, pe_settings::both, false); test_transfer(pe_settings::enabled, pe_settings::both, true); #else fprintf(stderr, "PE test not run because it's disabled\n"); #endif return 0; } <commit_msg>attempt to make test_pe_crypto pass under valgrind in reasonable time<commit_after>/* Copyright (c) 2007, Un Shyam All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <algorithm> #include <iostream> #include "libtorrent/hasher.hpp" #include "libtorrent/pe_crypto.hpp" #include "libtorrent/session.hpp" #include "setup_transfer.hpp" #include "test.hpp" #ifndef TORRENT_DISABLE_ENCRYPTION char const* pe_policy(libtorrent::pe_settings::enc_policy policy) { using namespace libtorrent; if (policy == pe_settings::disabled) return "disabled"; else if (policy == pe_settings::enabled) return "enabled"; else if (policy == pe_settings::forced) return "forced"; return "unknown"; } void display_pe_settings(libtorrent::pe_settings s) { using namespace libtorrent; fprintf(stderr, "out_enc_policy - %s\tin_enc_policy - %s\n" , pe_policy(s.out_enc_policy), pe_policy(s.in_enc_policy)); fprintf(stderr, "enc_level - %s\t\tprefer_rc4 - %s\n" , s.allowed_enc_level == pe_settings::plaintext ? "plaintext" : s.allowed_enc_level == pe_settings::rc4 ? "rc4" : s.allowed_enc_level == pe_settings::both ? "both" : "unknown" , s.prefer_rc4 ? "true": "false"); } void test_transfer(libtorrent::pe_settings::enc_policy policy , int timeout , libtorrent::pe_settings::enc_level level = libtorrent::pe_settings::both , bool pref_rc4 = false) { using namespace libtorrent; // these are declared before the session objects // so that they are destructed last. This enables // the sessions to destruct in parallel session_proxy p1; session_proxy p2; session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48800, 49000), "0.0.0.0", 0); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49800, 50000), "0.0.0.0", 0); pe_settings s; s.out_enc_policy = libtorrent::pe_settings::enabled; s.in_enc_policy = libtorrent::pe_settings::enabled; s.allowed_enc_level = pe_settings::both; ses2.set_pe_settings(s); s.out_enc_policy = policy; s.in_enc_policy = policy; s.allowed_enc_level = level; s.prefer_rc4 = pref_rc4; ses1.set_pe_settings(s); s = ses1.get_pe_settings(); fprintf(stderr, " Session1 \n"); display_pe_settings(s); s = ses2.get_pe_settings(); fprintf(stderr, " Session2 \n"); display_pe_settings(s); torrent_handle tor1; torrent_handle tor2; using boost::tuples::ignore; boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0, true, false, true , "_pe", 16 * 1024, 0, false, 0, true); fprintf(stderr, "waiting for transfer to complete\n"); for (int i = 0; i < timeout * 10; ++i) { torrent_status s = tor2.status(); print_alerts(ses1, "ses1"); print_alerts(ses2, "ses2"); if (s.is_seeding) break; test_sleep(100); } TEST_CHECK(tor2.status().is_seeding); if (tor2.status().is_seeding) fprintf(stderr, "done\n"); ses1.remove_torrent(tor1); ses2.remove_torrent(tor2); // this allows shutting down the sessions in parallel p1 = ses1.abort(); p2 = ses2.abort(); error_code ec; remove_all("tmp1_pe", ec); remove_all("tmp2_pe", ec); remove_all("tmp3_pe", ec); } void test_enc_handler(libtorrent::encryption_handler* a, libtorrent::encryption_handler* b) { #ifdef TORRENT_USE_VALGRIND const int repcount = 10; #else const int repcount = 128; #endif for (int rep = 0; rep < repcount; ++rep) { std::size_t buf_len = rand() % (512 * 1024); char* buf = new char[buf_len]; char* cmp_buf = new char[buf_len]; std::generate(buf, buf + buf_len, &std::rand); std::memcpy(cmp_buf, buf, buf_len); a->encrypt(buf, buf_len); TEST_CHECK(!std::equal(buf, buf + buf_len, cmp_buf)); b->decrypt(buf, buf_len); TEST_CHECK(std::equal(buf, buf + buf_len, cmp_buf)); b->encrypt(buf, buf_len); TEST_CHECK(!std::equal(buf, buf + buf_len, cmp_buf)); a->decrypt(buf, buf_len); TEST_CHECK(std::equal(buf, buf + buf_len, cmp_buf)); delete[] buf; delete[] cmp_buf; } } #endif int test_main() { using namespace libtorrent; #ifndef TORRENT_DISABLE_ENCRYPTION #ifdef TORRENT_USE_VALGRIND const int repcount = 10; #else const int repcount = 128; #endif for (int rep = 0; rep < repcount; ++rep) { dh_key_exchange DH1, DH2; DH1.compute_secret(DH2.get_local_key()); DH2.compute_secret(DH1.get_local_key()); TEST_CHECK(std::equal(DH1.get_secret(), DH1.get_secret() + 96, DH2.get_secret())); } dh_key_exchange DH1, DH2; DH1.compute_secret(DH2.get_local_key()); DH2.compute_secret(DH1.get_local_key()); TEST_CHECK(std::equal(DH1.get_secret(), DH1.get_secret() + 96, DH2.get_secret())); sha1_hash test1_key = hasher("test1_key",8).final(); sha1_hash test2_key = hasher("test2_key",8).final(); fprintf(stderr, "testing RC4 handler\n"); rc4_handler rc41; rc41.set_incoming_key(&test2_key[0], 20); rc41.set_outgoing_key(&test1_key[0], 20); rc4_handler rc42; rc42.set_incoming_key(&test1_key[0], 20); rc42.set_outgoing_key(&test2_key[0], 20); test_enc_handler(&rc41, &rc42); #ifdef TORRENT_USE_VALGRIND const int timeout = 10; #else const int timeout = 5; #endif test_transfer(pe_settings::disabled, timeout); test_transfer(pe_settings::forced, timeout, pe_settings::plaintext); test_transfer(pe_settings::forced, timeout, pe_settings::rc4); test_transfer(pe_settings::forced, timeout, pe_settings::both, false); test_transfer(pe_settings::forced, timeout, pe_settings::both, true); test_transfer(pe_settings::enabled, timeout, pe_settings::plaintext); test_transfer(pe_settings::enabled, timeout, pe_settings::rc4); test_transfer(pe_settings::enabled, timeout, pe_settings::both, false); test_transfer(pe_settings::enabled, timeout, pe_settings::both, true); #else fprintf(stderr, "PE test not run because it's disabled\n"); #endif return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2018 Nagisa Sekiguchi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef YDSH_LOGGER_BASE_HPP #define YDSH_LOGGER_BASE_HPP #include <unistd.h> #include <cstring> #include <string> #include <ctime> #include <cstdarg> #include <mutex> #include "resource.hpp" #include "util.hpp" #include "fatal.h" namespace ydsh { enum class LogLevel : unsigned int { INFO, WARNING, ERROR, FATAL, NONE }; inline const char *toString(LogLevel level) { const char *str[] = { "info", "warning", "error", "fatal", "none" }; return str[static_cast<unsigned int>(level)]; } namespace __detail_logger { template<bool T> class LoggerBase { protected: static_assert(T, "not allowed instantiation"); std::string prefix; FilePtr filePtr; LogLevel severity{LogLevel::FATAL}; std::mutex outMutex; /** * if prefix is mepty string, treat as null logger * @param prefix */ explicit LoggerBase(const char *prefix) : prefix(prefix) { this->syncSetting([&]{ this->syncSeverity(); this->syncAppender(); }); } ~LoggerBase() = default; void log(LogLevel level, const char *fmt, va_list list); public: // helper method for logger setting. template <typename Func> void syncSetting(Func func) { std::lock_guard<std::mutex> guard(this->outMutex); func(); } void operator()(LogLevel level, const char *fmt, ...) __attribute__ ((format(printf, 3, 4))) { va_list arg; va_start(arg, fmt); this->log(level, fmt, arg); va_end(arg); } bool enabled(LogLevel level) const { return static_cast<unsigned int>(level) < static_cast<unsigned int>(LogLevel::NONE) && static_cast<unsigned int>(level) >= static_cast<unsigned int>(this->severity); } // not-thread safe api. void syncSeverity(); void syncAppender(); void setAppender(FilePtr &&file) { this->filePtr = std::move(file); } const FilePtr &getAppender() const { return this->filePtr; } }; template <bool T> void LoggerBase<T>::log(LogLevel level, const char *fmt, va_list list) { if(!this->enabled(level)) { return; } // create body char *str = nullptr; if(vasprintf(&str, fmt, list) == -1) { fatal_perror(""); } // create header char header[128]; header[0] = '\0'; time_t timer = time(nullptr); struct tm local{}; tzset(); if(localtime_r(&timer, &local)) { char buf[32]; strftime(buf, arraySize(buf), "%F %T", &local); snprintf(header, arraySize(header), "%s <%s> [%d] ", buf, toString(level), getpid()); } // print body fprintf(this->filePtr.get(), "%s%s\n", header, str); fflush(this->filePtr.get()); free(str); if(level == LogLevel::FATAL) { abort(); } } template <bool T> void LoggerBase<T>::syncSeverity() { if(this->prefix.empty()) { this->severity = LogLevel::NONE; return; } std::string key = this->prefix; key += "_LEVEL"; const char *level = getenv(key.c_str()); if(level != nullptr) { for(auto i = static_cast<unsigned int>(LogLevel::INFO); i < static_cast<unsigned int>(LogLevel::NONE) + 1; i++) { auto s = static_cast<LogLevel>(i); if(strcasecmp(toString(s), level) == 0) { this->severity = s; break; } } } } template <bool T> void LoggerBase<T>::syncAppender() { std::string key = this->prefix; key += "_APPENDER"; const char *appender = getenv(key.c_str()); FilePtr file; if(appender && *appender != '\0') { file = createFilePtr(fopen, appender, "w"); } if(!file) { file = createFilePtr(fdopen, STDERR_FILENO, "w"); } this->setAppender(std::move(file)); } } // namespace __detail_logger using LoggerBase = __detail_logger::LoggerBase<true>; struct NullLogger : public LoggerBase { NullLogger() : LoggerBase("") {} }; template <typename T> class SingletonLogger : public LoggerBase, public Singleton<T> { protected: explicit SingletonLogger(const char *prefix) : LoggerBase(prefix) {} public: static void Info(const char *fmt, ...) __attribute__ ((format(printf, 1, 2))) { va_list arg; va_start(arg, fmt); Singleton<T>::instance().log(LogLevel::INFO, fmt, arg); va_end(arg); } static void Warning(const char *fmt, ...) __attribute__ ((format(printf, 1, 2))) { va_list arg; va_start(arg, fmt); Singleton<T>::instance().log(LogLevel::WARNING, fmt, arg); va_end(arg); } static void Error(const char *fmt, ...) __attribute__ ((format(printf, 1, 2))) { va_list arg; va_start(arg, fmt); Singleton<T>::instance().log(LogLevel::ERROR, fmt, arg); va_end(arg); } static void Fatal(const char *fmt, ...) __attribute__ ((format(printf, 1, 2))) { va_list arg; va_start(arg, fmt); Singleton<T>::instance().log(LogLevel::FATAL, fmt, arg); va_end(arg); } static bool Enabled(LogLevel level) { return Singleton<T>::instance().enabled(level); } }; } // namespace ydsh #endif //YDSH_LOGGER_BASE_HPP <commit_msg>imprive logger<commit_after>/* * Copyright (C) 2018 Nagisa Sekiguchi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef YDSH_LOGGER_BASE_HPP #define YDSH_LOGGER_BASE_HPP #include <unistd.h> #include <cstring> #include <string> #include <ctime> #include <cstdarg> #include <mutex> #include "resource.hpp" #include "util.hpp" #include "fatal.h" namespace ydsh { enum class LogLevel : unsigned int { INFO, WARNING, ERROR, FATAL, NONE }; inline const char *toString(LogLevel level) { const char *str[] = { "info", "warning", "error", "fatal", "none" }; return str[static_cast<unsigned int>(level)]; } namespace __detail_logger { template<bool T> class LoggerBase { protected: static_assert(T, "not allowed instantiation"); std::string prefix; FilePtr filePtr; LogLevel severity{LogLevel::FATAL}; std::mutex outMutex; /** * if prefix is mepty string, treat as null logger * @param prefix */ explicit LoggerBase(const char *prefix) : prefix(prefix) { this->syncSetting([&]{ this->syncSeverityWithEnv(); this->syncAppenderWithEnv(); }); } ~LoggerBase() = default; void log(LogLevel level, const char *fmt, va_list list); public: // helper method for logger setting. template <typename Func> void syncSetting(Func func) { std::lock_guard<std::mutex> guard(this->outMutex); func(); } void operator()(LogLevel level, const char *fmt, ...) __attribute__ ((format(printf, 3, 4))) { va_list arg; va_start(arg, fmt); this->log(level, fmt, arg); va_end(arg); } bool enabled(LogLevel level) const { return static_cast<unsigned int>(level) < static_cast<unsigned int>(LogLevel::NONE) && static_cast<unsigned int>(level) >= static_cast<unsigned int>(this->severity); } // not-thread safe api. void syncSeverityWithEnv(); void setSeverity(LogLevel level) { this->severity = level; } void syncAppenderWithEnv(); void setAppender(FilePtr &&file) { this->filePtr = std::move(file); } const FilePtr &getAppender() const { return this->filePtr; } }; template <bool T> void LoggerBase<T>::log(LogLevel level, const char *fmt, va_list list) { if(!this->enabled(level)) { return; } // create body char *str = nullptr; if(vasprintf(&str, fmt, list) == -1) { fatal_perror(""); } // create header char header[128]; header[0] = '\0'; time_t timer = time(nullptr); struct tm local{}; tzset(); if(localtime_r(&timer, &local)) { char buf[32]; strftime(buf, arraySize(buf), "%F %T", &local); snprintf(header, arraySize(header), "%s <%s> [%d] ", buf, toString(level), getpid()); } // print body fprintf(this->filePtr.get(), "%s%s\n", header, str); fflush(this->filePtr.get()); free(str); if(level == LogLevel::FATAL) { abort(); } } template <bool T> void LoggerBase<T>::syncSeverityWithEnv() { if(this->prefix.empty()) { this->setSeverity(LogLevel::NONE); return; } std::string key = this->prefix; key += "_LEVEL"; const char *level = getenv(key.c_str()); if(level != nullptr) { for(auto i = static_cast<unsigned int>(LogLevel::INFO); i < static_cast<unsigned int>(LogLevel::NONE) + 1; i++) { auto s = static_cast<LogLevel>(i); if(strcasecmp(toString(s), level) == 0) { this->setSeverity(s); return; } } } } template <bool T> void LoggerBase<T>::syncAppenderWithEnv() { std::string key = this->prefix; key += "_APPENDER"; const char *appender = getenv(key.c_str()); FilePtr file; if(appender && *appender != '\0') { file = createFilePtr(fopen, appender, "w"); } if(!file) { file = createFilePtr(fdopen, STDERR_FILENO, "w"); } this->setAppender(std::move(file)); } } // namespace __detail_logger using LoggerBase = __detail_logger::LoggerBase<true>; struct NullLogger : public LoggerBase { NullLogger() : LoggerBase("") {} }; template <typename T> class SingletonLogger : public LoggerBase, public Singleton<T> { protected: explicit SingletonLogger(const char *prefix) : LoggerBase(prefix) {} public: static void Info(const char *fmt, ...) __attribute__ ((format(printf, 1, 2))) { va_list arg; va_start(arg, fmt); Singleton<T>::instance().log(LogLevel::INFO, fmt, arg); va_end(arg); } static void Warning(const char *fmt, ...) __attribute__ ((format(printf, 1, 2))) { va_list arg; va_start(arg, fmt); Singleton<T>::instance().log(LogLevel::WARNING, fmt, arg); va_end(arg); } static void Error(const char *fmt, ...) __attribute__ ((format(printf, 1, 2))) { va_list arg; va_start(arg, fmt); Singleton<T>::instance().log(LogLevel::ERROR, fmt, arg); va_end(arg); } static void Fatal(const char *fmt, ...) __attribute__ ((format(printf, 1, 2))) { va_list arg; va_start(arg, fmt); Singleton<T>::instance().log(LogLevel::FATAL, fmt, arg); va_end(arg); } static bool Enabled(LogLevel level) { return Singleton<T>::instance().enabled(level); } }; } // namespace ydsh #endif //YDSH_LOGGER_BASE_HPP <|endoftext|>
<commit_before>#include <cstdint> #include <iostream> #include <numeric> #include <stdexcept> #include <adios2.h> #include <gtest/gtest.h> #ifdef ADIOS2_HAVE_MPI TEST(ADIOSInterface, MPICommRemoved) { MPI_Comm myComm; MPI_Comm_dup(MPI_COMM_WORLD, &myComm); adios2::ADIOS adios(myComm); adios2::IO io = adios.DeclareIO("TestIO"); MPI_Comm_free(&myComm); adios2::Engine engine = io.Open("test.bp", adios2::Mode::Write); } #endif class ADIOS2_CXX11_API : public ::testing::Test { public: ADIOS2_CXX11_API() #ifdef ADIOS2_HAVE_MPI : ad(MPI_COMM_WORLD, adios2::DebugON) #else : ad(adios2::DebugON) #endif { #ifdef ADIOS2_HAVE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); #endif } adios2::ADIOS ad; int rank = 0; int size = 1; }; class ADIOS2_CXX11_API_IO : public ADIOS2_CXX11_API { public: ADIOS2_CXX11_API_IO() : io(ad.DeclareIO("CXX11_API_TestIO")) {} adios2::IO io; }; TEST_F(ADIOS2_CXX11_API_IO, Engine) { io.SetEngine("bpfile"); EXPECT_EQ(io.EngineType(), "bpfile"); adios2::Engine engine = io.Open("types.bp", adios2::Mode::Write); EXPECT_EQ(engine.Name(), "types.bp"); EXPECT_EQ(engine.Type(), "BP3"); EXPECT_EQ(io.EngineType(), "bp"); // FIXME? Is it expected that adios2_open // changes the engine_type string? } TEST_F(ADIOS2_CXX11_API_IO, EngineDefault) { io.SetEngine(""); EXPECT_EQ(io.EngineType(), ""); adios2::Engine engine = io.Open("types.bp", adios2::Mode::Write); EXPECT_EQ(engine.Name(), "types.bp"); EXPECT_EQ(engine.Type(), "BP3"); EXPECT_EQ(io.EngineType(), "bp"); // FIXME? Is it expected that adios2_open // changes the engine_type string? } template <class T> struct MyData { using Block = std::vector<T>; using Box = adios2::Box<adios2::Dims>; explicit MyData(const std::vector<Box> &selections) : m_Blocks(selections.size()), m_Selections(selections) { for (int b = 0; b < nBlocks(); ++b) { m_Blocks[b].resize(selections[b].second[0]); } } size_t nBlocks() const { return m_Selections.size(); } size_t start(int b) const { return m_Selections[b].first[0]; } size_t count(int b) const { return m_Selections[b].second[0]; } const Box &selection(int b) const { return m_Selections[b]; } Block &operator[](int b) { return m_Blocks[b]; } private: std::vector<Block> m_Blocks; std::vector<Box> m_Selections; }; template <class T> struct MyDataView { using Block = T *; using Box = adios2::Box<adios2::Dims>; explicit MyDataView(const std::vector<Box> &selections) : m_Blocks(selections.size()), m_Selections(selections) { } void place(int b, T *arr) { m_Blocks[b] = arr; } size_t nBlocks() const { return m_Selections.size(); } size_t start(int b) const { return m_Selections[b].first[0]; } size_t count(int b) const { return m_Selections[b].second[0]; } const Box &selection(int b) const { return m_Selections[b]; } Block operator[](int b) { return m_Blocks[b]; } private: std::vector<Block> m_Blocks; std::vector<Box> m_Selections; }; class ADIOS2_CXX11_API_Put : public ADIOS2_CXX11_API_IO { public: using T = double; using Box = adios2::Box<adios2::Dims>; using ADIOS2_CXX11_API_IO::ADIOS2_CXX11_API_IO; void SetupDecomposition(size_t Nx) { m_Nx = Nx; m_Shape = {size * Nx}; m_Selections = {{{rank * Nx}, {Nx / 2}}, {{rank * Nx + Nx / 2}, {Nx / 2}}}; } template <class MyData> void PopulateBlock(MyData &myData, int b) { std::iota(&myData[b][0], &myData[b][myData.count(b)], T(myData.start(b))); } bool checkOutput(std::string filename) { if (rank != 0) { return true; } adios2::IO io = ad.DeclareIO("CXX11_API_CheckIO"); #ifdef ADIOS2_HAVE_MPI adios2::Engine engine = io.Open(filename, adios2::Mode::Read, MPI_COMM_SELF); #else adios2::Engine engine = io.Open(filename, adios2::Mode::Read); #endif adios2::Variable<T> var = io.InquireVariable<T>("var"); adios2::Dims shape = var.Shape(); std::vector<T> data(shape[0]); engine.Get(var, data, adios2::Mode::Sync); engine.Close(); std::vector<T> ref(shape[0]); std::iota(ref.begin(), ref.end(), T()); return data == ref; } size_t m_Nx; adios2::Dims m_Shape; std::vector<Box> m_Selections; }; TEST_F(ADIOS2_CXX11_API_Put, MultiBlockPutSync) { SetupDecomposition(10); adios2::Engine engine = io.Open("multi_sync.bp", adios2::Mode::Write); adios2::Variable<T> var = io.DefineVariable<T>("var", m_Shape); MyData<T> myData(m_Selections); for (int b = 0; b < myData.nBlocks(); ++b) { PopulateBlock(myData, b); var.SetSelection(myData.selection(b)); engine.Put(var, &myData[b][0], adios2::Mode::Sync); } engine.Close(); EXPECT_TRUE(checkOutput("multi_sync.bp")); } TEST_F(ADIOS2_CXX11_API_Put, MultiBlockPutDeferred) { SetupDecomposition(10); adios2::Engine engine = io.Open("multi_deferred.bp", adios2::Mode::Write); adios2::Variable<T> var = io.DefineVariable<T>("var", m_Shape); MyData<T> myData(m_Selections); for (int b = 0; b < myData.nBlocks(); ++b) { PopulateBlock(myData, b); var.SetSelection(myData.selection(b)); engine.Put(var, &myData[b][0], adios2::Mode::Deferred); } engine.Close(); EXPECT_TRUE(checkOutput("multi_deferred.bp")); } TEST_F(ADIOS2_CXX11_API_Put, MultiBlockPutDS) { SetupDecomposition(10); adios2::Engine engine = io.Open("multi_ds.bp", adios2::Mode::Write); adios2::Variable<T> var = io.DefineVariable<T>("var", m_Shape); MyData<T> myData(m_Selections); for (int b = 0; b < myData.nBlocks(); ++b) { PopulateBlock(myData, b); var.SetSelection(myData.selection(b)); if (b == 0) { engine.Put(var, &myData[b][0], adios2::Mode::Deferred); } else { engine.Put(var, &myData[b][0], adios2::Mode::Sync); } } engine.Close(); EXPECT_TRUE(checkOutput("multi_ds.bp")); } TEST_F(ADIOS2_CXX11_API_Put, MultiBlockPutZeroCopySync) { SetupDecomposition(10); adios2::Engine engine = io.Open("multi0_sync.bp", adios2::Mode::Write); adios2::Variable<T> var = io.DefineVariable<T>("var", m_Shape); MyDataView<T> myData(m_Selections); for (int b = 0; b < myData.nBlocks(); ++b) { var.SetSelection(myData.selection(b)); auto span = engine.Put(var); myData.place(b, span.data()); } for (int b = 0; b < myData.nBlocks(); ++b) { PopulateBlock(myData, b); } engine.Close(); EXPECT_TRUE(checkOutput("multi0_sync.bp")); } TEST_F(ADIOS2_CXX11_API_Put, MultiBlockPutZeroCopySync2) { SetupDecomposition(10); adios2::Engine engine = io.Open("multi0_sync2.bp", adios2::Mode::Write); adios2::Variable<T> var = io.DefineVariable<T>("var", m_Shape); MyDataView<T> myData(m_Selections); for (int b = 0; b < 1; ++b) { var.SetSelection(myData.selection(b)); auto span = engine.Put(var); myData.place(b, span.data()); } for (int b = 0; b < 1; ++b) { PopulateBlock(myData, b); } std::vector<T> lastBlock(m_Nx / 2); std::iota(lastBlock.begin(), lastBlock.end(), T(rank * m_Nx + m_Nx / 2)); var.SetSelection(myData.selection(1)); engine.Put(var, lastBlock.data(), adios2::Mode::Deferred); engine.Close(); EXPECT_TRUE(checkOutput("multi0_sync2.bp")); } #if 0 TEST_F(ADIOS2_CXX11_API_Put, MultiBlockPutZeroCopySync3) { SetupDecomposition(10); adios2::Engine engine = io.Open("multi0_sync3.bp", adios2::Mode::Write); adios2::Variable<T> var = io.DefineVariable<T>("var", m_Shape); MyDataView<T> myData(m_Selections); for (int b = 0; b < 1; ++b) { var.SetSelection(myData.selection(b)); auto span = engine.Put(var); myData.place(b, span.data()); } for (int b = 0; b < 1; ++b) { PopulateBlock(myData, b); } engine.Put(var, std::vector<T>{5., 6., 7., 8., 9.}.data(), adios2::Mode::Sync); engine.Close(); EXPECT_TRUE(checkOutput("multi0_sync3.bp")); } #endif TEST_F(ADIOS2_CXX11_API_Put, MultiBlockPut2FileGetSyncPutSync) { SetupDecomposition(10); // Generate data { adios2::Engine engine = io.Open("multi_2f_sync_input.bp", adios2::Mode::Write); adios2::Variable<T> var = io.DefineVariable<T>("var", m_Shape); MyData<T> myData(m_Selections); for (int b = 0; b < myData.nBlocks(); ++b) { PopulateBlock(myData, b); var.SetSelection(myData.selection(b)); engine.Put(var, &myData[b][0], adios2::Mode::Sync); } engine.Close(); } io.RemoveAllVariables(); adios2::Engine reader = io.Open("multi_2f_sync_input.bp", adios2::Mode::Read); adios2::Engine writer = io.Open("multi_2f_sync.bp", adios2::Mode::Write); adios2::Variable<T> var = io.InquireVariable<T>("var"); MyData<T> myData(m_Selections); for (int b = 0; b < myData.nBlocks(); ++b) { var.SetSelection(myData.selection(b)); reader.Get(var, &myData[b][0], adios2::Mode::Sync); writer.Put(var, &myData[b][0], adios2::Mode::Sync); } reader.Close(); writer.Close(); EXPECT_TRUE(checkOutput("multi_2f_sync.bp")); } TEST_F(ADIOS2_CXX11_API_Put, MultiBlock2FileGetSyncPutDef) { SetupDecomposition(10); // Generate data { adios2::Engine engine = io.Open("multi_2f_syncdef_input.bp", adios2::Mode::Write); adios2::Variable<T> var = io.DefineVariable<T>("var", m_Shape); MyData<T> myData(m_Selections); for (int b = 0; b < myData.nBlocks(); ++b) { PopulateBlock(myData, b); var.SetSelection(myData.selection(b)); engine.Put(var, &myData[b][0], adios2::Mode::Sync); } engine.Close(); } io.RemoveAllVariables(); adios2::Engine reader = io.Open("multi_2f_syncdef_input.bp", adios2::Mode::Read); adios2::Engine writer = io.Open("multi_2f_syncdef.bp", adios2::Mode::Write); adios2::Variable<T> var = io.InquireVariable<T>("var"); MyData<T> myData(m_Selections); for (int b = 0; b < myData.nBlocks(); ++b) { var.SetSelection(myData.selection(b)); reader.Get(var, &myData[b][0], adios2::Mode::Sync); writer.Put(var, &myData[b][0], adios2::Mode::Deferred); } reader.Close(); writer.Close(); EXPECT_TRUE(checkOutput("multi_2f_syncdef.bp")); } int main(int argc, char **argv) { #ifdef ADIOS2_HAVE_MPI MPI_Init(nullptr, nullptr); #endif int result; ::testing::InitGoogleTest(&argc, argv); result = RUN_ALL_TESTS(); #ifdef ADIOS2_HAVE_MPI MPI_Finalize(); #endif return result; } <commit_msg>testing: introduce GenerateOutput helper<commit_after>#include <cstdint> #include <iostream> #include <numeric> #include <stdexcept> #include <adios2.h> #include <gtest/gtest.h> #ifdef ADIOS2_HAVE_MPI TEST(ADIOSInterface, MPICommRemoved) { MPI_Comm myComm; MPI_Comm_dup(MPI_COMM_WORLD, &myComm); adios2::ADIOS adios(myComm); adios2::IO io = adios.DeclareIO("TestIO"); MPI_Comm_free(&myComm); adios2::Engine engine = io.Open("test.bp", adios2::Mode::Write); } #endif class ADIOS2_CXX11_API : public ::testing::Test { public: ADIOS2_CXX11_API() #ifdef ADIOS2_HAVE_MPI : ad(MPI_COMM_WORLD, adios2::DebugON) #else : ad(adios2::DebugON) #endif { #ifdef ADIOS2_HAVE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); #endif } adios2::ADIOS ad; int rank = 0; int size = 1; }; class ADIOS2_CXX11_API_IO : public ADIOS2_CXX11_API { public: ADIOS2_CXX11_API_IO() : io(ad.DeclareIO("CXX11_API_TestIO")) {} adios2::IO io; }; TEST_F(ADIOS2_CXX11_API_IO, Engine) { io.SetEngine("bpfile"); EXPECT_EQ(io.EngineType(), "bpfile"); adios2::Engine engine = io.Open("types.bp", adios2::Mode::Write); EXPECT_EQ(engine.Name(), "types.bp"); EXPECT_EQ(engine.Type(), "BP3"); EXPECT_EQ(io.EngineType(), "bp"); // FIXME? Is it expected that adios2_open // changes the engine_type string? } TEST_F(ADIOS2_CXX11_API_IO, EngineDefault) { io.SetEngine(""); EXPECT_EQ(io.EngineType(), ""); adios2::Engine engine = io.Open("types.bp", adios2::Mode::Write); EXPECT_EQ(engine.Name(), "types.bp"); EXPECT_EQ(engine.Type(), "BP3"); EXPECT_EQ(io.EngineType(), "bp"); // FIXME? Is it expected that adios2_open // changes the engine_type string? } template <class T> struct MyData { using Block = std::vector<T>; using Box = adios2::Box<adios2::Dims>; explicit MyData(const std::vector<Box> &selections) : m_Blocks(selections.size()), m_Selections(selections) { for (int b = 0; b < nBlocks(); ++b) { m_Blocks[b].resize(selections[b].second[0]); } } size_t nBlocks() const { return m_Selections.size(); } size_t start(int b) const { return m_Selections[b].first[0]; } size_t count(int b) const { return m_Selections[b].second[0]; } const Box &selection(int b) const { return m_Selections[b]; } Block &operator[](int b) { return m_Blocks[b]; } private: std::vector<Block> m_Blocks; std::vector<Box> m_Selections; }; template <class T> struct MyDataView { using Block = T *; using Box = adios2::Box<adios2::Dims>; explicit MyDataView(const std::vector<Box> &selections) : m_Blocks(selections.size()), m_Selections(selections) { } void place(int b, T *arr) { m_Blocks[b] = arr; } size_t nBlocks() const { return m_Selections.size(); } size_t start(int b) const { return m_Selections[b].first[0]; } size_t count(int b) const { return m_Selections[b].second[0]; } const Box &selection(int b) const { return m_Selections[b]; } Block operator[](int b) { return m_Blocks[b]; } private: std::vector<Block> m_Blocks; std::vector<Box> m_Selections; }; class ADIOS2_CXX11_API_Put : public ADIOS2_CXX11_API_IO { public: using T = double; using Box = adios2::Box<adios2::Dims>; using ADIOS2_CXX11_API_IO::ADIOS2_CXX11_API_IO; void SetupDecomposition(size_t Nx) { m_Nx = Nx; m_Shape = {size * Nx}; m_Selections = {{{rank * Nx}, {Nx / 2}}, {{rank * Nx + Nx / 2}, {Nx / 2}}}; } template <class MyData> void PopulateBlock(MyData &myData, int b) { std::iota(&myData[b][0], &myData[b][myData.count(b)], T(myData.start(b))); } void GenerateOutput(std::string filename) { adios2::IO io = ad.DeclareIO("CXX11_API_GenerateOutput"); adios2::Engine engine = io.Open(filename, adios2::Mode::Write); adios2::Variable<T> var = io.DefineVariable<T>("var", m_Shape); MyData<T> myData(m_Selections); for (int b = 0; b < myData.nBlocks(); ++b) { PopulateBlock(myData, b); var.SetSelection(myData.selection(b)); engine.Put(var, &myData[b][0], adios2::Mode::Sync); } engine.Close(); ad.RemoveIO("CXX11_API_GenerateOutput"); } bool checkOutput(std::string filename) { if (rank != 0) { return true; } adios2::IO io = ad.DeclareIO("CXX11_API_CheckIO"); #ifdef ADIOS2_HAVE_MPI adios2::Engine engine = io.Open(filename, adios2::Mode::Read, MPI_COMM_SELF); #else adios2::Engine engine = io.Open(filename, adios2::Mode::Read); #endif adios2::Variable<T> var = io.InquireVariable<T>("var"); adios2::Dims shape = var.Shape(); std::vector<T> data(shape[0]); engine.Get(var, data, adios2::Mode::Sync); engine.Close(); std::vector<T> ref(shape[0]); std::iota(ref.begin(), ref.end(), T()); return data == ref; } size_t m_Nx; adios2::Dims m_Shape; std::vector<Box> m_Selections; }; TEST_F(ADIOS2_CXX11_API_Put, MultiBlockPutSync) { SetupDecomposition(10); adios2::Engine engine = io.Open("multi_sync.bp", adios2::Mode::Write); adios2::Variable<T> var = io.DefineVariable<T>("var", m_Shape); MyData<T> myData(m_Selections); for (int b = 0; b < myData.nBlocks(); ++b) { PopulateBlock(myData, b); var.SetSelection(myData.selection(b)); engine.Put(var, &myData[b][0], adios2::Mode::Sync); } engine.Close(); EXPECT_TRUE(checkOutput("multi_sync.bp")); } TEST_F(ADIOS2_CXX11_API_Put, MultiBlockPutDeferred) { SetupDecomposition(10); adios2::Engine engine = io.Open("multi_deferred.bp", adios2::Mode::Write); adios2::Variable<T> var = io.DefineVariable<T>("var", m_Shape); MyData<T> myData(m_Selections); for (int b = 0; b < myData.nBlocks(); ++b) { PopulateBlock(myData, b); var.SetSelection(myData.selection(b)); engine.Put(var, &myData[b][0], adios2::Mode::Deferred); } engine.Close(); EXPECT_TRUE(checkOutput("multi_deferred.bp")); } TEST_F(ADIOS2_CXX11_API_Put, MultiBlockPutDS) { SetupDecomposition(10); adios2::Engine engine = io.Open("multi_ds.bp", adios2::Mode::Write); adios2::Variable<T> var = io.DefineVariable<T>("var", m_Shape); MyData<T> myData(m_Selections); for (int b = 0; b < myData.nBlocks(); ++b) { PopulateBlock(myData, b); var.SetSelection(myData.selection(b)); if (b == 0) { engine.Put(var, &myData[b][0], adios2::Mode::Deferred); } else { engine.Put(var, &myData[b][0], adios2::Mode::Sync); } } engine.Close(); EXPECT_TRUE(checkOutput("multi_ds.bp")); } TEST_F(ADIOS2_CXX11_API_Put, MultiBlockPutZeroCopySync) { SetupDecomposition(10); adios2::Engine engine = io.Open("multi0_sync.bp", adios2::Mode::Write); adios2::Variable<T> var = io.DefineVariable<T>("var", m_Shape); MyDataView<T> myData(m_Selections); for (int b = 0; b < myData.nBlocks(); ++b) { var.SetSelection(myData.selection(b)); auto span = engine.Put(var); myData.place(b, span.data()); } for (int b = 0; b < myData.nBlocks(); ++b) { PopulateBlock(myData, b); } engine.Close(); EXPECT_TRUE(checkOutput("multi0_sync.bp")); } TEST_F(ADIOS2_CXX11_API_Put, MultiBlockPutZeroCopySync2) { SetupDecomposition(10); adios2::Engine engine = io.Open("multi0_sync2.bp", adios2::Mode::Write); adios2::Variable<T> var = io.DefineVariable<T>("var", m_Shape); MyDataView<T> myData(m_Selections); for (int b = 0; b < 1; ++b) { var.SetSelection(myData.selection(b)); auto span = engine.Put(var); myData.place(b, span.data()); } for (int b = 0; b < 1; ++b) { PopulateBlock(myData, b); } std::vector<T> lastBlock(m_Nx / 2); std::iota(lastBlock.begin(), lastBlock.end(), T(rank * m_Nx + m_Nx / 2)); var.SetSelection(myData.selection(1)); engine.Put(var, lastBlock.data(), adios2::Mode::Deferred); engine.Close(); EXPECT_TRUE(checkOutput("multi0_sync2.bp")); } #if 0 TEST_F(ADIOS2_CXX11_API_Put, MultiBlockPutZeroCopySync3) { SetupDecomposition(10); adios2::Engine engine = io.Open("multi0_sync3.bp", adios2::Mode::Write); adios2::Variable<T> var = io.DefineVariable<T>("var", m_Shape); MyDataView<T> myData(m_Selections); for (int b = 0; b < 1; ++b) { var.SetSelection(myData.selection(b)); auto span = engine.Put(var); myData.place(b, span.data()); } for (int b = 0; b < 1; ++b) { PopulateBlock(myData, b); } engine.Put(var, std::vector<T>{5., 6., 7., 8., 9.}.data(), adios2::Mode::Sync); engine.Close(); EXPECT_TRUE(checkOutput("multi0_sync3.bp")); } #endif TEST_F(ADIOS2_CXX11_API_Put, MultiBlockPut2FileGetSyncPutSync) { SetupDecomposition(10); GenerateOutput("multi_2f_sync_input.bp"); adios2::Engine reader = io.Open("multi_2f_sync_input.bp", adios2::Mode::Read); adios2::Engine writer = io.Open("multi_2f_sync.bp", adios2::Mode::Write); adios2::Variable<T> var = io.InquireVariable<T>("var"); MyData<T> myData(m_Selections); for (int b = 0; b < myData.nBlocks(); ++b) { var.SetSelection(myData.selection(b)); reader.Get(var, &myData[b][0], adios2::Mode::Sync); writer.Put(var, &myData[b][0], adios2::Mode::Sync); } reader.Close(); writer.Close(); EXPECT_TRUE(checkOutput("multi_2f_sync.bp")); } TEST_F(ADIOS2_CXX11_API_Put, MultiBlock2FileGetSyncPutDef) { SetupDecomposition(10); GenerateOutput("multi_2f_syncdef_input.bp"); adios2::Engine reader = io.Open("multi_2f_syncdef_input.bp", adios2::Mode::Read); adios2::Engine writer = io.Open("multi_2f_syncdef.bp", adios2::Mode::Write); adios2::Variable<T> var = io.InquireVariable<T>("var"); MyData<T> myData(m_Selections); for (int b = 0; b < myData.nBlocks(); ++b) { var.SetSelection(myData.selection(b)); reader.Get(var, &myData[b][0], adios2::Mode::Sync); writer.Put(var, &myData[b][0], adios2::Mode::Deferred); } reader.Close(); writer.Close(); EXPECT_TRUE(checkOutput("multi_2f_syncdef.bp")); } int main(int argc, char **argv) { #ifdef ADIOS2_HAVE_MPI MPI_Init(nullptr, nullptr); #endif int result; ::testing::InitGoogleTest(&argc, argv); result = RUN_ALL_TESTS(); #ifdef ADIOS2_HAVE_MPI MPI_Finalize(); #endif return result; } <|endoftext|>
<commit_before>/* Copyright (c) 2021 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 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. */ /* This file verifies the following scenarios of hipMemcpy2DFromArray API 1. Negative Scenarios 2. Extent Validation Scenarios 3. hipMemcpy2DFromArray Basic Scenario 4. Pinned Memory scenarios on same and peer GPU 5. Device Context change scenario where memory is allocated in one GPU and API is triggered from peer GPU. */ #include <hip_test_common.hh> #include <hip_test_checkers.hh> static constexpr auto NUM_W{10}; static constexpr auto NUM_H{10}; /* * This testcase verifies device to host copy for hipMemcpy2DFromArray API * INPUT: Copying Host variable hData(Initialized with value Phi(1.618)) * --> A_d device variable * OUTPUT: For validating the result,Copying A_d device variable * --> A_h host variable * and verifying A_h with Phi */ TEST_CASE("Unit_hipMemcpy2DFromArray_Basic") { HIP_CHECK(hipSetDevice(0)); hipArray *A_d{nullptr}; size_t width{sizeof(float)*NUM_W}; float *A_h{nullptr}, *hData{nullptr}; // Initialization of variables HipTest::initArrays<float>(nullptr, nullptr, nullptr, &A_h, &hData, nullptr, width*NUM_H, false); hipChannelFormatDesc desc = hipCreateChannelDesc<float>(); HIP_CHECK(hipMallocArray(&A_d, &desc, NUM_W, NUM_H, hipArrayDefault)); HipTest::setDefaultData<float>(width*NUM_H, A_h, hData, nullptr); HIP_CHECK(hipMemcpy2DToArray(A_d, 0, 0, hData, width, width, NUM_H, hipMemcpyHostToDevice)); HIP_CHECK(hipMemcpy2DFromArray(A_h, width, A_d, 0, 0, width, NUM_H, hipMemcpyDeviceToHost)); REQUIRE(HipTest::checkArray(A_h, hData, NUM_W, NUM_H) == true); // Cleaning the memory HIP_CHECK(hipFreeArray(A_d)); HipTest::freeArrays<float>(nullptr, nullptr, nullptr, A_h, hData, nullptr, false); } /* * This testcase verifies the extent validation scenarios * of hipMemcpy2DFromArray API */ TEST_CASE("Unit_hipMemcpy2DFromArray_ExtentValidation") { HIP_CHECK(hipSetDevice(0)); hipArray *A_d{nullptr}; size_t width{sizeof(float)*NUM_W}; float *A_h{nullptr}, *hData{nullptr}, *valData{nullptr}; // Initialization of variables HipTest::initArrays<float>(nullptr, nullptr, nullptr, &A_h, &hData, nullptr, width*NUM_H, false); HipTest::initArrays<float>(nullptr, nullptr, nullptr, nullptr, &valData, nullptr, width*NUM_H, false); hipChannelFormatDesc desc = hipCreateChannelDesc<float>(); HIP_CHECK(hipMallocArray(&A_d, &desc, NUM_W, NUM_H, hipArrayDefault)); SECTION("Destination width is 0") { REQUIRE(hipMemcpy2DFromArray(A_h, 0, A_d, 0, 0, NUM_W*sizeof(float), NUM_H, hipMemcpyDeviceToHost) != hipSuccess); } // hipMemcpy2DFromArray API would return success for width and height as 0 // and does not perform any copy // Validating the result with the initialized value // 1.Initializing A_d with Pi value // 2.copying A_d-->hData variable // with height 0(copy will not be performed) // 3 validating hData<-->A_h which will not be equal as copy is not done. SECTION("Height is 0") { HIP_CHECK(hipMemcpy2DToArray(A_d, 0, 0, A_h, width, width, NUM_H, hipMemcpyHostToDevice)); HIP_CHECK(hipMemcpy2DFromArray(hData, width, A_d, 0, 0, width, 0, hipMemcpyDeviceToHost)); REQUIRE(HipTest::checkArray(hData, valData, NUM_W, NUM_H) == true); } // hipMemcpy2DFromArray API would return success for width and height as 0 // and does not perform any copy // Validating the result with the initialized value // 1.Initializing A_d with Pi value // 2.copying A_d-->hData variable // with width 0(copy will not be performed) // 3 validating hData<-->A_h which will not be equal as copy is not done. SECTION("Width is 0") { HIP_CHECK(hipMemcpy2DToArray(A_d, 0, 0, A_h, width, width, NUM_H, hipMemcpyHostToDevice)); HIP_CHECK(hipMemcpy2DFromArray(hData, width, A_d, 0, 0, 0, NUM_H, hipMemcpyDeviceToHost)); REQUIRE(HipTest::checkArray(hData, valData, NUM_W, NUM_H) == true); } // Cleaning the memory HIP_CHECK(hipFreeArray(A_d)); HipTest::freeArrays<float>(nullptr, nullptr, nullptr, A_h, hData, nullptr, false); HipTest::freeArrays<float>(nullptr, nullptr, nullptr, nullptr, valData, nullptr, false); } /* * This Scenario Verifies hipMemcpy2DFromArray API by copying the * data from pinned host memory to device on same GPU * INPUT: Copying Host variable PinnMem(Initialized with value "10" ) * --> A_d device variable * OUTPUT: For validating the result,Copying A_d device variable * --> A_h host variable * and verifying A_h with PinnedMem[0](i.e., 10) */ TEST_CASE("Unit_hipMemcpy2DFromArray_PinnedMemSameGPU") { HIP_CHECK(hipSetDevice(0)); hipArray *A_d{nullptr}; constexpr auto def_val{10}; size_t width{sizeof(float)*NUM_W}; float *A_h{nullptr}, *PinnMem{nullptr}; // Initialization of variables HipTest::initArrays<float>(nullptr, nullptr, nullptr, &A_h, nullptr, nullptr, width*NUM_H, false); HIP_CHECK(hipHostMalloc(reinterpret_cast<void**>(&PinnMem), width * NUM_H)); hipChannelFormatDesc desc = hipCreateChannelDesc<float>(); HIP_CHECK(hipMallocArray(&A_d, &desc, NUM_W, NUM_H, hipArrayDefault)); HipTest::setDefaultData<float>(width*NUM_H, A_h, nullptr, nullptr); for (int i = 0; i < NUM_W*NUM_H; i++) { PinnMem[i] = def_val + i; } HIP_CHECK(hipMemcpy2DToArray(A_d, 0, 0, PinnMem, width, width, NUM_H, hipMemcpyHostToDevice)); HIP_CHECK(hipMemcpy2DFromArray(A_h, width, A_d, 0, 0, width, NUM_H, hipMemcpyDeviceToHost)); REQUIRE(HipTest::checkArray(A_h, PinnMem, NUM_W, NUM_H) == true); // Cleaning the memory HIP_CHECK(hipFreeArray(A_d)); HIP_CHECK(hipHostFree(PinnMem)); HipTest::freeArrays<float>(nullptr, nullptr, nullptr, A_h, nullptr, nullptr, false); } /* * This Scenario Verifies hipMemcpy2DFromArray API by copying the * data from pinned host memory to device from Peer GPU. * Device Memory is allocated in GPU 0 and the API is trigerred from GPU1 * INPUT: Intializa A_d with A_h * Copy A_d->E_h which is a pinned host memory * OUTPUT: For validating the result,Copying A_d device variable * --> E_h host variable * and verifying A_h with E_h */ TEST_CASE("Unit_hipMemcpy2DFromArray_multiDevicePinnedMemPeerGpu") { int numDevices = 0; constexpr auto def_val{10}; HIP_CHECK(hipGetDeviceCount(&numDevices)); if (numDevices > 1) { int canAccessPeer = 0; hipDeviceCanAccessPeer(&canAccessPeer, 0, 1); if (canAccessPeer) { HIP_CHECK(hipSetDevice(0)); hipArray *A_d{nullptr}; size_t width{sizeof(float)*NUM_W}; float *A_h{nullptr}, *E_h{nullptr}; // Initialization of variables HipTest::initArrays<float>(nullptr, nullptr, nullptr, &A_h, nullptr, nullptr, width*NUM_H, false); hipChannelFormatDesc desc = hipCreateChannelDesc<float>(); HIP_CHECK(hipMallocArray(&A_d, &desc, NUM_W, NUM_H, hipArrayDefault)); HipTest::setDefaultData<float>(width*NUM_H, A_h, nullptr, nullptr); HIP_CHECK(hipMemcpy2DToArray(A_d, 0, 0, A_h, width, width, NUM_H, hipMemcpyHostToDevice)); HIP_CHECK(hipHostMalloc(reinterpret_cast<void**>(&E_h), width * NUM_H)); for (int i = 0; i < NUM_W*NUM_H; i++) { E_h[i] = def_val + i; } HIP_CHECK(hipSetDevice(1)); HIP_CHECK(hipMemcpy2DFromArray(E_h, width, A_d, 0, 0, width, NUM_H, hipMemcpyDeviceToHost)); REQUIRE(HipTest::checkArray(A_h, E_h, NUM_W, NUM_H) == true); // Cleaning the memory HIP_CHECK(hipFreeArray(A_d)); HIP_CHECK(hipHostFree(E_h)); HipTest::freeArrays<float>(nullptr, nullptr, nullptr, A_h, nullptr, nullptr, false); } else { SUCCEED("Device Does not have P2P capability"); } } else { SUCCEED("Number of devices are < 2"); } } /* * This scenario verifies the hipMemcpy2DFromArray API in case of device * context change. * Memory is allocated in GPU-0 and the API is triggered from GPU-1 * INPUT: Copying Host variable hData(Initial value Phi) * --> A_d device variable * whose memory is allocated in GPU 0 * OUTPUT: For validating the result,Copying A_d device variable * --> A_h host variable * and verifying A_h with Phi * */ TEST_CASE("Unit_hipMemcpy2DFromArray_multiDeviceContextChange") { int numDevices = 0; HIP_CHECK(hipGetDeviceCount(&numDevices)); if (numDevices > 1) { int canAccessPeer = 0; hipDeviceCanAccessPeer(&canAccessPeer, 0, 1); if (canAccessPeer) { HIP_CHECK(hipSetDevice(0)); hipArray *A_d{nullptr}; size_t width{sizeof(float)*NUM_W}; float *A_h{nullptr}, *hData{nullptr}; // Initialization of variables HipTest::initArrays<float>(nullptr, nullptr, nullptr, &A_h, &hData, nullptr, width*NUM_H, false); hipChannelFormatDesc desc = hipCreateChannelDesc<float>(); HIP_CHECK(hipMallocArray(&A_d, &desc, NUM_W, NUM_H, hipArrayDefault)); HipTest::setDefaultData<float>(width*NUM_H, A_h, hData, nullptr); HIP_CHECK(hipSetDevice(1)); HIP_CHECK(hipMemcpy2DToArray(A_d, 0, 0, hData, width, width, NUM_H, hipMemcpyHostToDevice)); HIP_CHECK(hipMemcpy2DFromArray(A_h, width, A_d, 0, 0, width, NUM_H, hipMemcpyDeviceToHost)); REQUIRE(HipTest::checkArray(A_h, hData, NUM_W, NUM_H) == true); // Cleaning the memory HIP_CHECK(hipFreeArray(A_d)); HipTest::freeArrays<float>(nullptr, nullptr, nullptr, A_h, hData, nullptr, false); } else { SUCCEED("Device Does not have P2P capability"); } } else { SUCCEED("Number of devices are < 2"); } } /* This testcase verifies the negative scenarios of * hipMemcpy2DFromArray API */ TEST_CASE("Unit_hipMemcpy2DFromArray_Negative") { HIP_CHECK(hipSetDevice(0)); hipArray *A_d{nullptr}; size_t width{sizeof(float)*NUM_W}; float *A_h{nullptr}, *hData{nullptr}; // Initialization of variables HipTest::initArrays<float>(nullptr, nullptr, nullptr, &A_h, &hData, nullptr, width*NUM_H, false); HipTest::setDefaultData<float>(width*NUM_H, A_h, hData, nullptr); hipChannelFormatDesc desc = hipCreateChannelDesc<float>(); HIP_CHECK(hipMallocArray(&A_d, &desc, NUM_W, NUM_H, hipArrayDefault)); SECTION("Nullptr to destination") { REQUIRE(hipMemcpy2DFromArray(nullptr, width, A_d, 0, 0, width, NUM_H, hipMemcpyDeviceToHost) != hipSuccess); } SECTION("Nullptr to source") { REQUIRE(hipMemcpy2DFromArray(A_h, width, nullptr, 0, 0, width, NUM_H, hipMemcpyDeviceToHost) != hipSuccess); } SECTION("Passing offset more than 0") { REQUIRE(hipMemcpy2DFromArray(A_h, width, A_d, 1, 1, width, NUM_H, hipMemcpyDeviceToHost) != hipSuccess); } SECTION("Passing array more than allocated") { REQUIRE(hipMemcpy2DFromArray(A_h, width, A_d, 0, 0, width+2, NUM_H+2, hipMemcpyDeviceToHost) != hipSuccess); } // Cleaning of memory HIP_CHECK(hipFreeArray(A_d)); HipTest::freeArrays<float>(nullptr, nullptr, nullptr, A_h, hData, nullptr, false); } <commit_msg>SWDEV-1 - Add missing checks in hipMemcpy2DFromArray.cc<commit_after>/* Copyright (c) 2021 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 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. */ /* This file verifies the following scenarios of hipMemcpy2DFromArray API 1. Negative Scenarios 2. Extent Validation Scenarios 3. hipMemcpy2DFromArray Basic Scenario 4. Pinned Memory scenarios on same and peer GPU 5. Device Context change scenario where memory is allocated in one GPU and API is triggered from peer GPU. */ #include <hip_test_common.hh> #include <hip_test_checkers.hh> static constexpr auto NUM_W{10}; static constexpr auto NUM_H{10}; /* * This testcase verifies device to host copy for hipMemcpy2DFromArray API * INPUT: Copying Host variable hData(Initialized with value Phi(1.618)) * --> A_d device variable * OUTPUT: For validating the result,Copying A_d device variable * --> A_h host variable * and verifying A_h with Phi */ TEST_CASE("Unit_hipMemcpy2DFromArray_Basic") { HIP_CHECK(hipSetDevice(0)); hipArray *A_d{nullptr}; size_t width{sizeof(float)*NUM_W}; float *A_h{nullptr}, *hData{nullptr}; // Initialization of variables HipTest::initArrays<float>(nullptr, nullptr, nullptr, &A_h, &hData, nullptr, width*NUM_H, false); hipChannelFormatDesc desc = hipCreateChannelDesc<float>(); HIP_CHECK(hipMallocArray(&A_d, &desc, NUM_W, NUM_H, hipArrayDefault)); HipTest::setDefaultData<float>(width*NUM_H, A_h, hData, nullptr); HIP_CHECK(hipMemcpy2DToArray(A_d, 0, 0, hData, width, width, NUM_H, hipMemcpyHostToDevice)); HIP_CHECK(hipMemcpy2DFromArray(A_h, width, A_d, 0, 0, width, NUM_H, hipMemcpyDeviceToHost)); REQUIRE(HipTest::checkArray(A_h, hData, NUM_W, NUM_H) == true); // Cleaning the memory HIP_CHECK(hipFreeArray(A_d)); HipTest::freeArrays<float>(nullptr, nullptr, nullptr, A_h, hData, nullptr, false); } /* * This testcase verifies the extent validation scenarios * of hipMemcpy2DFromArray API */ TEST_CASE("Unit_hipMemcpy2DFromArray_ExtentValidation") { HIP_CHECK(hipSetDevice(0)); hipArray *A_d{nullptr}; size_t width{sizeof(float)*NUM_W}; float *A_h{nullptr}, *hData{nullptr}, *valData{nullptr}; // Initialization of variables HipTest::initArrays<float>(nullptr, nullptr, nullptr, &A_h, &hData, nullptr, width*NUM_H, false); HipTest::initArrays<float>(nullptr, nullptr, nullptr, nullptr, &valData, nullptr, width*NUM_H, false); hipChannelFormatDesc desc = hipCreateChannelDesc<float>(); HIP_CHECK(hipMallocArray(&A_d, &desc, NUM_W, NUM_H, hipArrayDefault)); SECTION("Destination width is 0") { REQUIRE(hipMemcpy2DFromArray(A_h, 0, A_d, 0, 0, NUM_W*sizeof(float), NUM_H, hipMemcpyDeviceToHost) != hipSuccess); } // hipMemcpy2DFromArray API would return success for width and height as 0 // and does not perform any copy // Validating the result with the initialized value // 1.Initializing A_d with Pi value // 2.copying A_d-->hData variable // with height 0(copy will not be performed) // 3 validating hData<-->A_h which will not be equal as copy is not done. SECTION("Height is 0") { HIP_CHECK(hipMemcpy2DToArray(A_d, 0, 0, A_h, width, width, NUM_H, hipMemcpyHostToDevice)); HIP_CHECK(hipMemcpy2DFromArray(hData, width, A_d, 0, 0, width, 0, hipMemcpyDeviceToHost)); REQUIRE(HipTest::checkArray(hData, valData, NUM_W, NUM_H) == true); } // hipMemcpy2DFromArray API would return success for width and height as 0 // and does not perform any copy // Validating the result with the initialized value // 1.Initializing A_d with Pi value // 2.copying A_d-->hData variable // with width 0(copy will not be performed) // 3 validating hData<-->A_h which will not be equal as copy is not done. SECTION("Width is 0") { HIP_CHECK(hipMemcpy2DToArray(A_d, 0, 0, A_h, width, width, NUM_H, hipMemcpyHostToDevice)); HIP_CHECK(hipMemcpy2DFromArray(hData, width, A_d, 0, 0, 0, NUM_H, hipMemcpyDeviceToHost)); REQUIRE(HipTest::checkArray(hData, valData, NUM_W, NUM_H) == true); } // Cleaning the memory HIP_CHECK(hipFreeArray(A_d)); HipTest::freeArrays<float>(nullptr, nullptr, nullptr, A_h, hData, nullptr, false); HipTest::freeArrays<float>(nullptr, nullptr, nullptr, nullptr, valData, nullptr, false); } /* * This Scenario Verifies hipMemcpy2DFromArray API by copying the * data from pinned host memory to device on same GPU * INPUT: Copying Host variable PinnMem(Initialized with value "10" ) * --> A_d device variable * OUTPUT: For validating the result,Copying A_d device variable * --> A_h host variable * and verifying A_h with PinnedMem[0](i.e., 10) */ TEST_CASE("Unit_hipMemcpy2DFromArray_PinnedMemSameGPU") { HIP_CHECK(hipSetDevice(0)); hipArray *A_d{nullptr}; constexpr auto def_val{10}; size_t width{sizeof(float)*NUM_W}; float *A_h{nullptr}, *PinnMem{nullptr}; // Initialization of variables HipTest::initArrays<float>(nullptr, nullptr, nullptr, &A_h, nullptr, nullptr, width*NUM_H, false); HIP_CHECK(hipHostMalloc(reinterpret_cast<void**>(&PinnMem), width * NUM_H)); hipChannelFormatDesc desc = hipCreateChannelDesc<float>(); HIP_CHECK(hipMallocArray(&A_d, &desc, NUM_W, NUM_H, hipArrayDefault)); HipTest::setDefaultData<float>(width*NUM_H, A_h, nullptr, nullptr); for (int i = 0; i < NUM_W*NUM_H; i++) { PinnMem[i] = def_val + i; } HIP_CHECK(hipMemcpy2DToArray(A_d, 0, 0, PinnMem, width, width, NUM_H, hipMemcpyHostToDevice)); HIP_CHECK(hipMemcpy2DFromArray(A_h, width, A_d, 0, 0, width, NUM_H, hipMemcpyDeviceToHost)); REQUIRE(HipTest::checkArray(A_h, PinnMem, NUM_W, NUM_H) == true); // Cleaning the memory HIP_CHECK(hipFreeArray(A_d)); HIP_CHECK(hipHostFree(PinnMem)); HipTest::freeArrays<float>(nullptr, nullptr, nullptr, A_h, nullptr, nullptr, false); } /* * This Scenario Verifies hipMemcpy2DFromArray API by copying the * data from pinned host memory to device from Peer GPU. * Device Memory is allocated in GPU 0 and the API is trigerred from GPU1 * INPUT: Intializa A_d with A_h * Copy A_d->E_h which is a pinned host memory * OUTPUT: For validating the result,Copying A_d device variable * --> E_h host variable * and verifying A_h with E_h */ TEST_CASE("Unit_hipMemcpy2DFromArray_multiDevicePinnedMemPeerGpu") { int numDevices = 0; constexpr auto def_val{10}; HIP_CHECK(hipGetDeviceCount(&numDevices)); if (numDevices > 1) { int canAccessPeer = 0; HIP_CHECK(hipDeviceCanAccessPeer(&canAccessPeer, 0, 1)); if (canAccessPeer) { HIP_CHECK(hipSetDevice(0)); hipArray *A_d{nullptr}; size_t width{sizeof(float)*NUM_W}; float *A_h{nullptr}, *E_h{nullptr}; // Initialization of variables HipTest::initArrays<float>(nullptr, nullptr, nullptr, &A_h, nullptr, nullptr, width*NUM_H, false); hipChannelFormatDesc desc = hipCreateChannelDesc<float>(); HIP_CHECK(hipMallocArray(&A_d, &desc, NUM_W, NUM_H, hipArrayDefault)); HipTest::setDefaultData<float>(width*NUM_H, A_h, nullptr, nullptr); HIP_CHECK(hipMemcpy2DToArray(A_d, 0, 0, A_h, width, width, NUM_H, hipMemcpyHostToDevice)); HIP_CHECK(hipHostMalloc(reinterpret_cast<void**>(&E_h), width * NUM_H)); for (int i = 0; i < NUM_W*NUM_H; i++) { E_h[i] = def_val + i; } HIP_CHECK(hipSetDevice(1)); HIP_CHECK(hipMemcpy2DFromArray(E_h, width, A_d, 0, 0, width, NUM_H, hipMemcpyDeviceToHost)); REQUIRE(HipTest::checkArray(A_h, E_h, NUM_W, NUM_H) == true); // Cleaning the memory HIP_CHECK(hipFreeArray(A_d)); HIP_CHECK(hipHostFree(E_h)); HipTest::freeArrays<float>(nullptr, nullptr, nullptr, A_h, nullptr, nullptr, false); } else { SUCCEED("Device Does not have P2P capability"); } } else { SUCCEED("Number of devices are < 2"); } } /* * This scenario verifies the hipMemcpy2DFromArray API in case of device * context change. * Memory is allocated in GPU-0 and the API is triggered from GPU-1 * INPUT: Copying Host variable hData(Initial value Phi) * --> A_d device variable * whose memory is allocated in GPU 0 * OUTPUT: For validating the result,Copying A_d device variable * --> A_h host variable * and verifying A_h with Phi * */ TEST_CASE("Unit_hipMemcpy2DFromArray_multiDeviceContextChange") { int numDevices = 0; HIP_CHECK(hipGetDeviceCount(&numDevices)); if (numDevices > 1) { int canAccessPeer = 0; HIP_CHECK(hipDeviceCanAccessPeer(&canAccessPeer, 0, 1)); if (canAccessPeer) { HIP_CHECK(hipSetDevice(0)); hipArray *A_d{nullptr}; size_t width{sizeof(float)*NUM_W}; float *A_h{nullptr}, *hData{nullptr}; // Initialization of variables HipTest::initArrays<float>(nullptr, nullptr, nullptr, &A_h, &hData, nullptr, width*NUM_H, false); hipChannelFormatDesc desc = hipCreateChannelDesc<float>(); HIP_CHECK(hipMallocArray(&A_d, &desc, NUM_W, NUM_H, hipArrayDefault)); HipTest::setDefaultData<float>(width*NUM_H, A_h, hData, nullptr); HIP_CHECK(hipSetDevice(1)); HIP_CHECK(hipMemcpy2DToArray(A_d, 0, 0, hData, width, width, NUM_H, hipMemcpyHostToDevice)); HIP_CHECK(hipMemcpy2DFromArray(A_h, width, A_d, 0, 0, width, NUM_H, hipMemcpyDeviceToHost)); REQUIRE(HipTest::checkArray(A_h, hData, NUM_W, NUM_H) == true); // Cleaning the memory HIP_CHECK(hipFreeArray(A_d)); HipTest::freeArrays<float>(nullptr, nullptr, nullptr, A_h, hData, nullptr, false); } else { SUCCEED("Device Does not have P2P capability"); } } else { SUCCEED("Number of devices are < 2"); } } /* This testcase verifies the negative scenarios of * hipMemcpy2DFromArray API */ TEST_CASE("Unit_hipMemcpy2DFromArray_Negative") { HIP_CHECK(hipSetDevice(0)); hipArray *A_d{nullptr}; size_t width{sizeof(float)*NUM_W}; float *A_h{nullptr}, *hData{nullptr}; // Initialization of variables HipTest::initArrays<float>(nullptr, nullptr, nullptr, &A_h, &hData, nullptr, width*NUM_H, false); HipTest::setDefaultData<float>(width*NUM_H, A_h, hData, nullptr); hipChannelFormatDesc desc = hipCreateChannelDesc<float>(); HIP_CHECK(hipMallocArray(&A_d, &desc, NUM_W, NUM_H, hipArrayDefault)); SECTION("Nullptr to destination") { REQUIRE(hipMemcpy2DFromArray(nullptr, width, A_d, 0, 0, width, NUM_H, hipMemcpyDeviceToHost) != hipSuccess); } SECTION("Nullptr to source") { REQUIRE(hipMemcpy2DFromArray(A_h, width, nullptr, 0, 0, width, NUM_H, hipMemcpyDeviceToHost) != hipSuccess); } SECTION("Passing offset more than 0") { REQUIRE(hipMemcpy2DFromArray(A_h, width, A_d, 1, 1, width, NUM_H, hipMemcpyDeviceToHost) != hipSuccess); } SECTION("Passing array more than allocated") { REQUIRE(hipMemcpy2DFromArray(A_h, width, A_d, 0, 0, width+2, NUM_H+2, hipMemcpyDeviceToHost) != hipSuccess); } // Cleaning of memory HIP_CHECK(hipFreeArray(A_d)); HipTest::freeArrays<float>(nullptr, nullptr, nullptr, A_h, hData, nullptr, false); } <|endoftext|>
<commit_before>// this file defines the itkBasicFiltersTest for the test driver // and all it expects is that you have a function called RegisterTests #include <iostream> #include "itkTestMain.h" void RegisterTests() { REGISTER_TEST(itkAsinImageFilterAndAdaptorTest ); REGISTER_TEST(itkAcosImageFilterAndAdaptorTest ); REGISTER_TEST(itkAtanImageFilterAndAdaptorTest ); REGISTER_TEST(itkAdaptImageFilterTest ); REGISTER_TEST(itkAdaptImageFilterTest2 ); REGISTER_TEST(itkBasicArchitectureTest ); REGISTER_TEST(itkBinaryDilateImageFilterTest ); REGISTER_TEST(itkBinaryMagnitudeImageFilterTest ); REGISTER_TEST(itkBloxBoundaryPointImageTest ); REGISTER_TEST(itkBloxCoreAtomTest ); REGISTER_TEST(itkChangeInformationImageFilterTest ); REGISTER_TEST(itkConfidenceConnectedImageFilterTest ); REGISTER_TEST(itkConnectedThresholdImageFilterTest ); REGISTER_TEST(itkCosImageFilterAndAdaptorTest ); REGISTER_TEST(itkCurvatureAnisotropicDiffusionImageFilterTest ); REGISTER_TEST(itkCyclicReferences ); REGISTER_TEST(itkDanielssonDistanceMapImageFilterTest ); REGISTER_TEST(itkDifferenceOfGaussiansGradientTest ); REGISTER_TEST(itkEdgePotentialImageFilterTest ); REGISTER_TEST(itkEigenAnalysis2DImageFilterTest ); REGISTER_TEST(itkIsolatedConnectedImageFilterTest ); REGISTER_TEST(itkExpImageFilterAndAdaptorTest ); REGISTER_TEST(itkExpandImageFilterTest ); REGISTER_TEST(itkVectorExpandImageFilterTest ); REGISTER_TEST(itkFilterDispatchTest ); REGISTER_TEST(itkAddImageFilterTest ); REGISTER_TEST(itkFlipImageFilterTest ); REGISTER_TEST(itkFloodFillIteratorTest ); REGISTER_TEST(itkGaussianImageSourceTest ); REGISTER_TEST(itkImageAdaptorNthElementTest ); REGISTER_TEST(itkImageAdaptorPipeLineTest ); REGISTER_TEST(itkImageToParametricSpaceFilterTest ); REGISTER_TEST(itkImportImageTest ); REGISTER_TEST(itkInteriorExteriorMeshFilterTest ); REGISTER_TEST(itkJoinImageFilterTest ); REGISTER_TEST(itkLog10ImageFilterAndAdaptorTest ); REGISTER_TEST(itkLogImageFilterAndAdaptorTest ); REGISTER_TEST(itkMeanImageFilterTest ); REGISTER_TEST(itkMedianImageFilterTest ); REGISTER_TEST(itkMultiplyImageFilterTest ); REGISTER_TEST(itkMinimumMaximumImageFilterTest ); REGISTER_TEST(itkNeighborhoodConnectedImageFilterTest ); REGISTER_TEST(itkNormalizeImageFilterTest ); REGISTER_TEST(itkPermuteAxesImageFilterTest ); REGISTER_TEST(itkPlaheImageFilterTest ); REGISTER_TEST(itkReflectiveImageRegionIteratorTest ); REGISTER_TEST(itkReflectImageFilterTest ); REGISTER_TEST(itkResampleImageTest ); REGISTER_TEST(itkRecursiveGaussianImageFiltersTest ); REGISTER_TEST(itkShiftScaleImageFilterTest ); REGISTER_TEST(itkShrinkImageTest ); REGISTER_TEST(itkStatisticsImageFilterTest ); REGISTER_TEST(itkConstantPadImageTest ); REGISTER_TEST(itkWrapPadImageTest ); REGISTER_TEST(itkMirrorPadImageTest ); REGISTER_TEST(itkExtractImageTest ); REGISTER_TEST(itkSinImageFilterAndAdaptorTest ); REGISTER_TEST(itkSpatialFunctionImageEvaluatorFilterTest ); REGISTER_TEST(itkSqrtImageFilterAndAdaptorTest ); REGISTER_TEST(itkStreamingImageFilterTest ); REGISTER_TEST(itkStreamingImageFilterTest2 ); REGISTER_TEST(itkSubtractImageFilterTest ); REGISTER_TEST(itkTanImageFilterAndAdaptorTest ); REGISTER_TEST(itkTernaryMagnitudeImageFilterTest ); REGISTER_TEST(itkThresholdImageFilterTest ); REGISTER_TEST(itkTransformMeshFilterTest ); REGISTER_TEST(itkVectorAnisotropicDiffusionImageFilterTest ); REGISTER_TEST(itkGradientAnisotropicDiffusionImageFilterTest ); REGISTER_TEST(itkGradientMagnitudeImageFilterTest ); REGISTER_TEST(itkGradientImageFilterTest ); REGISTER_TEST(itkGradientRecursiveGaussianFilterTest ); REGISTER_TEST(itkNeighborhoodOperatorImageFilterTest ); REGISTER_TEST(itkVectorNeighborhoodOperatorImageFilterTest ); REGISTER_TEST(itkNaryAddImageFilterTest ); REGISTER_TEST(itkDerivativeImageFilterTest ); REGISTER_TEST(itkDiscreteGaussianImageFilterTest ); REGISTER_TEST(itkWarpImageFilterTest ); REGISTER_TEST(itkZeroCrossingImageFilterTest ); REGISTER_TEST(itkLaplacianImageFilterTest ); REGISTER_TEST(itkDivideImageFilterTest ); REGISTER_TEST(itkSobelEdgeDetectionImageFilterTest ); REGISTER_TEST(itkZeroCrossingBasedEdgeDetectionImageFilterTest ); REGISTER_TEST(itkCannyEdgeDetectionImageFilterTest ); } <commit_msg>ENH: new test.<commit_after>// this file defines the itkBasicFiltersTest for the test driver // and all it expects is that you have a function called RegisterTests #include <iostream> #include "itkTestMain.h" void RegisterTests() { REGISTER_TEST(itkAsinImageFilterAndAdaptorTest ); REGISTER_TEST(itkAcosImageFilterAndAdaptorTest ); REGISTER_TEST(itkAtanImageFilterAndAdaptorTest ); REGISTER_TEST(itkAdaptImageFilterTest ); REGISTER_TEST(itkAdaptImageFilterTest2 ); REGISTER_TEST(itkBasicArchitectureTest ); REGISTER_TEST(itkBinaryDilateImageFilterTest ); REGISTER_TEST(itkBinaryMagnitudeImageFilterTest ); REGISTER_TEST(itkBloxBoundaryPointImageTest ); REGISTER_TEST(itkBloxCoreAtomTest ); REGISTER_TEST(itkChangeInformationImageFilterTest ); REGISTER_TEST(itkConfidenceConnectedImageFilterTest ); REGISTER_TEST(itkConnectedThresholdImageFilterTest ); REGISTER_TEST(itkCosImageFilterAndAdaptorTest ); REGISTER_TEST(itkCurvatureAnisotropicDiffusionImageFilterTest ); REGISTER_TEST(itkCyclicReferences ); REGISTER_TEST(itkDanielssonDistanceMapImageFilterTest ); REGISTER_TEST(itkDifferenceOfGaussiansGradientTest ); REGISTER_TEST(itkEdgePotentialImageFilterTest ); REGISTER_TEST(itkEigenAnalysis2DImageFilterTest ); REGISTER_TEST(itkIsolatedConnectedImageFilterTest ); REGISTER_TEST(itkExpImageFilterAndAdaptorTest ); REGISTER_TEST(itkExpandImageFilterTest ); REGISTER_TEST(itkVectorExpandImageFilterTest ); REGISTER_TEST(itkFilterDispatchTest ); REGISTER_TEST(itkAddImageFilterTest ); REGISTER_TEST(itkFlipImageFilterTest ); REGISTER_TEST(itkFloodFillIteratorTest ); REGISTER_TEST(itkGaussianImageSourceTest ); REGISTER_TEST(itkHardConnectedComponentImageFilterTest ); REGISTER_TEST(itkImageAdaptorNthElementTest ); REGISTER_TEST(itkImageAdaptorPipeLineTest ); REGISTER_TEST(itkImageToParametricSpaceFilterTest ); REGISTER_TEST(itkImportImageTest ); REGISTER_TEST(itkInteriorExteriorMeshFilterTest ); REGISTER_TEST(itkJoinImageFilterTest ); REGISTER_TEST(itkLog10ImageFilterAndAdaptorTest ); REGISTER_TEST(itkLogImageFilterAndAdaptorTest ); REGISTER_TEST(itkMeanImageFilterTest ); REGISTER_TEST(itkMedianImageFilterTest ); REGISTER_TEST(itkMultiplyImageFilterTest ); REGISTER_TEST(itkMinimumMaximumImageFilterTest ); REGISTER_TEST(itkNeighborhoodConnectedImageFilterTest ); REGISTER_TEST(itkNormalizeImageFilterTest ); REGISTER_TEST(itkPermuteAxesImageFilterTest ); REGISTER_TEST(itkPlaheImageFilterTest ); REGISTER_TEST(itkReflectiveImageRegionIteratorTest ); REGISTER_TEST(itkReflectImageFilterTest ); REGISTER_TEST(itkResampleImageTest ); REGISTER_TEST(itkRecursiveGaussianImageFiltersTest ); REGISTER_TEST(itkShiftScaleImageFilterTest ); REGISTER_TEST(itkShrinkImageTest ); REGISTER_TEST(itkStatisticsImageFilterTest ); REGISTER_TEST(itkConstantPadImageTest ); REGISTER_TEST(itkWrapPadImageTest ); REGISTER_TEST(itkMirrorPadImageTest ); REGISTER_TEST(itkExtractImageTest ); REGISTER_TEST(itkSinImageFilterAndAdaptorTest ); REGISTER_TEST(itkSpatialFunctionImageEvaluatorFilterTest ); REGISTER_TEST(itkSqrtImageFilterAndAdaptorTest ); REGISTER_TEST(itkStreamingImageFilterTest ); REGISTER_TEST(itkStreamingImageFilterTest2 ); REGISTER_TEST(itkSubtractImageFilterTest ); REGISTER_TEST(itkTanImageFilterAndAdaptorTest ); REGISTER_TEST(itkTernaryMagnitudeImageFilterTest ); REGISTER_TEST(itkThresholdImageFilterTest ); REGISTER_TEST(itkTransformMeshFilterTest ); REGISTER_TEST(itkVectorAnisotropicDiffusionImageFilterTest ); REGISTER_TEST(itkGradientAnisotropicDiffusionImageFilterTest ); REGISTER_TEST(itkGradientMagnitudeImageFilterTest ); REGISTER_TEST(itkGradientImageFilterTest ); REGISTER_TEST(itkGradientRecursiveGaussianFilterTest ); REGISTER_TEST(itkNeighborhoodOperatorImageFilterTest ); REGISTER_TEST(itkVectorNeighborhoodOperatorImageFilterTest ); REGISTER_TEST(itkNaryAddImageFilterTest ); REGISTER_TEST(itkDerivativeImageFilterTest ); REGISTER_TEST(itkDiscreteGaussianImageFilterTest ); REGISTER_TEST(itkWarpImageFilterTest ); REGISTER_TEST(itkZeroCrossingImageFilterTest ); REGISTER_TEST(itkLaplacianImageFilterTest ); REGISTER_TEST(itkDivideImageFilterTest ); REGISTER_TEST(itkSobelEdgeDetectionImageFilterTest ); REGISTER_TEST(itkZeroCrossingBasedEdgeDetectionImageFilterTest ); REGISTER_TEST(itkCannyEdgeDetectionImageFilterTest ); } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkSTLContainerAdaptorTest.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 "itkVectorContainer.h" #include "itkMapContainer.h" #include "itkSTLContainerAdaptor.h" #include "itkSTLConstContainerAdaptor.h" int itkSTLContainerAdaptorTest(int, char**) { typedef unsigned long IndexType; typedef int ElementType; const unsigned int containerSize = 100; // Test with the VectorContainer { // create a local scope std::cout << "Testing the VectorContainer " << std::endl; typedef itk::VectorContainer<IndexType, ElementType> VectorContainerType; VectorContainerType::Pointer vectorContainer = VectorContainerType::New(); typedef std::vector<ElementType> STLVectorType; STLVectorType vectorSource; for (unsigned int i = 0; i < containerSize; i++) { vectorSource.push_back(containerSize - i); } const unsigned int containerSize = vectorSource.size(); typedef itk::STLContainerAdaptor<VectorContainerType> AdaptorType; typedef AdaptorType::TargetType TargetType; std::cout << "----- Testing non-const Adaptor " << std::endl; vectorContainer->Print(std::cout); { // define a local scope AdaptorType adaptor( vectorContainer ); TargetType & targetRef = adaptor.GetSTLContainerRef(); std::cout << "Testing assignment... "; targetRef.reserve( vectorSource.size() ); targetRef.assign( vectorSource.begin(), vectorSource.end() ); STLVectorType::const_iterator it = vectorSource.begin(); VectorContainerType::ConstIterator cIter = vectorContainer->Begin(); while( it != vectorSource.end() && cIter != vectorContainer->End() ) { if( *it != cIter.Value() ) { std::cerr << "Error in comparision !" << std::endl; return EXIT_FAILURE; } ++cIter; ++it; } // here, check for premature ending of the while loop if( it != vectorSource.end() || cIter != vectorContainer->End() ) { std::cerr << "Error, iteration on containers didn't finished simultaneously" << std::endl; } std::cout << "Passed !" << std::endl; // Test of index access std::cout << "Testing index access... "; for (unsigned int i = 0; i < containerSize; i++) { if( vectorSource[i] != vectorContainer->GetElement(i) ) { std::cerr << "Error, comparing element # " << i << std::endl; return EXIT_FAILURE; } } std::cout << "Passed !" << std::endl; } typedef itk::STLConstContainerAdaptor<VectorContainerType> ConstAdaptorType; typedef ConstAdaptorType::TargetType ConstTargetType; std::cout << "----- Testing const Adaptor " << std::endl; { // define a local scope ConstAdaptorType constAdaptor(vectorContainer); ConstTargetType & constTargetRef = constAdaptor.GetSTLConstContainerRef(); STLVectorType destination; std::cout << "Testing reading assignment... "; destination.assign( constTargetRef.begin(), constTargetRef.end() ); STLVectorType::const_iterator it = destination.begin(); VectorContainerType::ConstIterator cIter = vectorContainer->Begin(); while( it != destination.end() && cIter != vectorContainer->End() ) { if( *it != cIter.Value() ) { std::cerr << "Error in comparision !" << std::endl; return EXIT_FAILURE; } ++it; ++cIter; } // here, check for premature ending of the while loop if( it != destination.end() || cIter != vectorContainer->End() ) { std::cerr << "Error, iteration on containers didn't finished simultaneously" << std::endl; } std::cout << "Passed !" << std::endl; // Test of index access std::cout << "Testing index access... "; for (unsigned int i = 0; i < containerSize; i++) { if( destination[i] != vectorContainer->GetElement(i) ) { std::cerr << "Error, comparing element # " << i << std::endl; return EXIT_FAILURE; } } std::cout << "Passed !" << std::endl; } std::cout << std::endl; std::cout << "VectorContainer test passed ! " << std::endl; } // Test with the MapContainer typedef itk::MapContainer<IndexType, ElementType> MapContainerType; { // create a local scope std::cout << "Testing the MapContainer " << std::endl; typedef itk::MapContainer<IndexType, ElementType> MapContainerType; MapContainerType::Pointer mapContainer = MapContainerType::New(); typedef std::map<int,ElementType> STLMapType; STLMapType mapSource; for (unsigned int i = 0; i < containerSize; i++) { mapSource[i] = containerSize - i; } const unsigned int containerSize = mapSource.size(); typedef itk::STLContainerAdaptor<MapContainerType> AdaptorType; typedef AdaptorType::TargetType TargetType; std::cout << "----- Testing non-const Adaptor " << std::endl; mapContainer->Print(std::cout); { // define a local scope AdaptorType adaptor( mapContainer ); TargetType & targetRef = adaptor.GetSTLContainerRef(); std::cout << "Testing assignment... "; for(unsigned int i=0; i < containerSize; i++) { targetRef[i] = mapSource[i]; } STLMapType::const_iterator it = mapSource.begin(); MapContainerType::ConstIterator cIter = mapContainer->Begin(); while( it != mapSource.end() && cIter != mapContainer->End() ) { if( it->second != cIter.Value() ) { std::cerr << "Error in comparision !" << std::endl; return EXIT_FAILURE; } ++cIter; ++it; } // here, check for premature ending of the while loop if( it != mapSource.end() || cIter != mapContainer->End() ) { std::cerr << "Error, iteration on containers didn't finished simultaneously" << std::endl; } std::cout << "Passed !" << std::endl; // Test of index access std::cout << "Testing index access... "; for (unsigned int i = 0; i < containerSize; i++) { if( mapSource[i] != mapContainer->GetElement(i) ) { std::cerr << "Error, comparing element # " << i << std::endl; return EXIT_FAILURE; } } std::cout << "Passed !" << std::endl; } typedef itk::STLConstContainerAdaptor<MapContainerType> ConstAdaptorType; typedef ConstAdaptorType::TargetType ConstTargetType; std::cout << "----- Testing const Adaptor " << std::endl; { // define a local scope ConstAdaptorType constAdaptor(mapContainer); ConstTargetType & constTargetRef = constAdaptor.GetSTLConstContainerRef(); STLMapType destination; std::cout << "Testing reading assignment... "; for( unsigned int i=0; i < containerSize; i++) { destination[i] = constTargetRef.find(i)->second; } STLMapType::const_iterator it = destination.begin(); MapContainerType::ConstIterator cIter = mapContainer->Begin(); while( it != destination.end() && cIter != mapContainer->End() ) { if( it->second != cIter.Value() ) { std::cerr << "Error in comparision !" << std::endl; return EXIT_FAILURE; } ++it; ++cIter; } // here, check for premature ending of the while loop if( it != destination.end() || cIter != mapContainer->End() ) { std::cerr << "Error, iteration on containers didn't finished simultaneously" << std::endl; } std::cout << "Passed !" << std::endl; // Test of index access std::cout << "Testing index access... "; for (unsigned int i = 0; i < containerSize; i++) { if( destination[i] != mapContainer->GetElement(i) ) { std::cerr << "Error, comparing element # " << i << std::endl; return EXIT_FAILURE; } } std::cout << "Passed !" << std::endl; } std::cout << std::endl; std::cout << "MapContainer test passed ! " << std::endl; } return EXIT_SUCCESS; } <commit_msg>FIX: for() scope still broken in Visual C++ forces to use the letter "j" from time to time.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkSTLContainerAdaptorTest.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 "itkVectorContainer.h" #include "itkMapContainer.h" #include "itkSTLContainerAdaptor.h" #include "itkSTLConstContainerAdaptor.h" int itkSTLContainerAdaptorTest(int, char**) { typedef unsigned long IndexType; typedef int ElementType; const unsigned int containerSize = 100; // Test with the VectorContainer { // create a local scope std::cout << "Testing the VectorContainer " << std::endl; typedef itk::VectorContainer<IndexType, ElementType> VectorContainerType; VectorContainerType::Pointer vectorContainer = VectorContainerType::New(); typedef std::vector<ElementType> STLVectorType; STLVectorType vectorSource; for (unsigned int i = 0; i < containerSize; i++) { vectorSource.push_back(containerSize - i); } const unsigned int containerSize = vectorSource.size(); typedef itk::STLContainerAdaptor<VectorContainerType> AdaptorType; typedef AdaptorType::TargetType TargetType; std::cout << "----- Testing non-const Adaptor " << std::endl; vectorContainer->Print(std::cout); { // define a local scope AdaptorType adaptor( vectorContainer ); TargetType & targetRef = adaptor.GetSTLContainerRef(); std::cout << "Testing assignment... "; targetRef.reserve( vectorSource.size() ); targetRef.assign( vectorSource.begin(), vectorSource.end() ); STLVectorType::const_iterator it = vectorSource.begin(); VectorContainerType::ConstIterator cIter = vectorContainer->Begin(); while( it != vectorSource.end() && cIter != vectorContainer->End() ) { if( *it != cIter.Value() ) { std::cerr << "Error in comparision !" << std::endl; return EXIT_FAILURE; } ++cIter; ++it; } // here, check for premature ending of the while loop if( it != vectorSource.end() || cIter != vectorContainer->End() ) { std::cerr << "Error, iteration on containers didn't finished simultaneously" << std::endl; } std::cout << "Passed !" << std::endl; // Test of index access std::cout << "Testing index access... "; for (unsigned int i = 0; i < containerSize; i++) { if( vectorSource[i] != vectorContainer->GetElement(i) ) { std::cerr << "Error, comparing element # " << i << std::endl; return EXIT_FAILURE; } } std::cout << "Passed !" << std::endl; } typedef itk::STLConstContainerAdaptor<VectorContainerType> ConstAdaptorType; typedef ConstAdaptorType::TargetType ConstTargetType; std::cout << "----- Testing const Adaptor " << std::endl; { // define a local scope ConstAdaptorType constAdaptor(vectorContainer); ConstTargetType & constTargetRef = constAdaptor.GetSTLConstContainerRef(); STLVectorType destination; std::cout << "Testing reading assignment... "; destination.assign( constTargetRef.begin(), constTargetRef.end() ); STLVectorType::const_iterator it = destination.begin(); VectorContainerType::ConstIterator cIter = vectorContainer->Begin(); while( it != destination.end() && cIter != vectorContainer->End() ) { if( *it != cIter.Value() ) { std::cerr << "Error in comparision !" << std::endl; return EXIT_FAILURE; } ++it; ++cIter; } // here, check for premature ending of the while loop if( it != destination.end() || cIter != vectorContainer->End() ) { std::cerr << "Error, iteration on containers didn't finished simultaneously" << std::endl; } std::cout << "Passed !" << std::endl; // Test of index access std::cout << "Testing index access... "; for (unsigned int i = 0; i < containerSize; i++) { if( destination[i] != vectorContainer->GetElement(i) ) { std::cerr << "Error, comparing element # " << i << std::endl; return EXIT_FAILURE; } } std::cout << "Passed !" << std::endl; } std::cout << std::endl; std::cout << "VectorContainer test passed ! " << std::endl; } // Test with the MapContainer typedef itk::MapContainer<IndexType, ElementType> MapContainerType; { // create a local scope std::cout << "Testing the MapContainer " << std::endl; typedef itk::MapContainer<IndexType, ElementType> MapContainerType; MapContainerType::Pointer mapContainer = MapContainerType::New(); typedef std::map<int,ElementType> STLMapType; STLMapType mapSource; for (unsigned int i = 0; i < containerSize; i++) { mapSource[i] = containerSize - i; } const unsigned int containerSize = mapSource.size(); typedef itk::STLContainerAdaptor<MapContainerType> AdaptorType; typedef AdaptorType::TargetType TargetType; std::cout << "----- Testing non-const Adaptor " << std::endl; mapContainer->Print(std::cout); { // define a local scope AdaptorType adaptor( mapContainer ); TargetType & targetRef = adaptor.GetSTLContainerRef(); std::cout << "Testing assignment... "; for(unsigned int i=0; i < containerSize; i++) { targetRef[i] = mapSource[i]; } STLMapType::const_iterator it = mapSource.begin(); MapContainerType::ConstIterator cIter = mapContainer->Begin(); while( it != mapSource.end() && cIter != mapContainer->End() ) { if( it->second != cIter.Value() ) { std::cerr << "Error in comparision !" << std::endl; return EXIT_FAILURE; } ++cIter; ++it; } // here, check for premature ending of the while loop if( it != mapSource.end() || cIter != mapContainer->End() ) { std::cerr << "Error, iteration on containers didn't finished simultaneously" << std::endl; } std::cout << "Passed !" << std::endl; // Test of index access std::cout << "Testing index access... "; for (unsigned int j = 0; j < containerSize; j++) { if( mapSource[j] != mapContainer->GetElement(j) ) { std::cerr << "Error, comparing element # " << j << std::endl; return EXIT_FAILURE; } } std::cout << "Passed !" << std::endl; } typedef itk::STLConstContainerAdaptor<MapContainerType> ConstAdaptorType; typedef ConstAdaptorType::TargetType ConstTargetType; std::cout << "----- Testing const Adaptor " << std::endl; { // define a local scope ConstAdaptorType constAdaptor(mapContainer); ConstTargetType & constTargetRef = constAdaptor.GetSTLConstContainerRef(); STLMapType destination; std::cout << "Testing reading assignment... "; for( unsigned int i=0; i < containerSize; i++) { destination[i] = constTargetRef.find(i)->second; } STLMapType::const_iterator it = destination.begin(); MapContainerType::ConstIterator cIter = mapContainer->Begin(); while( it != destination.end() && cIter != mapContainer->End() ) { if( it->second != cIter.Value() ) { std::cerr << "Error in comparision !" << std::endl; return EXIT_FAILURE; } ++it; ++cIter; } // here, check for premature ending of the while loop if( it != destination.end() || cIter != mapContainer->End() ) { std::cerr << "Error, iteration on containers didn't finished simultaneously" << std::endl; } std::cout << "Passed !" << std::endl; // Test of index access std::cout << "Testing index access... "; for (unsigned int j = 0; j < containerSize; j++) { if( destination[j] != mapContainer->GetElement(j) ) { std::cerr << "Error, comparing element # " << j << std::endl; return EXIT_FAILURE; } } std::cout << "Passed !" << std::endl; } std::cout << std::endl; std::cout << "MapContainer test passed ! " << std::endl; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkDataSetMapper.cc Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkDataSetMapper.hh" #include "vtkPolyMapper.hh" vtkDataSetMapper::vtkDataSetMapper() { this->GeometryExtractor = NULL; this->PolyMapper = NULL; } vtkDataSetMapper::~vtkDataSetMapper() { // delete internally created objects. if ( this->GeometryExtractor ) this->GeometryExtractor->Delete(); if ( this->PolyMapper ) this->PolyMapper->Delete(); } void vtkDataSetMapper::SetInput(vtkDataSet *in) { if (in != this->Input ) { this->Input = in; this->Modified(); } } // // Return bounding box of data // float *vtkDataSetMapper::GetBounds() { static float bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0}; if ( ! this->Input ) return bounds; else { this->Input->Update(); return this->Input->GetBounds(); } } // // Receives from Actor -> maps data to primitives // void vtkDataSetMapper::Render(vtkRenderer *ren, vtkActor *act) { // // make sure that we've been properly initialized // if ( !this->Input ) { vtkErrorMacro(<< "No input!\n"); return; } // // Need a lookup table // if ( this->LookupTable == NULL ) this->CreateDefaultLookupTable(); this->LookupTable->Build(); // // Now can create appropriate mapper // if ( this->PolyMapper == NULL ) { vtkGeometryFilter *gf = new vtkGeometryFilter(); vtkPolyMapper *pm = new vtkPolyMapper; pm->SetInput(gf->GetOutput()); this->GeometryExtractor = gf; this->PolyMapper = pm; } // update ourselves in case something has changed this->PolyMapper->SetLookupTable(this->GetLookupTable()); this->PolyMapper->SetScalarsVisible(this->GetScalarsVisible()); this->PolyMapper->SetScalarRange(this->GetScalarRange()); this->GeometryExtractor->SetInput(this->Input); this->PolyMapper->Render(ren,act); } void vtkDataSetMapper::PrintSelf(ostream& os, vtkIndent indent) { vtkMapper::PrintSelf(os,indent); if ( this->PolyMapper ) { os << indent << "Poly Mapper: (" << this->PolyMapper << ")\n"; } else { os << indent << "Poly Mapper: (none)\n"; } if ( this->GeometryExtractor ) { os << indent << "Geometry Extractor: (" << this->GeometryExtractor << ")\n"; } else { os << indent << "Geometry Extractor: (none)\n"; } } <commit_msg>ENH: Improved performance for vtkPolyData input.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkDataSetMapper.cc Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkDataSetMapper.hh" #include "vtkPolyMapper.hh" vtkDataSetMapper::vtkDataSetMapper() { this->GeometryExtractor = NULL; this->PolyMapper = NULL; } vtkDataSetMapper::~vtkDataSetMapper() { // delete internally created objects. if ( this->GeometryExtractor ) this->GeometryExtractor->Delete(); if ( this->PolyMapper ) this->PolyMapper->Delete(); } void vtkDataSetMapper::SetInput(vtkDataSet *in) { if (in != this->Input ) { this->Input = in; this->Modified(); } } // // Return bounding box of data // float *vtkDataSetMapper::GetBounds() { static float bounds[] = {-1.0,1.0, -1.0,1.0, -1.0,1.0}; if ( ! this->Input ) return bounds; else { this->Input->Update(); return this->Input->GetBounds(); } } // // Receives from Actor -> maps data to primitives // void vtkDataSetMapper::Render(vtkRenderer *ren, vtkActor *act) { // // make sure that we've been properly initialized // if ( !this->Input ) { vtkErrorMacro(<< "No input!\n"); return; } // // Need a lookup table // if ( this->LookupTable == NULL ) this->CreateDefaultLookupTable(); this->LookupTable->Build(); // // Now can create appropriate mapper // if ( this->PolyMapper == NULL ) { vtkGeometryFilter *gf = new vtkGeometryFilter(); vtkPolyMapper *pm = new vtkPolyMapper; pm->SetInput(gf->GetOutput()); this->GeometryExtractor = gf; this->PolyMapper = pm; } // // For efficiency: if input type is vtkPolyData, there's no need to pass it thru // the geometry filter. // if ( ! strcmp(this->Input->GetDataType(),"vtkPolyData") ) { this->PolyMapper->SetInput((vtkPolyData *)this->Input); } else { this->GeometryExtractor->SetInput(this->Input); this->PolyMapper->SetInput(this->GeometryExtractor->GetOutput()); } // update ourselves in case something has changed this->PolyMapper->SetLookupTable(this->GetLookupTable()); this->PolyMapper->SetScalarsVisible(this->GetScalarsVisible()); this->PolyMapper->SetScalarRange(this->GetScalarRange()); this->PolyMapper->Render(ren,act); } void vtkDataSetMapper::PrintSelf(ostream& os, vtkIndent indent) { vtkMapper::PrintSelf(os,indent); if ( this->PolyMapper ) { os << indent << "Poly Mapper: (" << this->PolyMapper << ")\n"; } else { os << indent << "Poly Mapper: (none)\n"; } if ( this->GeometryExtractor ) { os << indent << "Geometry Extractor: (" << this->GeometryExtractor << ")\n"; } else { os << indent << "Geometry Extractor: (none)\n"; } } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/desktop_background/desktop_background_view.h" #include "ash/ash_export.h" #include "ash/shell.h" #include "ash/shell_window_ids.h" #include "base/utf_string_conversions.h" #include "grit/ui_resources.h" #include "ui/aura/root_window.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas.h" #include "ui/gfx/image/image.h" #include "ui/views/widget/widget.h" namespace ash { namespace internal { //////////////////////////////////////////////////////////////////////////////// // DesktopBackgroundView, public: DesktopBackgroundView::DesktopBackgroundView() { wallpaper_ = *ui::ResourceBundle::GetSharedInstance().GetImageNamed( IDR_AURA_WALLPAPER).ToSkBitmap(); wallpaper_.buildMipMap(false); } DesktopBackgroundView::~DesktopBackgroundView() { } //////////////////////////////////////////////////////////////////////////////// // DesktopBackgroundView, views::View overrides: void DesktopBackgroundView::OnPaint(gfx::Canvas* canvas) { canvas->DrawBitmapInt(wallpaper_, 0, 0, wallpaper_.width(), wallpaper_.height(), 0, 0, width(), height(), true); } bool DesktopBackgroundView::OnMousePressed(const views::MouseEvent& event) { return true; } void DesktopBackgroundView::OnMouseReleased(const views::MouseEvent& event) { if (event.IsRightMouseButton()) Shell::GetInstance()->ShowBackgroundMenu(GetWidget(), event.location()); } views::Widget* CreateDesktopBackground() { views::Widget* desktop_widget = new views::Widget; views::Widget::InitParams params( views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); DesktopBackgroundView* view = new DesktopBackgroundView; params.delegate = view; params.parent = Shell::GetInstance()->GetContainer( ash::internal::kShellWindowId_DesktopBackgroundContainer); desktop_widget->Init(params); desktop_widget->SetContentsView(view); desktop_widget->Show(); desktop_widget->GetNativeView()->SetName("DesktopBackgroundView"); return desktop_widget; } } // namespace internal } // namespace ash <commit_msg>Change Aura desktop background behavior.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/desktop_background/desktop_background_view.h" #include "ash/ash_export.h" #include "ash/shell.h" #include "ash/shell_window_ids.h" #include "base/utf_string_conversions.h" #include "grit/ui_resources.h" #include "ui/aura/root_window.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas.h" #include "ui/gfx/image/image.h" #include "ui/views/widget/widget.h" namespace ash { namespace internal { //////////////////////////////////////////////////////////////////////////////// // DesktopBackgroundView, public: DesktopBackgroundView::DesktopBackgroundView() { wallpaper_ = *ui::ResourceBundle::GetSharedInstance().GetImageNamed( IDR_AURA_WALLPAPER).ToSkBitmap(); wallpaper_.buildMipMap(false); } DesktopBackgroundView::~DesktopBackgroundView() { } //////////////////////////////////////////////////////////////////////////////// // DesktopBackgroundView, views::View overrides: void DesktopBackgroundView::OnPaint(gfx::Canvas* canvas) { // Scale the image while maintaining the aspect ratio, cropping as // necessary to fill the background. Ideally the image should be larger // than the largest display supported, if not we will center it rather than // streching to avoid upsampling artifacts (Note that we could tile too, but // decided not to do this at the moment). gfx::Rect wallpaper_rect(0, 0, wallpaper_.width(), wallpaper_.height()); if (wallpaper_.width() > width() && wallpaper_.height() > height()) { // The dimension with the smallest ratio must be cropped, the other one // is preserved. Both are set in gfx::Size cropped_size. double horizontal_ratio = static_cast<double>(width()) / static_cast<double>(wallpaper_.width()); double vertical_ratio = static_cast<double>(height()) / static_cast<double>(wallpaper_.height()); gfx::Size cropped_size; if (vertical_ratio > horizontal_ratio) { cropped_size = gfx::Size( static_cast<int>( round(static_cast<double>(width()) / vertical_ratio)), wallpaper_.height()); } else { cropped_size = gfx::Size(wallpaper_.width(), static_cast<int>( round(static_cast<double>(height()) / horizontal_ratio))); } gfx::Rect wallpaper_cropped_rect = wallpaper_rect.Center(cropped_size); canvas->DrawBitmapInt(wallpaper_, wallpaper_cropped_rect.x(), wallpaper_cropped_rect.y(), wallpaper_cropped_rect.width(), wallpaper_cropped_rect.height(), 0, 0, width(), height(), true); } else { // Center the wallpaper in the destination rectangle (Skia will crop // as needed). canvas->DrawBitmapInt(wallpaper_, (width() - wallpaper_.width()) / 2, (height() - wallpaper_.height()) / 2); } } bool DesktopBackgroundView::OnMousePressed(const views::MouseEvent& event) { return true; } void DesktopBackgroundView::OnMouseReleased(const views::MouseEvent& event) { if (event.IsRightMouseButton()) Shell::GetInstance()->ShowBackgroundMenu(GetWidget(), event.location()); } views::Widget* CreateDesktopBackground() { views::Widget* desktop_widget = new views::Widget; views::Widget::InitParams params( views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); DesktopBackgroundView* view = new DesktopBackgroundView; params.delegate = view; params.parent = Shell::GetInstance()->GetContainer( ash::internal::kShellWindowId_DesktopBackgroundContainer); desktop_widget->Init(params); desktop_widget->SetContentsView(view); desktop_widget->Show(); desktop_widget->GetNativeView()->SetName("DesktopBackgroundView"); return desktop_widget; } } // namespace internal } // namespace ash <|endoftext|>
<commit_before>// $Id$ // // Test Suite for geos::operation::geounion::CascadedPolygonUnion class. // tut #include <tut.hpp> // geos #include <geos/operation/union/UnaryUnionOp.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/Geometry.h> #include <geos/geom/Polygon.h> #include <geos/geom/Point.h> #include <geos/io/WKTReader.h> #include <geos/io/WKTWriter.h> // std #include <memory> #include <string> #include <vector> #include <iostream> namespace tut { // // Test Group // // Common data used by tests struct test_unaryuniontest_data { geos::geom::GeometryFactory gf; geos::io::WKTReader wktreader; geos::io::WKTWriter wktwriter; typedef geos::geom::Geometry::AutoPtr GeomPtr; typedef geos::geom::Geometry Geom; typedef geos::operation::geounion::UnaryUnionOp UnaryUnionOp; test_unaryuniontest_data() : gf(), wktreader(&gf) { wktwriter.setTrim(true); } void delAll(std::vector<Geom*>& geoms) { for (size_t i=0; i<geoms.size(); ++i) delete geoms[i]; } GeomPtr readWKT(const std::string& inputWKT) { return GeomPtr(wktreader.read(inputWKT)); } void readWKT(const char* const* inputWKT, std::vector<Geom*>& geoms) { for (const char* const* ptr=inputWKT; *ptr; ++ptr) { geoms.push_back(readWKT(*ptr).release()); } } static GeomPtr normalize(const Geom& g) { GeomPtr g2 ( g.clone() ); g2->normalize(); return g2; } bool isEqual(const Geom& a, const Geom& b) { using std::cout; using std::endl; GeomPtr a2 = normalize(a); GeomPtr b2 = normalize(b); bool eq = a2->equalsExact(b2.get()); if ( ! eq ) { cout << "OBTAINED: " << wktwriter.write(b2.get()) << endl; } return eq; } void doTest(const char* const* inputWKT, const std::string& expectedWKT) { std::vector<Geom*> geoms; readWKT(inputWKT, geoms); GeomPtr result; if ( geoms.empty() ) result = UnaryUnionOp::Union(geoms, gf); else result = UnaryUnionOp::Union(geoms); bool ok = isEqual(*readWKT(expectedWKT), *result); delAll(geoms); ensure(ok); } }; typedef test_group<test_unaryuniontest_data> group; typedef group::object object; group test_unaryuniontest_group("geos::operation::geounion::UnaryUnionOp"); template<> template<> void object::test<1>() { static char const* const geoms[] = { NULL }; doTest(geoms, "GEOMETRYCOLLECTION EMPTY"); } template<> template<> void object::test<2>() { static char const* const geoms[] = { "POINT (1 1)", "POINT (2 2)", NULL }; doTest(geoms, "MULTIPOINT ((1 1), (2 2))"); } template<> template<> void object::test<3>() { static char const* const geoms[] = { "GEOMETRYCOLLECTION (POLYGON ((0 0, 0 90, 90 90, 90 0, 0 0)), POLYGON ((120 0, 120 90, 210 90, 210 0, 120 0)), LINESTRING (40 50, 40 140), LINESTRING (160 50, 160 140), POINT (60 50), POINT (60 140), POINT (40 140))", NULL }; doTest(geoms, "GEOMETRYCOLLECTION (POINT (60 140), LINESTRING (40 90, 40 140), LINESTRING (160 90, 160 140), POLYGON ((0 0, 0 90, 40 90, 90 90, 90 0, 0 0)), POLYGON ((120 0, 120 90, 160 90, 210 90, 210 0, 120 0)))"); } template<> template<> void object::test<4>() { static char const* const geoms[] = { "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", "MULTIPOLYGON (((20 0, 20 10, 40 10, 40 0, 20 0)),((5 5, 5 8, 8 8, 8 5, 5 5)))", "POINT (5 5)", "POINT (-5 5)", "LINESTRING (-10 -10, -10 0, -10 20)", "LINESTRING (-10 2, 10 2)", NULL }; doTest(geoms, "GEOMETRYCOLLECTION (POLYGON ((0 0, 0 2, 0 10, 10 10, 10 2, 10 0, 0 0)), POLYGON ((20 0, 20 10, 40 10, 40 0, 20 0)), LINESTRING (-10 -10, -10 0, -10 2), LINESTRING (-10 2, 0 2), LINESTRING (-10 2, -10 20), POINT (-5 5))"); } } // namespace tut <commit_msg>Add test exposing the std::copy bug of two commits ago<commit_after>// $Id$ // // Test Suite for geos::operation::geounion::CascadedPolygonUnion class. // tut #include <tut.hpp> // geos #include <geos/operation/union/UnaryUnionOp.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/Geometry.h> #include <geos/geom/Polygon.h> #include <geos/geom/Point.h> #include <geos/io/WKTReader.h> #include <geos/io/WKTWriter.h> // std #include <memory> #include <string> #include <vector> #include <iostream> namespace tut { // // Test Group // // Common data used by tests struct test_unaryuniontest_data { geos::geom::GeometryFactory gf; geos::io::WKTReader wktreader; geos::io::WKTWriter wktwriter; typedef geos::geom::Geometry::AutoPtr GeomPtr; typedef geos::geom::Geometry Geom; typedef geos::operation::geounion::UnaryUnionOp UnaryUnionOp; test_unaryuniontest_data() : gf(), wktreader(&gf) { wktwriter.setTrim(true); } void delAll(std::vector<Geom*>& geoms) { for (size_t i=0; i<geoms.size(); ++i) delete geoms[i]; } GeomPtr readWKT(const std::string& inputWKT) { return GeomPtr(wktreader.read(inputWKT)); } void readWKT(const char* const* inputWKT, std::vector<Geom*>& geoms) { for (const char* const* ptr=inputWKT; *ptr; ++ptr) { geoms.push_back(readWKT(*ptr).release()); } } static GeomPtr normalize(const Geom& g) { GeomPtr g2 ( g.clone() ); g2->normalize(); return g2; } bool isEqual(const Geom& a, const Geom& b) { using std::cout; using std::endl; GeomPtr a2 = normalize(a); GeomPtr b2 = normalize(b); bool eq = a2->equalsExact(b2.get()); if ( ! eq ) { cout << "OBTAINED: " << wktwriter.write(b2.get()) << endl; } return eq; } void doTest(const char* const* inputWKT, const std::string& expectedWKT) { std::vector<Geom*> geoms; readWKT(inputWKT, geoms); GeomPtr result; if ( geoms.empty() ) result = UnaryUnionOp::Union(geoms, gf); else result = UnaryUnionOp::Union(geoms); bool ok = isEqual(*readWKT(expectedWKT), *result); delAll(geoms); ensure(ok); } }; typedef test_group<test_unaryuniontest_data> group; typedef group::object object; group test_unaryuniontest_group("geos::operation::geounion::UnaryUnionOp"); template<> template<> void object::test<1>() { static char const* const geoms[] = { NULL }; doTest(geoms, "GEOMETRYCOLLECTION EMPTY"); } template<> template<> void object::test<2>() { static char const* const geoms[] = { "POINT (1 1)", "POINT (2 2)", NULL }; doTest(geoms, "MULTIPOINT ((1 1), (2 2))"); } template<> template<> void object::test<3>() { static char const* const geoms[] = { "GEOMETRYCOLLECTION (POLYGON ((0 0, 0 90, 90 90, 90 0, 0 0)), POLYGON ((120 0, 120 90, 210 90, 210 0, 120 0)), LINESTRING (40 50, 40 140), LINESTRING (160 50, 160 140), POINT (60 50), POINT (60 140), POINT (40 140))", NULL }; doTest(geoms, "GEOMETRYCOLLECTION (POINT (60 140), LINESTRING (40 90, 40 140), LINESTRING (160 90, 160 140), POLYGON ((0 0, 0 90, 40 90, 90 90, 90 0, 0 0)), POLYGON ((120 0, 120 90, 160 90, 210 90, 210 0, 120 0)))"); } template<> template<> void object::test<4>() { static char const* const geoms[] = { "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))", "MULTIPOLYGON (((20 0, 20 10, 40 10, 40 0, 20 0)),((5 5, 5 8, 8 8, 8 5, 5 5)))", "POINT (5 5)", "POINT (-5 5)", "LINESTRING (-10 -10, -10 0, -10 20)", "LINESTRING (-10 2, 10 2)", NULL }; doTest(geoms, "GEOMETRYCOLLECTION (POLYGON ((0 0, 0 2, 0 10, 10 10, 10 2, 10 0, 0 0)), POLYGON ((20 0, 20 10, 40 10, 40 0, 20 0)), LINESTRING (-10 -10, -10 0, -10 2), LINESTRING (-10 2, 0 2), LINESTRING (-10 2, -10 20), POINT (-5 5))"); } template<> template<> void object::test<5>() { static char const* const geoms[] = { "LINESTRING (40 60, 120 110)", "POINT (120 110)", "POINT (40 60)", "POINT (100 70)", "POINT (80 50)", NULL }; doTest(geoms, "GEOMETRYCOLLECTION (POINT (80 50), POINT (100 70), LINESTRING (40 60, 120 110))"); } } // namespace tut <|endoftext|>
<commit_before>/* * This file is part of meego-keyboard * * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation (directui@nokia.com) * * If you have questions regarding the use of this file, please contact * Nokia at directui@nokia.com. * * 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 * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "ut_mtoolbarmanager.h" #include <mtoolbarmanager.h> #include <mtoolbardata.h> #include <mtoolbarid.h> #include <QCoreApplication> #include <QDebug> #include <QDir> namespace { const int ValidToolbarCount = 2; QString Toolbar1 = "/toolbar1.xml"; QString Toolbar2 = "/toolbar2.xml"; QString Toolbar3 = "/toolbar3.xml"; // this file does not exist } void Ut_MToolbarManager::initTestCase() { // Avoid waiting if im server is not responding // MApplication::setLoadMInputContext(false); static char *argv[1] = {(char *) "ut_toolbarmanager"}; static int argc = 1; app = new QCoreApplication(argc, argv); Toolbar1 = QCoreApplication::applicationDirPath() + Toolbar1; QVERIFY2(QFile(Toolbar1).exists(), "toolbar1.xml does not exist"); Toolbar2 = QCoreApplication::applicationDirPath() + Toolbar2; QVERIFY2(QFile(Toolbar2).exists(), "toolbar2.xml does not exist"); Toolbar3 = QCoreApplication::applicationDirPath() + Toolbar3; QVERIFY2(!QFile(Toolbar3).exists(), "toolbar3.xml should not exist"); } void Ut_MToolbarManager::cleanupTestCase() { delete app; app = 0; } void Ut_MToolbarManager::init() { subject = new MToolbarManager; } void Ut_MToolbarManager::cleanup() { delete subject; subject = 0; } void Ut_MToolbarManager::testLoadToolbar() { QList<MToolbarId> toolbarIds; for (qlonglong i = 1; i <= 3; i ++) { MToolbarId id(i, "Ut_MToolbarManager"); toolbarIds << id; } QStringList toolbars; toolbars << Toolbar1 << Toolbar2 << Toolbar3; int toolbarCount = 0; // register all toolbars for (int i = 0; i < toolbarIds.count(); i++) { subject->registerToolbar(toolbarIds.at(i), toolbars.at(i)); toolbarCount ++; QTest::qWait(50); //toolbar loop can only cache no more than MaximumToolbarCount toolbars if (i < ValidToolbarCount) QCOMPARE(subject->toolbarList().count(), toolbarCount); else QCOMPARE(subject->toolbarList().count(), ValidToolbarCount); } for (int i = 0; i < toolbarIds.count(); i++) { QSharedPointer<MToolbarData> toolbar = subject->toolbarData(toolbarIds.at(i)); if (i < ValidToolbarCount) { QVERIFY(!toolbar.isNull()); } else { QVERIFY(toolbar.isNull()); } } toolbarCount = ValidToolbarCount; for (int i = 0; i < toolbarIds.count(); i++) { subject->unregisterToolbar(toolbarIds.at(i)); if (i < ValidToolbarCount) { --toolbarCount; } QCOMPARE(subject->toolbars.count(), toolbarCount); QVERIFY(!subject->toolbars.contains(toolbarIds.at(i))); } } void Ut_MToolbarManager::testSetItemAttribute() { MToolbarId id1(1, "Ut_MToolbarManager"); MToolbarId id2(2, "Ut_MToolbarManager"); QList<MToolbarId> toolbarIds; toolbarIds << id1 << id2; QStringList toolbars; toolbars << Toolbar1 << Toolbar1; int toolbarCount = 0; // register all toolbars for (int i = 0; i < toolbarIds.count(); i++) { subject->registerToolbar(toolbarIds.at(i), toolbars.at(i)); toolbarCount ++; QTest::qWait(50); //toolbar loop can only cache no more than MaximumToolbarCount toolbars if (i < ValidToolbarCount) QCOMPARE(subject->toolbarList().count(), toolbarCount); else QCOMPARE(subject->toolbarList().count(), ValidToolbarCount); } subject->setToolbarItemAttribute(id1, "test1", "text", QVariant(QString("some text"))); QSharedPointer<MToolbarData> toolbar = subject->toolbarData(id1); QVERIFY(!toolbar.isNull()); QSharedPointer<MToolbarItem> item = toolbar->item("test1"); QVERIFY(!item.isNull()); QCOMPARE(item->text(), QString("some text")); toolbar = subject->toolbarData(id2); QVERIFY(!toolbar.isNull()); item = toolbar->item("test1"); QVERIFY(!item.isNull()); QVERIFY(item->text() != "some text"); // pass incorrect parameters. Test should not crash here MToolbarId invalidId; subject->setToolbarItemAttribute(invalidId, "test1", "text", QVariant(QString("some text"))); subject->setToolbarItemAttribute(id1, "invalid-item-name", "text", QVariant(QString("some text"))); } QTEST_APPLESS_MAIN(Ut_MToolbarManager); <commit_msg>Changes: updated unit test for toolbar manager<commit_after>/* * This file is part of meego-keyboard * * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation (directui@nokia.com) * * If you have questions regarding the use of this file, please contact * Nokia at directui@nokia.com. * * 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 * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "ut_mtoolbarmanager.h" #include <mtoolbarmanager.h> #include <mtoolbardata.h> #include <mtoolbarid.h> #include <QCoreApplication> #include <QDebug> #include <QDir> namespace { const int ValidToolbarCount = 3; QString Toolbar1 = "/toolbar1.xml"; QString Toolbar2 = "/toolbar2.xml"; QString Toolbar3 = "/toolbar3.xml"; // this file does not exist } void Ut_MToolbarManager::initTestCase() { // Avoid waiting if im server is not responding // MApplication::setLoadMInputContext(false); static char *argv[1] = {(char *) "ut_toolbarmanager"}; static int argc = 1; app = new QCoreApplication(argc, argv); Toolbar1 = QCoreApplication::applicationDirPath() + Toolbar1; QVERIFY2(QFile(Toolbar1).exists(), "toolbar1.xml does not exist"); Toolbar2 = QCoreApplication::applicationDirPath() + Toolbar2; QVERIFY2(QFile(Toolbar2).exists(), "toolbar2.xml does not exist"); Toolbar3 = QCoreApplication::applicationDirPath() + Toolbar3; QVERIFY2(!QFile(Toolbar3).exists(), "toolbar3.xml should not exist"); } void Ut_MToolbarManager::cleanupTestCase() { delete app; app = 0; } void Ut_MToolbarManager::init() { subject = new MToolbarManager; } void Ut_MToolbarManager::cleanup() { delete subject; subject = 0; } void Ut_MToolbarManager::testLoadToolbar() { QList<MToolbarId> toolbarIds; for (qlonglong i = 1; i <= 3; i ++) { MToolbarId id(i, "Ut_MToolbarManager"); toolbarIds << id; } QStringList toolbars; toolbars << Toolbar1 << Toolbar2 << Toolbar3; int toolbarCount = 0; // register all toolbars for (int i = 0; i < toolbarIds.count(); i++) { subject->registerToolbar(toolbarIds.at(i), toolbars.at(i)); toolbarCount ++; QTest::qWait(50); if (i < ValidToolbarCount) QCOMPARE(subject->toolbarList().count(), toolbarCount + 1); else QCOMPARE(subject->toolbarList().count(), ValidToolbarCount + 1); } for (int i = 0; i < toolbarIds.count(); i++) { QSharedPointer<MToolbarData> toolbar = subject->toolbarData(toolbarIds.at(i)); QVERIFY(!toolbar.isNull()); } toolbarCount = ValidToolbarCount; for (int i = 0; i < toolbarIds.count(); i++) { subject->unregisterToolbar(toolbarIds.at(i)); if (i < ValidToolbarCount) { --toolbarCount; } QCOMPARE(subject->toolbars.count(), toolbarCount + 1); QVERIFY(!subject->toolbars.contains(toolbarIds.at(i))); } } void Ut_MToolbarManager::testSetItemAttribute() { MToolbarId id1(1, "Ut_MToolbarManager"); MToolbarId id2(2, "Ut_MToolbarManager"); QList<MToolbarId> toolbarIds; toolbarIds << id1 << id2; QStringList toolbars; toolbars << Toolbar1 << Toolbar1; int toolbarCount = 0; // register all toolbars for (int i = 0; i < toolbarIds.count(); i++) { subject->registerToolbar(toolbarIds.at(i), toolbars.at(i)); toolbarCount ++; QTest::qWait(50); //toolbar loop can only cache no more than MaximumToolbarCount toolbars if (i < ValidToolbarCount) QCOMPARE(subject->toolbarList().count(), toolbarCount + 1); else QCOMPARE(subject->toolbarList().count(), ValidToolbarCount + 1); } subject->setToolbarItemAttribute(id1, "test1", "text", QVariant(QString("some text"))); QSharedPointer<MToolbarData> toolbar = subject->toolbarData(id1); QVERIFY(!toolbar.isNull()); QSharedPointer<MToolbarItem> item = toolbar->item("test1"); QVERIFY(!item.isNull()); QCOMPARE(item->text(), QString("some text")); toolbar = subject->toolbarData(id2); QVERIFY(!toolbar.isNull()); item = toolbar->item("test1"); QVERIFY(!item.isNull()); QVERIFY(item->text() != "some text"); // pass incorrect parameters. Test should not crash here MToolbarId invalidId; subject->setToolbarItemAttribute(invalidId, "test1", "text", QVariant(QString("some text"))); subject->setToolbarItemAttribute(id1, "invalid-item-name", "text", QVariant(QString("some text"))); } QTEST_APPLESS_MAIN(Ut_MToolbarManager); <|endoftext|>
<commit_before>#include "main_window.hpp" #include "../utility/threads.hpp" #include <QApplication> #include <iostream> using namespace std; using namespace datavis; int main(int argc, char *argv[]) { QApplication app(argc, argv); auto args = app.arguments(); QString file_path; if (args.size() > 1) { file_path = args[1]; } background_thread()->start(); auto main_win = new MainWindow; { auto fm = main_win->fontMetrics(); main_win->resize(fm.averageCharWidth() * 50, fm.height() * 30); main_win->move(50,50); } if (!file_path.isEmpty()) { main_win->openFile(file_path); } main_win->show(); int status = app.exec(); delete main_win; background_thread()->quit(); background_thread()->wait(); return status; } <commit_msg>Improve main window placement<commit_after>#include "main_window.hpp" #include "../utility/threads.hpp" #include <QApplication> #include <QScreen> #include <iostream> using namespace std; using namespace datavis; int main(int argc, char *argv[]) { QApplication app(argc, argv); auto args = app.arguments(); QString file_path; if (args.size() > 1) { file_path = args[1]; } background_thread()->start(); auto main_win = new MainWindow; { auto * screen = qGuiApp->primaryScreen(); if (screen) { auto screenRect = screen->availableGeometry(); main_win->resize(screenRect.width() * 0.3, screenRect.height()); main_win->move(screen->availableGeometry().topLeft()); } } if (!file_path.isEmpty()) { main_win->openFile(file_path); } main_win->show(); int status = app.exec(); delete main_win; background_thread()->quit(); background_thread()->wait(); return status; } <|endoftext|>
<commit_before>/* * Copyright 2007-2020 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "TempListener.hxx" #include "net/UniqueSocketDescriptor.hxx" #include "system/Error.hxx" #include <sys/stat.h> static void make_child_socket_path(struct sockaddr_un *address) { address->sun_family = AF_LOCAL; strcpy(address->sun_path, "/tmp/cm4all-beng-proxy-socket-XXXXXX"); if (*mktemp(address->sun_path) == 0) throw MakeErrno("mktemp() failed"); } TempListener::~TempListener() noexcept { if (IsDefined()) unlink(address.sun_path); } UniqueSocketDescriptor TempListener::Create(int socket_type, int backlog) { make_child_socket_path(&address); unlink(address.sun_path); UniqueSocketDescriptor fd; if (!fd.Create(AF_LOCAL, socket_type, 0)) throw MakeErrno("failed to create local socket"); /* allow only beng-proxy to connect to it */ fchmod(fd.Get(), 0600); if (!fd.Bind(GetAddress())) throw MakeErrno("failed to bind local socket"); if (!fd.Listen(backlog)) throw MakeErrno("failed to listen on local socket"); return fd; } UniqueSocketDescriptor TempListener::Connect() const { UniqueSocketDescriptor fd; if (!fd.CreateNonBlock(AF_LOCAL, SOCK_STREAM, 0)) throw MakeErrno("Failed to create socket"); if (!fd.Connect(GetAddress())) { int e = errno; fd.Close(); throw MakeErrno(e, "Failed to connect"); } return fd; } <commit_msg>net/TempListener: assign sun_family after successful mktemp() call<commit_after>/* * Copyright 2007-2020 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "TempListener.hxx" #include "net/UniqueSocketDescriptor.hxx" #include "system/Error.hxx" #include <sys/stat.h> static void make_child_socket_path(struct sockaddr_un *address) { strcpy(address->sun_path, "/tmp/cm4all-beng-proxy-socket-XXXXXX"); if (*mktemp(address->sun_path) == 0) throw MakeErrno("mktemp() failed"); address->sun_family = AF_LOCAL; } TempListener::~TempListener() noexcept { if (IsDefined()) unlink(address.sun_path); } UniqueSocketDescriptor TempListener::Create(int socket_type, int backlog) { make_child_socket_path(&address); unlink(address.sun_path); UniqueSocketDescriptor fd; if (!fd.Create(AF_LOCAL, socket_type, 0)) throw MakeErrno("failed to create local socket"); /* allow only beng-proxy to connect to it */ fchmod(fd.Get(), 0600); if (!fd.Bind(GetAddress())) throw MakeErrno("failed to bind local socket"); if (!fd.Listen(backlog)) throw MakeErrno("failed to listen on local socket"); return fd; } UniqueSocketDescriptor TempListener::Connect() const { UniqueSocketDescriptor fd; if (!fd.CreateNonBlock(AF_LOCAL, SOCK_STREAM, 0)) throw MakeErrno("Failed to create socket"); if (!fd.Connect(GetAddress())) { int e = errno; fd.Close(); throw MakeErrno(e, "Failed to connect"); } return fd; } <|endoftext|>
<commit_before> #include<osl/module.hxx> #include <osl/time.h> #include <rtl/ustring.hxx> #include <stdio.h> #include <cppuhelper/factory.hxx> #include <cppuhelper/servicefactory.hxx> #include <cppuhelper/bootstrap.hxx> #include <com/sun/star/lang/XMultiComponentFactory.hpp> #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/registry/XSimpleRegistry.hpp> #include <stdio.h> using namespace ::rtl; using namespace ::osl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::cppu; using namespace ::com::sun::star::registry; sal_Bool test1(); sal_Bool test2(); sal_Bool test3(); sal_Bool test4(); int main(int argc, char* argv[]) { sal_Bool bTest1= test1(); sal_Bool bTest2= test2(); sal_Bool bTest3= test3(); sal_Bool bTest4= test4(); if( bTest1 && bTest2 && bTest3 && bTest4) printf("\n#########################\n Test was successful\n#######################\n"); return 0; } sal_Bool test1() { printf("\n Test1: com.sun.star.bridge.OleBridgeSupplier2\n"); Reference<XSimpleRegistry> xreg= createSimpleRegistry(); xreg->open( OUString( RTL_CONSTASCII_USTRINGPARAM("applicat.rdb")), sal_False, sal_False ); Reference< XComponentContext > context= bootstrap_InitialComponentContext(xreg); Reference<XMultiComponentFactory> fac= context->getServiceManager(); OUString sService1( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.OleBridgeSupplier2")); Reference<XInterface> xint1= fac->createInstanceWithContext( sService1, context); OUString sModule( RTL_CONSTASCII_USTRINGPARAM("oleautobridge.uno" SAL_DLLEXTENSION)); oslModule hMod= osl_loadModule( sModule.pData, 0); osl_unloadModule( hMod); rtl_unloadUnusedModules( NULL); OUString sFactoryFunc( RTL_CONSTASCII_USTRINGPARAM("component_getFactory")); void* pSymbol= osl_getSymbol( hMod,sFactoryFunc.pData); // true, instance alive sal_Bool bTest1= pSymbol ? sal_True : sal_False; xint1=0; rtl_unloadUnusedModules( NULL); pSymbol= osl_getSymbol( hMod,sFactoryFunc.pData); sal_Bool bTest2= pSymbol ? sal_False : sal_True; Reference<XComponent> xcomp( context, UNO_QUERY); xcomp->dispose(); return bTest2 && bTest1; } sal_Bool test2() { printf("Test2: com.sun.star.bridge.OleBridgeSupplierVar1\n"); Reference<XSimpleRegistry> xreg= createSimpleRegistry(); xreg->open( OUString( RTL_CONSTASCII_USTRINGPARAM("applicat.rdb")), sal_False, sal_False ); Reference< XComponentContext > context= bootstrap_InitialComponentContext(xreg); Reference<XMultiComponentFactory> fac= context->getServiceManager(); OUString sService2( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.OleBridgeSupplierVar1")); Reference<XInterface> xint= fac->createInstanceWithContext( sService2, context); OUString sModule( RTL_CONSTASCII_USTRINGPARAM("oleautobridge.uno" SAL_DLLEXTENSION)); oslModule hMod= osl_loadModule( sModule.pData, 0); osl_unloadModule( hMod); rtl_unloadUnusedModules( NULL); OUString sFactoryFunc( RTL_CONSTASCII_USTRINGPARAM("component_getFactory")); void* pSymbol= osl_getSymbol( hMod,sFactoryFunc.pData); // true, instance alive sal_Bool bTest1= pSymbol ? sal_True : sal_False; xint=0; rtl_unloadUnusedModules( NULL); pSymbol= osl_getSymbol( hMod,sFactoryFunc.pData); sal_Bool bTest2= pSymbol ? sal_False : sal_True; Reference<XComponent> xcomp( context, UNO_QUERY); xcomp->dispose(); return bTest1 && bTest2; } sal_Bool test3() { printf("Test3: com.sun.star.bridge.OleObjectFactory\n"); Reference<XSimpleRegistry> xreg= createSimpleRegistry(); xreg->open( OUString( RTL_CONSTASCII_USTRINGPARAM("applicat.rdb")), sal_False, sal_False ); Reference< XComponentContext > context= bootstrap_InitialComponentContext(xreg); Reference<XMultiComponentFactory> fac= context->getServiceManager(); OUString sService( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.OleObjectFactory")); Reference<XInterface> xint= fac->createInstanceWithContext( sService, context); OUString sModule( RTL_CONSTASCII_USTRINGPARAM("oleautobridge.uno" SAL_DLLEXTENSION)); oslModule hMod= osl_loadModule( sModule.pData, 0); osl_unloadModule( hMod); rtl_unloadUnusedModules( NULL); OUString sFactoryFunc( RTL_CONSTASCII_USTRINGPARAM("component_getFactory")); void* pSymbol= osl_getSymbol( hMod,sFactoryFunc.pData); // true, instance alive sal_Bool bTest1= pSymbol ? sal_True : sal_False; xint=0; rtl_unloadUnusedModules( NULL); pSymbol= osl_getSymbol( hMod,sFactoryFunc.pData); sal_Bool bTest2= pSymbol ? sal_False : sal_True; Reference<XComponent> xcomp( context, UNO_QUERY); xcomp->dispose(); // for (int i=0; i < 10; i++) // { // Reference<XSimpleRegistry> xreg= createSimpleRegistry(); // xreg->open( OUString( RTL_CONSTASCII_USTRINGPARAM("applicat.rdb")), // sal_False, sal_False ); // Reference< XComponentContext > context= bootstrap_InitialComponentContext(xreg); // Reference<XComponent> xcomp( context, UNO_QUERY); // xcomp->dispose(); // // } // return sal_True; return bTest1 && bTest2; } sal_Bool test4() { void* pSymbol= NULL; sal_Bool bTest1= sal_False; sal_Bool bTest2= sal_False; oslModule hMod= NULL; OUString sModule( RTL_CONSTASCII_USTRINGPARAM("oleautobridge.uno" SAL_DLLEXTENSION)); OUString sFactoryFunc( RTL_CONSTASCII_USTRINGPARAM("component_getFactory")); { printf("Test4: com.sun.star.bridge.OleApplicationRegistration\n"); Reference<XSimpleRegistry> xreg= createSimpleRegistry(); xreg->open( OUString( RTL_CONSTASCII_USTRINGPARAM("applicat.rdb")), sal_False, sal_False ); Reference< XComponentContext > context= bootstrap_InitialComponentContext(xreg); Reference<XMultiComponentFactory> fac= context->getServiceManager(); OUString sService4( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.OleApplicationRegistration")); Reference<XInterface> xint= fac->createInstanceWithContext( sService4, context); hMod= osl_loadModule( sModule.pData, 0); osl_unloadModule( hMod); rtl_unloadUnusedModules( NULL); void* pSymbol= osl_getSymbol( hMod,sFactoryFunc.pData); // true, instance alive bTest1= pSymbol ? sal_True : sal_False; // OleApplicationRegistration is a one-instance-service, therefore kill service manager first Reference<XComponent> xcomp( context, UNO_QUERY); xcomp->dispose(); } rtl_unloadUnusedModules( NULL); pSymbol= osl_getSymbol( hMod,sFactoryFunc.pData); bTest2= pSymbol ? sal_False : sal_True; return bTest1 && bTest2; } <commit_msg>INTEGRATION: CWS jl5vba (1.2.144); FILE MERGED 2004/01/19 12:21:02 jl 1.2.144.1: #112439# join cws ab02vba<commit_after> #include<osl/module.hxx> #include <osl/time.h> #include <rtl/ustring.hxx> #include <stdio.h> #include <cppuhelper/factory.hxx> #include <cppuhelper/servicefactory.hxx> #include <cppuhelper/bootstrap.hxx> #include <com/sun/star/lang/XMultiComponentFactory.hpp> #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/registry/XSimpleRegistry.hpp> #include <stdio.h> using namespace ::rtl; using namespace ::osl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::cppu; using namespace ::com::sun::star::registry; sal_Bool test1(); sal_Bool test2(); sal_Bool test3(); sal_Bool test4(); int main(int argc, char* argv[]) { sal_Bool bTest1= test1(); sal_Bool bTest2= test2(); sal_Bool bTest3= test3(); sal_Bool bTest4= test4(); if( bTest1 && bTest2 && bTest3 && bTest4) printf("\n#########################\n Test was successful\n#######################\n"); return 0; } sal_Bool test1() { printf("\n Test1: com.sun.star.bridge.oleautomation.BridgeSupplier\n"); Reference<XSimpleRegistry> xreg= createSimpleRegistry(); xreg->open( OUString( RTL_CONSTASCII_USTRINGPARAM("services.rdb")), sal_False, sal_False ); Reference< XComponentContext > context= bootstrap_InitialComponentContext(xreg); Reference<XMultiComponentFactory> fac= context->getServiceManager(); OUString sService1( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.oleautomation.BridgeSupplier")); Reference<XInterface> xint1= fac->createInstanceWithContext( sService1, context); OUString sModule( RTL_CONSTASCII_USTRINGPARAM("oleautobridge.uno" SAL_DLLEXTENSION)); oslModule hMod= osl_loadModule( sModule.pData, 0); osl_unloadModule( hMod); rtl_unloadUnusedModules( NULL); OUString sFactoryFunc( RTL_CONSTASCII_USTRINGPARAM("component_getFactory")); void* pSymbol= osl_getSymbol( hMod,sFactoryFunc.pData); // true, instance alive sal_Bool bTest1= pSymbol ? sal_True : sal_False; xint1=0; rtl_unloadUnusedModules( NULL); pSymbol= osl_getSymbol( hMod,sFactoryFunc.pData); sal_Bool bTest2= pSymbol ? sal_False : sal_True; Reference<XComponent> xcomp( context, UNO_QUERY); xcomp->dispose(); return bTest2 && bTest1; } sal_Bool test2() { printf("Test2: com.sun.star.bridge.OleBridgeSupplierVar1\n"); Reference<XSimpleRegistry> xreg= createSimpleRegistry(); xreg->open( OUString( RTL_CONSTASCII_USTRINGPARAM("services.rdb")), sal_False, sal_False ); Reference< XComponentContext > context= bootstrap_InitialComponentContext(xreg); Reference<XMultiComponentFactory> fac= context->getServiceManager(); OUString sService2( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.OleBridgeSupplierVar1")); Reference<XInterface> xint= fac->createInstanceWithContext( sService2, context); OUString sModule( RTL_CONSTASCII_USTRINGPARAM("oleautobridge.uno" SAL_DLLEXTENSION)); oslModule hMod= osl_loadModule( sModule.pData, 0); osl_unloadModule( hMod); rtl_unloadUnusedModules( NULL); OUString sFactoryFunc( RTL_CONSTASCII_USTRINGPARAM("component_getFactory")); void* pSymbol= osl_getSymbol( hMod,sFactoryFunc.pData); // true, instance alive sal_Bool bTest1= pSymbol ? sal_True : sal_False; xint=0; rtl_unloadUnusedModules( NULL); pSymbol= osl_getSymbol( hMod,sFactoryFunc.pData); sal_Bool bTest2= pSymbol ? sal_False : sal_True; Reference<XComponent> xcomp( context, UNO_QUERY); xcomp->dispose(); return bTest1 && bTest2; } sal_Bool test3() { printf("Test3: com.sun.star.bridge.oleautomation.Factory\n"); Reference<XSimpleRegistry> xreg= createSimpleRegistry(); xreg->open( OUString( RTL_CONSTASCII_USTRINGPARAM("services.rdb")), sal_False, sal_False ); Reference< XComponentContext > context= bootstrap_InitialComponentContext(xreg); Reference<XMultiComponentFactory> fac= context->getServiceManager(); OUString sService( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.oleautomation.Factory")); Reference<XInterface> xint= fac->createInstanceWithContext( sService, context); OUString sModule( RTL_CONSTASCII_USTRINGPARAM("oleautobridge.uno" SAL_DLLEXTENSION)); oslModule hMod= osl_loadModule( sModule.pData, 0); osl_unloadModule( hMod); rtl_unloadUnusedModules( NULL); OUString sFactoryFunc( RTL_CONSTASCII_USTRINGPARAM("component_getFactory")); void* pSymbol= osl_getSymbol( hMod,sFactoryFunc.pData); // true, instance alive sal_Bool bTest1= pSymbol ? sal_True : sal_False; xint=0; rtl_unloadUnusedModules( NULL); pSymbol= osl_getSymbol( hMod,sFactoryFunc.pData); sal_Bool bTest2= pSymbol ? sal_False : sal_True; Reference<XComponent> xcomp( context, UNO_QUERY); xcomp->dispose(); // for (int i=0; i < 10; i++) // { // Reference<XSimpleRegistry> xreg= createSimpleRegistry(); // xreg->open( OUString( RTL_CONSTASCII_USTRINGPARAM("applicat.rdb")), // sal_False, sal_False ); // Reference< XComponentContext > context= bootstrap_InitialComponentContext(xreg); // Reference<XComponent> xcomp( context, UNO_QUERY); // xcomp->dispose(); // // } // return sal_True; return bTest1 && bTest2; } sal_Bool test4() { void* pSymbol= NULL; sal_Bool bTest1= sal_False; sal_Bool bTest2= sal_False; oslModule hMod= NULL; OUString sModule( RTL_CONSTASCII_USTRINGPARAM("oleautobridge.uno" SAL_DLLEXTENSION)); OUString sFactoryFunc( RTL_CONSTASCII_USTRINGPARAM("component_getFactory")); { printf("Test4: com.sun.star.bridge.oleautomation.ApplicationRegistration\n"); Reference<XSimpleRegistry> xreg= createSimpleRegistry(); xreg->open( OUString( RTL_CONSTASCII_USTRINGPARAM("services.rdb")), sal_False, sal_False ); Reference< XComponentContext > context= bootstrap_InitialComponentContext(xreg); Reference<XMultiComponentFactory> fac= context->getServiceManager(); OUString sService4( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.oleautomation.ApplicationRegistration")); Reference<XInterface> xint= fac->createInstanceWithContext( sService4, context); hMod= osl_loadModule( sModule.pData, 0); osl_unloadModule( hMod); rtl_unloadUnusedModules( NULL); void* pSymbol= osl_getSymbol( hMod,sFactoryFunc.pData); // true, instance alive bTest1= pSymbol ? sal_True : sal_False; // ApplicationRegistration is a one-instance-service, therefore kill service manager first Reference<XComponent> xcomp( context, UNO_QUERY); xcomp->dispose(); } rtl_unloadUnusedModules( NULL); pSymbol= osl_getSymbol( hMod,sFactoryFunc.pData); bTest2= pSymbol ? sal_False : sal_True; return bTest1 && bTest2; } <|endoftext|>
<commit_before>// Creates BED of regions in the specified genome that are in a column // with no duplicates in any of the target genomes. #include "hal.h" #include "halBedLine.h" using namespace std; using namespace hal; static CLParserPtr initParser() { CLParserPtr optionsParser = hdf5CLParserInstance(true); optionsParser->addArgument("halFile", "hal tree"); optionsParser->addArgument("referenceGenome", "genome to create the BED file " "for"); optionsParser->addOption("targetGenomes", "genomes to check for homologous " "duplicated sites (comma-separated, default=leaves)", ""); optionsParser->addOption("seqStartNum", "sequence number to start with", 0); optionsParser->addOption("seqEndNum", "sequence number to end with", -1); optionsParser->addOptionFlag("requireAllTargets", "require the regions to be present in all target genomes", false); return optionsParser; } int main(int argc, char *argv[]) { string halPath, referenceGenomeName, targetGenomesUnsplit; hal_index_t seqStartPos = 0; hal_index_t seqEndPos = -1; CLParserPtr optParser = initParser(); bool requireAllTargets = false; try { optParser->parseOptions(argc, argv); halPath = optParser->getArgument<string>("halFile"); referenceGenomeName = optParser->getArgument<string>("referenceGenome"); targetGenomesUnsplit = optParser->getOption<string>("targetGenomes"); seqStartPos = optParser->getOption<hal_index_t>("seqStartNum"); seqEndPos = optParser->getOption<hal_index_t>("seqEndNum"); requireAllTargets = optParser->getFlag("requireAllTargets"); } catch (exception &e) { cerr << e.what() << endl; optParser->printUsage(cerr); return 1; } AlignmentConstPtr alignment = openHalAlignment(halPath, optParser); vector<string> targetGenomeNames; if (targetGenomesUnsplit != "") { // Target genomes provided targetGenomeNames = chopString(targetGenomesUnsplit, ","); } else { // Use all leaf genomes as targets targetGenomeNames = alignment->getLeafNamesBelow(alignment->getRootName()); } set<const Genome *> targetGenomes; for (size_t i = 0; i < targetGenomeNames.size(); i++) { targetGenomes.insert(alignment->openGenome(targetGenomeNames[i])); } const Genome *referenceGenome = alignment->openGenome(referenceGenomeName); ColumnIteratorConstPtr colIt = referenceGenome->getColumnIterator(); BedLine curBedLine; ostream &os = cout; SequenceIteratorConstPtr seqIt = referenceGenome->getSequenceIterator(seqStartPos); SequenceIteratorConstPtr seqItEnd = (seqEndPos == -1) ? referenceGenome->getSequenceEndIterator() : referenceGenome->getSequenceIterator(seqEndPos + 1); for (; seqIt != seqItEnd; seqIt->toNext()) { ColumnIteratorConstPtr colIt = seqIt->getSequence()->getColumnIterator(); bool inRegion = false; BedLine curBedLine; while (1) { bool wasInRegion = inRegion; inRegion = true; const ColumnIterator::ColumnMap *cols = colIt->getColumnMap(); ColumnIterator::ColumnMap::const_iterator colMapIt; set <const Genome *> seenGenomes; unsigned int targetGenomeCount = 0; for (colMapIt = cols->begin(); colMapIt != cols->end(); colMapIt++) { if (colMapIt->second->empty()) { // The column map can contain empty entries. continue; } const Genome *colGenome = colMapIt->first->getGenome(); if (targetGenomes.count(colGenome)) { targetGenomeCount++; if (seenGenomes.count(colGenome) || colMapIt->second->size() > 1) { // Duplication -- not single-copy among targets. inRegion = false; } seenGenomes.insert(colGenome); } } if (requireAllTargets && (targetGenomeCount < targetGenomes.size())) { // not in every genome inRegion = false; } if (!inRegion && wasInRegion) { const hal_index_t pos = colIt->getReferenceSequencePosition(); curBedLine._end = pos; curBedLine.write(os); } if (inRegion && !wasInRegion) { // start of single-copy region, output start of bed entry const Sequence * seq = seqIt->getSequence(); const hal_index_t pos = colIt->getReferenceSequencePosition(); curBedLine._chrName = seq->getName(); curBedLine._start = pos; } if (colIt->lastColumn()) { // Have to break here instead of at the beginning of the loop to // avoid missing the last column. // UPDATE TO LATEST CODE FROM ABOVE (OR STOP BEING LAZY) if (inRegion) { // current single-copy region has ended, finish bed entry const hal_index_t pos = colIt->getReferenceSequencePosition(); curBedLine._end = pos; curBedLine.write(os); } break; } if (colIt->getReferenceSequencePosition() % 10000 == 0) { colIt->defragment(); } // colIt->toRight(); colIt->toSite(colIt->getReferenceSequencePosition() + seqIt->getSequence()->getStartPosition() + 1, seqIt->getSequence()->getEndPosition(), true); } } } <commit_msg>add chr, start, length options for finding single-copy regions<commit_after>// Creates BED of regions in the specified genome that are in a column // with no duplicates in any of the target genomes. #include "hal.h" #include "halBedLine.h" using namespace std; using namespace hal; static CLParserPtr initParser() { CLParserPtr optionsParser = hdf5CLParserInstance(true); optionsParser->addArgument("halFile", "hal tree"); optionsParser->addArgument("referenceGenome", "genome to create the BED file " "for"); optionsParser->addOption("targetGenomes", "genomes to check for homologous " "duplicated sites (comma-separated, default=leaves)", ""); optionsParser->addOption("refSequence", "sequence to traverse", ""); optionsParser->addOption("start", "start position within the sequence " "(within entire genome if --refSequence is not " "set)", 0); optionsParser->addOption("length", "length to traverse (default: until end " "of genome/sequence)", -1); optionsParser->addOptionFlag("requireAllTargets", "require the regions to be present in all target genomes", false); return optionsParser; } int main(int argc, char *argv[]) { string halPath, referenceGenomeName, targetGenomesUnsplit, refSequence; hal_index_t start, length; CLParserPtr optParser = initParser(); bool requireAllTargets = false; try { optParser->parseOptions(argc, argv); halPath = optParser->getArgument<string>("halFile"); referenceGenomeName = optParser->getArgument<string>("referenceGenome"); targetGenomesUnsplit = optParser->getOption<string>("targetGenomes"); refSequence = optParser->getOption<string>("refSequence"); start = optParser->getOption<hal_index_t>("start"); length = optParser->getOption<hal_index_t>("length"); requireAllTargets = optParser->getFlag("requireAllTargets"); } catch (exception &e) { cerr << e.what() << endl; optParser->printUsage(cerr); return 1; } AlignmentConstPtr alignment = openHalAlignment(halPath, optParser); vector<string> targetGenomeNames; if (targetGenomesUnsplit != "") { // Target genomes provided targetGenomeNames = chopString(targetGenomesUnsplit, ","); } else { // Use all leaf genomes as targets targetGenomeNames = alignment->getLeafNamesBelow(alignment->getRootName()); } set<const Genome *> targetGenomes; for (size_t i = 0; i < targetGenomeNames.size(); i++) { targetGenomes.insert(alignment->openGenome(targetGenomeNames[i])); } const Genome *referenceGenome = alignment->openGenome(referenceGenomeName); if (referenceGenome == NULL) { throw hal_exception("Genome " + referenceGenomeName + " not present in alignment"); } ostream &os = cout; const SegmentedSequence *sequence; size_t seqStart, seqEnd; if (refSequence != "") { sequence = referenceGenome->getSequence(refSequence); seqStart = referenceGenome->getSequence(refSequence)->getStartPosition(); seqEnd = referenceGenome->getSequence(refSequence)->getEndPosition(); } else { sequence = referenceGenome; seqStart = 0; seqEnd = referenceGenome->getSequenceLength() - 1; } if (length > (hal_index_t) (seqEnd - seqStart - start)) { throw hal_exception("region too long, goes off the end of sequence or genome."); } ColumnIteratorConstPtr colIt = sequence->getColumnIterator(&targetGenomes, 0, start, length == -1 ? NULL_INDEX : start + length); bool inRegion = false; BedLine curBedLine; const Sequence *prevSequence = NULL; hal_index_t prevPos = NULL_INDEX; while (1) { bool wasInRegion = inRegion; inRegion = true; const ColumnIterator::ColumnMap *cols = colIt->getColumnMap(); ColumnIterator::ColumnMap::const_iterator colMapIt; set <const Genome *> seenGenomes; unsigned int targetGenomeCount = 0; for (colMapIt = cols->begin(); colMapIt != cols->end(); colMapIt++) { if (colMapIt->second->empty()) { // The column map can contain empty entries. continue; } const Genome *colGenome = colMapIt->first->getGenome(); if (targetGenomes.count(colGenome)) { targetGenomeCount++; if (seenGenomes.count(colGenome) || colMapIt->second->size() > 1) { // Duplication -- not single-copy among targets. inRegion = false; } seenGenomes.insert(colGenome); } } if (requireAllTargets && (targetGenomeCount < targetGenomes.size())) { // not in every genome inRegion = false; } if ((prevSequence != NULL && prevSequence != colIt->getReferenceSequence()) || colIt->lastColumn()) { if (wasInRegion || inRegion) { // current single-copy region has ended, finish bed entry curBedLine._end = prevPos + 1; curBedLine.write(os); curBedLine._chrName = colIt->getReferenceSequence()->getName(); curBedLine._start = 0; } if (colIt->lastColumn()) { // Have to break here instead of at the beginning of the loop to // avoid missing the last column. break; } } else if (!inRegion && wasInRegion) { const hal_index_t pos = colIt->getReferenceSequencePosition(); curBedLine._end = pos; curBedLine.write(os); } else if (inRegion && !wasInRegion) { // start of single-copy region, output start of bed entry const Sequence *seq = colIt->getReferenceSequence(); const hal_index_t pos = colIt->getReferenceSequencePosition(); curBedLine._chrName = seq->getName(); curBedLine._start = pos; } if (colIt->getReferenceSequencePosition() % 10000 == 0) { colIt->defragment(); } prevSequence = colIt->getReferenceSequence(); prevPos = colIt->getReferenceSequencePosition(); colIt->toSite(colIt->getReferenceSequencePosition() + colIt->getReferenceSequence()->getStartPosition() + 1, length == -1 ? seqEnd : start + length + colIt->getReferenceSequence()->getStartPosition(), true); } } <|endoftext|>
<commit_before>/************************************************************************* This file is part of libresourceqt Copyright (C) 2010 Nokia Corporation. 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 version 2.1 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *************************************************************************/ #include <QSignalSpy> #include <QList> #include "test-resource-set.h" using namespace ResourcePolicy; Resource * TestResourceSet::resourceFromType(ResourceType type) { switch (type) { case AudioPlaybackType: return new AudioResource; case AudioRecorderType: return new AudioRecorderResource; case VideoPlaybackType: return new VideoResource; case VideoRecorderType: return new VideoRecorderResource; case VibraType: return new VibraResource; case LedsType: return new LedsResource; case BacklightType: return new BacklightResource; case SystemButtonType: return new SystemButtonResource; case LockButtonType: return new LockButtonResource; case ScaleButtonType: return new ScaleButtonResource; case SnapButtonType: return new SnapButtonResource; case LensCoverType: return new LensCoverResource; case HeadsetButtonsType: return new HeadsetButtonsResource; default: return NULL; } } using namespace ResourcePolicy; TestResourceSet::TestResourceSet() : audioResource(NULL) , audioRecorderResource(NULL) , videoResource(NULL) , videoRecorderResource(NULL) , vibraResource(NULL) , ledsResource(NULL) , backlightResource(NULL) , systemButtonResource(NULL) , lockButtonResource(NULL) , scaleButtonResource(NULL) , snapButtonResource(NULL) , lensCoverResource(NULL) , headsetButtonsResource(NULL) { } TestResourceSet::~TestResourceSet() { } void TestResourceSet::testIdentifier() { ResourceSet resourceSet("player"); ResourceSet otherSet("game"); bool identifiersAreUnique = (resourceSet.id() != otherSet.id()); QVERIFY(identifiersAreUnique); } void TestResourceSet::testAddResource() { ResourceSet resourceSet("player"); for (int i = 0;i < NumberOfTypes;i++) { ResourceType type = (ResourceType)i; resourceSet.addResource(type); bool setContainsGivenResource = resourceSet.contains(type); QVERIFY(setContainsGivenResource); } } void TestResourceSet::testAddResourceObject() { ResourceSet resourceSet("player"); for (int i = 0;i < NumberOfTypes;i++) { ResourceType type = (ResourceType)i; Resource *resource = resourceFromType(type); resourceSet.addResourceObject(resource); bool setContainsGivenResource = resourceSet.contains(type); QVERIFY(setContainsGivenResource); } } void TestResourceSet::testDelResource() { ResourceSet resourceSet("player"); for (int i = 0;i < NumberOfTypes;i++) { ResourceType type = (ResourceType)i; resourceSet.addResource(type); bool setContainsGivenResource = resourceSet.contains(type); QVERIFY(setContainsGivenResource); } for (int i = 0;i < NumberOfTypes;i++) { ResourceType type = (ResourceType)i; resourceSet.deleteResource(type); bool setNoLongerContainType = !resourceSet.contains(type); QVERIFY(setNoLongerContainType); for (int j = 0; j < NumberOfTypes; j++) { if (j == i) continue; ResourceType otherType = (ResourceType)j; bool setStillContainsOtherTypes = resourceSet.contains(otherType); QVERIFY(setStillContainsOtherTypes); } resourceSet.addResource(type); } } void TestResourceSet::testContainsSet() { ResourceSet resourceSet("player"); QList<ResourceType> types, subset; for (int i = 0;i < NumberOfTypes;i++) { ResourceType type = (ResourceType)i; resourceSet.addResource(type); types.append(type); } subset << AudioPlaybackType << VideoPlaybackType << AudioRecorderType << VideoRecorderType << LensCoverType; bool containsAll = resourceSet.contains(types); bool containsSubset = resourceSet.contains(subset); QVERIFY(containsAll); QVERIFY(containsSubset); } void TestResourceSet::testConnectToSignals() { ResourceSet resourceSet("player"); bool signalConnectionSucceeded=false; signalConnectionSucceeded = QObject::connect(&resourceSet, SIGNAL(resourcesBecameAvailable(const QList<ResourcePolicy::ResourceType> &)), this, SLOT(handleResourcesBecameAvailable(const QList<ResourcePolicy::ResourceType> &))); QVERIFY(signalConnectionSucceeded); signalConnectionSucceeded = QObject::connect(&resourceSet, SIGNAL(resourcesGranted(const QList<ResourcePolicy::ResourceType> &)), this, SLOT(handleResourcesGranted(const QList<ResourcePolicy::ResourceType> &))); QVERIFY(signalConnectionSucceeded); signalConnectionSucceeded = QObject::connect(&resourceSet, SIGNAL(resourcesDenied()), this, SLOT(handleResourcesDenied())); QVERIFY(signalConnectionSucceeded); signalConnectionSucceeded = QObject::connect(&resourceSet, SIGNAL(resourcesReleased()), this, SLOT(handleResourcesReleased())); QVERIFY(signalConnectionSucceeded); signalConnectionSucceeded = QObject::connect(&resourceSet, SIGNAL(lostResources()), this, SLOT(handleLostResources())); QVERIFY(signalConnectionSucceeded); } void TestResourceSet::handleResourcesBecameAvailable(const QList<ResourcePolicy::ResourceType> &) { } void TestResourceSet::handleResourcesGranted(const QList<ResourcePolicy::ResourceType> &) { } void TestResourceSet::handleResourcesDenied() { } void TestResourceSet::handleResourcesReleased() { } void TestResourceSet::handleLostResources() { } void TestResourceSet::testConnectEngine() { ResourceSet resourceSet("player"); bool connectOk = resourceSet.initAndConnect(); QVERIFY(connectOk); } void TestResourceSet::testConnectEngine2() { ResourceSet resourceSet("player"); bool addOk = resourceSet.addResource(AudioPlaybackType); QVERIFY(addOk); bool connectOk = resourceSet.initAndConnect(); QVERIFY(connectOk); } void TestResourceSet::testAcquire() { ResourceSet resourceSet("player"); // Test that signals gets emitted QSignalSpy stateSpy(&resourceSet, SIGNAL(resourcesGranted(const QList<ResourcePolicy::ResourceType> &))); QVERIFY(stateSpy.isValid()); QSignalSpy stateSpy2(&resourceSet, SIGNAL(resourcesReleased())); QVERIFY(stateSpy2.isValid()); bool addOk = resourceSet.addResource(AudioPlaybackType); QVERIFY(addOk); bool connectOk = resourceSet.initAndConnect(); QVERIFY(connectOk); bool acquireOk = resourceSet.acquire(); QVERIFY(acquireOk); QTest::qWait(500); // Check the signal parameters QCOMPARE(stateSpy.count(), 1); bool releaseOk = resourceSet.release(); QVERIFY(releaseOk); QTest::qWait(500); // Check the signal parameters QCOMPARE(stateSpy2.count(), 1); } QTEST_MAIN(TestResourceSet) <commit_msg>Tests: Better way to wait for a signal.<commit_after>/************************************************************************* This file is part of libresourceqt Copyright (C) 2010 Nokia Corporation. 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 version 2.1 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *************************************************************************/ #include <QSignalSpy> #include <QList> #include <QEventLoop> #include "test-resource-set.h" using namespace ResourcePolicy; Resource * TestResourceSet::resourceFromType(ResourceType type) { switch (type) { case AudioPlaybackType: return new AudioResource; case AudioRecorderType: return new AudioRecorderResource; case VideoPlaybackType: return new VideoResource; case VideoRecorderType: return new VideoRecorderResource; case VibraType: return new VibraResource; case LedsType: return new LedsResource; case BacklightType: return new BacklightResource; case SystemButtonType: return new SystemButtonResource; case LockButtonType: return new LockButtonResource; case ScaleButtonType: return new ScaleButtonResource; case SnapButtonType: return new SnapButtonResource; case LensCoverType: return new LensCoverResource; case HeadsetButtonsType: return new HeadsetButtonsResource; default: return NULL; } } using namespace ResourcePolicy; TestResourceSet::TestResourceSet() : audioResource(NULL) , audioRecorderResource(NULL) , videoResource(NULL) , videoRecorderResource(NULL) , vibraResource(NULL) , ledsResource(NULL) , backlightResource(NULL) , systemButtonResource(NULL) , lockButtonResource(NULL) , scaleButtonResource(NULL) , snapButtonResource(NULL) , lensCoverResource(NULL) , headsetButtonsResource(NULL) { } TestResourceSet::~TestResourceSet() { } void TestResourceSet::testIdentifier() { ResourceSet resourceSet("player"); ResourceSet otherSet("game"); bool identifiersAreUnique = (resourceSet.id() != otherSet.id()); QVERIFY(identifiersAreUnique); } void TestResourceSet::testAddResource() { ResourceSet resourceSet("player"); for (int i = 0;i < NumberOfTypes;i++) { ResourceType type = (ResourceType)i; resourceSet.addResource(type); bool setContainsGivenResource = resourceSet.contains(type); QVERIFY(setContainsGivenResource); } } void TestResourceSet::testAddResourceObject() { ResourceSet resourceSet("player"); for (int i = 0;i < NumberOfTypes;i++) { ResourceType type = (ResourceType)i; Resource *resource = resourceFromType(type); resourceSet.addResourceObject(resource); bool setContainsGivenResource = resourceSet.contains(type); QVERIFY(setContainsGivenResource); } } void TestResourceSet::testDelResource() { ResourceSet resourceSet("player"); for (int i = 0;i < NumberOfTypes;i++) { ResourceType type = (ResourceType)i; resourceSet.addResource(type); bool setContainsGivenResource = resourceSet.contains(type); QVERIFY(setContainsGivenResource); } for (int i = 0;i < NumberOfTypes;i++) { ResourceType type = (ResourceType)i; resourceSet.deleteResource(type); bool setNoLongerContainType = !resourceSet.contains(type); QVERIFY(setNoLongerContainType); for (int j = 0; j < NumberOfTypes; j++) { if (j == i) continue; ResourceType otherType = (ResourceType)j; bool setStillContainsOtherTypes = resourceSet.contains(otherType); QVERIFY(setStillContainsOtherTypes); } resourceSet.addResource(type); } } void TestResourceSet::testContainsSet() { ResourceSet resourceSet("player"); QList<ResourceType> types, subset; for (int i = 0;i < NumberOfTypes;i++) { ResourceType type = (ResourceType)i; resourceSet.addResource(type); types.append(type); } subset << AudioPlaybackType << VideoPlaybackType << AudioRecorderType << VideoRecorderType << LensCoverType; bool containsAll = resourceSet.contains(types); bool containsSubset = resourceSet.contains(subset); QVERIFY(containsAll); QVERIFY(containsSubset); } void TestResourceSet::testConnectToSignals() { ResourceSet resourceSet("player"); bool signalConnectionSucceeded=false; signalConnectionSucceeded = QObject::connect(&resourceSet, SIGNAL(resourcesBecameAvailable(const QList<ResourcePolicy::ResourceType> &)), this, SLOT(handleResourcesBecameAvailable(const QList<ResourcePolicy::ResourceType> &))); QVERIFY(signalConnectionSucceeded); signalConnectionSucceeded = QObject::connect(&resourceSet, SIGNAL(resourcesGranted(const QList<ResourcePolicy::ResourceType> &)), this, SLOT(handleResourcesGranted(const QList<ResourcePolicy::ResourceType> &))); QVERIFY(signalConnectionSucceeded); signalConnectionSucceeded = QObject::connect(&resourceSet, SIGNAL(resourcesDenied()), this, SLOT(handleResourcesDenied())); QVERIFY(signalConnectionSucceeded); signalConnectionSucceeded = QObject::connect(&resourceSet, SIGNAL(resourcesReleased()), this, SLOT(handleResourcesReleased())); QVERIFY(signalConnectionSucceeded); signalConnectionSucceeded = QObject::connect(&resourceSet, SIGNAL(lostResources()), this, SLOT(handleLostResources())); QVERIFY(signalConnectionSucceeded); } void TestResourceSet::handleResourcesBecameAvailable(const QList<ResourcePolicy::ResourceType> &) { } void TestResourceSet::handleResourcesGranted(const QList<ResourcePolicy::ResourceType> &) { } void TestResourceSet::handleResourcesDenied() { } void TestResourceSet::handleResourcesReleased() { } void TestResourceSet::handleLostResources() { } void TestResourceSet::testConnectEngine() { ResourceSet resourceSet("player"); bool connectOk = resourceSet.initAndConnect(); QVERIFY(connectOk); } void TestResourceSet::testConnectEngine2() { ResourceSet resourceSet("player"); bool addOk = resourceSet.addResource(AudioPlaybackType); QVERIFY(addOk); bool connectOk = resourceSet.initAndConnect(); QVERIFY(connectOk); } void TestResourceSet::testAcquire() { ResourceSet resourceSet("player"); // Test that signals gets emitted QSignalSpy stateSpy(&resourceSet, SIGNAL(resourcesGranted(const QList<ResourcePolicy::ResourceType> &))); QVERIFY(stateSpy.isValid()); QSignalSpy stateSpy2(&resourceSet, SIGNAL(resourcesReleased())); QVERIFY(stateSpy2.isValid()); bool addOk = resourceSet.addResource(AudioPlaybackType); QVERIFY(addOk); bool connectOk = resourceSet.initAndConnect(); QVERIFY(connectOk); bool acquireOk = resourceSet.acquire(); QVERIFY(acquireOk); QEventLoop loop; loop.connect(&resourceSet, SIGNAL(resourcesGranted(const QList<ResourcePolicy::ResourceType> &)), SLOT(quit())); loop.exec(); // Check the signal parameters QCOMPARE(stateSpy.count(), 1); bool releaseOk = resourceSet.release(); QVERIFY(releaseOk); QEventLoop loop2; loop2.connect(&resourceSet, SIGNAL(resourcesReleased()), SLOT(quit())); loop2.exec(); // Check the signal parameters QCOMPARE(stateSpy2.count(), 1); } QTEST_MAIN(TestResourceSet) <|endoftext|>
<commit_before>#include <shogun/classifier/svm/SVMOcas.h> #include <shogun/features/DataGenerator.h> #include <shogun/features/DenseFeatures.h> #include <gtest/gtest.h> using namespace shogun; TEST(SVMOcasTest,train) { index_t num_samples = 50; SGMatrix<float64_t> data = CDataGenerator::generate_gaussians(num_samples, 2, 2); CDenseFeatures<float64_t> features(data); SGVector<index_t> train_idx(num_samples), test_idx(num_samples); SGVector<float64_t> labels(num_samples); for (index_t i = 0, j = 0; i < data.num_cols; ++i) { if (i % 2 == 0) train_idx[j] = i; else test_idx[j++] = i; labels[i/2] = (i < data.num_cols/2) ? 1.0 : -1.0; } CDenseFeatures<float64_t>* train_feats = (CDenseFeatures<float64_t>*)features.copy_subset(train_idx); CDenseFeatures<float64_t>* test_feats = (CDenseFeatures<float64_t>*)features.copy_subset(test_idx); CBinaryLabels* ground_truth = new CBinaryLabels(labels); CSVMOcas* ocas = new CSVMOcas(1.0, train_feats, ground_truth); ocas->set_epsilon(1e-5); ocas->train(); float64_t objective = ocas->compute_primal_objective(); EXPECT_NEAR(objective, 0.022321841487323236, 1e-2); CLabels* pred = ocas->apply(test_feats); for (int i = 0; i < num_samples; ++i) EXPECT_EQ(ground_truth->get_int_label(i), ((CBinaryLabels*)pred)->get_int_label(i)); SG_UNREF(ocas); SG_UNREF(train_feats); SG_UNREF(test_feats); SG_UNREF(pred); } <commit_msg>require single thread usage & initialize rnd number generator<commit_after>#include <shogun/classifier/svm/SVMOcas.h> #include <shogun/features/DataGenerator.h> #include <shogun/features/DenseFeatures.h> #include <gtest/gtest.h> using namespace shogun; TEST(SVMOcasTest,train) { index_t num_samples = 50; CMath::init_random(5); SGMatrix<float64_t> data = CDataGenerator::generate_gaussians(num_samples, 2, 2); CDenseFeatures<float64_t> features(data); SGVector<index_t> train_idx(num_samples), test_idx(num_samples); SGVector<float64_t> labels(num_samples); for (index_t i = 0, j = 0; i < data.num_cols; ++i) { if (i % 2 == 0) train_idx[j] = i; else test_idx[j++] = i; labels[i/2] = (i < data.num_cols/2) ? 1.0 : -1.0; } CDenseFeatures<float64_t>* train_feats = (CDenseFeatures<float64_t>*)features.copy_subset(train_idx); CDenseFeatures<float64_t>* test_feats = (CDenseFeatures<float64_t>*)features.copy_subset(test_idx); CBinaryLabels* ground_truth = new CBinaryLabels(labels); CSVMOcas* ocas = new CSVMOcas(1.0, train_feats, ground_truth); ocas->parallel->set_num_threads(1); ocas->set_epsilon(1e-5); ocas->train(); float64_t objective = ocas->compute_primal_objective(); EXPECT_NEAR(objective, 0.022321841487323236, 1e-2); CLabels* pred = ocas->apply(test_feats); for (int i = 0; i < num_samples; ++i) EXPECT_EQ(ground_truth->get_int_label(i), ((CBinaryLabels*)pred)->get_int_label(i)); SG_UNREF(ocas); SG_UNREF(train_feats); SG_UNREF(test_feats); SG_UNREF(pred); } <|endoftext|>
<commit_before>/* * Copyright 2004-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/lib/cpp2/test/frozen2/view_helper/gen-cpp2/view_helper_layouts.h> #include <thrift/lib/cpp2/test/frozen2/view_helper/gen-cpp2/view_helper_types.h> #include <thrift/lib/cpp2/frozen/FrozenUtil.h> #include <thrift/lib/cpp2/util/Frozen2ViewHelpers.h> #include <gtest/gtest.h> using namespace ::apache::thrift::frozen; using namespace ::test::frozen2; #define ASSERT_VIEW_EQ(OBJ, MAPPED, NAME) \ ASSERT_EQ( \ ViewHelper<Layout<decltype(MAPPED.NAME())>::View>::thaw(MAPPED.NAME()), \ OBJ.NAME) TEST(ViewHelperTest, TestThaw) { TestStruct strct; strct.i32Field = 0xBAD; strct.strField = "foo"; strct.doubleField = 1.5; strct.boolField = true; strct.listField = {"bar", "baz"}; strct.mapField = { {0, "a"}, {1, "b"}, }; strct.enumField = TestEnum::Foo; std::string frozen; freezeToString(strct, frozen); auto mapped = mapFrozen<TestStruct>(std::move(frozen)); ASSERT_VIEW_EQ(strct, mapped, i32Field); ASSERT_VIEW_EQ(strct, mapped, strField); ASSERT_VIEW_EQ(strct, mapped, doubleField); ASSERT_VIEW_EQ(strct, mapped, boolField); ASSERT_VIEW_EQ(strct, mapped, listField); ASSERT_VIEW_EQ(strct, mapped, mapField); ASSERT_VIEW_EQ(strct, mapped, enumField); } <commit_msg>Fix typo in test<commit_after>/* * Copyright 2004-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/lib/cpp2/test/frozen2/view_helper/gen-cpp2/view_helper_layouts.h> #include <thrift/lib/cpp2/test/frozen2/view_helper/gen-cpp2/view_helper_types.h> #include <thrift/lib/cpp2/frozen/FrozenUtil.h> #include <thrift/lib/cpp2/util/Frozen2ViewHelpers.h> #include <gtest/gtest.h> using namespace ::apache::thrift::frozen; using namespace ::test::frozen2; #define ASSERT_VIEW_EQ(OBJ, MAPPED, NAME) \ ASSERT_EQ(ViewHelper<decltype(MAPPED.NAME())>::thaw(MAPPED.NAME()), OBJ.NAME) TEST(ViewHelperTest, TestThaw) { TestStruct strct; strct.i32Field = 0xBAD; strct.strField = "foo"; strct.doubleField = 1.5; strct.boolField = true; strct.listField = {"bar", "baz"}; strct.mapField = { {0, "a"}, {1, "b"}, }; strct.enumField = TestEnum::Foo; std::string frozen; freezeToString(strct, frozen); auto mapped = mapFrozen<TestStruct>(std::move(frozen)); ASSERT_VIEW_EQ(strct, mapped, i32Field); ASSERT_VIEW_EQ(strct, mapped, strField); ASSERT_VIEW_EQ(strct, mapped, doubleField); ASSERT_VIEW_EQ(strct, mapped, boolField); ASSERT_VIEW_EQ(strct, mapped, listField); ASSERT_VIEW_EQ(strct, mapped, mapField); ASSERT_VIEW_EQ(strct, mapped, enumField); } <|endoftext|>
<commit_before>/* * Copyright 2017-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/lib/cpp2/transport/core/ThriftClient.h> #include <folly/Baton.h> #include <folly/ExceptionWrapper.h> #include <folly/Logging.h> #include <folly/io/async/Request.h> #include <thrift/lib/cpp/transport/TTransportException.h> #include <thrift/lib/cpp2/async/ResponseChannel.h> #include <thrift/lib/cpp2/transport/core/ThriftChannelIf.h> #include <thrift/lib/cpp2/transport/core/ThriftClientCallback.h> #include <thrift/lib/thrift/gen-cpp2/RpcMetadata_types.h> namespace apache { namespace thrift { using apache::thrift::async::TAsyncTransport; using apache::thrift::protocol::PROTOCOL_TYPES; using apache::thrift::transport::THeader; using apache::thrift::transport::TTransportException; using folly::EventBase; using folly::IOBuf; using folly::RequestContext; namespace { /** * Used as the callback for sendRequestSync. It delegates to the * wrapped callback and posts on the baton object to allow the * synchronous call to continue. */ class WaitableRequestCallback final : public RequestCallback { public: WaitableRequestCallback( std::unique_ptr<RequestCallback> cb, folly::Baton<>& baton, bool oneway) : cb_(std::move(cb)), baton_(baton), oneway_(oneway) {} void requestSent() override { cb_->requestSent(); if (oneway_) { baton_.post(); } } void replyReceived(ClientReceiveState&& rs) override { DCHECK(!oneway_); cb_->replyReceived(std::move(rs)); baton_.post(); } void requestError(ClientReceiveState&& rs) override { DCHECK(rs.isException()); cb_->requestError(std::move(rs)); baton_.post(); } private: std::unique_ptr<RequestCallback> cb_; folly::Baton<>& baton_; bool oneway_; }; } // namespace ThriftClient::ThriftClient( std::shared_ptr<ClientConnectionIf> connection, folly::EventBase* callbackEvb) : connection_(connection), callbackEvb_(callbackEvb) {} ThriftClient::ThriftClient(std::shared_ptr<ClientConnectionIf> connection) : ThriftClient(connection, connection->getEventBase()) {} void ThriftClient::setProtocolId(uint16_t protocolId) { protocolId_ = protocolId; } uint32_t ThriftClient::sendRequestSync( RpcOptions& rpcOptions, std::unique_ptr<RequestCallback> cb, std::unique_ptr<ContextStack> ctx, std::unique_ptr<IOBuf> buf, std::shared_ptr<THeader> header) { // Synchronous calls may be made from any thread except the one used // by the underlying connection. That thread is used to handle the // callback and to release this thread that will be waiting on // "baton". EventBase* connectionEvb = connection_->getEventBase(); DCHECK(!connectionEvb->inRunningEventBaseThread()); folly::Baton<> baton; DCHECK(typeid(ClientSyncCallback) == typeid(*cb)); bool oneway = static_cast<ClientSyncCallback&>(*cb).isOneway(); auto scb = std::make_unique<WaitableRequestCallback>(std::move(cb), baton, oneway); int result = sendRequestHelper( rpcOptions, oneway, std::move(scb), std::move(ctx), std::move(buf), std::move(header), connectionEvb); baton.wait(); return result; } uint32_t ThriftClient::sendRequest( RpcOptions& rpcOptions, std::unique_ptr<RequestCallback> cb, std::unique_ptr<ContextStack> ctx, std::unique_ptr<IOBuf> buf, std::shared_ptr<THeader> header) { return sendRequestHelper( rpcOptions, false, std::move(cb), std::move(ctx), std::move(buf), std::move(header), callbackEvb_); } uint32_t ThriftClient::sendOnewayRequest( RpcOptions& rpcOptions, std::unique_ptr<RequestCallback> cb, std::unique_ptr<ContextStack> ctx, std::unique_ptr<IOBuf> buf, std::shared_ptr<THeader> header) { sendRequestHelper( rpcOptions, true, std::move(cb), std::move(ctx), std::move(buf), std::move(header), callbackEvb_); return ResponseChannel::ONEWAY_REQUEST_ID; } uint32_t ThriftClient::sendRequestHelper( RpcOptions& rpcOptions, bool oneway, std::unique_ptr<RequestCallback> cb, std::unique_ptr<ContextStack> ctx, std::unique_ptr<IOBuf> buf, std::shared_ptr<THeader> header, EventBase* callbackEvb) noexcept { DestructorGuard dg(this); cb->context_ = RequestContext::saveContext(); auto metadata = std::make_unique<RequestRpcMetadata>(); if (oneway) { metadata->kind = RpcKind::SINGLE_REQUEST_NO_RESPONSE; } else { metadata->kind = RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE; } metadata->__isset.kind = true; if (rpcOptions.getTimeout() > std::chrono::milliseconds(0)) { metadata->clientTimeoutMs = rpcOptions.getTimeout().count(); metadata->__isset.clientTimeoutMs = true; } if (rpcOptions.getQueueTimeout() > std::chrono::milliseconds(0)) { metadata->queueTimeoutMs = rpcOptions.getQueueTimeout().count(); metadata->__isset.queueTimeoutMs = true; } if (rpcOptions.getPriority() < concurrency::N_PRIORITIES) { metadata->priority = static_cast<RpcPriority>(rpcOptions.getPriority()); metadata->__isset.priority = true; } metadata->otherMetadata = header->releaseWriteHeaders(); auto* eh = header->getExtraWriteHeaders(); if (eh) { metadata->otherMetadata.insert(eh->begin(), eh->end()); } auto& pwh = getPersistentWriteHeaders(); metadata->otherMetadata.insert(pwh.begin(), pwh.end()); if (!metadata->otherMetadata.empty()) { metadata->__isset.otherMetadata = true; } auto callback = std::make_unique<ThriftClientCallback>( callbackEvb, std::move(cb), std::move(ctx), isSecurityActive(), protocolId_); auto conn = connection_; connection_->getEventBase()->runInEventBaseThread([conn = std::move(conn), metadata = std::move(metadata), buf = std::move(buf), callback = std::move( callback)]() mutable { getChannelAndSendThriftRequest( conn.get(), std::move(metadata), std::move(buf), std::move(callback)); }); return 0; } void ThriftClient::getChannelAndSendThriftRequest( ClientConnectionIf* connection, std::unique_ptr<RequestRpcMetadata> metadata, std::unique_ptr<IOBuf> payload, std::unique_ptr<ThriftClientCallback> callback) noexcept { DCHECK(connection->getEventBase()->isInEventBaseThread()); try { auto channel = connection->getChannel(); channel->sendThriftRequest( std::move(metadata), std::move(payload), std::move(callback)); } catch (TTransportException& te) { auto callbackEvb = callback->getEventBase(); callbackEvb->runInEventBaseThread([callback = std::move(callback), te = std::move(te)]() mutable { callback->onError( folly::make_exception_wrapper<TTransportException>(std::move(te))); }); return; } } EventBase* ThriftClient::getEventBase() const { return callbackEvb_; } uint16_t ThriftClient::getProtocolId() { return protocolId_; } void ThriftClient::setCloseCallback(CloseCallback* /*cb*/) { // TBD } TAsyncTransport* ThriftClient::getTransport() { return connection_->getTransport(); } bool ThriftClient::good() { return connection_->good(); } ClientChannel::SaturationStatus ThriftClient::getSaturationStatus() { return connection_->getSaturationStatus(); } void ThriftClient::attachEventBase(folly::EventBase* eventBase) { connection_->attachEventBase(eventBase); } void ThriftClient::detachEventBase() { connection_->detachEventBase(); } bool ThriftClient::isDetachable() { return connection_->isDetachable(); } bool ThriftClient::isSecurityActive() { return connection_->isSecurityActive(); } uint32_t ThriftClient::getTimeout() { return connection_->getTimeout(); } void ThriftClient::setTimeout(uint32_t ms) { return connection_->setTimeout(ms); } void ThriftClient::closeNow() { connection_->closeNow(); } CLIENT_TYPE ThriftClient::getClientType() { return connection_->getClientType(); } } // namespace thrift } // namespace apache <commit_msg>Client: Add protocol ID to metadata<commit_after>/* * Copyright 2017-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrift/lib/cpp2/transport/core/ThriftClient.h> #include <folly/Baton.h> #include <folly/ExceptionWrapper.h> #include <folly/Logging.h> #include <folly/io/async/Request.h> #include <thrift/lib/cpp/transport/TTransportException.h> #include <thrift/lib/cpp2/async/ResponseChannel.h> #include <thrift/lib/cpp2/transport/core/ThriftChannelIf.h> #include <thrift/lib/cpp2/transport/core/ThriftClientCallback.h> #include <thrift/lib/thrift/gen-cpp2/RpcMetadata_types.h> namespace apache { namespace thrift { using apache::thrift::async::TAsyncTransport; using apache::thrift::protocol::PROTOCOL_TYPES; using apache::thrift::transport::THeader; using apache::thrift::transport::TTransportException; using folly::EventBase; using folly::IOBuf; using folly::RequestContext; namespace { /** * Used as the callback for sendRequestSync. It delegates to the * wrapped callback and posts on the baton object to allow the * synchronous call to continue. */ class WaitableRequestCallback final : public RequestCallback { public: WaitableRequestCallback( std::unique_ptr<RequestCallback> cb, folly::Baton<>& baton, bool oneway) : cb_(std::move(cb)), baton_(baton), oneway_(oneway) {} void requestSent() override { cb_->requestSent(); if (oneway_) { baton_.post(); } } void replyReceived(ClientReceiveState&& rs) override { DCHECK(!oneway_); cb_->replyReceived(std::move(rs)); baton_.post(); } void requestError(ClientReceiveState&& rs) override { DCHECK(rs.isException()); cb_->requestError(std::move(rs)); baton_.post(); } private: std::unique_ptr<RequestCallback> cb_; folly::Baton<>& baton_; bool oneway_; }; } // namespace ThriftClient::ThriftClient( std::shared_ptr<ClientConnectionIf> connection, folly::EventBase* callbackEvb) : connection_(connection), callbackEvb_(callbackEvb) {} ThriftClient::ThriftClient(std::shared_ptr<ClientConnectionIf> connection) : ThriftClient(connection, connection->getEventBase()) {} void ThriftClient::setProtocolId(uint16_t protocolId) { protocolId_ = protocolId; } uint32_t ThriftClient::sendRequestSync( RpcOptions& rpcOptions, std::unique_ptr<RequestCallback> cb, std::unique_ptr<ContextStack> ctx, std::unique_ptr<IOBuf> buf, std::shared_ptr<THeader> header) { // Synchronous calls may be made from any thread except the one used // by the underlying connection. That thread is used to handle the // callback and to release this thread that will be waiting on // "baton". EventBase* connectionEvb = connection_->getEventBase(); DCHECK(!connectionEvb->inRunningEventBaseThread()); folly::Baton<> baton; DCHECK(typeid(ClientSyncCallback) == typeid(*cb)); bool oneway = static_cast<ClientSyncCallback&>(*cb).isOneway(); auto scb = std::make_unique<WaitableRequestCallback>(std::move(cb), baton, oneway); int result = sendRequestHelper( rpcOptions, oneway, std::move(scb), std::move(ctx), std::move(buf), std::move(header), connectionEvb); baton.wait(); return result; } uint32_t ThriftClient::sendRequest( RpcOptions& rpcOptions, std::unique_ptr<RequestCallback> cb, std::unique_ptr<ContextStack> ctx, std::unique_ptr<IOBuf> buf, std::shared_ptr<THeader> header) { return sendRequestHelper( rpcOptions, false, std::move(cb), std::move(ctx), std::move(buf), std::move(header), callbackEvb_); } uint32_t ThriftClient::sendOnewayRequest( RpcOptions& rpcOptions, std::unique_ptr<RequestCallback> cb, std::unique_ptr<ContextStack> ctx, std::unique_ptr<IOBuf> buf, std::shared_ptr<THeader> header) { sendRequestHelper( rpcOptions, true, std::move(cb), std::move(ctx), std::move(buf), std::move(header), callbackEvb_); return ResponseChannel::ONEWAY_REQUEST_ID; } uint32_t ThriftClient::sendRequestHelper( RpcOptions& rpcOptions, bool oneway, std::unique_ptr<RequestCallback> cb, std::unique_ptr<ContextStack> ctx, std::unique_ptr<IOBuf> buf, std::shared_ptr<THeader> header, EventBase* callbackEvb) noexcept { DestructorGuard dg(this); cb->context_ = RequestContext::saveContext(); auto metadata = std::make_unique<RequestRpcMetadata>(); metadata->protocol = static_cast<apache::thrift::ProtocolId>(protocolId_); metadata->__isset.protocol = true; if (oneway) { metadata->kind = RpcKind::SINGLE_REQUEST_NO_RESPONSE; } else { metadata->kind = RpcKind::SINGLE_REQUEST_SINGLE_RESPONSE; } metadata->__isset.kind = true; if (rpcOptions.getTimeout() > std::chrono::milliseconds(0)) { metadata->clientTimeoutMs = rpcOptions.getTimeout().count(); metadata->__isset.clientTimeoutMs = true; } if (rpcOptions.getQueueTimeout() > std::chrono::milliseconds(0)) { metadata->queueTimeoutMs = rpcOptions.getQueueTimeout().count(); metadata->__isset.queueTimeoutMs = true; } if (rpcOptions.getPriority() < concurrency::N_PRIORITIES) { metadata->priority = static_cast<RpcPriority>(rpcOptions.getPriority()); metadata->__isset.priority = true; } metadata->otherMetadata = header->releaseWriteHeaders(); auto* eh = header->getExtraWriteHeaders(); if (eh) { metadata->otherMetadata.insert(eh->begin(), eh->end()); } auto& pwh = getPersistentWriteHeaders(); metadata->otherMetadata.insert(pwh.begin(), pwh.end()); if (!metadata->otherMetadata.empty()) { metadata->__isset.otherMetadata = true; } auto callback = std::make_unique<ThriftClientCallback>( callbackEvb, std::move(cb), std::move(ctx), isSecurityActive(), protocolId_); auto conn = connection_; connection_->getEventBase()->runInEventBaseThread([conn = std::move(conn), metadata = std::move(metadata), buf = std::move(buf), callback = std::move( callback)]() mutable { getChannelAndSendThriftRequest( conn.get(), std::move(metadata), std::move(buf), std::move(callback)); }); return 0; } void ThriftClient::getChannelAndSendThriftRequest( ClientConnectionIf* connection, std::unique_ptr<RequestRpcMetadata> metadata, std::unique_ptr<IOBuf> payload, std::unique_ptr<ThriftClientCallback> callback) noexcept { DCHECK(connection->getEventBase()->isInEventBaseThread()); try { auto channel = connection->getChannel(); channel->sendThriftRequest( std::move(metadata), std::move(payload), std::move(callback)); } catch (TTransportException& te) { auto callbackEvb = callback->getEventBase(); callbackEvb->runInEventBaseThread([callback = std::move(callback), te = std::move(te)]() mutable { callback->onError( folly::make_exception_wrapper<TTransportException>(std::move(te))); }); return; } } EventBase* ThriftClient::getEventBase() const { return callbackEvb_; } uint16_t ThriftClient::getProtocolId() { return protocolId_; } void ThriftClient::setCloseCallback(CloseCallback* /*cb*/) { // TBD } TAsyncTransport* ThriftClient::getTransport() { return connection_->getTransport(); } bool ThriftClient::good() { return connection_->good(); } ClientChannel::SaturationStatus ThriftClient::getSaturationStatus() { return connection_->getSaturationStatus(); } void ThriftClient::attachEventBase(folly::EventBase* eventBase) { connection_->attachEventBase(eventBase); } void ThriftClient::detachEventBase() { connection_->detachEventBase(); } bool ThriftClient::isDetachable() { return connection_->isDetachable(); } bool ThriftClient::isSecurityActive() { return connection_->isSecurityActive(); } uint32_t ThriftClient::getTimeout() { return connection_->getTimeout(); } void ThriftClient::setTimeout(uint32_t ms) { return connection_->setTimeout(ms); } void ThriftClient::closeNow() { connection_->closeNow(); } CLIENT_TYPE ThriftClient::getClientType() { return connection_->getClientType(); } } // namespace thrift } // namespace apache <|endoftext|>
<commit_before>/* * Copyright 2008-2009 NVIDIA Corporation * * 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 <thrust/functional.h> #include <thrust/transform.h> #include <thrust/replace.h> #include <thrust/iterator/zip_iterator.h> #include <thrust/iterator/iterator_traits.h> #include <thrust/detail/device/scan.h> #include <thrust/detail/raw_buffer.h> namespace thrust { namespace detail { namespace device { namespace generic { namespace detail { template <typename OutputType, typename HeadFlagType, typename AssociativeOperator> struct segmented_scan_functor { AssociativeOperator binary_op; typedef typename thrust::tuple<OutputType, HeadFlagType> result_type; __host__ __device__ segmented_scan_functor(AssociativeOperator _binary_op) : binary_op(_binary_op) {} __host__ __device__ result_type operator()(result_type a, result_type b) { return result_type(thrust::get<1>(b) ? thrust::get<0>(b) : binary_op(thrust::get<0>(a), thrust::get<0>(b)), thrust::get<1>(a) | thrust::get<1>(b)); } }; } // end namespace detail template<typename InputIterator1, typename InputIterator2, typename OutputIterator, typename AssociativeOperator, typename BinaryPredicate> OutputIterator inclusive_segmented_scan(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, AssociativeOperator binary_op, BinaryPredicate pred) { typedef typename thrust::iterator_traits<OutputIterator>::value_type OutputType; typedef typename thrust::iterator_space<OutputIterator>::type Space; typedef unsigned int HeadFlagType; if(first1 != last1) { const size_t n = last1 - first1; // compute head flags thrust::detail::raw_buffer<HeadFlagType,Space> flags(n); flags[0] = 1; thrust::transform(first2, first2 + (n - 1), first2 + 1, flags.begin() + 1, thrust::not2(pred)); // scan key-flag tuples, // For additional details refer to Section 2 of the following paper // S. Sengupta, M. Harris, and M. Garland. "Efficient parallel scan algorithms for GPUs" // NVIDIA Technical Report NVR-2008-003, December 2008 // http://mgarland.org/files/papers/nvr-2008-003.pdf thrust::detail::device::inclusive_scan (thrust::make_zip_iterator(thrust::make_tuple(first1, flags.begin())), thrust::make_zip_iterator(thrust::make_tuple(last1, flags.end())), thrust::make_zip_iterator(thrust::make_tuple(result, flags.begin())), detail::segmented_scan_functor<OutputType, HeadFlagType, AssociativeOperator>(binary_op)); } return result + (last1 - first1); } template<typename InputIterator1, typename InputIterator2, typename OutputIterator, typename T, typename AssociativeOperator, typename BinaryPredicate> OutputIterator exclusive_segmented_scan(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, const T init, AssociativeOperator binary_op, BinaryPredicate pred) { typedef typename thrust::iterator_traits<OutputIterator>::value_type OutputType; typedef typename thrust::iterator_space<OutputIterator>::type Space; typedef unsigned int HeadFlagType; if(first1 != last1) { const size_t n = last1 - first1; InputIterator2 last2 = first2 + n; // compute head flags thrust::detail::raw_buffer<HeadFlagType,Space> flags(n); flags[0] = 1; thrust::transform(first2, last2 - 1, first2 + 1, flags.begin() + 1, thrust::not2(pred)); // shift input one to the right and initialize segments with init thrust::detail::raw_buffer<OutputType,Space> temp(n); thrust::replace_copy_if(first1, last1, flags.begin() + 1, temp.begin() + 1, thrust::negate<HeadFlagType>(), init); temp[0] = init; // scan key-flag tuples, // For additional details refer to Section 2 of the following paper // S. Sengupta, M. Harris, and M. Garland. "Efficient parallel scan algorithms for GPUs" // NVIDIA Technical Report NVR-2008-003, December 2008 // http://mgarland.org/files/papers/nvr-2008-003.pdf thrust::inclusive_scan(thrust::make_zip_iterator(thrust::make_tuple(temp.begin(), flags.begin())), thrust::make_zip_iterator(thrust::make_tuple(temp.end(), flags.end())), thrust::make_zip_iterator(thrust::make_tuple(result, flags.begin())), detail::segmented_scan_functor<OutputType, HeadFlagType, AssociativeOperator>(binary_op)); } return result + (last1 - first1); } } // end namespace generic } // end namespace device } // end namespace detail } // end namespace thrust <commit_msg>fix bug in segmented_scan<commit_after>/* * Copyright 2008-2009 NVIDIA Corporation * * 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 <thrust/functional.h> #include <thrust/transform.h> #include <thrust/replace.h> #include <thrust/iterator/zip_iterator.h> #include <thrust/iterator/iterator_traits.h> #include <thrust/detail/device/scan.h> #include <thrust/detail/raw_buffer.h> namespace thrust { namespace detail { namespace device { namespace generic { namespace detail { template <typename OutputType, typename HeadFlagType, typename AssociativeOperator> struct segmented_scan_functor { AssociativeOperator binary_op; typedef typename thrust::tuple<OutputType, HeadFlagType> result_type; __host__ __device__ segmented_scan_functor(AssociativeOperator _binary_op) : binary_op(_binary_op) {} __host__ __device__ result_type operator()(result_type a, result_type b) { return result_type(thrust::get<1>(b) ? thrust::get<0>(b) : binary_op(thrust::get<0>(a), thrust::get<0>(b)), thrust::get<1>(a) | thrust::get<1>(b)); } }; } // end namespace detail template<typename InputIterator1, typename InputIterator2, typename OutputIterator, typename AssociativeOperator, typename BinaryPredicate> OutputIterator inclusive_segmented_scan(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, AssociativeOperator binary_op, BinaryPredicate pred) { typedef typename thrust::iterator_traits<OutputIterator>::value_type OutputType; typedef typename thrust::iterator_space<OutputIterator>::type Space; typedef unsigned int HeadFlagType; if(first1 != last1) { const size_t n = last1 - first1; // compute head flags thrust::detail::raw_buffer<HeadFlagType,Space> flags(n); flags[0] = 1; thrust::transform(first2, first2 + (n - 1), first2 + 1, flags.begin() + 1, thrust::not2(pred)); // scan key-flag tuples, // For additional details refer to Section 2 of the following paper // S. Sengupta, M. Harris, and M. Garland. "Efficient parallel scan algorithms for GPUs" // NVIDIA Technical Report NVR-2008-003, December 2008 // http://mgarland.org/files/papers/nvr-2008-003.pdf thrust::detail::device::inclusive_scan (thrust::make_zip_iterator(thrust::make_tuple(first1, flags.begin())), thrust::make_zip_iterator(thrust::make_tuple(last1, flags.end())), thrust::make_zip_iterator(thrust::make_tuple(result, flags.begin())), detail::segmented_scan_functor<OutputType, HeadFlagType, AssociativeOperator>(binary_op)); } return result + (last1 - first1); } template<typename InputIterator1, typename InputIterator2, typename OutputIterator, typename T, typename AssociativeOperator, typename BinaryPredicate> OutputIterator exclusive_segmented_scan(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, const T init, AssociativeOperator binary_op, BinaryPredicate pred) { typedef typename thrust::iterator_traits<OutputIterator>::value_type OutputType; typedef typename thrust::iterator_space<OutputIterator>::type Space; typedef unsigned int HeadFlagType; if(first1 != last1) { const size_t n = last1 - first1; InputIterator2 last2 = first2 + n; // compute head flags thrust::detail::raw_buffer<HeadFlagType,Space> flags(n); flags[0] = 1; thrust::transform(first2, last2 - 1, first2 + 1, flags.begin() + 1, thrust::not2(pred)); // shift input one to the right and initialize segments with init thrust::detail::raw_buffer<OutputType,Space> temp(n); thrust::replace_copy_if(first1, last1 - 1, flags.begin() + 1, temp.begin() + 1, thrust::negate<HeadFlagType>(), init); temp[0] = init; // scan key-flag tuples, // For additional details refer to Section 2 of the following paper // S. Sengupta, M. Harris, and M. Garland. "Efficient parallel scan algorithms for GPUs" // NVIDIA Technical Report NVR-2008-003, December 2008 // http://mgarland.org/files/papers/nvr-2008-003.pdf thrust::inclusive_scan(thrust::make_zip_iterator(thrust::make_tuple(temp.begin(), flags.begin())), thrust::make_zip_iterator(thrust::make_tuple(temp.end(), flags.end())), thrust::make_zip_iterator(thrust::make_tuple(result, flags.begin())), detail::segmented_scan_functor<OutputType, HeadFlagType, AssociativeOperator>(binary_op)); } return result + (last1 - first1); } } // end namespace generic } // end namespace device } // end namespace detail } // end namespace thrust <|endoftext|>
<commit_before>/* dtkPluginGenerator.cpp --- * * Author: Julien Wintz * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Mon Mar 9 21:41:18 2009 (+0100) * Version: $Id$ * Last-Updated: Tue May 4 15:32:39 2010 (+0200) * By: Julien Wintz * Update #: 175 */ /* Commentary: * */ /* Change log: * */ #include "dtkPluginGenerator.h" dtkPluginGenerator::dtkPluginGenerator(void) { this->d = new dtkPluginGeneratorPrivate; } dtkPluginGenerator::~dtkPluginGenerator(void) { delete this->d; this->d = NULL; } void dtkPluginGenerator::setOutputDirectory(const QString& directory) { d->output = directory; } void dtkPluginGenerator::setPrefix(const QString& prefix) { d->prefix = prefix; } void dtkPluginGenerator::setSuffix(const QString& suffix) { d->suffix = suffix; } void dtkPluginGenerator::setType(const QString& type) { d->type = type; } void dtkPluginGenerator::setDescription(const QString& desc) { d->description = desc; } void dtkPluginGenerator::setLicense(const QString& license) { d->license = license; } bool dtkPluginGenerator::run(void) { d->parent = QDir(d->output); if(!d->parent.exists()) { qWarning() << "dtkPluginGenerator: parent directory is not valid."; return false; } d->plugin = QString("%1%2%3") .arg(QString(d->prefix).toLower()) .arg(d->type) .arg(d->suffix); if(!d->parent.mkdir(QString(d->plugin))) { qWarning() << "dtkPluginGenerator: unable to create target directory."; return false; } d->target = QDir(d->parent); if(!d->target.cd(QString(d->plugin))) { qWarning() << "dtkPluginGenerator: unable to move to target directory."; return false; } return generateCMakeLists() && generateTypeHeaderFile() && generateTypeSourceFile() && generatePluginHeaderFile() && generatePluginSourceFile() && generateExportHeaderFile() && generateHelpCollectionFile() && generateHelpConfigurationFile() && generateReadmeFile() && generateCopyingFile(); } // ///////////////////////////////////////////////////////////////// // CMakeLists.txt // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generateCMakeLists(void) { QFile targetFile(d->target.absoluteFilePath("CMakeLists.txt")); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open CMakeLists.txt for writing"; return false; } QFile templateFile(":template/cmake"); if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading"; return false; } QTextStream stream(&targetFile); stream << QString(templateFile.readAll()).arg(QString(d->plugin)); targetFile.close(); templateFile.close(); return true; } // ///////////////////////////////////////////////////////////////// // Type header file // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generateTypeHeaderFile(void) { QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append(".h"))); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open" << QString(d->plugin).append(".h") << "for writing"; return false; } QFile templateFile(":template/type.h"); if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading"; return false; } QTextStream stream(&targetFile); stream << QString(templateFile.readAll()) .arg(QString(d->plugin)) .arg(QString(d->plugin).toUpper()) .arg(QString(d->type)) .arg(QString(d->plugin).remove(d->prefix).prepend(QString(d->prefix).replace(0, 1, QString(d->prefix).left(1).toUpper()))); targetFile.close(); templateFile.close(); return true; } // ///////////////////////////////////////////////////////////////// // Type source file // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generateTypeSourceFile(void) { QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append(".cpp"))); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open" << QString(d->plugin).append(".cpp") << "for writing"; return false; } QFile templateFile(":template/type.cpp"); if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading"; return false; } QTextStream stream(&targetFile); stream << QString(templateFile.readAll()) .arg(QString(d->plugin)) .arg(QString(d->type)) .arg(QString(d->plugin).remove(d->prefix).prepend(QString(d->prefix).replace(0, 1, QString(d->prefix).left(1).toUpper()))); targetFile.close(); templateFile.close(); return true; } // ///////////////////////////////////////////////////////////////// // Plugin header file // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generatePluginHeaderFile(void) { QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append("Plugin.h"))); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open" << QString(d->plugin).append("Plugin.h") << "for writing"; return false; } QFile templateFile(":template/plugin.h"); if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading"; return false; } QTextStream stream(&targetFile); stream << QString(templateFile.readAll()) .arg(QString(d->plugin)) .arg(QString(d->plugin).toUpper()); targetFile.close(); templateFile.close(); return true; } // ///////////////////////////////////////////////////////////////// // Plugin source file // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generatePluginSourceFile(void) { QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append("Plugin.cpp"))); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open" << QString(d->plugin).append("Plugin.cpp") << "for writing"; return false; } QFile templateFile(":template/plugin.cpp"); if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading"; return false; } QTextStream stream(&targetFile); stream << QString(templateFile.readAll()).arg(QString(d->plugin)); targetFile.close(); templateFile.close(); return true; } // ///////////////////////////////////////////////////////////////// // Export file // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generateExportHeaderFile(void) { QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append("PluginExport.h"))); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open" << QString(d->plugin).append("PluginExport.h") << "for writing"; return false; } QFile templateFile(":template/export.h"); if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading"; return false; } QTextStream stream(&targetFile); stream << QString(templateFile.readAll()).arg(QString(d->plugin)).arg(QString(d->plugin).toUpper()); targetFile.close(); templateFile.close(); return true; } // ///////////////////////////////////////////////////////////////// // Help collection file // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generateHelpCollectionFile(void) { QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append("Plugin.qhcp.in"))); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open" << QString(d->plugin).append("Plugin.qhcp.in") << "for writing"; return false; } QFile templateFile(":template/qhcp"); if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading"; return false; } QTextStream stream(&targetFile); stream << QString(templateFile.readAll()); targetFile.close(); templateFile.close(); return true; } // ///////////////////////////////////////////////////////////////// // Help configuration file // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generateHelpConfigurationFile(void) { QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append("Plugin.doxyfile.in"))); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open" << QString(d->plugin).append("Plugin.doxyfile.in") << "for writing"; return false; } QFile templateFile(":template/doxyfile"); if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading"; return false; } QTextStream stream(&targetFile); stream << QString(templateFile.readAll()); targetFile.close(); templateFile.close(); return true; } // ///////////////////////////////////////////////////////////////// // README file // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generateReadmeFile(void) { QFile targetFile(d->target.absoluteFilePath("README.txt")); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open CMakeLists.txt for writing"; return false; } QTextStream stream(&targetFile); stream << d->description; targetFile.close(); return true; } // ///////////////////////////////////////////////////////////////// // COPYING file // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generateCopyingFile(void) { QFile targetFile(d->target.absoluteFilePath("COPYING.txt")); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open COPYING.txt for writing"; return false; } QFile templateFile(QString(":template/license/").append(d->license)); if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading"; return false; } QTextStream stream(&targetFile); stream << QString(templateFile.readAll()).arg(QString(d->plugin)); targetFile.close(); return true; } <commit_msg>Plugin generator template files have no placeholders so far.<commit_after>/* dtkPluginGenerator.cpp --- * * Author: Julien Wintz * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Mon Mar 9 21:41:18 2009 (+0100) * Version: $Id$ * Last-Updated: Fri Feb 11 14:51:33 2011 (+0100) * By: Julien Wintz * Update #: 176 */ /* Commentary: * */ /* Change log: * */ #include "dtkPluginGenerator.h" dtkPluginGenerator::dtkPluginGenerator(void) { this->d = new dtkPluginGeneratorPrivate; } dtkPluginGenerator::~dtkPluginGenerator(void) { delete this->d; this->d = NULL; } void dtkPluginGenerator::setOutputDirectory(const QString& directory) { d->output = directory; } void dtkPluginGenerator::setPrefix(const QString& prefix) { d->prefix = prefix; } void dtkPluginGenerator::setSuffix(const QString& suffix) { d->suffix = suffix; } void dtkPluginGenerator::setType(const QString& type) { d->type = type; } void dtkPluginGenerator::setDescription(const QString& desc) { d->description = desc; } void dtkPluginGenerator::setLicense(const QString& license) { d->license = license; } bool dtkPluginGenerator::run(void) { d->parent = QDir(d->output); if(!d->parent.exists()) { qWarning() << "dtkPluginGenerator: parent directory is not valid."; return false; } d->plugin = QString("%1%2%3") .arg(QString(d->prefix).toLower()) .arg(d->type) .arg(d->suffix); if(!d->parent.mkdir(QString(d->plugin))) { qWarning() << "dtkPluginGenerator: unable to create target directory."; return false; } d->target = QDir(d->parent); if(!d->target.cd(QString(d->plugin))) { qWarning() << "dtkPluginGenerator: unable to move to target directory."; return false; } return generateCMakeLists() && generateTypeHeaderFile() && generateTypeSourceFile() && generatePluginHeaderFile() && generatePluginSourceFile() && generateExportHeaderFile() && generateHelpCollectionFile() && generateHelpConfigurationFile() && generateReadmeFile() && generateCopyingFile(); } // ///////////////////////////////////////////////////////////////// // CMakeLists.txt // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generateCMakeLists(void) { QFile targetFile(d->target.absoluteFilePath("CMakeLists.txt")); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open CMakeLists.txt for writing"; return false; } QFile templateFile(":template/cmake"); if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading"; return false; } QTextStream stream(&targetFile); stream << QString(templateFile.readAll()).arg(QString(d->plugin)); targetFile.close(); templateFile.close(); return true; } // ///////////////////////////////////////////////////////////////// // Type header file // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generateTypeHeaderFile(void) { QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append(".h"))); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open" << QString(d->plugin).append(".h") << "for writing"; return false; } QFile templateFile(":template/type.h"); if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading"; return false; } QTextStream stream(&targetFile); stream << QString(templateFile.readAll()) .arg(QString(d->plugin)) .arg(QString(d->plugin).toUpper()) .arg(QString(d->type)) .arg(QString(d->plugin).remove(d->prefix).prepend(QString(d->prefix).replace(0, 1, QString(d->prefix).left(1).toUpper()))); targetFile.close(); templateFile.close(); return true; } // ///////////////////////////////////////////////////////////////// // Type source file // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generateTypeSourceFile(void) { QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append(".cpp"))); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open" << QString(d->plugin).append(".cpp") << "for writing"; return false; } QFile templateFile(":template/type.cpp"); if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading"; return false; } QTextStream stream(&targetFile); stream << QString(templateFile.readAll()) .arg(QString(d->plugin)) .arg(QString(d->type)) .arg(QString(d->plugin).remove(d->prefix).prepend(QString(d->prefix).replace(0, 1, QString(d->prefix).left(1).toUpper()))); targetFile.close(); templateFile.close(); return true; } // ///////////////////////////////////////////////////////////////// // Plugin header file // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generatePluginHeaderFile(void) { QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append("Plugin.h"))); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open" << QString(d->plugin).append("Plugin.h") << "for writing"; return false; } QFile templateFile(":template/plugin.h"); if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading"; return false; } QTextStream stream(&targetFile); stream << QString(templateFile.readAll()) .arg(QString(d->plugin)) .arg(QString(d->plugin).toUpper()); targetFile.close(); templateFile.close(); return true; } // ///////////////////////////////////////////////////////////////// // Plugin source file // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generatePluginSourceFile(void) { QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append("Plugin.cpp"))); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open" << QString(d->plugin).append("Plugin.cpp") << "for writing"; return false; } QFile templateFile(":template/plugin.cpp"); if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading"; return false; } QTextStream stream(&targetFile); stream << QString(templateFile.readAll()).arg(QString(d->plugin)); targetFile.close(); templateFile.close(); return true; } // ///////////////////////////////////////////////////////////////// // Export file // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generateExportHeaderFile(void) { QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append("PluginExport.h"))); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open" << QString(d->plugin).append("PluginExport.h") << "for writing"; return false; } QFile templateFile(":template/export.h"); if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading"; return false; } QTextStream stream(&targetFile); stream << QString(templateFile.readAll()).arg(QString(d->plugin)).arg(QString(d->plugin).toUpper()); targetFile.close(); templateFile.close(); return true; } // ///////////////////////////////////////////////////////////////// // Help collection file // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generateHelpCollectionFile(void) { QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append("Plugin.qhcp.in"))); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open" << QString(d->plugin).append("Plugin.qhcp.in") << "for writing"; return false; } QFile templateFile(":template/qhcp"); if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading"; return false; } QTextStream stream(&targetFile); stream << QString(templateFile.readAll()); targetFile.close(); templateFile.close(); return true; } // ///////////////////////////////////////////////////////////////// // Help configuration file // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generateHelpConfigurationFile(void) { QFile targetFile(d->target.absoluteFilePath(QString(d->plugin).append("Plugin.doxyfile.in"))); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open" << QString(d->plugin).append("Plugin.doxyfile.in") << "for writing"; return false; } QFile templateFile(":template/doxyfile"); if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading"; return false; } QTextStream stream(&targetFile); stream << QString(templateFile.readAll()); targetFile.close(); templateFile.close(); return true; } // ///////////////////////////////////////////////////////////////// // README file // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generateReadmeFile(void) { QFile targetFile(d->target.absoluteFilePath("README.txt")); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open CMakeLists.txt for writing"; return false; } QTextStream stream(&targetFile); stream << d->description; targetFile.close(); return true; } // ///////////////////////////////////////////////////////////////// // COPYING file // ///////////////////////////////////////////////////////////////// bool dtkPluginGenerator::generateCopyingFile(void) { QFile targetFile(d->target.absoluteFilePath("COPYING.txt")); if(!targetFile.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "dtkPluginGenerator: unable to open COPYING.txt for writing"; return false; } QFile templateFile(QString(":template/license/").append(d->license)); if(!templateFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "dtkPluginGenerator: unable to open template file " << templateFile.fileName() << " for reading"; return false; } QTextStream stream(&targetFile); stream << QString(templateFile.readAll()); targetFile.close(); return true; } <|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 <toolkit/helper/accessibilityclient.hxx> #include <toolkit/helper/accessiblefactory.hxx> #include <osl/module.h> #include <osl/diagnose.h> #include <tools/solar.h> // #define UNLOAD_ON_LAST_CLIENT_DYING // this is not recommended currently. If enabled, the implementation will log // the number of active clients, and unload the acc library when the last client // goes away. // Sounds like a good idea, unfortunately, there's no guarantee that all objects // implemented in this library are already dead. // Iow, just because an object implementing an XAccessible (implemented in this lib // here) died, it's not said that everybody released all references to the // XAccessibleContext used by this component, and implemented in the acc lib. // So we cannot really unload the lib. // // Alternatively, if the lib would us own "usage counting", i.e. every component // implemented therein would affect a static ref count, the acc lib could care // for unloading itself. //........................................................................ namespace toolkit { //........................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::accessibility; namespace { #ifdef UNLOAD_ON_LAST_CLIENT_DYING static oslInterlockedCount s_nAccessibilityClients = 0; #endif // UNLOAD_ON_LAST_CLIENT_DYING static oslModule s_hAccessibleImplementationModule = NULL; static GetStandardAccComponentFactory s_pAccessibleFactoryFunc = NULL; static ::rtl::Reference< IAccessibleFactory > s_pFactory; } //==================================================================== //= AccessibleDummyFactory //==================================================================== class AccessibleDummyFactory : public IAccessibleFactory { public: AccessibleDummyFactory(); protected: virtual ~AccessibleDummyFactory(); private: AccessibleDummyFactory( const AccessibleDummyFactory& ); // never implemented AccessibleDummyFactory& operator=( const AccessibleDummyFactory& ); // never implemented oslInterlockedCount m_refCount; public: // IReference virtual oslInterlockedCount SAL_CALL acquire(); virtual oslInterlockedCount SAL_CALL release(); // IAccessibleFactory ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXButton* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXCheckBox* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXRadioButton* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXListBox* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXFixedHyperlink* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXFixedText* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXScrollBar* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXEdit* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXComboBox* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXToolBox* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXWindow* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > createAccessible( Menu* /*_pMenu*/, sal_Bool /*_bIsMenuBar*/ ) { return NULL; } }; //-------------------------------------------------------------------- AccessibleDummyFactory::AccessibleDummyFactory() { } //-------------------------------------------------------------------- AccessibleDummyFactory::~AccessibleDummyFactory() { } //-------------------------------------------------------------------- oslInterlockedCount SAL_CALL AccessibleDummyFactory::acquire() { return osl_atomic_increment( &m_refCount ); } //-------------------------------------------------------------------- oslInterlockedCount SAL_CALL AccessibleDummyFactory::release() { if ( 0 == osl_atomic_decrement( &m_refCount ) ) { delete this; return 0; } return m_refCount; } //==================================================================== //= AccessibilityClient //==================================================================== //-------------------------------------------------------------------- AccessibilityClient::AccessibilityClient() :m_bInitialized( false ) { } //-------------------------------------------------------------------- #ifndef DISABLE_DYNLOADING extern "C" { static void SAL_CALL thisModule() {} } #else extern "C" void *getStandardAccessibleFactory(); #endif void AccessibilityClient::ensureInitialized() { if ( m_bInitialized ) return; ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); #ifdef UNLOAD_ON_LAST_CLIENT_DYING if ( 1 == osl_atomic_increment( &s_nAccessibilityClients ) ) { // the first client #endif // UNLOAD_ON_LAST_CLIENT_DYING // load the library implementing the factory if ( !s_pFactory.get() ) { #ifndef DISABLE_DYNLOADING const ::rtl::OUString sModuleName( SVLIBRARY( "acc" ) ); s_hAccessibleImplementationModule = osl_loadModuleRelative( &thisModule, sModuleName.pData, 0 ); if ( s_hAccessibleImplementationModule != NULL ) { const ::rtl::OUString sFactoryCreationFunc = ::rtl::OUString("getStandardAccessibleFactory"); s_pAccessibleFactoryFunc = (GetStandardAccComponentFactory) osl_getFunctionSymbol( s_hAccessibleImplementationModule, sFactoryCreationFunc.pData ); } OSL_ENSURE( s_pAccessibleFactoryFunc, "AccessibilityClient::ensureInitialized: could not load the library, or not retrieve the needed symbol!" ); #else s_pAccessibleFactoryFunc = getStandardAccessibleFactory; #endif // get a factory instance if ( s_pAccessibleFactoryFunc ) { IAccessibleFactory* pFactory = static_cast< IAccessibleFactory* >( (*s_pAccessibleFactoryFunc)() ); OSL_ENSURE( pFactory, "AccessibilityClient::ensureInitialized: no factory provided by the A11Y lib!" ); if ( pFactory ) { s_pFactory = pFactory; pFactory->release(); } } } if ( !s_pFactory.get() ) // the attempt to load the lib, or to create the factory, failed // -> fall back to a dummy factory s_pFactory = new AccessibleDummyFactory; #ifdef UNLOAD_ON_LAST_CLIENT_DYING } #endif m_bInitialized = true; } //-------------------------------------------------------------------- AccessibilityClient::~AccessibilityClient() { if ( m_bInitialized ) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); #ifdef UNLOAD_ON_LAST_CLIENT_DYING if( 0 == osl_atomic_decrement( &s_nAccessibilityClients ) ) { s_pFactory = NULL; s_pAccessibleFactoryFunc = NULL; if ( s_hAccessibleImplementationModule ) { osl_unloadModule( s_hAccessibleImplementationModule ); s_hAccessibleImplementationModule = NULL; } } #endif // UNLOAD_ON_LAST_CLIENT_DYING } } //-------------------------------------------------------------------- IAccessibleFactory& AccessibilityClient::getFactory() { ensureInitialized(); OSL_ENSURE( s_pFactory.is(), "AccessibilityClient::getFactory: at least a dummy factory should have been created!" ); return *s_pFactory; } //........................................................................ } // namespace toolkit //........................................................................ /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>WaE: 's_hAccessibleImplementationModule' defined but not used<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 <toolkit/helper/accessibilityclient.hxx> #include <toolkit/helper/accessiblefactory.hxx> #include <osl/module.h> #include <osl/diagnose.h> #include <tools/solar.h> // #define UNLOAD_ON_LAST_CLIENT_DYING // this is not recommended currently. If enabled, the implementation will log // the number of active clients, and unload the acc library when the last client // goes away. // Sounds like a good idea, unfortunately, there's no guarantee that all objects // implemented in this library are already dead. // Iow, just because an object implementing an XAccessible (implemented in this lib // here) died, it's not said that everybody released all references to the // XAccessibleContext used by this component, and implemented in the acc lib. // So we cannot really unload the lib. // // Alternatively, if the lib would us own "usage counting", i.e. every component // implemented therein would affect a static ref count, the acc lib could care // for unloading itself. //........................................................................ namespace toolkit { //........................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::accessibility; namespace { #ifdef UNLOAD_ON_LAST_CLIENT_DYING static oslInterlockedCount s_nAccessibilityClients = 0; #endif // UNLOAD_ON_LAST_CLIENT_DYING #ifndef DISABLE_DYNLOADING static oslModule s_hAccessibleImplementationModule = NULL; #endif static GetStandardAccComponentFactory s_pAccessibleFactoryFunc = NULL; static ::rtl::Reference< IAccessibleFactory > s_pFactory; } //==================================================================== //= AccessibleDummyFactory //==================================================================== class AccessibleDummyFactory : public IAccessibleFactory { public: AccessibleDummyFactory(); protected: virtual ~AccessibleDummyFactory(); private: AccessibleDummyFactory( const AccessibleDummyFactory& ); // never implemented AccessibleDummyFactory& operator=( const AccessibleDummyFactory& ); // never implemented oslInterlockedCount m_refCount; public: // IReference virtual oslInterlockedCount SAL_CALL acquire(); virtual oslInterlockedCount SAL_CALL release(); // IAccessibleFactory ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXButton* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXCheckBox* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXRadioButton* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXListBox* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXFixedHyperlink* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXFixedText* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXScrollBar* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXEdit* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXComboBox* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXToolBox* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > createAccessibleContext( VCLXWindow* /*_pXWindow*/ ) { return NULL; } ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > createAccessible( Menu* /*_pMenu*/, sal_Bool /*_bIsMenuBar*/ ) { return NULL; } }; //-------------------------------------------------------------------- AccessibleDummyFactory::AccessibleDummyFactory() { } //-------------------------------------------------------------------- AccessibleDummyFactory::~AccessibleDummyFactory() { } //-------------------------------------------------------------------- oslInterlockedCount SAL_CALL AccessibleDummyFactory::acquire() { return osl_atomic_increment( &m_refCount ); } //-------------------------------------------------------------------- oslInterlockedCount SAL_CALL AccessibleDummyFactory::release() { if ( 0 == osl_atomic_decrement( &m_refCount ) ) { delete this; return 0; } return m_refCount; } //==================================================================== //= AccessibilityClient //==================================================================== //-------------------------------------------------------------------- AccessibilityClient::AccessibilityClient() :m_bInitialized( false ) { } //-------------------------------------------------------------------- #ifndef DISABLE_DYNLOADING extern "C" { static void SAL_CALL thisModule() {} } #else extern "C" void *getStandardAccessibleFactory(); #endif void AccessibilityClient::ensureInitialized() { if ( m_bInitialized ) return; ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); #ifdef UNLOAD_ON_LAST_CLIENT_DYING if ( 1 == osl_atomic_increment( &s_nAccessibilityClients ) ) { // the first client #endif // UNLOAD_ON_LAST_CLIENT_DYING // load the library implementing the factory if ( !s_pFactory.get() ) { #ifndef DISABLE_DYNLOADING const ::rtl::OUString sModuleName( SVLIBRARY( "acc" ) ); s_hAccessibleImplementationModule = osl_loadModuleRelative( &thisModule, sModuleName.pData, 0 ); if ( s_hAccessibleImplementationModule != NULL ) { const ::rtl::OUString sFactoryCreationFunc = ::rtl::OUString("getStandardAccessibleFactory"); s_pAccessibleFactoryFunc = (GetStandardAccComponentFactory) osl_getFunctionSymbol( s_hAccessibleImplementationModule, sFactoryCreationFunc.pData ); } OSL_ENSURE( s_pAccessibleFactoryFunc, "AccessibilityClient::ensureInitialized: could not load the library, or not retrieve the needed symbol!" ); #else s_pAccessibleFactoryFunc = getStandardAccessibleFactory; #endif // get a factory instance if ( s_pAccessibleFactoryFunc ) { IAccessibleFactory* pFactory = static_cast< IAccessibleFactory* >( (*s_pAccessibleFactoryFunc)() ); OSL_ENSURE( pFactory, "AccessibilityClient::ensureInitialized: no factory provided by the A11Y lib!" ); if ( pFactory ) { s_pFactory = pFactory; pFactory->release(); } } } if ( !s_pFactory.get() ) // the attempt to load the lib, or to create the factory, failed // -> fall back to a dummy factory s_pFactory = new AccessibleDummyFactory; #ifdef UNLOAD_ON_LAST_CLIENT_DYING } #endif m_bInitialized = true; } //-------------------------------------------------------------------- AccessibilityClient::~AccessibilityClient() { if ( m_bInitialized ) { ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); #ifdef UNLOAD_ON_LAST_CLIENT_DYING if( 0 == osl_atomic_decrement( &s_nAccessibilityClients ) ) { s_pFactory = NULL; s_pAccessibleFactoryFunc = NULL; if ( s_hAccessibleImplementationModule ) { osl_unloadModule( s_hAccessibleImplementationModule ); s_hAccessibleImplementationModule = NULL; } } #endif // UNLOAD_ON_LAST_CLIENT_DYING } } //-------------------------------------------------------------------- IAccessibleFactory& AccessibilityClient::getFactory() { ensureInitialized(); OSL_ENSURE( s_pFactory.is(), "AccessibilityClient::getFactory: at least a dummy factory should have been created!" ); return *s_pFactory; } //........................................................................ } // namespace toolkit //........................................................................ /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef HTTP_REQUEST_LINE_HPP #define HTTP_REQUEST_LINE_HPP #include <cctype> #include <regex> #include "common.hpp" #include "methods.hpp" #include "version.hpp" namespace http { //----------------------------------- // This class represents the request-line // of an incoming http request message //----------------------------------- class Request_Line { public: //----------------------------------- // Constructor to create a default // request-line which is as follows: // // <GET / HTTP/1.1> //----------------------------------- explicit Request_Line() = default; //----------------------------------- // Constructor to construct a request-line // from the incoming character stream of // data which is a <std::string> object // // @tparam (std::string) request - The character stream of // data //----------------------------------- template <typename Request> explicit Request_Line(Request&& request); // Copy / move constructors Request_Line(Request_Line&) = default; Request_Line(Request_Line&&) = default; ~Request_Line() noexcept = default; Request_Line& operator = (Request_Line&) = default; Request_Line& operator = (Request_Line&&) = default; //----------------------------------- // Get the method of the message // // @return - The method of the message //----------------------------------- const Method& get_method() const noexcept; //----------------------------------- // Set the method of the message // // @param method - The method of the message //----------------------------------- void set_method(const Method& method); //----------------------------------- // Get the URI of the message // // @return - The URI of the message //----------------------------------- const URI& get_uri() const noexcept; //----------------------------------- // Set the URI of the message // // @param uri - The URI of the message //----------------------------------- void set_uri(const URI& uri); //----------------------------------- // Get the version of the message // // @return - The version of the message //----------------------------------- const Version& get_version() const noexcept; //----------------------------------- // Set the version of the message // // @param version - The version of the message //----------------------------------- void set_version(const Version& version) noexcept; //----------------------------------- // Get a string representation of this // class // // @return - A string representation //----------------------------------- std::string to_string() const; //----------------------------------- // Operator to transform this class // into string form //----------------------------------- operator std::string () const; //----------------------------------- private: //----------------------------------- // Class data members //----------------------------------- Method method_ { GET }; URI uri_ {"/"}; Version version_ {1U, 1U}; }; //< class Request_Line class Request_line_error : public std::runtime_error { using runtime_error::runtime_error; }; /**--v----------- Implementation Details -----------v--**/ template <typename Request> inline Request_Line::Request_Line(Request&& request) { if (request.empty() or request.size() < 16 /*<-(16) minimum request length */) { return; } // Extract HTTP method std::string request_line = {request.substr(0, request.find("\r\n"))}; // Should identify strings according to RFC 2616 sect.5.1 // https://tools.ietf.org/html/rfc2616#section-5.1 std::regex re_request_line { "\\s*(GET|POST|PUT|DELETE|OPTIONS|HEAD|TRACE|CONNECT) " // Method "(\\S+) " // URI "HTTP/(\\d+)\\.(\\d+)" // Version Major.Minor }; std::smatch m; auto matched = std::regex_match(request_line,m, re_request_line); if (not matched) throw Request_line_error("Invalid request line: " + request_line); method_ = method::code(m[1]); //uri_ = URI {m[2]}; new (&uri_) URI(m[2]); unsigned maj = static_cast<unsigned>(std::stoul(m[3])); unsigned min = static_cast<unsigned>(std::stoul(m[4])); version_ = Version{maj, min}; // Trim the request for further processing request = request.substr(request.find("\r\n") + 2); } inline const Method& Request_Line::get_method() const noexcept { return method_; } inline void Request_Line::set_method(const Method& method) { method_ = method; } inline const URI& Request_Line::get_uri() const noexcept { return uri_; } inline void Request_Line::set_uri(const URI& uri) { //uri_ = uri; new (&uri_) URI(uri); } inline const Version& Request_Line::get_version() const noexcept { return version_; } inline void Request_Line::set_version(const Version& version) noexcept { version_ = version; } inline std::string Request_Line::to_string() const { return method::str(method_)+" "+uri_.to_string()+" " +version_.to_string(); } inline Request_Line::operator std::string () const { std::ostringstream req_line; //----------------------------- req_line << method_ << " " << uri_ << " " << version_ << "\r\n"; //------------------------------ return req_line.str(); } inline std::ostream& operator << (std::ostream& output_device, const Request_Line& req_line) { return output_device << req_line.to_string(); } /**--^----------- Implementation Details -----------^--**/ } //< namespace http #endif //< HTTP_REQUEST_LINE_HPP <commit_msg>Changed validation rule<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef HTTP_REQUEST_LINE_HPP #define HTTP_REQUEST_LINE_HPP #include <cctype> #include <regex> #include "common.hpp" #include "methods.hpp" #include "version.hpp" namespace http { //----------------------------------- // This class represents the request-line // of an incoming http request message //----------------------------------- class Request_Line { public: //----------------------------------- // Constructor to create a default // request-line which is as follows: // // <GET / HTTP/1.1> //----------------------------------- explicit Request_Line() = default; //----------------------------------- // Constructor to construct a request-line // from the incoming character stream of // data which is a <std::string> object // // @tparam (std::string) request - The character stream of // data //----------------------------------- template <typename Request> explicit Request_Line(Request&& request); // Copy / move constructors Request_Line(Request_Line&) = default; Request_Line(Request_Line&&) = default; ~Request_Line() noexcept = default; Request_Line& operator = (Request_Line&) = default; Request_Line& operator = (Request_Line&&) = default; //----------------------------------- // Get the method of the message // // @return - The method of the message //----------------------------------- const Method& get_method() const noexcept; //----------------------------------- // Set the method of the message // // @param method - The method of the message //----------------------------------- void set_method(const Method& method); //----------------------------------- // Get the URI of the message // // @return - The URI of the message //----------------------------------- const URI& get_uri() const noexcept; //----------------------------------- // Set the URI of the message // // @param uri - The URI of the message //----------------------------------- void set_uri(const URI& uri); //----------------------------------- // Get the version of the message // // @return - The version of the message //----------------------------------- const Version& get_version() const noexcept; //----------------------------------- // Set the version of the message // // @param version - The version of the message //----------------------------------- void set_version(const Version& version) noexcept; //----------------------------------- // Get a string representation of this // class // // @return - A string representation //----------------------------------- std::string to_string() const; //----------------------------------- // Operator to transform this class // into string form //----------------------------------- operator std::string () const; //----------------------------------- private: //----------------------------------- // Class data members //----------------------------------- Method method_ { GET }; URI uri_ {"/"}; Version version_ {1U, 1U}; }; //< class Request_Line class Request_line_error : public std::runtime_error { using runtime_error::runtime_error; }; /**--v----------- Implementation Details -----------v--**/ template <typename Request> inline Request_Line::Request_Line(Request&& request) { if (request.empty() or request.size() < 15 /*<-(15) minimum request length */) { throw Request_line_error("Invalid request line: " + request_line); } // Extract HTTP method std::string request_line = {request.substr(0, request.find("\r\n"))}; // Should identify strings according to RFC 2616 sect.5.1 // https://tools.ietf.org/html/rfc2616#section-5.1 std::regex re_request_line { "\\s*(GET|POST|PUT|DELETE|OPTIONS|HEAD|TRACE|CONNECT) " // Method "(\\S+) " // URI "HTTP/(\\d+)\\.(\\d+)" // Version Major.Minor }; std::smatch m; auto matched = std::regex_match(request_line,m, re_request_line); if (not matched) throw Request_line_error("Invalid request line: " + request_line); method_ = method::code(m[1]); //uri_ = URI {m[2]}; new (&uri_) URI(m[2]); unsigned maj = static_cast<unsigned>(std::stoul(m[3])); unsigned min = static_cast<unsigned>(std::stoul(m[4])); version_ = Version{maj, min}; // Trim the request for further processing request = request.substr(request.find("\r\n") + 2); } inline const Method& Request_Line::get_method() const noexcept { return method_; } inline void Request_Line::set_method(const Method& method) { method_ = method; } inline const URI& Request_Line::get_uri() const noexcept { return uri_; } inline void Request_Line::set_uri(const URI& uri) { //uri_ = uri; new (&uri_) URI(uri); } inline const Version& Request_Line::get_version() const noexcept { return version_; } inline void Request_Line::set_version(const Version& version) noexcept { version_ = version; } inline std::string Request_Line::to_string() const { return method::str(method_)+" "+uri_.to_string()+" " +version_.to_string(); } inline Request_Line::operator std::string () const { std::ostringstream req_line; //----------------------------- req_line << method_ << " " << uri_ << " " << version_ << "\r\n"; //------------------------------ return req_line.str(); } inline std::ostream& operator << (std::ostream& output_device, const Request_Line& req_line) { return output_device << req_line.to_string(); } /**--^----------- Implementation Details -----------^--**/ } //< namespace http #endif //< HTTP_REQUEST_LINE_HPP <|endoftext|>
<commit_before>#ifndef COMPONENT_HH #define COMPONENT_HH #include <G4LogicalVolume.hh> class G4VUserPrimaryGeneratorAction; class G4UserEventAction; class G4UserRunAction; class G4UserStackingAction; class G4UserSteppingAction; class G4UserTrackingAction; class G4VUserPhysicsList; class G4VPhysicalVolume; namespace g4 { class GeometryBuilder; class ComponentManager; /** * @brief A component for the G4Application architecture. * * Instances of this class are shared. Ideally, they have no state, otherwise * careful thread-safety is necessary. * * The components may be created at different stages of application * run. Therefore, useful initialization code can be put * into `OnLoad` method. */ class Component { public: virtual ~Component() { } /** * @short Create part of the geometry and insert it into * provided G4LogicalVolume * * @param logVolume In most cases, this is the world volume (in most cases) */ virtual void BuildGeometry(G4LogicalVolume* logVolume) { } virtual G4VPhysicalVolume* CreateWorld() { return nullptr; } virtual void ConstructSDandField() { } virtual G4VUserPrimaryGeneratorAction* CreatePrimaryGeneratorAction() { return nullptr; } virtual G4UserEventAction* CreateEventAction() { return nullptr; } virtual G4UserRunAction* CreateRunAction() { return nullptr; } virtual G4UserStackingAction* CreateStackingAction() { return nullptr; } virtual G4UserSteppingAction* CreateSteppingAction() { return nullptr; } virtual G4UserTrackingAction* CreateTrackingAction() { return nullptr; } virtual G4VUserPhysicsList* CreatePhysicsList() { return nullptr; } protected: friend class ComponentManager; virtual void OnLoad() { } }; } #endif // COMPONENT_HH <commit_msg>Build without warnings using GCC<commit_after>#ifndef COMPONENT_HH #define COMPONENT_HH #include <G4LogicalVolume.hh> class G4VUserPrimaryGeneratorAction; class G4UserEventAction; class G4UserRunAction; class G4UserStackingAction; class G4UserSteppingAction; class G4UserTrackingAction; class G4VUserPhysicsList; class G4VPhysicalVolume; namespace g4 { class GeometryBuilder; class ComponentManager; /** * @brief A component for the G4Application architecture. * * Instances of this class are shared. Ideally, they have no state, otherwise * careful thread-safety is necessary. * * The components may be created at different stages of application * run. Therefore, useful initialization code can be put * into `OnLoad` method. */ class Component { public: virtual ~Component() { } /** * @short Create part of the geometry and insert it into * provided G4LogicalVolume * * @param logVolume In most cases, this is the world volume (in most cases) */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" virtual void BuildGeometry(G4LogicalVolume* logVolume) { } #pragma GCC diagnostic pop virtual G4VPhysicalVolume* CreateWorld() { return nullptr; } virtual void ConstructSDandField() { } virtual G4VUserPrimaryGeneratorAction* CreatePrimaryGeneratorAction() { return nullptr; } virtual G4UserEventAction* CreateEventAction() { return nullptr; } virtual G4UserRunAction* CreateRunAction() { return nullptr; } virtual G4UserStackingAction* CreateStackingAction() { return nullptr; } virtual G4UserSteppingAction* CreateSteppingAction() { return nullptr; } virtual G4UserTrackingAction* CreateTrackingAction() { return nullptr; } virtual G4VUserPhysicsList* CreatePhysicsList() { return nullptr; } protected: friend class ComponentManager; virtual void OnLoad() { } }; } #endif // COMPONENT_HH <|endoftext|>
<commit_before>/* ************************************************ * GEANT4 CAD INTERFACE * * File: CADMesh.hh * * Author: Christopher M Poole, * Email: mail@christopherpoole.net * * Date: 7th March, 2011 **************************************************/ #pragma once namespace CADMesh { namespace File { enum Type { Unknown, PLY, STL, DAE, OBJ, TET, OFF, }; } } <commit_msg>Added a static mapping of file types to their extensions.<commit_after>/* ************************************************ * GEANT4 CAD INTERFACE * * File: CADMesh.hh * * Author: Christopher M Poole, * Email: mail@christopherpoole.net * * Date: 7th March, 2011 **************************************************/ #pragma once // STL // #include <string> #include <map> namespace CADMesh { namespace File { enum Type { Unknown, PLY, STL, DAE, OBJ, TET, OFF, }; static std::map<Type, std::string> Entension = { { PLY, "ply" }, { STL, "stl" }, { DAE, "dae" }, { OBJ, "obj" }, { TET, "tet" }, { OFF, "off" } }; } } <|endoftext|>
<commit_before>// $RCSfile: $ // $Revision: $ $Date: $ // Auth: Samson Bonfante (bonfante@steptools.com) // // Copyright (c) 1991-2016 by STEP Tools 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 "nodeAptStepMaker.h" #include "nodeUtils.h" AptStepMaker* AptStepMaker::_singleton = nullptr; apt2step* AptStepMaker::getApt() { if (_singleton == nullptr) _singleton = new AptStepMaker(); return _singleton->_apt; } NAN_METHOD(AptStepMaker::New) { if (info.IsConstructCall()) { if (!info[0]->IsUndefined()) { return; } if (_singleton == nullptr) _singleton = new AptStepMaker(); _singleton->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } else { return; } } NAN_MODULE_INIT(AptStepMaker::Init) { v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); tpl->SetClassName(Nan::New("AptStepMaker").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "GetToolEID", GetToolEID); Nan::SetPrototypeMethod(tpl, "GetToolIdentifier", GetToolIdentifier); Nan::SetPrototypeMethod(tpl, "GetToolNumber", GetToolNumber); Nan::SetPrototypeMethod(tpl, "GetUUID", GetUUID); Nan::SetPrototypeMethod(tpl, "GetWorkpieceExecutableAll", GetWorkpieceExecutableAll); Nan::SetPrototypeMethod(tpl, "GetWorkpiecePlacement", GetWorkpiecePlacement); Nan::SetPrototypeMethod(tpl, "GetExecutableWorkpieceToBe", GetExecutableWorkpieceToBe); Nan::SetPrototypeMethod(tpl, "GetCurrentWorkpiece", GetCurrentWorkpiece); Nan::SetPrototypeMethod(tpl, "GetCurrentWorkplan", GetCurrentWorkplan); Nan::SetPrototypeMethod(tpl, "GetWorkplanSetup", GetWorkplanSetup); Nan::SetPrototypeMethod(tpl, "OpenProject", OpenProject); Nan::SetPrototypeMethod(tpl, "OpenSTEP", OpenSTEP); Nan::SetPrototypeMethod(tpl, "SaveAsModules", SaveAsModules); Nan::SetPrototypeMethod(tpl, "SaveAsP21", SaveAsP21); Nan::SetPrototypeMethod(tpl, "SetNameGet", SetNameGet); constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); Nan::Set(target, Nan::New("AptStepMaker").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked()); } NAN_METHOD(AptStepMaker::GetToolEID) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsString()) return; char * toolNum = 0; v8StringToChar(info[0], toolNum); int toolEID; if (!apt->_apt->get_tool_id(toolNum, toolEID)) //TODO: Handle error return; info.GetReturnValue().Set(toolEID); return; } NAN_METHOD(AptStepMaker::GetToolIdentifier) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsString()) return; char * toolNum = 0; v8StringToChar(info[0], toolNum); const char * toolID = 0; if (!apt->_apt->get_tool_identifier(toolNum, toolID)) // TODO: Handle error return; info.GetReturnValue().Set(CharTov8String((char *)toolNum)); return; } NAN_METHOD(AptStepMaker::GetToolNumber) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsInt32()) return; Nan::Maybe<int32_t> id = Nan::To<int32_t>(info[0]); const char * tlNum = 0; if (!apt->_apt->get_tool_number(id.FromJust(), tlNum)) //TODO: Handle Error return; info.GetReturnValue().Set(CharTov8String((char *)tlNum)); return; } NAN_METHOD(AptStepMaker::GetUUID) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsInt32()) return; Nan::Maybe<int32_t> eid = Nan::To<int32_t>(info[0]); const char * uuid; if (!apt->_apt->get_uuid(eid.FromJust(), uuid)) //TODO: Handle error return; info.GetReturnValue().Set(CharTov8String((char *)uuid)); return; } NAN_METHOD(AptStepMaker::GetWorkpieceExecutableAll) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsInt32()) return; Nan::Maybe<int32_t> wpid = Nan::To<int32_t>(info[0]); int count = 0; if (!apt->_apt->workpiece_executable_count(wpid.FromJust(), count)) //Throw Exception return; v8::Local<v8::Array> array = Nan::New<v8::Array>(); for (int i = 0; i < count; i++) { int exe_id = 0; if (!apt->_apt->workpiece_executable_next(wpid.FromJust(), i, exe_id)) //Throw Exception return; else array->Set(i, Nan::New(exe_id)); } info.GetReturnValue().Set(array); return; } NAN_METHOD(AptStepMaker::GetWorkpiecePlacement) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsInt32()) return; Nan::Maybe<int32_t> wpid = Nan::To<int32_t>(info[0]); double x; double y; double z; double i; double j; double k; double a; double b; double c; if (!apt->_apt->get_workpiece_placement(wpid.FromJust(), x, y, z, i, j, k, a, b, c)) //TODO: Handle error return; v8::Local<v8::Array> array = Nan::New<v8::Array>(); array->Set(0, Nan::New(x)); array->Set(1, Nan::New(y)); array->Set(2, Nan::New(z)); array->Set(3, Nan::New(i)); array->Set(4, Nan::New(j)); array->Set(5, Nan::New(k)); array->Set(6, Nan::New(a)); array->Set(7, Nan::New(b)); array->Set(8, Nan::New(c)); info.GetReturnValue().Set(array); return; } NAN_METHOD(AptStepMaker::GetExecutableWorkpieceToBe) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsInt32()) return; Nan::Maybe<int32_t> wsid = Nan::To<int32_t>(info[0]); int wpid; if (!apt->_apt->executable_removal_workpiece(wsid.FromJust(), wpid)) //TODO: Handle error return; info.GetReturnValue().Set(wpid); return; } NAN_METHOD(AptStepMaker::GetCurrentWorkpiece) { AptStepMaker* apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); int wsid; int dummy; if (!apt->_apt->more_current_ids(wsid, dummy, dummy, dummy, dummy)) //TODO: Handle error return; info.GetReturnValue().Set(wsid); return; } NAN_METHOD(AptStepMaker::GetCurrentWorkplan) { AptStepMaker* apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); int wpid; int dummy; if (!apt->_apt->more_current_ids(dummy, wpid, dummy, dummy, dummy)) //TODO: Handle error return; info.GetReturnValue().Set(wpid); return; } NAN_METHOD(AptStepMaker::GetWorkplanSetup) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsInt32()) return; Nan::Maybe<int32_t> wpid = Nan::To<int32_t>(info[0]); double x; double y; double z; double i; double j; double k; double a; double b; double c; if (!apt->_apt->workplan_setup_get(wpid.FromJust(), x, y, z, i, j, k, a, b, c)) //TODO: Handle error return; v8::Local<v8::Array> array = Nan::New<v8::Array>(); array->Set(0, Nan::New(x)); array->Set(1, Nan::New(y)); array->Set(2, Nan::New(z)); array->Set(3, Nan::New(i)); array->Set(4, Nan::New(j)); array->Set(5, Nan::New(k)); array->Set(6, Nan::New(a)); array->Set(7, Nan::New(b)); array->Set(8, Nan::New(c)); info.GetReturnValue().Set(array); return; } NAN_METHOD(AptStepMaker::OpenProject) { AptStepMaker* apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsString()) return; char * fname = 0; v8StringToChar(info[0], fname); if (!apt->_apt->read_238_file(fname)) //TODO: Handle Error. return; return; //Success finding, return. } NAN_METHOD(AptStepMaker::OpenSTEP) { AptStepMaker* apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsString()) return; char * fname = 0; v8StringToChar(info[0], fname); if (!apt->_apt->read_203_file(fname)) //TODO: Handle Error. return; return; //Success finding, return. } NAN_METHOD(AptStepMaker::SaveAsModules) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info[0]->IsUndefined()) return; if (!info[0]->IsString()) return; char* file_name_utf8; v8StringToChar(info[0], file_name_utf8); if (!apt->_apt->save_file(file_name_utf8, true)) //Throw Exception return; } NAN_METHOD(AptStepMaker::SaveAsP21) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info[0]->IsUndefined()) return; if (!info[0]->IsString()) return; char* file_name_utf8; v8StringToChar(info[0], file_name_utf8); if (!apt->_apt->save_file(file_name_utf8, false)) //Throw Exception return; } NAN_METHOD(AptStepMaker::SetNameGet) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsInt32()) return; Nan::Maybe<int32_t> eid = Nan::To<int32_t>(info[0]); const char * szName; if (!apt->_apt->get_name(eid.FromJust(), szName)) //TODO: Handle error return; info.GetReturnValue().Set(CharTov8String((char *)szName)); return; }<commit_msg>Current instead of more current<commit_after>// $RCSfile: $ // $Revision: $ $Date: $ // Auth: Samson Bonfante (bonfante@steptools.com) // // Copyright (c) 1991-2016 by STEP Tools 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 "nodeAptStepMaker.h" #include "nodeUtils.h" AptStepMaker* AptStepMaker::_singleton = nullptr; apt2step* AptStepMaker::getApt() { if (_singleton == nullptr) _singleton = new AptStepMaker(); return _singleton->_apt; } NAN_METHOD(AptStepMaker::New) { if (info.IsConstructCall()) { if (!info[0]->IsUndefined()) { return; } if (_singleton == nullptr) _singleton = new AptStepMaker(); _singleton->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } else { return; } } NAN_MODULE_INIT(AptStepMaker::Init) { v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); tpl->SetClassName(Nan::New("AptStepMaker").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "GetToolEID", GetToolEID); Nan::SetPrototypeMethod(tpl, "GetToolIdentifier", GetToolIdentifier); Nan::SetPrototypeMethod(tpl, "GetToolNumber", GetToolNumber); Nan::SetPrototypeMethod(tpl, "GetUUID", GetUUID); Nan::SetPrototypeMethod(tpl, "GetWorkpieceExecutableAll", GetWorkpieceExecutableAll); Nan::SetPrototypeMethod(tpl, "GetWorkpiecePlacement", GetWorkpiecePlacement); Nan::SetPrototypeMethod(tpl, "GetExecutableWorkpieceToBe", GetExecutableWorkpieceToBe); Nan::SetPrototypeMethod(tpl, "GetCurrentWorkpiece", GetCurrentWorkpiece); Nan::SetPrototypeMethod(tpl, "GetCurrentWorkplan", GetCurrentWorkplan); Nan::SetPrototypeMethod(tpl, "GetWorkplanSetup", GetWorkplanSetup); Nan::SetPrototypeMethod(tpl, "OpenProject", OpenProject); Nan::SetPrototypeMethod(tpl, "OpenSTEP", OpenSTEP); Nan::SetPrototypeMethod(tpl, "SaveAsModules", SaveAsModules); Nan::SetPrototypeMethod(tpl, "SaveAsP21", SaveAsP21); Nan::SetPrototypeMethod(tpl, "SetNameGet", SetNameGet); constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); Nan::Set(target, Nan::New("AptStepMaker").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked()); } NAN_METHOD(AptStepMaker::GetToolEID) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsString()) return; char * toolNum = 0; v8StringToChar(info[0], toolNum); int toolEID; if (!apt->_apt->get_tool_id(toolNum, toolEID)) //TODO: Handle error return; info.GetReturnValue().Set(toolEID); return; } NAN_METHOD(AptStepMaker::GetToolIdentifier) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsString()) return; char * toolNum = 0; v8StringToChar(info[0], toolNum); const char * toolID = 0; if (!apt->_apt->get_tool_identifier(toolNum, toolID)) // TODO: Handle error return; info.GetReturnValue().Set(CharTov8String((char *)toolNum)); return; } NAN_METHOD(AptStepMaker::GetToolNumber) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsInt32()) return; Nan::Maybe<int32_t> id = Nan::To<int32_t>(info[0]); const char * tlNum = 0; if (!apt->_apt->get_tool_number(id.FromJust(), tlNum)) //TODO: Handle Error return; info.GetReturnValue().Set(CharTov8String((char *)tlNum)); return; } NAN_METHOD(AptStepMaker::GetUUID) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsInt32()) return; Nan::Maybe<int32_t> eid = Nan::To<int32_t>(info[0]); const char * uuid; if (!apt->_apt->get_uuid(eid.FromJust(), uuid)) //TODO: Handle error return; info.GetReturnValue().Set(CharTov8String((char *)uuid)); return; } NAN_METHOD(AptStepMaker::GetWorkpieceExecutableAll) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsInt32()) return; Nan::Maybe<int32_t> wpid = Nan::To<int32_t>(info[0]); int count = 0; if (!apt->_apt->workpiece_executable_count(wpid.FromJust(), count)) //Throw Exception return; v8::Local<v8::Array> array = Nan::New<v8::Array>(); for (int i = 0; i < count; i++) { int exe_id = 0; if (!apt->_apt->workpiece_executable_next(wpid.FromJust(), i, exe_id)) //Throw Exception return; else array->Set(i, Nan::New(exe_id)); } info.GetReturnValue().Set(array); return; } NAN_METHOD(AptStepMaker::GetWorkpiecePlacement) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsInt32()) return; Nan::Maybe<int32_t> wpid = Nan::To<int32_t>(info[0]); double x; double y; double z; double i; double j; double k; double a; double b; double c; if (!apt->_apt->get_workpiece_placement(wpid.FromJust(), x, y, z, i, j, k, a, b, c)) //TODO: Handle error return; v8::Local<v8::Array> array = Nan::New<v8::Array>(); array->Set(0, Nan::New(x)); array->Set(1, Nan::New(y)); array->Set(2, Nan::New(z)); array->Set(3, Nan::New(i)); array->Set(4, Nan::New(j)); array->Set(5, Nan::New(k)); array->Set(6, Nan::New(a)); array->Set(7, Nan::New(b)); array->Set(8, Nan::New(c)); info.GetReturnValue().Set(array); return; } NAN_METHOD(AptStepMaker::GetExecutableWorkpieceToBe) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsInt32()) return; Nan::Maybe<int32_t> wsid = Nan::To<int32_t>(info[0]); int wpid; if (!apt->_apt->executable_removal_workpiece(wsid.FromJust(), wpid)) //TODO: Handle error return; info.GetReturnValue().Set(wpid); return; } NAN_METHOD(AptStepMaker::GetCurrentWorkpiece) { AptStepMaker* apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); int wsid; int dummy; if (!apt->_apt->more_current_ids(wsid, dummy, dummy, dummy, dummy)) //TODO: Handle error return; info.GetReturnValue().Set(wsid); return; } NAN_METHOD(AptStepMaker::GetCurrentWorkplan) { AptStepMaker* apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); int wpid; int dummy; if (!apt->_apt->current_ids(dummy, wpid, dummy, dummy, dummy)) //TODO: Handle error return; info.GetReturnValue().Set(wpid); return; } NAN_METHOD(AptStepMaker::GetWorkplanSetup) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsInt32()) return; Nan::Maybe<int32_t> wpid = Nan::To<int32_t>(info[0]); double x; double y; double z; double i; double j; double k; double a; double b; double c; if (!apt->_apt->workplan_setup_get(wpid.FromJust(), x, y, z, i, j, k, a, b, c)) //TODO: Handle error return; v8::Local<v8::Array> array = Nan::New<v8::Array>(); array->Set(0, Nan::New(x)); array->Set(1, Nan::New(y)); array->Set(2, Nan::New(z)); array->Set(3, Nan::New(i)); array->Set(4, Nan::New(j)); array->Set(5, Nan::New(k)); array->Set(6, Nan::New(a)); array->Set(7, Nan::New(b)); array->Set(8, Nan::New(c)); info.GetReturnValue().Set(array); return; } NAN_METHOD(AptStepMaker::OpenProject) { AptStepMaker* apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsString()) return; char * fname = 0; v8StringToChar(info[0], fname); if (!apt->_apt->read_238_file(fname)) //TODO: Handle Error. return; return; //Success finding, return. } NAN_METHOD(AptStepMaker::OpenSTEP) { AptStepMaker* apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsString()) return; char * fname = 0; v8StringToChar(info[0], fname); if (!apt->_apt->read_203_file(fname)) //TODO: Handle Error. return; return; //Success finding, return. } NAN_METHOD(AptStepMaker::SaveAsModules) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info[0]->IsUndefined()) return; if (!info[0]->IsString()) return; char* file_name_utf8; v8StringToChar(info[0], file_name_utf8); if (!apt->_apt->save_file(file_name_utf8, true)) //Throw Exception return; } NAN_METHOD(AptStepMaker::SaveAsP21) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info[0]->IsUndefined()) return; if (!info[0]->IsString()) return; char* file_name_utf8; v8StringToChar(info[0], file_name_utf8); if (!apt->_apt->save_file(file_name_utf8, false)) //Throw Exception return; } NAN_METHOD(AptStepMaker::SetNameGet) { AptStepMaker * apt = Nan::ObjectWrap::Unwrap<AptStepMaker>(info.This()); if (apt == 0) //Throw Exception return; if (info.Length() != 1) //Function should get one argument. return; if (!info[0]->IsInt32()) return; Nan::Maybe<int32_t> eid = Nan::To<int32_t>(info[0]); const char * szName; if (!apt->_apt->get_name(eid.FromJust(), szName)) //TODO: Handle error return; info.GetReturnValue().Set(CharTov8String((char *)szName)); return; }<|endoftext|>
<commit_before>// // ofxInFocusSerial.cpp // greveGulv // // Created by Tobias Ebsen on 13/05/14. // // #include "ofxInFocusSerial.h" bool ofxInFocusSerial::setup(string portName) { bool result = ofSerial::setup(portName, 19200); // Disable hardware flow control struct termios options; tcgetattr(fd, &options); options.c_cflag &= ~CRTSCTS; tcsetattr(fd, TCSANOW, &options); return result; } vector<string> ofxInFocusSerial::getPortNames() { vector<string> names; vector<ofSerialDeviceInfo> list = ofSerial::getDeviceList(); vector<ofSerialDeviceInfo>::iterator it = list.begin(); for (; it!=list.end(); ++it) { names.push_back(it->getDeviceName()); } return names; } bool ofxInFocusSerial::isPowerOn() { commandRead("PWR"); return getResponseInt() == 1; } void ofxInFocusSerial::setPowerOn(bool on) { commandWrite("PWR", on ? 1 : 0); } int ofxInFocusSerial::getLampHoursNormal() { commandRead("LMO"); return getResponseInt(); } int ofxInFocusSerial::getLampHoursEco() { commandRead("LME"); return getResponseInt(); } bool ofxInFocusSerial::isLampEco() { commandRead("IPM"); return getResponseInt() == 1; } void ofxInFocusSerial::setLampEco(bool eco) { commandWrite("IPM", eco ? 1 : 0); } string ofxInFocusSerial::getFirmwareVersion() { commandRead("FVS"); return getResponseString(); } int ofxInFocusSerial::getSystemState() { commandRead("SYS"); return getResponseInt(); } void ofxInFocusSerial::write(string str) { ofSerial::writeBytes((unsigned char*)str.c_str(), str.length()); } string ofxInFocusSerial::read() { char str[64]; int n = ofSerial::readBytes((unsigned char*)str, sizeof(str)); if (n > 0) str[n] = 0; else str[0] = 0; return str; } void ofxInFocusSerial::commandWrite(string cmd, int value) { write("(" + cmd + ofToString(value) + ")"); ofSerial::drain(); } string ofxInFocusSerial::commandRead(string cmd) { write("(" + cmd + "?)"); ofSerial::drain(); unsigned long long before = ofGetElapsedTimeMillis(); response = read(); while (response.find(")") == -1 && ofGetElapsedTimeMillis() - before < 2000) { ofSleepMillis(1); response.append(read()); }; return response; } int ofxInFocusSerial::getResponseInt() { int b = response.find(","); int e = response.find(")"); if (b != -1 && e != -1) { string str = response.substr(b+1,e-b-1); return ofToInt(str); } return -1; } string ofxInFocusSerial::getResponseString() { int b = response.find("\""); int e = response.find_last_of('\"'); if (b != -1 && e != -1) return response.substr(b+1, e-b-1); else return ""; }<commit_msg>Fixed flow control again<commit_after>// // ofxInFocusSerial.cpp // greveGulv // // Created by Tobias Ebsen on 13/05/14. // // #include "ofxInFocusSerial.h" bool ofxInFocusSerial::setup(string portName) { bool result = ofSerial::setup(portName, 19200); // Disable hardware flow control struct termios options; tcgetattr(fd, &options); options.c_iflag &= ~(IXON | IXOFF); options.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN); options.c_cflag &= ~CRTSCTS; tcsetattr(fd, TCSANOW, &options); return result; } vector<string> ofxInFocusSerial::getPortNames() { vector<string> names; vector<ofSerialDeviceInfo> list = ofSerial::getDeviceList(); vector<ofSerialDeviceInfo>::iterator it = list.begin(); for (; it!=list.end(); ++it) { names.push_back(it->getDeviceName()); } return names; } bool ofxInFocusSerial::isPowerOn() { commandRead("PWR"); return getResponseInt() == 1; } void ofxInFocusSerial::setPowerOn(bool on) { commandWrite("PWR", on ? 1 : 0); } int ofxInFocusSerial::getLampHoursNormal() { commandRead("LMO"); return getResponseInt(); } int ofxInFocusSerial::getLampHoursEco() { commandRead("LME"); return getResponseInt(); } bool ofxInFocusSerial::isLampEco() { commandRead("IPM"); return getResponseInt() == 1; } void ofxInFocusSerial::setLampEco(bool eco) { commandWrite("IPM", eco ? 1 : 0); } string ofxInFocusSerial::getFirmwareVersion() { commandRead("FVS"); return getResponseString(); } int ofxInFocusSerial::getSystemState() { commandRead("SYS"); return getResponseInt(); } void ofxInFocusSerial::write(string str) { ofSerial::writeBytes((unsigned char*)str.c_str(), str.length()); } string ofxInFocusSerial::read() { char str[64]; int n = ofSerial::readBytes((unsigned char*)str, sizeof(str)); if (n > 0) str[n] = 0; else str[0] = 0; return str; } void ofxInFocusSerial::commandWrite(string cmd, int value) { write("(" + cmd + ofToString(value) + ")"); ofSerial::drain(); } string ofxInFocusSerial::commandRead(string cmd) { ofSerial::flush(); write("(" + cmd + "?)"); ofSerial::drain(); unsigned long long before = ofGetElapsedTimeMillis(); response = read(); while (response.find(")") == -1 && ofGetElapsedTimeMillis() - before < 2000) { ofSleepMillis(1); response.append(read()); }; return response; } int ofxInFocusSerial::getResponseInt() { int b = response.find(","); int e = response.find(")"); if (b != -1 && e != -1) { string str = response.substr(b+1,e-b-1); return ofToInt(str); } return -1; } string ofxInFocusSerial::getResponseString() { int b = response.find("\""); int e = response.find_last_of('\"'); if (b != -1 && e != -1) return response.substr(b+1, e-b-1); else return ""; } <|endoftext|>
<commit_before>#include <iostream> using namespace std; int main() { int x, y, z; cin >> x >> y >> z; if (x == y) { if (x == z) { cout << 3; } } else {if (y == z) { cout << 2; } else {cout << 0;} } return 0; }<commit_msg>Delete task25.cpp<commit_after><|endoftext|>
<commit_before><commit_msg>linux: fix build error on gcc-4.4 on Ubuntu<commit_after><|endoftext|>
<commit_before><commit_msg>Fix ninebox rendering.<commit_after><|endoftext|>
<commit_before><commit_msg>Fix a comment. This was brought up by Ojan in a review for my previous patch, but I forgot to fix it before checking in. Review URL: http://codereview.chromium.org/12877<commit_after><|endoftext|>
<commit_before>// Copyright 2020 Google LLC // // 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 <limits> #include <string> static void TestArithmetic() { int a = 1; int int_max = std::numeric_limits<int>::max(); int int_min = std::numeric_limits<int>::min(); unsigned int uint_max = std::numeric_limits<unsigned int>::max(); unsigned int uint_zero = 0; long long ll_max = std::numeric_limits<long long>::max(); long long ll_min = std::numeric_limits<long long>::min(); unsigned long long ull_max = std::numeric_limits<unsigned long long>::max(); unsigned long long ull_zero = 0; // BREAK(TestArithmetic) } static void TestBitwiseOperators() { uint32_t mask_ff = 0xFF; // BREAK(TestBitwiseOperators) } static void TestPointerArithmetic() { const char* p_char1 = "hello"; int offset = 5; int array[10]; array[0] = 0; array[offset] = offset; int* p_int0 = &array[0]; const int* cp_int0 = &array[0]; const int* cp_int5 = &array[offset]; typedef int* td_int_ptr_t; td_int_ptr_t td_int_ptr0 = &array[0]; void* p_void = (void*)p_char1; void** pp_void0 = &p_void; void** pp_void1 = pp_void0 + 1; // BREAK(TestPointerArithmetic) } static void TestLogicalOperators() { bool trueVar = true; bool falseVar = false; const char* p_ptr = "🦊"; const char* p_nullptr = nullptr; struct S { } s; // BREAK(TestLogicalOperators) } static void TestLocalVariables() { int a = 1; int b = 2; char c = -3; unsigned short s = 4; // BREAK(TestLocalVariables) } static void TestIndirection() { int val = 1; int* p = &val; // BREAK(TestIndirection) } // Referenced by TestInstanceVariables class C { public: int field_ = 1337; }; // Referenced by TestAddressOf int globalVar = 0xDEADBEEF; extern int externGlobalVar; class TestMethods { public: void TestInstanceVariables() { C c; c.field_ = -1; C& c_ref = c; C* c_ptr = &c; // BREAK(TestInstanceVariables) } void TestAddressOf(int param) { std::string s = "hello"; const char* s_str = s.c_str(); // BREAK(TestAddressOf) } private: int field_ = 1; }; static void TestSubscript() { const char* char_ptr = "lorem"; const char char_arr[] = "ipsum"; int int_arr[] = {1, 2, 3}; C c_arr[2]; c_arr[0].field_ = 0; c_arr[1].field_ = 1; C(&c_arr_ref)[2] = c_arr; int idx_1 = 1; const int& idx_1_ref = idx_1; typedef int td_int_t; typedef td_int_t td_td_int_t; typedef int* td_int_ptr_t; typedef int& td_int_ref_t; td_int_t td_int_idx_1 = 1; td_td_int_t td_td_int_idx_2 = 2; td_int_t td_int_arr[3] = {1, 2, 3}; td_int_ptr_t td_int_ptr = td_int_arr; td_int_ref_t td_int_idx_1_ref = td_int_idx_1; td_int_t(&td_int_arr_ref)[3] = td_int_arr; unsigned char uchar_idx = std::numeric_limits<unsigned char>::max(); uint8_t uint8_arr[256]; uint8_arr[255] = 0xAB; // BREAK(TestSubscript) } // Referenced by TestCStyleCast namespace ns { typedef int myint; class Foo {}; namespace inner { using mydouble = double; class Foo {}; } // namespace inner } // namespace ns static void TestCStyleCast() { int a = 1; int* ap = &a; void* vp = &a; int na = -1; float f = 1.1; typedef int myint; myint myint_ = 1; ns::myint ns_myint_ = 2; ns::Foo ns_foo_; ns::Foo* ns_foo_ptr_ = &ns_foo_; ns::inner::mydouble ns_inner_mydouble_ = 1.2; ns::inner::Foo ns_inner_foo_; ns::inner::Foo* ns_inner_foo_ptr_ = &ns_inner_foo_; // BREAK(TestCStyleCastBasicType) // BREAK(TestCStyleCastPointer) } // Referenced by TestQualifiedId. namespace ns { int i = 1; namespace ns { int i = 2; } // namespace ns } // namespace ns class Foo { public: static const int x = 42; static const int y; }; const int Foo::y = 42; static void TestQualifiedId() { // BREAK(TestQualifiedId) } // Referenced by TestTemplateTypes. template <typename T> struct T_1 { static const int cx; typedef double myint; T_1() {} T_1(T x) : x(x) {} T x; }; template <typename T> const int T_1<T>::cx = 42; template <> const int T_1<int>::cx = 24; template <typename T1, typename T2> struct T_2 { typedef float myint; T_2() {} T1 x; T2 y; }; namespace ns { template <typename T> struct T_1 { static const int cx; typedef int myint; T_1() {} T_1(T x) : x(x) {} T x; }; template <typename T> const int T_1<T>::cx = 46; template <> const int T_1<int>::cx = 64; } // namespace ns static void TestTemplateTypes() { int i; int* p = &i; { T_1<int> _; } { T_1<int*> _; } { T_1<int**> _; } { T_1<int&> _(i); } { T_1<int*&> _(p); } { T_1<double> _; } { T_2<int, char> _; } { T_2<char, int> _; } { T_2<T_1<int>, T_1<char>> _; } { T_2<T_1<T_1<int>>, T_1<char>> _; } { ns::T_1<int> _; } { ns::T_1<ns::T_1<int>> _; } { T_1<int>::myint _ = 0; } { T_1<int*>::myint _ = 0; } { T_1<int**>::myint _ = 0; } { T_1<int&>::myint _ = 0; } { T_1<int*&>::myint _ = 0; } { T_1<T_1<int>>::myint _ = 0; } { T_1<T_1<int*>>::myint _ = 0; } { T_1<T_1<int**>>::myint _ = 0; } { T_1<T_1<int&>>::myint _ = 0; } { T_1<T_1<int*&>>::myint _ = 0; } { T_2<int, char>::myint _ = 0; } { T_2<int*, char&>::myint _ = 0; } { T_2<int&, char*>::myint _ = 0; } { T_2<T_1<T_1<int>>, T_1<char>>::myint _ = 0; } { ns::T_1<int>::myint _ = 0; } { ns::T_1<int*>::myint _ = 0; } { ns::T_1<int**>::myint _ = 0; } { ns::T_1<int&>::myint _ = 0; } { ns::T_1<int*&>::myint _ = 0; } { ns::T_1<T_1<int>>::myint _ = 0; } { ns::T_1<T_1<int*>>::myint _ = 0; } { ns::T_1<T_1<int**>>::myint _ = 0; } { ns::T_1<T_1<int&>>::myint _ = 0; } { ns::T_1<T_1<int*&>>::myint _ = 0; } { ns::T_1<ns::T_1<int>>::myint _ = 0; } { ns::T_1<ns::T_1<int*>>::myint _ = 0; } { ns::T_1<ns::T_1<int**>>::myint _ = 0; } { ns::T_1<ns::T_1<int&>>::myint _ = 0; } { ns::T_1<ns::T_1<int*&>>::myint _ = 0; } (void)T_1<double>::cx; (void)ns::T_1<double>::cx; (void)ns::T_1<ns::T_1<int>>::cx; // BREAK(TestTemplateTypes) } namespace test_binary { void main() { TestMethods tm; TestArithmetic(); TestBitwiseOperators(); TestPointerArithmetic(); TestLogicalOperators(); TestLocalVariables(); tm.TestInstanceVariables(); TestIndirection(); tm.TestAddressOf(42); TestSubscript(); TestCStyleCast(); TestQualifiedId(); TestTemplateTypes(); // break here } } // namespace test_binary int main() { test_binary::main(); } <commit_msg>Add missing variables in test_binary<commit_after>// Copyright 2020 Google LLC // // 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 <limits> #include <string> static void TestArithmetic() { int a = 1; int int_max = std::numeric_limits<int>::max(); int int_min = std::numeric_limits<int>::min(); unsigned int uint_max = std::numeric_limits<unsigned int>::max(); unsigned int uint_zero = 0; long long ll_max = std::numeric_limits<long long>::max(); long long ll_min = std::numeric_limits<long long>::min(); unsigned long long ull_max = std::numeric_limits<unsigned long long>::max(); unsigned long long ull_zero = 0; // BREAK(TestArithmetic) } static void TestBitwiseOperators() { uint32_t mask_ff = 0xFF; unsigned long long ull_max = std::numeric_limits<unsigned long long>::max(); unsigned long long ull_zero = 0; struct S { } s; const char* p = nullptr; // BREAK(TestBitwiseOperators) } static void TestPointerArithmetic() { const char* p_char1 = "hello"; int offset = 5; int array[10]; array[0] = 0; array[offset] = offset; int* p_int0 = &array[0]; const int* cp_int0 = &array[0]; const int* cp_int5 = &array[offset]; typedef int* td_int_ptr_t; td_int_ptr_t td_int_ptr0 = &array[0]; void* p_void = (void*)p_char1; void** pp_void0 = &p_void; void** pp_void1 = pp_void0 + 1; // BREAK(TestPointerArithmetic) } static void TestLogicalOperators() { bool trueVar = true; bool falseVar = false; const char* p_ptr = "🦊"; const char* p_nullptr = nullptr; struct S { } s; // BREAK(TestLogicalOperators) } static void TestLocalVariables() { int a = 1; int b = 2; char c = -3; unsigned short s = 4; // BREAK(TestLocalVariables) } static void TestIndirection() { int val = 1; int* p = &val; // BREAK(TestIndirection) } // Referenced by TestInstanceVariables class C { public: int field_ = 1337; }; // Referenced by TestAddressOf int globalVar = 0xDEADBEEF; extern int externGlobalVar; class TestMethods { public: void TestInstanceVariables() { C c; c.field_ = -1; C& c_ref = c; C* c_ptr = &c; // BREAK(TestInstanceVariables) } void TestAddressOf(int param) { std::string s = "hello"; const char* s_str = s.c_str(); // BREAK(TestAddressOf) } private: int field_ = 1; }; static void TestSubscript() { const char* char_ptr = "lorem"; const char char_arr[] = "ipsum"; int int_arr[] = {1, 2, 3}; C c_arr[2]; c_arr[0].field_ = 0; c_arr[1].field_ = 1; C(&c_arr_ref)[2] = c_arr; int idx_1 = 1; const int& idx_1_ref = idx_1; typedef int td_int_t; typedef td_int_t td_td_int_t; typedef int* td_int_ptr_t; typedef int& td_int_ref_t; td_int_t td_int_idx_1 = 1; td_td_int_t td_td_int_idx_2 = 2; td_int_t td_int_arr[3] = {1, 2, 3}; td_int_ptr_t td_int_ptr = td_int_arr; td_int_ref_t td_int_idx_1_ref = td_int_idx_1; td_int_t(&td_int_arr_ref)[3] = td_int_arr; unsigned char uchar_idx = std::numeric_limits<unsigned char>::max(); uint8_t uint8_arr[256]; uint8_arr[255] = 0xAB; // BREAK(TestSubscript) } // Referenced by TestCStyleCast namespace ns { typedef int myint; class Foo {}; namespace inner { using mydouble = double; class Foo {}; } // namespace inner } // namespace ns static void TestCStyleCast() { int a = 1; int* ap = &a; void* vp = &a; int na = -1; float f = 1.1; typedef int myint; myint myint_ = 1; ns::myint ns_myint_ = 2; ns::Foo ns_foo_; ns::Foo* ns_foo_ptr_ = &ns_foo_; ns::inner::mydouble ns_inner_mydouble_ = 1.2; ns::inner::Foo ns_inner_foo_; ns::inner::Foo* ns_inner_foo_ptr_ = &ns_inner_foo_; // BREAK(TestCStyleCastBasicType) // BREAK(TestCStyleCastPointer) } // Referenced by TestQualifiedId. namespace ns { int i = 1; namespace ns { int i = 2; } // namespace ns } // namespace ns class Foo { public: static const int x = 42; static const int y; }; const int Foo::y = 42; static void TestQualifiedId() { // BREAK(TestQualifiedId) } // Referenced by TestTemplateTypes. template <typename T> struct T_1 { static const int cx; typedef double myint; T_1() {} T_1(T x) : x(x) {} T x; }; template <typename T> const int T_1<T>::cx = 42; template <> const int T_1<int>::cx = 24; template <typename T1, typename T2> struct T_2 { typedef float myint; T_2() {} T1 x; T2 y; }; namespace ns { template <typename T> struct T_1 { static const int cx; typedef int myint; T_1() {} T_1(T x) : x(x) {} T x; }; template <typename T> const int T_1<T>::cx = 46; template <> const int T_1<int>::cx = 64; } // namespace ns static void TestTemplateTypes() { int i; int* p = &i; { T_1<int> _; } { T_1<int*> _; } { T_1<int**> _; } { T_1<int&> _(i); } { T_1<int*&> _(p); } { T_1<double> _; } { T_2<int, char> _; } { T_2<char, int> _; } { T_2<T_1<int>, T_1<char>> _; } { T_2<T_1<T_1<int>>, T_1<char>> _; } { ns::T_1<int> _; } { ns::T_1<ns::T_1<int>> _; } { T_1<int>::myint _ = 0; } { T_1<int*>::myint _ = 0; } { T_1<int**>::myint _ = 0; } { T_1<int&>::myint _ = 0; } { T_1<int*&>::myint _ = 0; } { T_1<T_1<int>>::myint _ = 0; } { T_1<T_1<int*>>::myint _ = 0; } { T_1<T_1<int**>>::myint _ = 0; } { T_1<T_1<int&>>::myint _ = 0; } { T_1<T_1<int*&>>::myint _ = 0; } { T_2<int, char>::myint _ = 0; } { T_2<int*, char&>::myint _ = 0; } { T_2<int&, char*>::myint _ = 0; } { T_2<T_1<T_1<int>>, T_1<char>>::myint _ = 0; } { ns::T_1<int>::myint _ = 0; } { ns::T_1<int*>::myint _ = 0; } { ns::T_1<int**>::myint _ = 0; } { ns::T_1<int&>::myint _ = 0; } { ns::T_1<int*&>::myint _ = 0; } { ns::T_1<T_1<int>>::myint _ = 0; } { ns::T_1<T_1<int*>>::myint _ = 0; } { ns::T_1<T_1<int**>>::myint _ = 0; } { ns::T_1<T_1<int&>>::myint _ = 0; } { ns::T_1<T_1<int*&>>::myint _ = 0; } { ns::T_1<ns::T_1<int>>::myint _ = 0; } { ns::T_1<ns::T_1<int*>>::myint _ = 0; } { ns::T_1<ns::T_1<int**>>::myint _ = 0; } { ns::T_1<ns::T_1<int&>>::myint _ = 0; } { ns::T_1<ns::T_1<int*&>>::myint _ = 0; } (void)T_1<double>::cx; (void)ns::T_1<double>::cx; (void)ns::T_1<ns::T_1<int>>::cx; // BREAK(TestTemplateTypes) } namespace test_binary { void main() { TestMethods tm; TestArithmetic(); TestBitwiseOperators(); TestPointerArithmetic(); TestLogicalOperators(); TestLocalVariables(); tm.TestInstanceVariables(); TestIndirection(); tm.TestAddressOf(42); TestSubscript(); TestCStyleCast(); TestQualifiedId(); TestTemplateTypes(); // break here } } // namespace test_binary int main() { test_binary::main(); } <|endoftext|>
<commit_before><commit_msg>Enable WorkerTest.WorkerContextMultiPort on Linux. BUG=22898 TEST=none<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/thread.h" #include "chrome/browser/worker_host/worker_service.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_layout_test.h" static const char kTestCompleteCookie[] = "status"; static const char kTestCompleteSuccess[] = "OK"; class WorkerTest : public UILayoutTest { protected: virtual ~WorkerTest() { } void RunTest(const std::wstring& test_case) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); GURL url = GetTestUrl(L"workers", test_case); ASSERT_TRUE(tab->NavigateToURL(url)); std::string value = WaitUntilCookieNonEmpty(tab.get(), url, kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs); ASSERT_STREQ(kTestCompleteSuccess, value.c_str()); } }; TEST_F(WorkerTest, SingleWorker) { RunTest(L"single_worker.html"); } TEST_F(WorkerTest, MultipleWorkers) { RunTest(L"multi_worker.html"); } // WorkerFastLayoutTests works on the linux try servers, but fails on the // build bots and fails on mac valgrind. #if !defined(OS_WIN) #define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests #endif // WorkerFastLayoutTests failed on all platforms since r27553. // http://crbug.com/23391 TEST_F(WorkerTest, DISABLED_WorkerFastLayoutTests) { static const char* kLayoutTestFiles[] = { "stress-js-execution.html", #if defined(OS_WIN) // Workers don't properly initialize the V8 stack guard. // (http://code.google.com/p/chromium/issues/detail?id=21653). "use-machine-stack.html", #endif "worker-call.html", // Disabled because cloning ports are too slow in Chromium to meet the // thresholds in this test. // http://code.google.com/p/chromium/issues/detail?id=22780 // "worker-cloneport.html", "worker-close.html", "worker-constructor.html", "worker-context-gc.html", "worker-context-multi-port.html", "worker-event-listener.html", "worker-gc.html", // worker-lifecycle.html relies on layoutTestController.workerThreadCount // which is not currently implemented. // "worker-lifecycle.html", "worker-location.html", "worker-messageport.html", // Disabled after r27089 (WebKit merge), http://crbug.com/22947 // "worker-messageport-gc.html", "worker-multi-port.html", "worker-navigator.html", "worker-replace-global-constructor.html", "worker-replace-self.html", "worker-script-error.html", "worker-terminate.html", "worker-timeout.html" }; FilePath fast_test_dir; fast_test_dir = fast_test_dir.AppendASCII("LayoutTests"); fast_test_dir = fast_test_dir.AppendASCII("fast"); FilePath worker_test_dir; worker_test_dir = worker_test_dir.AppendASCII("workers"); InitializeForLayoutTest(fast_test_dir, worker_test_dir, false); // Worker tests also rely on common files in js/resources. FilePath js_dir = fast_test_dir.AppendASCII("js"); FilePath resource_dir; resource_dir = resource_dir.AppendASCII("resources"); AddResourceForLayoutTest(js_dir, resource_dir); for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i) RunLayoutTest(kLayoutTestFiles[i], false); } TEST_F(WorkerTest, WorkerHttpLayoutTests) { static const char* kLayoutTestFiles[] = { // flakey? BUG 16934 "text-encoding.html", #if defined(OS_WIN) // Fails on the mac (and linux?): // http://code.google.com/p/chromium/issues/detail?id=22599 "worker-importScripts.html", #endif "worker-redirect.html", }; FilePath http_test_dir; http_test_dir = http_test_dir.AppendASCII("LayoutTests"); http_test_dir = http_test_dir.AppendASCII("http"); http_test_dir = http_test_dir.AppendASCII("tests"); FilePath worker_test_dir; worker_test_dir = worker_test_dir.AppendASCII("workers"); InitializeForLayoutTest(http_test_dir, worker_test_dir, true); StartHttpServer(new_http_root_dir_); for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i) RunLayoutTest(kLayoutTestFiles[i], true); StopHttpServer(); } TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) { static const char* kLayoutTestFiles[] = { "abort-exception-assert.html", #if defined(OS_WIN) // Fails on the mac (and linux?): // http://code.google.com/p/chromium/issues/detail?id=22599 "close.html", #endif //"methods-async.html", //"methods.html", "xmlhttprequest-file-not-found.html" }; FilePath http_test_dir; http_test_dir = http_test_dir.AppendASCII("LayoutTests"); http_test_dir = http_test_dir.AppendASCII("http"); http_test_dir = http_test_dir.AppendASCII("tests"); FilePath worker_test_dir; worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest"); worker_test_dir = worker_test_dir.AppendASCII("workers"); InitializeForLayoutTest(http_test_dir, worker_test_dir, true); StartHttpServer(new_http_root_dir_); for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i) RunLayoutTest(kLayoutTestFiles[i], true); StopHttpServer(); } TEST_F(WorkerTest, MessagePorts) { static const char* kLayoutTestFiles[] = { "message-channel-gc.html", "message-channel-gc-2.html", "message-channel-gc-3.html", "message-channel-gc-4.html", "message-port.html", "message-port-clone.html", // http://code.google.com/p/chromium/issues/detail?id=23709 // "message-port-constructor-for-deleted-document.html", "message-port-deleted-document.html", "message-port-deleted-frame.html", // http://crbug.com/23597 (caused by http://trac.webkit.org/changeset/48978) // "message-port-inactive-document.html", "message-port-multi.html", "message-port-no-wrapper.html", // Only works with run-webkit-tests --leaks. //"message-channel-listener-circular-ownership.html", }; FilePath fast_test_dir; fast_test_dir = fast_test_dir.AppendASCII("LayoutTests"); fast_test_dir = fast_test_dir.AppendASCII("fast"); FilePath worker_test_dir; worker_test_dir = worker_test_dir.AppendASCII("events"); InitializeForLayoutTest(fast_test_dir, worker_test_dir, false); // MessagePort tests also rely on common files in js/resources. FilePath js_dir = fast_test_dir.AppendASCII("js"); FilePath resource_dir; resource_dir = resource_dir.AppendASCII("resources"); AddResourceForLayoutTest(js_dir, resource_dir); for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i) RunLayoutTest(kLayoutTestFiles[i], false); } // Disable LimitPerPage on Linux. Seems to work on Mac though: // http://code.google.com/p/chromium/issues/detail?id=22608 #if !defined(OS_LINUX) TEST_F(WorkerTest, LimitPerPage) { int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate; GURL url = GetTestUrl(L"workers", L"many_workers.html"); url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1)); scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(url)); EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1), UITest::GetBrowserProcessCount()); } #endif // http://code.google.com/p/chromium/issues/detail?id=22608 TEST_F(WorkerTest, DISABLED_LimitTotal) { int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate; int total_workers = WorkerService::kMaxWorkersWhenSeparate; int tab_count = (total_workers / max_workers_per_tab) + 1; GURL url = GetTestUrl(L"workers", L"many_workers.html"); url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab)); scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(url)); scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); for (int i = 1; i < tab_count; ++i) window->AppendTab(url); // Check that we didn't create more than the max number of workers. EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count), UITest::GetBrowserProcessCount()); // Now close the first tab and check that the queued workers were started. ASSERT_TRUE(tab->Close(true)); // Give the tab process time to shut down. PlatformThread::Sleep(sleep_timeout_ms()); EXPECT_EQ(total_workers + 1 + (UITest::in_process_renderer() ? 0 : tab_count), UITest::GetBrowserProcessCount()); } <commit_msg>Enable WorkerTest.LimitTotal<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/worker_host/worker_service.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_layout_test.h" static const char kTestCompleteCookie[] = "status"; static const char kTestCompleteSuccess[] = "OK"; class WorkerTest : public UILayoutTest { protected: virtual ~WorkerTest() { } void RunTest(const std::wstring& test_case) { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); GURL url = GetTestUrl(L"workers", test_case); ASSERT_TRUE(tab->NavigateToURL(url)); std::string value = WaitUntilCookieNonEmpty(tab.get(), url, kTestCompleteCookie, kTestIntervalMs, kTestWaitTimeoutMs); ASSERT_STREQ(kTestCompleteSuccess, value.c_str()); } }; TEST_F(WorkerTest, SingleWorker) { RunTest(L"single_worker.html"); } TEST_F(WorkerTest, MultipleWorkers) { RunTest(L"multi_worker.html"); } // WorkerFastLayoutTests works on the linux try servers, but fails on the // build bots and fails on mac valgrind. #if !defined(OS_WIN) #define WorkerFastLayoutTests DISABLED_WorkerFastLayoutTests #endif // WorkerFastLayoutTests failed on all platforms since r27553. // http://crbug.com/23391 TEST_F(WorkerTest, DISABLED_WorkerFastLayoutTests) { static const char* kLayoutTestFiles[] = { "stress-js-execution.html", #if defined(OS_WIN) // Workers don't properly initialize the V8 stack guard. // (http://code.google.com/p/chromium/issues/detail?id=21653). "use-machine-stack.html", #endif "worker-call.html", // Disabled because cloning ports are too slow in Chromium to meet the // thresholds in this test. // http://code.google.com/p/chromium/issues/detail?id=22780 // "worker-cloneport.html", "worker-close.html", "worker-constructor.html", "worker-context-gc.html", "worker-context-multi-port.html", "worker-event-listener.html", "worker-gc.html", // worker-lifecycle.html relies on layoutTestController.workerThreadCount // which is not currently implemented. // "worker-lifecycle.html", "worker-location.html", "worker-messageport.html", // Disabled after r27089 (WebKit merge), http://crbug.com/22947 // "worker-messageport-gc.html", "worker-multi-port.html", "worker-navigator.html", "worker-replace-global-constructor.html", "worker-replace-self.html", "worker-script-error.html", "worker-terminate.html", "worker-timeout.html" }; FilePath fast_test_dir; fast_test_dir = fast_test_dir.AppendASCII("LayoutTests"); fast_test_dir = fast_test_dir.AppendASCII("fast"); FilePath worker_test_dir; worker_test_dir = worker_test_dir.AppendASCII("workers"); InitializeForLayoutTest(fast_test_dir, worker_test_dir, false); // Worker tests also rely on common files in js/resources. FilePath js_dir = fast_test_dir.AppendASCII("js"); FilePath resource_dir; resource_dir = resource_dir.AppendASCII("resources"); AddResourceForLayoutTest(js_dir, resource_dir); for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i) RunLayoutTest(kLayoutTestFiles[i], false); } TEST_F(WorkerTest, WorkerHttpLayoutTests) { static const char* kLayoutTestFiles[] = { // flakey? BUG 16934 "text-encoding.html", #if defined(OS_WIN) // Fails on the mac (and linux?): // http://code.google.com/p/chromium/issues/detail?id=22599 "worker-importScripts.html", #endif "worker-redirect.html", }; FilePath http_test_dir; http_test_dir = http_test_dir.AppendASCII("LayoutTests"); http_test_dir = http_test_dir.AppendASCII("http"); http_test_dir = http_test_dir.AppendASCII("tests"); FilePath worker_test_dir; worker_test_dir = worker_test_dir.AppendASCII("workers"); InitializeForLayoutTest(http_test_dir, worker_test_dir, true); StartHttpServer(new_http_root_dir_); for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i) RunLayoutTest(kLayoutTestFiles[i], true); StopHttpServer(); } TEST_F(WorkerTest, WorkerXhrHttpLayoutTests) { static const char* kLayoutTestFiles[] = { "abort-exception-assert.html", #if defined(OS_WIN) // Fails on the mac (and linux?): // http://code.google.com/p/chromium/issues/detail?id=22599 "close.html", #endif //"methods-async.html", //"methods.html", "xmlhttprequest-file-not-found.html" }; FilePath http_test_dir; http_test_dir = http_test_dir.AppendASCII("LayoutTests"); http_test_dir = http_test_dir.AppendASCII("http"); http_test_dir = http_test_dir.AppendASCII("tests"); FilePath worker_test_dir; worker_test_dir = worker_test_dir.AppendASCII("xmlhttprequest"); worker_test_dir = worker_test_dir.AppendASCII("workers"); InitializeForLayoutTest(http_test_dir, worker_test_dir, true); StartHttpServer(new_http_root_dir_); for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i) RunLayoutTest(kLayoutTestFiles[i], true); StopHttpServer(); } TEST_F(WorkerTest, MessagePorts) { static const char* kLayoutTestFiles[] = { "message-channel-gc.html", "message-channel-gc-2.html", "message-channel-gc-3.html", "message-channel-gc-4.html", "message-port.html", "message-port-clone.html", // http://code.google.com/p/chromium/issues/detail?id=23709 // "message-port-constructor-for-deleted-document.html", "message-port-deleted-document.html", "message-port-deleted-frame.html", // http://crbug.com/23597 (caused by http://trac.webkit.org/changeset/48978) // "message-port-inactive-document.html", "message-port-multi.html", "message-port-no-wrapper.html", // Only works with run-webkit-tests --leaks. //"message-channel-listener-circular-ownership.html", }; FilePath fast_test_dir; fast_test_dir = fast_test_dir.AppendASCII("LayoutTests"); fast_test_dir = fast_test_dir.AppendASCII("fast"); FilePath worker_test_dir; worker_test_dir = worker_test_dir.AppendASCII("events"); InitializeForLayoutTest(fast_test_dir, worker_test_dir, false); // MessagePort tests also rely on common files in js/resources. FilePath js_dir = fast_test_dir.AppendASCII("js"); FilePath resource_dir; resource_dir = resource_dir.AppendASCII("resources"); AddResourceForLayoutTest(js_dir, resource_dir); for (size_t i = 0; i < arraysize(kLayoutTestFiles); ++i) RunLayoutTest(kLayoutTestFiles[i], false); } // Disable LimitPerPage on Linux. Seems to work on Mac though: // http://code.google.com/p/chromium/issues/detail?id=22608 #if !defined(OS_LINUX) TEST_F(WorkerTest, LimitPerPage) { int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate; GURL url = GetTestUrl(L"workers", L"many_workers.html"); url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab + 1)); scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(url)); EXPECT_EQ(max_workers_per_tab + 1 + (UITest::in_process_renderer() ? 0 : 1), UITest::GetBrowserProcessCount()); } #endif TEST_F(WorkerTest, LimitTotal) { int max_workers_per_tab = WorkerService::kMaxWorkersPerTabWhenSeparate; int total_workers = WorkerService::kMaxWorkersWhenSeparate; int tab_count = (total_workers / max_workers_per_tab) + 1; GURL url = GetTestUrl(L"workers", L"many_workers.html"); url = GURL(url.spec() + StringPrintf("?count=%d", max_workers_per_tab)); scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); ASSERT_TRUE(tab->NavigateToURL(url)); scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); for (int i = 1; i < tab_count; ++i) window->AppendTab(url); // The 1 is for the browser process. int number_of_processes = 1 + (UITest::in_process_renderer() ? 0 : tab_count); #if defined(OS_LINUX) // On Linux, we also have a zygote process and a sandbox host process. number_of_processes += 2; #endif // Check that we didn't create more than the max number of workers. EXPECT_EQ(total_workers + number_of_processes, UITest::GetBrowserProcessCount()); // Now close a page and check that the queued workers were started. tab->NavigateToURL(GetTestUrl(L"google", L"google.html")); EXPECT_EQ(total_workers + number_of_processes, UITest::GetBrowserProcessCount()); } <|endoftext|>
<commit_before><commit_msg>Fix wrong macro OS_MAC -> OS_MACOSX<commit_after><|endoftext|>
<commit_before>/* lua_buffers.cc - Implementation of our buffer-related lua primitives. * * ----------------------------------------------------------------------- * * Copyright (C) 2016 Steve Kemp https://steve.kemp.fi/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <clocale> #include <cstdlib> #include <string.h> #include <malloc.h> #include "editor.h" #include "lua_primitives.h" /* * Get/Set current buffer. */ int buffer_lua(lua_State *L) { Editor *e = Editor::instance(); /* * If called with a number, then select the given buffer. */ if (lua_isnumber(L, -1)) { int off = lua_tonumber(L, -1); e->set_current_buffer(off); } /* * If called with a string then select the buffer * by name, and return the offset. */ if (lua_isstring(L, -1)) { const char *name = lua_tostring(L, -1); int off = e->buffer_by_name(name); if (off != -1) e->set_current_buffer(off); lua_pushnumber(L, off); return 1; } /* * Return the number of the current buffer. */ int cur = e->get_current_buffer(); lua_pushnumber(L, cur); return 1; } /* * Get/Set the name of the buffer. */ int buffer_name_lua(lua_State *L) { Editor *e = Editor::instance(); Buffer *buffer = e->current_buffer(); const char *name = lua_tostring(L, -1); if (name) { buffer->set_name(name); } lua_pushstring(L, buffer->get_name()); return 1; } /* * Count the buffers. */ int buffers_lua(lua_State *L) { Editor *e = Editor::instance(); std::vector<Buffer *>buffers = e->get_buffers(); lua_createtable(L, buffers.size(), 0); for (int i = 0; i < (int)buffers.size(); i++) { Buffer *b = buffers.at(i); lua_pushstring(L, b->get_name()); lua_rawseti(L, -2, i + 1); } return 1; } /* * Select a buffer, interactively. */ int choose_buffer_lua(lua_State *L) { (void)L; Editor *e = Editor::instance(); int selected = e->get_current_buffer(); int original = e->get_current_buffer(); int max = e->count_buffers(); /* * Hide the cursor */ curs_set(0); ::clear(); while (true) { for (int i = 0; i < max ; i++) { if (selected == i) attron(A_STANDOUT); e->set_current_buffer(i); Buffer *b = e->current_buffer(); std::string tmp; tmp = std::to_string(i + 1); tmp += " "; tmp += b->get_name(); tmp += " "; if (b->dirty()) tmp += " <modified>"; while ((int)tmp.size() < e->width()) tmp += " "; mvwaddstr(stdscr, i, 0, tmp.c_str()); if (selected == i) attroff(A_STANDOUT); } /* * poll for input. */ unsigned int ch; int res = get_wch(&ch); if (res == ERR) continue; if (ch == '\n') { curs_set(1); e->set_current_buffer(selected); return 0; } if (ch == 27) { curs_set(1); e->set_current_buffer(original); return 0; } if (ch == KEY_UP) { selected -= 1; if (selected < 0) selected = max - 1; } if (ch == KEY_DOWN) { selected += 1; if (selected >= max) selected = 0; } } return 0; } /* * Create a new buffer. */ int create_buffer_lua(lua_State *L) { /* * The name of the buffer. */ const char *name = lua_tostring(L, -1); Editor *e = Editor::instance(); e->new_buffer(name); return 0; } /* * Kill the current buffer. */ int kill_buffer_lua(lua_State *L) { (void)L; Editor *e = Editor::instance(); e->kill_current_buffer(); return 0; } <commit_msg>fixed comment<commit_after>/* lua_buffers.cc - Implementation of our buffer-related lua primitives. * * ----------------------------------------------------------------------- * * Copyright (C) 2016 Steve Kemp https://steve.kemp.fi/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <clocale> #include <cstdlib> #include <string.h> #include <malloc.h> #include "editor.h" #include "lua_primitives.h" /* * Get/Set current buffer. */ int buffer_lua(lua_State *L) { Editor *e = Editor::instance(); /* * If called with a number, then select the given buffer. */ if (lua_isnumber(L, -1)) { int off = lua_tonumber(L, -1); e->set_current_buffer(off); } /* * If called with a string then select the buffer * by name, and return the offset. */ if (lua_isstring(L, -1)) { const char *name = lua_tostring(L, -1); int off = e->buffer_by_name(name); if (off != -1) e->set_current_buffer(off); lua_pushnumber(L, off); return 1; } /* * Return the number of the current buffer. */ int cur = e->get_current_buffer(); lua_pushnumber(L, cur); return 1; } /* * Get/Set the name of the buffer. */ int buffer_name_lua(lua_State *L) { Editor *e = Editor::instance(); Buffer *buffer = e->current_buffer(); const char *name = lua_tostring(L, -1); if (name) { buffer->set_name(name); } lua_pushstring(L, buffer->get_name()); return 1; } /* * Return a table of all known buffers. */ int buffers_lua(lua_State *L) { Editor *e = Editor::instance(); std::vector<Buffer *>buffers = e->get_buffers(); lua_createtable(L, buffers.size(), 0); for (int i = 0; i < (int)buffers.size(); i++) { Buffer *b = buffers.at(i); lua_pushstring(L, b->get_name()); lua_rawseti(L, -2, i + 1); } return 1; } /* * Select a buffer, interactively. */ int choose_buffer_lua(lua_State *L) { (void)L; Editor *e = Editor::instance(); int selected = e->get_current_buffer(); int original = e->get_current_buffer(); int max = e->count_buffers(); /* * Hide the cursor */ curs_set(0); ::clear(); while (true) { for (int i = 0; i < max ; i++) { if (selected == i) attron(A_STANDOUT); e->set_current_buffer(i); Buffer *b = e->current_buffer(); std::string tmp; tmp = std::to_string(i + 1); tmp += " "; tmp += b->get_name(); tmp += " "; if (b->dirty()) tmp += " <modified>"; while ((int)tmp.size() < e->width()) tmp += " "; mvwaddstr(stdscr, i, 0, tmp.c_str()); if (selected == i) attroff(A_STANDOUT); } /* * poll for input. */ unsigned int ch; int res = get_wch(&ch); if (res == ERR) continue; if (ch == '\n') { curs_set(1); e->set_current_buffer(selected); return 0; } if (ch == 27) { curs_set(1); e->set_current_buffer(original); return 0; } if (ch == KEY_UP) { selected -= 1; if (selected < 0) selected = max - 1; } if (ch == KEY_DOWN) { selected += 1; if (selected >= max) selected = 0; } } return 0; } /* * Create a new buffer. */ int create_buffer_lua(lua_State *L) { /* * The name of the buffer. */ const char *name = lua_tostring(L, -1); Editor *e = Editor::instance(); e->new_buffer(name); return 0; } /* * Kill the current buffer. */ int kill_buffer_lua(lua_State *L) { (void)L; Editor *e = Editor::instance(); e->kill_current_buffer(); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> #include <sstream> #include <getopt.h> #include <cstring> #include <less/less/LessTokenizer.h> #include <less/less/LessParser.h> #include <less/css/CssWriter.h> #include <less/css/CssPrettyWriter.h> #include <less/stylesheet/Stylesheet.h> #include <less/css/IOException.h> #include <less/lessstylesheet/LessStylesheet.h> using namespace std; /** * /main Less CSS compiler, implemented in C++. * */ void usage () { cout << "Usage: lessc [OPTION]... [FILE]\n" "\n" " FILE Less source file. If not given, source \ is read from stdin.\n" " -h, --help Show this message and exit.\n" " --version Print the program name and version.\n" "\n" " -o, --output=<FILE> Send output to FILE\n" " -f, --format Format output CSS with newlines and \ indentation. By default the output is unformatted.\n" "\n" " -m, --source-map=[FILE] Generate a source map.\n" " --source-map-rootpath=<PATH> PATH is prepended to the \ source file references in the source map, and also to the source map \ reference in the css output. \n" " --source-map-basepath=<PATH> PATH is removed from the \ source file references in the source map, and also from the source \ map reference in the css output.\n" " --rootpath=<PATH> Prefix PATH to urls and import \ statements in output. \n" " -I, --include-path=<FILE> Specify paths to look for \ imported .less files.\n" "\n" "Example:\n" " lessc in.less -o out.css\n" "\n" "Report bugs to: " PACKAGE_BUGREPORT "\n" PACKAGE_NAME " home page: <" PACKAGE_URL ">\n"; } void version () { cout << PACKAGE_STRING "\n" "Copyright 2012 Bram van der Kroef\n" "License: MIT License\n"; } /** * Copy a given path to a new string and add a trailing slash if necessary. */ char* createPath(const char* path, size_t len) { size_t newlen = len + (path[len - 1] != '/' ? 1 : 0); char* p = new char[newlen + 1]; std::strncpy(p, path, len); p[newlen - 1] = '/'; p[newlen] = '\0'; return p; } void parsePathList(const char* path, std::list<const char*>& paths) { const char* start = path; const char* end = path; size_t len; while((end = std::strchr(start, ':')) != NULL) { len = (end - start); // skip empty paths if (len > 0) paths.push_back(createPath(start, len)); start = end + 1; } len = std::strlen(start); if (len > 0) paths.push_back(createPath(start, len)); } bool parseInput(LessStylesheet &stylesheet, istream &in, const char* source, std::list<const char*> &sources, std::list<const char*> &includePaths) { std::list<const char*>::iterator i; LessTokenizer tokenizer(in, source); LessParser parser(tokenizer, sources); parser.includePaths = &includePaths; try{ parser.parseStylesheet(stylesheet); } catch(ParseException* e) { cerr << e->getSource() << ": Line " << e->getLineNumber() << ", Column " << e->getColumn() << " Parse Error: " << e->what() << endl; return false; } catch(exception* e) { cerr << " Error: " << e->what() << endl; return false; } return true; } bool processStylesheet (LessStylesheet &stylesheet, Stylesheet &css) { ProcessingContext context; try{ stylesheet.process(css, context); } catch(ParseException* e) { cerr << e->getSource() << ": Line " << e->getLineNumber() << ", Column " << e->getColumn() << " Parse Error: " << e->what() << endl; return false; } catch(ValueException* e) { cerr << e->getSource() << ": Line " << e->getLineNumber() << ", Column " << e->getColumn() << " Error: " << e->what() << endl; return false; } catch(exception* e) { cerr << "Error: " << e->what() << endl; return false; } return true; } void writeDependencies(const char* output, const std::list<const char*> &sources) { std::list<const char *>::const_iterator i; cout << output << ": "; for (i = sources.begin(); i != sources.end(); i++) { if (i != sources.begin()) cout << ", "; cout << (*i); } cout << endl; } int main(int argc, char * argv[]){ istream* in = &cin; ostream* out = &cout; bool formatoutput = false; char* source = NULL; string output = "-"; LessStylesheet stylesheet; std::list<const char*> sources; Stylesheet css; CssWriter* writer; bool depends = false, lint = false; std::string sourcemap_file = ""; ostream* sourcemap_s = NULL; SourceMapWriter* sourcemap = NULL; const char* sourcemap_rootpath = NULL; const char* sourcemap_basepath = NULL; const char* rootpath = NULL; std::list<const char*> includePaths; static struct option long_options[] = { {"version", no_argument, 0, 1}, {"help", no_argument, 0, 'h'}, {"output", required_argument, 0, 'o'}, {"format", no_argument, 0, 'f'}, {"source-map", optional_argument, 0, 'm'}, {"source-map-rootpath", required_argument, 0, 2}, {"source-map-basepath", required_argument, 0, 3}, {"include-path", required_argument, 0, 'I'}, {"rootpath", required_argument, 0, 4}, {"depends", no_argument, 0, 'M'}, {"lint", no_argument, 0, 'l'}, {0,0,0,0} }; try { int c, option_index; while((c = getopt_long(argc, argv, ":o:hfv:m::I:Ml", long_options, &option_index)) != -1) { switch (c) { case 1: version(); return 0; case 'h': usage(); return 0; case 'o': output = optarg; break; case 'f': formatoutput = true; break; case 'm': if (optarg) sourcemap_file = optarg; else sourcemap_file = "-"; break; case 2: sourcemap_rootpath = createPath(optarg, std::strlen(optarg)); break; case 3: sourcemap_basepath = createPath(optarg, std::strlen(optarg)); break; case 'I': parsePathList(optarg, includePaths); break; case 4: rootpath = createPath(optarg, std::strlen(optarg)); break; case 'M': depends = true; break; case 'l': lint = true; break; default: cerr << "Unrecognized option. " << endl; usage(); return 1; } } if (argc - optind >= 1) { source = new char[std::strlen(argv[optind]) + 1]; std::strcpy(source, argv[optind]); in = new ifstream(source); if (in->fail() || in->bad()) throw new IOException("Error opening file."); } else { source = new char[2]; std::strcpy(source, "-"); } if (sourcemap_file == "-") { if (output == "-") { throw new IOException("source-map option requires that \ a file name is specified for either the source map or the css \ output file."); } else { sourcemap_file = output; sourcemap_file += ".map"; } } sources.push_back(source); if (parseInput(stylesheet, *in, source, sources, includePaths)) { if (lint) { return 0; } if (depends) { writeDependencies(output.c_str(), sources); return 0; } if (!processStylesheet(stylesheet, css)) { return 1; } if (output != "-") out = new ofstream(output.c_str()); if (sourcemap_file != "") { sourcemap_s = new ofstream(sourcemap_file.c_str()); sourcemap = new SourceMapWriter(*sourcemap_s, sources, output.c_str(), sourcemap_rootpath, sourcemap_basepath); writer = formatoutput ? new CssPrettyWriter(*out, *sourcemap) : new CssWriter(*out, *sourcemap); } else { writer = formatoutput ? new CssPrettyWriter(*out) : new CssWriter(*out); } writer->rootpath = rootpath; css.write(*writer); if (sourcemap != NULL) { if (sourcemap_basepath != NULL && sourcemap_file.compare(0, std::strlen(sourcemap_basepath), sourcemap_basepath) == 0) { sourcemap_file.erase(0, std::strlen(sourcemap_basepath)); } if (sourcemap_rootpath != NULL) sourcemap_file.insert(0, sourcemap_rootpath); writer->writeSourceMapUrl(sourcemap_file.c_str()); sourcemap->close(); delete sourcemap; if (sourcemap_s != NULL) delete sourcemap_s; } delete writer; *out << endl; } else return 1; delete [] source; } catch (IOException* e) { cerr << " Error: " << e->what() << endl; return 1; } return 0; } <commit_msg>Move output writing code to its own function.<commit_after>#include <iostream> #include <fstream> #include <string> #include <sstream> #include <getopt.h> #include <cstring> #include <less/less/LessTokenizer.h> #include <less/less/LessParser.h> #include <less/css/CssWriter.h> #include <less/css/CssPrettyWriter.h> #include <less/stylesheet/Stylesheet.h> #include <less/css/IOException.h> #include <less/lessstylesheet/LessStylesheet.h> using namespace std; /** * /main Less CSS compiler, implemented in C++. * */ void usage () { cout << "Usage: lessc [OPTION]... [FILE]\n" "\n" " FILE Less source file. If not given, source \ is read from stdin.\n" " -h, --help Show this message and exit.\n" " --version Print the program name and version.\n" "\n" " -o, --output=<FILE> Send output to FILE\n" " -f, --format Format output CSS with newlines and \ indentation. By default the output is unformatted.\n" "\n" " -m, --source-map=[FILE] Generate a source map.\n" " --source-map-rootpath=<PATH> PATH is prepended to the \ source file references in the source map, and also to the source map \ reference in the css output. \n" " --source-map-basepath=<PATH> PATH is removed from the \ source file references in the source map, and also from the source \ map reference in the css output.\n" " --rootpath=<PATH> Prefix PATH to urls and import \ statements in output. \n" " -I, --include-path=<FILE> Specify paths to look for \ imported .less files.\n" "\n" "Example:\n" " lessc in.less -o out.css\n" "\n" "Report bugs to: " PACKAGE_BUGREPORT "\n" PACKAGE_NAME " home page: <" PACKAGE_URL ">\n"; } void version () { cout << PACKAGE_STRING "\n" "Copyright 2012 Bram van der Kroef\n" "License: MIT License\n"; } /** * Copy a given path to a new string and add a trailing slash if necessary. */ char* createPath(const char* path, size_t len) { size_t newlen = len + (path[len - 1] != '/' ? 1 : 0); char* p = new char[newlen + 1]; std::strncpy(p, path, len); p[newlen - 1] = '/'; p[newlen] = '\0'; return p; } void parsePathList(const char* path, std::list<const char*>& paths) { const char* start = path; const char* end = path; size_t len; while((end = std::strchr(start, ':')) != NULL) { len = (end - start); // skip empty paths if (len > 0) paths.push_back(createPath(start, len)); start = end + 1; } len = std::strlen(start); if (len > 0) paths.push_back(createPath(start, len)); } bool parseInput(LessStylesheet &stylesheet, istream &in, const char* source, std::list<const char*> &sources, std::list<const char*> &includePaths) { std::list<const char*>::iterator i; LessTokenizer tokenizer(in, source); LessParser parser(tokenizer, sources); parser.includePaths = &includePaths; try{ parser.parseStylesheet(stylesheet); } catch(ParseException* e) { cerr << e->getSource() << ": Line " << e->getLineNumber() << ", Column " << e->getColumn() << " Parse Error: " << e->what() << endl; return false; } catch(exception* e) { cerr << " Error: " << e->what() << endl; return false; } return true; } bool processStylesheet (LessStylesheet &stylesheet, Stylesheet &css) { ProcessingContext context; try{ stylesheet.process(css, context); } catch(ParseException* e) { cerr << e->getSource() << ": Line " << e->getLineNumber() << ", Column " << e->getColumn() << " Parse Error: " << e->what() << endl; return false; } catch(ValueException* e) { cerr << e->getSource() << ": Line " << e->getLineNumber() << ", Column " << e->getColumn() << " Error: " << e->what() << endl; return false; } catch(exception* e) { cerr << "Error: " << e->what() << endl; return false; } return true; } void writeOutput(Stylesheet &css, const char* output, bool formatoutput, const char* rootpath, std::list<const char*> &sources, std::string sourcemap_file, const char* sourcemap_rootpath, const char* sourcemap_basepath) { ostream* out = &cout; CssWriter* writer; ostream* sourcemap_s = NULL; SourceMapWriter* sourcemap = NULL; if (strcmp(output, "-") != 0) out = new ofstream(output); if (!sourcemap_file.empty()) { sourcemap_s = new ofstream(sourcemap_file); sourcemap = new SourceMapWriter(*sourcemap_s, sources, output, sourcemap_rootpath, sourcemap_basepath); writer = formatoutput ? new CssPrettyWriter(*out, *sourcemap) : new CssWriter(*out, *sourcemap); } else { writer = formatoutput ? new CssPrettyWriter(*out) : new CssWriter(*out); } writer->rootpath = rootpath; css.write(*writer); if (sourcemap != NULL) { if (sourcemap_basepath != NULL && sourcemap_file.compare(0, std::strlen(sourcemap_basepath), sourcemap_basepath) == 0) { sourcemap_file.erase(0, std::strlen(sourcemap_basepath)); } if (sourcemap_rootpath != NULL) sourcemap_file.insert(0, sourcemap_rootpath); writer->writeSourceMapUrl(sourcemap_file.c_str()); sourcemap->close(); delete sourcemap; if (sourcemap_s != NULL) delete sourcemap_s; } delete writer; *out << endl; } void writeDependencies(const char* output, const std::list<const char*> &sources) { std::list<const char *>::const_iterator i; cout << output << ": "; for (i = sources.begin(); i != sources.end(); i++) { if (i != sources.begin()) cout << ", "; cout << (*i); } cout << endl; } int main(int argc, char * argv[]){ istream* in = &cin; bool formatoutput = false; char* source = NULL; string output = "-"; LessStylesheet stylesheet; std::list<const char*> sources; Stylesheet css; bool depends = false, lint = false; std::string sourcemap_file = ""; const char* sourcemap_rootpath = NULL; const char* sourcemap_basepath = NULL; const char* rootpath = NULL; std::list<const char*> includePaths; static struct option long_options[] = { {"version", no_argument, 0, 1}, {"help", no_argument, 0, 'h'}, {"output", required_argument, 0, 'o'}, {"format", no_argument, 0, 'f'}, {"source-map", optional_argument, 0, 'm'}, {"source-map-rootpath", required_argument, 0, 2}, {"source-map-basepath", required_argument, 0, 3}, {"include-path", required_argument, 0, 'I'}, {"rootpath", required_argument, 0, 4}, {"depends", no_argument, 0, 'M'}, {"lint", no_argument, 0, 'l'}, {0,0,0,0} }; try { int c, option_index; while((c = getopt_long(argc, argv, ":o:hfv:m::I:Ml", long_options, &option_index)) != -1) { switch (c) { case 1: version(); return 0; case 'h': usage(); return 0; case 'o': output = optarg; break; case 'f': formatoutput = true; break; case 'm': if (optarg) sourcemap_file = optarg; else sourcemap_file = "-"; break; case 2: sourcemap_rootpath = createPath(optarg, std::strlen(optarg)); break; case 3: sourcemap_basepath = createPath(optarg, std::strlen(optarg)); break; case 'I': parsePathList(optarg, includePaths); break; case 4: rootpath = createPath(optarg, std::strlen(optarg)); break; case 'M': depends = true; break; case 'l': lint = true; break; default: cerr << "Unrecognized option. " << endl; usage(); return 1; } } if (argc - optind >= 1) { source = new char[std::strlen(argv[optind]) + 1]; std::strcpy(source, argv[optind]); in = new ifstream(source); if (in->fail() || in->bad()) throw new IOException("Error opening file."); } else { source = new char[2]; std::strcpy(source, "-"); } if (sourcemap_file == "-") { if (output == "-") { throw new IOException("source-map option requires that \ a file name is specified for either the source map or the css \ output file."); } else { sourcemap_file = output; sourcemap_file += ".map"; } } sources.push_back(source); if (parseInput(stylesheet, *in, source, sources, includePaths)) { if (depends) { writeDependencies(output.c_str(), sources); return 0; } if (!processStylesheet(stylesheet, css)) { return 1; } if (lint) { return 0; } writeOutput(css, output.c_str(), formatoutput, rootpath, sources, sourcemap_file, sourcemap_rootpath, sourcemap_basepath); } else return 1; delete [] source; } catch (IOException* e) { cerr << " Error: " << e->what() << endl; return 1; } return 0; } <|endoftext|>
<commit_before>#include "../headers/mainwindow.h" #include "ui_mainwindow.h" #include "../headers/gtautils.hpp" namespace SAMP_Ex2 { MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); m_lblDefaultNick = new QLabel(this); m_lblDefaultNick->setText("Nickname : "); m_lnDefaultNick = new QLineEdit(this); m_lnDefaultNick->setMaxLength(20); m_lnDefaultNick->setMaximumWidth(150); m_chkBoxDefaultNick = new QCheckBox(this); m_chkBoxDefaultNick->setText("Use it by default"); QWidget* toolBarSpacer = new QWidget(this); toolBarSpacer->setMinimumWidth(10); ui->mainToolBar->addWidget(m_lblDefaultNick); ui->mainToolBar->addWidget(m_lnDefaultNick); ui->mainToolBar->addWidget(toolBarSpacer); ui->mainToolBar->addWidget(m_chkBoxDefaultNick); } MainWindow::~MainWindow() { delete ui; } } <commit_msg>Add GetFavListServers function<commit_after>#include "../headers/mainwindow.h" #include "ui_mainwindow.h" #include "../headers/gtautils.hpp" namespace SAMP_Ex2 { MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); m_lblDefaultNick = new QLabel(this); m_lblDefaultNick->setText("Nickname : "); m_lnDefaultNick = new QLineEdit(this); m_lnDefaultNick->setMaxLength(20); m_lnDefaultNick->setMaximumWidth(150); m_chkBoxDefaultNick = new QCheckBox(this); m_chkBoxDefaultNick->setText("Use it by default"); QWidget* toolBarSpacer = new QWidget(this); toolBarSpacer->setMinimumWidth(10); ui->mainToolBar->addWidget(m_lblDefaultNick); ui->mainToolBar->addWidget(m_lnDefaultNick); ui->mainToolBar->addWidget(toolBarSpacer); ui->mainToolBar->addWidget(m_chkBoxDefaultNick); } void MainWindow::GetFavListServers() { QFile file("favlist.xml"); file.open(QIODevice::ReadOnly); QXmlStreamReader stream(&file); QString Ip; QString Name; QString Pass; try { while(stream.readNext() && !stream.isEndDocument()) { if(stream.name() == "server") { qDebug() << "server found"; while(stream.readNext() && !stream.isEndElement()) { if(stream.name() == "ip") { Ip = stream.readElementText(); /* Configure le avec ta liste */ //ui->listWidget->addItem("Ip: "+ Ip); } if(stream.name() == "nickname") { Name = stream.readElementText(); } if(stream.name() == "password") { Pass = stream.readElementText(); } } qDebug() << "IP: " + Ip; } } } catch(QException &ex) { qDebug() << "Bug In try"; } stream.clear(); file.close(); } MainWindow::~MainWindow() { delete ui; } } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include "version.h" #include <QFileDialog> #include <QMessageBox> #include <QCloseEvent> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->PauseResume_Button->setFocus(); connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(close())); connect(ui->actionCenter_All, SIGNAL(triggered()), &ui->centralwidget->universe, SLOT(centerAll())); connect(ui->actionDelete, SIGNAL(triggered()), &ui->centralwidget->universe, SLOT(deleteSelected())); connect(ui->actionDelete_Escapees, SIGNAL(triggered()), &ui->centralwidget->universe, SLOT(deleteEscapees())); connect(ui->actionInteractive_Planet_Placement, SIGNAL(triggered()), ui->centralwidget, SLOT(beginInteractiveCreation())); connect(ui->actionInteractive_Planet_Placement, SIGNAL(triggered(bool)), ui->toggleFiringModePushButton, SLOT(setChecked(bool))); connect(ui->actionInteractive_Orbital_Placement, SIGNAL(triggered()), ui->centralwidget, SLOT(beginOrbitalCreation())); connect(ui->toggleFiringModePushButton, SIGNAL(toggled(bool)), ui->centralwidget, SLOT(enableFiringMode(bool))); connect(ui->actionTake_Screenshot, SIGNAL(triggered()), ui->centralwidget, SLOT(takeScreenshot())); connect(ui->gridRangeSpinBox, SIGNAL(valueChanged(int)), ui->centralwidget, SLOT(setGridRange(int))); ui->statusbar->addPermanentWidget(planetCountLabel = new QLabel(ui->statusbar)); ui->statusbar->addPermanentWidget(fpsLabel = new QLabel(ui->statusbar)); ui->statusbar->addPermanentWidget(averagefpsLabel = new QLabel(ui->statusbar)); fpsLabel->setFixedWidth(120); planetCountLabel->setFixedWidth(120); averagefpsLabel->setFixedWidth(160); connect(&ui->centralwidget->universe, SIGNAL(updatePlanetCountMessage(QString)), planetCountLabel, SLOT(setText(QString))); connect(ui->centralwidget, SIGNAL(updateFPSStatusMessage(QString)), fpsLabel, SLOT(setText(QString))); connect(ui->centralwidget, SIGNAL(updateAverageFPSStatusMessage(QString)), averagefpsLabel, SLOT(setText(QString))); connect(ui->actionNew_Planet, SIGNAL(toggled(bool)), ui->newPlanet_DockWidget, SLOT(setVisible(bool))); connect(ui->newPlanet_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionNew_Planet, SLOT(setChecked(bool))); connect(ui->actionSpeed_Control, SIGNAL(toggled(bool)), ui->speedControl_DockWidget, SLOT(setVisible(bool))); connect(ui->speedControl_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionSpeed_Control, SLOT(setChecked(bool))); connect(ui->actionView_Settings, SIGNAL(toggled(bool)), ui->viewSettings_DockWidget, SLOT(setVisible(bool))); connect(ui->viewSettings_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionView_Settings, SLOT(setChecked(bool))); connect(ui->actionFiring_Mode_Settings, SIGNAL(toggled(bool)), ui->firingSettings_DockWidget, SLOT(setVisible(bool))); connect(ui->firingSettings_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionFiring_Mode_Settings, SLOT(setChecked(bool))); connect(ui->actionRandom_Settings, SIGNAL(toggled(bool)), ui->randomSettings_DockWidget, SLOT(setVisible(bool))); connect(ui->randomSettings_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionRandom_Settings, SLOT(setChecked(bool))); ui->actionFiring_Mode_Settings->setChecked(false); ui->actionRandom_Settings->setChecked(false); } MainWindow::~MainWindow(){ delete ui; delete planetCountLabel; delete averagefpsLabel; delete fpsLabel; } void MainWindow::closeEvent(QCloseEvent *e){ if(!ui->centralwidget->universe.isEmpty()){ float tmpsimspeed = ui->centralwidget->universe.simspeed; ui->centralwidget->universe.simspeed = 0.0f; if(QMessageBox::warning(this, tr("Are You Sure?"), tr("Are you sure you wish to exit? (universe will not be saved...)"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::No){ ui->centralwidget->universe.simspeed = tmpsimspeed; return e->ignore(); } } e->accept(); } void MainWindow::on_createPlanet_PushButton_clicked(){ ui->centralwidget->universe.selected = ui->centralwidget->universe.addPlanet( Planet(QVector3D(ui->newPosX_SpinBox->value(), ui->newPosY_SpinBox->value(), ui->newPosZ_SpinBox->value()), QVector3D(ui->newVelocityX_SpinBox->value(), ui->newVelocityY_SpinBox->value(), ui->newVelocityZ_SpinBox->value()) * PlanetsUniverse::velocityfac, ui->newMass_SpinBox->value())); } void MainWindow::on_actionClear_Velocity_triggered(){ if(ui->centralwidget->universe.isSelectedValid()){ ui->centralwidget->universe.getSelected().velocity = QVector3D(); } } void MainWindow::on_speed_Dial_valueChanged(int value){ ui->centralwidget->universe.simspeed = float(value * speeddialmax) / ui->speed_Dial->maximum(); ui->speedDisplay_lcdNumber->display(ui->centralwidget->universe.simspeed); if(ui->centralwidget->universe.simspeed <= 0.0f){ ui->PauseResume_Button->setText(tr("Resume")); ui->PauseResume_Button->setIcon(QIcon(":/icons/silk/control_play_blue.png")); }else{ ui->PauseResume_Button->setText(tr("Pause")); ui->PauseResume_Button->setIcon(QIcon(":/icons/silk/control_pause_blue.png")); } } void MainWindow::on_PauseResume_Button_clicked(){ if(ui->speed_Dial->value() == 0){ ui->speed_Dial->setValue(ui->speed_Dial->maximum() / speeddialmax); }else{ ui->speed_Dial->setValue(0); } } void MainWindow::on_FastForward_Button_clicked(){ if(ui->speed_Dial->value() == ui->speed_Dial->maximum() || ui->speed_Dial->value() == 0){ ui->speed_Dial->setValue(ui->speed_Dial->maximum() / speeddialmax); }else{ ui->speed_Dial->setValue(ui->speed_Dial->value() * 2); } } void MainWindow::on_actionNew_Simulation_triggered(){ if(!ui->centralwidget->universe.isEmpty()){ float tmpsimspeed = ui->centralwidget->universe.simspeed; ui->centralwidget->universe.simspeed = 0.0f; if(QMessageBox::warning(this, tr("Are You Sure?"), tr("Are you sure you wish to destroy the universe? (i.e. delete all planets.)"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes){ ui->centralwidget->universe.deleteAll(); } ui->centralwidget->universe.simspeed = tmpsimspeed; } } void MainWindow::on_actionOpen_Simulation_triggered(){ float tmpsimspeed = ui->centralwidget->universe.simspeed; ui->centralwidget->universe.simspeed = 0.0f; QString filename = QFileDialog::getOpenFileName(this, tr("Open Simulation"), "", tr("Simulation files (*.xml)")); ui->centralwidget->universe.load(filename); ui->centralwidget->universe.simspeed = tmpsimspeed; } void MainWindow::on_actionSave_Simulation_triggered(){ float tmpsimspeed = ui->centralwidget->universe.simspeed; ui->centralwidget->universe.simspeed = 0.0f; if(!ui->centralwidget->universe.isEmpty()){ QString filename = QFileDialog::getSaveFileName(this, tr("Save Simulation"), "", tr("Simulation files (*.xml)")); ui->centralwidget->universe.save(filename); }else{ QMessageBox::warning(this, tr("Error Saving Simulation."), tr("No planets to save!")); } ui->centralwidget->universe.simspeed = tmpsimspeed; } void MainWindow::on_actionFollow_Selection_triggered(){ ui->centralwidget->following = ui->centralwidget->universe.selected; ui->centralwidget->followState = PlanetsWidget::Single; } void MainWindow::on_actionClear_Follow_triggered(){ ui->centralwidget->following = 0; ui->centralwidget->followState = PlanetsWidget::FollowNone; } void MainWindow::on_actionPlain_Average_triggered(){ ui->centralwidget->followState = PlanetsWidget::PlainAverage; } void MainWindow::on_actionWeighted_Average_triggered(){ ui->centralwidget->followState = PlanetsWidget::WeightedAverage; } void MainWindow::on_actionAbout_triggered(){ float tmpsimspeed = ui->centralwidget->universe.simspeed; ui->centralwidget->universe.simspeed = 0.0f; QMessageBox::about(this, tr("About Planets3D"), tr("<html><head/><body>" "<p>Planets3D is a simple 3D gravitational simulator</p>" "<p>Website: <a href=\"https://github.com/chipgw/planets-3d\">github.com/chipgw/planets-3d</a></p>" "<p>Build Info:</p><ul>" "<li>Git sha1: %2</li>" "<li>Build type: %3</li>" "<li>Compiler: %4</li>" "</ul></body></html>") .arg(version::git_revision) .arg(version::build_type) .arg(version::compiler)); ui->centralwidget->universe.simspeed = tmpsimspeed; } void MainWindow::on_actionAbout_Qt_triggered(){ float tmpsimspeed = ui->centralwidget->universe.simspeed; ui->centralwidget->universe.simspeed = 0.0f; QMessageBox::aboutQt(this); ui->centralwidget->universe.simspeed = tmpsimspeed; } void MainWindow::on_stepsPerFrameSpinBox_valueChanged(int value){ ui->centralwidget->universe.stepsPerFrame = value; } void MainWindow::on_trailLengthSpinBox_valueChanged(int value){ Planet::pathLength = value; } void MainWindow::on_trailRecordDistanceDoubleSpinBox_valueChanged(double value){ Planet::pathRecordDistance = value * value; } void MainWindow::on_firingVelocityDoubleSpinBox_valueChanged(double value){ ui->centralwidget->firingSpeed = value * PlanetsUniverse::velocityfac; } void MainWindow::on_firingMassSpinBox_valueChanged(int value){ ui->centralwidget->firingMass = value; } void MainWindow::on_actionGrid_toggled(bool value){ ui->centralwidget->drawGrid = value; } void MainWindow::on_actionDraw_Paths_toggled(bool value){ ui->centralwidget->drawPlanetTrails = value; } void MainWindow::on_actionPlanet_Colors_toggled(bool value){ ui->centralwidget->drawPlanetColors = value; } void MainWindow::on_actionHide_Planets_toggled(bool value){ ui->centralwidget->hidePlanets = value; } void MainWindow::on_generateRandomPushButton_clicked(){ ui->centralwidget->universe.generateRandom(ui->randomAmountSpinBox->value(), ui->randomRangeDoubleSpinBox->value(), ui->randomSpeedDoubleSpinBox->value() * PlanetsUniverse::velocityfac, ui->randomMassDoubleSpinBox->value()); } const int MainWindow::speeddialmax = 32; <commit_msg>enable drawing trails when planets are hidden.<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "version.h" #include <QFileDialog> #include <QMessageBox> #include <QCloseEvent> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->PauseResume_Button->setFocus(); connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(close())); connect(ui->actionCenter_All, SIGNAL(triggered()), &ui->centralwidget->universe, SLOT(centerAll())); connect(ui->actionDelete, SIGNAL(triggered()), &ui->centralwidget->universe, SLOT(deleteSelected())); connect(ui->actionDelete_Escapees, SIGNAL(triggered()), &ui->centralwidget->universe, SLOT(deleteEscapees())); connect(ui->actionInteractive_Planet_Placement, SIGNAL(triggered()), ui->centralwidget, SLOT(beginInteractiveCreation())); connect(ui->actionInteractive_Planet_Placement, SIGNAL(triggered(bool)), ui->toggleFiringModePushButton, SLOT(setChecked(bool))); connect(ui->actionInteractive_Orbital_Placement, SIGNAL(triggered()), ui->centralwidget, SLOT(beginOrbitalCreation())); connect(ui->toggleFiringModePushButton, SIGNAL(toggled(bool)), ui->centralwidget, SLOT(enableFiringMode(bool))); connect(ui->actionTake_Screenshot, SIGNAL(triggered()), ui->centralwidget, SLOT(takeScreenshot())); connect(ui->gridRangeSpinBox, SIGNAL(valueChanged(int)), ui->centralwidget, SLOT(setGridRange(int))); ui->statusbar->addPermanentWidget(planetCountLabel = new QLabel(ui->statusbar)); ui->statusbar->addPermanentWidget(fpsLabel = new QLabel(ui->statusbar)); ui->statusbar->addPermanentWidget(averagefpsLabel = new QLabel(ui->statusbar)); fpsLabel->setFixedWidth(120); planetCountLabel->setFixedWidth(120); averagefpsLabel->setFixedWidth(160); connect(&ui->centralwidget->universe, SIGNAL(updatePlanetCountMessage(QString)), planetCountLabel, SLOT(setText(QString))); connect(ui->centralwidget, SIGNAL(updateFPSStatusMessage(QString)), fpsLabel, SLOT(setText(QString))); connect(ui->centralwidget, SIGNAL(updateAverageFPSStatusMessage(QString)), averagefpsLabel, SLOT(setText(QString))); connect(ui->actionNew_Planet, SIGNAL(toggled(bool)), ui->newPlanet_DockWidget, SLOT(setVisible(bool))); connect(ui->newPlanet_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionNew_Planet, SLOT(setChecked(bool))); connect(ui->actionSpeed_Control, SIGNAL(toggled(bool)), ui->speedControl_DockWidget, SLOT(setVisible(bool))); connect(ui->speedControl_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionSpeed_Control, SLOT(setChecked(bool))); connect(ui->actionView_Settings, SIGNAL(toggled(bool)), ui->viewSettings_DockWidget, SLOT(setVisible(bool))); connect(ui->viewSettings_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionView_Settings, SLOT(setChecked(bool))); connect(ui->actionFiring_Mode_Settings, SIGNAL(toggled(bool)), ui->firingSettings_DockWidget, SLOT(setVisible(bool))); connect(ui->firingSettings_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionFiring_Mode_Settings, SLOT(setChecked(bool))); connect(ui->actionRandom_Settings, SIGNAL(toggled(bool)), ui->randomSettings_DockWidget, SLOT(setVisible(bool))); connect(ui->randomSettings_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionRandom_Settings, SLOT(setChecked(bool))); ui->actionFiring_Mode_Settings->setChecked(false); ui->actionRandom_Settings->setChecked(false); } MainWindow::~MainWindow(){ delete ui; delete planetCountLabel; delete averagefpsLabel; delete fpsLabel; } void MainWindow::closeEvent(QCloseEvent *e){ if(!ui->centralwidget->universe.isEmpty()){ float tmpsimspeed = ui->centralwidget->universe.simspeed; ui->centralwidget->universe.simspeed = 0.0f; if(QMessageBox::warning(this, tr("Are You Sure?"), tr("Are you sure you wish to exit? (universe will not be saved...)"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::No){ ui->centralwidget->universe.simspeed = tmpsimspeed; return e->ignore(); } } e->accept(); } void MainWindow::on_createPlanet_PushButton_clicked(){ ui->centralwidget->universe.selected = ui->centralwidget->universe.addPlanet( Planet(QVector3D(ui->newPosX_SpinBox->value(), ui->newPosY_SpinBox->value(), ui->newPosZ_SpinBox->value()), QVector3D(ui->newVelocityX_SpinBox->value(), ui->newVelocityY_SpinBox->value(), ui->newVelocityZ_SpinBox->value()) * PlanetsUniverse::velocityfac, ui->newMass_SpinBox->value())); } void MainWindow::on_actionClear_Velocity_triggered(){ if(ui->centralwidget->universe.isSelectedValid()){ ui->centralwidget->universe.getSelected().velocity = QVector3D(); } } void MainWindow::on_speed_Dial_valueChanged(int value){ ui->centralwidget->universe.simspeed = float(value * speeddialmax) / ui->speed_Dial->maximum(); ui->speedDisplay_lcdNumber->display(ui->centralwidget->universe.simspeed); if(ui->centralwidget->universe.simspeed <= 0.0f){ ui->PauseResume_Button->setText(tr("Resume")); ui->PauseResume_Button->setIcon(QIcon(":/icons/silk/control_play_blue.png")); }else{ ui->PauseResume_Button->setText(tr("Pause")); ui->PauseResume_Button->setIcon(QIcon(":/icons/silk/control_pause_blue.png")); } } void MainWindow::on_PauseResume_Button_clicked(){ if(ui->speed_Dial->value() == 0){ ui->speed_Dial->setValue(ui->speed_Dial->maximum() / speeddialmax); }else{ ui->speed_Dial->setValue(0); } } void MainWindow::on_FastForward_Button_clicked(){ if(ui->speed_Dial->value() == ui->speed_Dial->maximum() || ui->speed_Dial->value() == 0){ ui->speed_Dial->setValue(ui->speed_Dial->maximum() / speeddialmax); }else{ ui->speed_Dial->setValue(ui->speed_Dial->value() * 2); } } void MainWindow::on_actionNew_Simulation_triggered(){ if(!ui->centralwidget->universe.isEmpty()){ float tmpsimspeed = ui->centralwidget->universe.simspeed; ui->centralwidget->universe.simspeed = 0.0f; if(QMessageBox::warning(this, tr("Are You Sure?"), tr("Are you sure you wish to destroy the universe? (i.e. delete all planets.)"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes){ ui->centralwidget->universe.deleteAll(); } ui->centralwidget->universe.simspeed = tmpsimspeed; } } void MainWindow::on_actionOpen_Simulation_triggered(){ float tmpsimspeed = ui->centralwidget->universe.simspeed; ui->centralwidget->universe.simspeed = 0.0f; QString filename = QFileDialog::getOpenFileName(this, tr("Open Simulation"), "", tr("Simulation files (*.xml)")); ui->centralwidget->universe.load(filename); ui->centralwidget->universe.simspeed = tmpsimspeed; } void MainWindow::on_actionSave_Simulation_triggered(){ float tmpsimspeed = ui->centralwidget->universe.simspeed; ui->centralwidget->universe.simspeed = 0.0f; if(!ui->centralwidget->universe.isEmpty()){ QString filename = QFileDialog::getSaveFileName(this, tr("Save Simulation"), "", tr("Simulation files (*.xml)")); ui->centralwidget->universe.save(filename); }else{ QMessageBox::warning(this, tr("Error Saving Simulation."), tr("No planets to save!")); } ui->centralwidget->universe.simspeed = tmpsimspeed; } void MainWindow::on_actionFollow_Selection_triggered(){ ui->centralwidget->following = ui->centralwidget->universe.selected; ui->centralwidget->followState = PlanetsWidget::Single; } void MainWindow::on_actionClear_Follow_triggered(){ ui->centralwidget->following = 0; ui->centralwidget->followState = PlanetsWidget::FollowNone; } void MainWindow::on_actionPlain_Average_triggered(){ ui->centralwidget->followState = PlanetsWidget::PlainAverage; } void MainWindow::on_actionWeighted_Average_triggered(){ ui->centralwidget->followState = PlanetsWidget::WeightedAverage; } void MainWindow::on_actionAbout_triggered(){ float tmpsimspeed = ui->centralwidget->universe.simspeed; ui->centralwidget->universe.simspeed = 0.0f; QMessageBox::about(this, tr("About Planets3D"), tr("<html><head/><body>" "<p>Planets3D is a simple 3D gravitational simulator</p>" "<p>Website: <a href=\"https://github.com/chipgw/planets-3d\">github.com/chipgw/planets-3d</a></p>" "<p>Build Info:</p><ul>" "<li>Git sha1: %2</li>" "<li>Build type: %3</li>" "<li>Compiler: %4</li>" "</ul></body></html>") .arg(version::git_revision) .arg(version::build_type) .arg(version::compiler)); ui->centralwidget->universe.simspeed = tmpsimspeed; } void MainWindow::on_actionAbout_Qt_triggered(){ float tmpsimspeed = ui->centralwidget->universe.simspeed; ui->centralwidget->universe.simspeed = 0.0f; QMessageBox::aboutQt(this); ui->centralwidget->universe.simspeed = tmpsimspeed; } void MainWindow::on_stepsPerFrameSpinBox_valueChanged(int value){ ui->centralwidget->universe.stepsPerFrame = value; } void MainWindow::on_trailLengthSpinBox_valueChanged(int value){ Planet::pathLength = value; } void MainWindow::on_trailRecordDistanceDoubleSpinBox_valueChanged(double value){ Planet::pathRecordDistance = value * value; } void MainWindow::on_firingVelocityDoubleSpinBox_valueChanged(double value){ ui->centralwidget->firingSpeed = value * PlanetsUniverse::velocityfac; } void MainWindow::on_firingMassSpinBox_valueChanged(int value){ ui->centralwidget->firingMass = value; } void MainWindow::on_actionGrid_toggled(bool value){ ui->centralwidget->drawGrid = value; } void MainWindow::on_actionDraw_Paths_toggled(bool value){ ui->centralwidget->drawPlanetTrails = value; } void MainWindow::on_actionPlanet_Colors_toggled(bool value){ ui->centralwidget->drawPlanetColors = value; } void MainWindow::on_actionHide_Planets_toggled(bool value){ ui->centralwidget->hidePlanets = value; if(value){ ui->actionDraw_Paths->setChecked(true); } } void MainWindow::on_generateRandomPushButton_clicked(){ ui->centralwidget->universe.generateRandom(ui->randomAmountSpinBox->value(), ui->randomRangeDoubleSpinBox->value(), ui->randomSpeedDoubleSpinBox->value() * PlanetsUniverse::velocityfac, ui->randomMassDoubleSpinBox->value()); } const int MainWindow::speeddialmax = 32; <|endoftext|>
<commit_before>/* This file is part of the KDE project. Copyright (C) 2011 Harald Sitter <sitter@kde.org> Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 or 3 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "streamreader.h" #include "debug.h" QT_BEGIN_NAMESPACE #ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM namespace Phonon { namespace Gstreamer { StreamReader::StreamReader(const Phonon::MediaSource &source, MediaObject *parent) : m_pos(0) , m_size(0) , m_eos(false) , m_locked(false) , m_seekable(false) , m_mediaObject(parent) { DEBUG_BLOCK; connectToSource(source); } StreamReader::~StreamReader() { DEBUG_BLOCK; } int StreamReader::currentBufferSize() const { return m_buffer.size(); } void StreamReader::writeData(const QByteArray &data) { DEBUG_BLOCK; m_buffer.append(data); m_waitingForData.wakeAll(); } void StreamReader::setCurrentPos(qint64 pos) { QMutexLocker locker(&m_mutex); m_pos = pos; seekStream(pos); m_buffer.clear(); } quint64 StreamReader::currentPos() const { return m_pos; } GstFlowReturn StreamReader::read(quint64 pos, int length, char *buffer) { DEBUG_BLOCK; QMutexLocker locker(&m_mutex); if (currentPos() != pos) { if (!streamSeekable()) { return GST_FLOW_NOT_SUPPORTED; } // TODO: technically an error can occur here, however the abstractstream // API does not consider this, so we must assume that everything always goes // alright and continue processing. setCurrentPos(pos); } while (currentBufferSize() < length) { int oldSize = currentBufferSize(); needData(); m_waitingForData.wait(&m_mutex); // Abort instantly if we got unlocked, whether we got sufficient data or not // is absolutely unimportant at this point. if (!m_locked) { break; } if (oldSize == currentBufferSize()) { // We didn't get any data, check if we are at the end of stream already. if (m_eos) { return GST_FLOW_UNEXPECTED; } } } if (m_mediaObject->state() != Phonon::BufferingState && m_mediaObject->state() != Phonon::LoadingState) { enoughData(); } qMemCopy(buffer, m_buffer.data(), length); m_pos += length; //truncate the buffer m_buffer = m_buffer.mid(length); return GST_FLOW_OK; } void StreamReader::endOfData() { DEBUG_BLOCK; QMutexLocker locker(&m_mutex); m_eos = true; m_waitingForData.wakeAll(); } void StreamReader::start() { DEBUG_BLOCK; QMutexLocker locker(&m_mutex); m_buffer.clear(); m_eos = false; m_locked = true; m_pos = 0; m_seekable = false; m_size = 0; reset(); } void StreamReader::stop() { DEBUG_BLOCK; enoughData(); m_waitingForData.wakeAll(); } void StreamReader::unlock() { DEBUG_BLOCK; QMutexLocker locker(&m_mutex); enoughData(); m_locked = false; m_waitingForData.wakeAll(); } void StreamReader::setStreamSize(qint64 newSize) { m_size = newSize; } qint64 StreamReader::streamSize() const { return m_size; } void StreamReader::setStreamSeekable(bool seekable) { // if (seekable) { // // The initial stream size of a seekable stream *must* not be 0 or // // GStreamer will refuse to typefind. // m_size = 1; // } m_seekable = seekable; } bool StreamReader::streamSeekable() const { // TODO - problems with pull seeking and the way our current stack works. return false; // return m_seekable; } } } #endif //QT_NO_PHONON_ABSTRACTMEDIASTREAM QT_END_NAMESPACE <commit_msg>a bit of threading here, a bit of threading there...<commit_after>/* This file is part of the KDE project. Copyright (C) 2011 Harald Sitter <sitter@kde.org> Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 or 3 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "streamreader.h" #include "debug.h" QT_BEGIN_NAMESPACE #ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM namespace Phonon { namespace Gstreamer { StreamReader::StreamReader(const Phonon::MediaSource &source, MediaObject *parent) : m_pos(0) , m_size(0) , m_eos(false) , m_locked(false) , m_seekable(false) , m_mediaObject(parent) { DEBUG_BLOCK; connectToSource(source); } StreamReader::~StreamReader() { DEBUG_BLOCK; } //------------------------------------------------------------------------------ // Thead safe because every changing function is locked ------------------------ //------------------------------------------------------------------------------ int StreamReader::currentBufferSize() const { return m_buffer.size(); } quint64 StreamReader::currentPos() const { return m_pos; } qint64 StreamReader::streamSize() const { return m_size; } bool StreamReader::streamSeekable() const { // TODO - problems with pull seeking and the way our current stack works. return false; // return m_seekable; } //------------------------------------------------------------------------------ // Explicit thread safe by locking the mutex --------------------------------- //------------------------------------------------------------------------------ void StreamReader::setCurrentPos(qint64 pos) { QMutexLocker locker(&m_mutex); m_pos = pos; seekStream(pos); m_buffer.clear(); } void StreamReader::writeData(const QByteArray &data) { QMutexLocker locker(&m_mutex); DEBUG_BLOCK; m_buffer.append(data); m_waitingForData.wakeAll(); } GstFlowReturn StreamReader::read(quint64 pos, int length, char *buffer) { QMutexLocker locker(&m_mutex); DEBUG_BLOCK; if (currentPos() != pos) { if (!streamSeekable()) { return GST_FLOW_NOT_SUPPORTED; } // TODO: technically an error can occur here, however the abstractstream // API does not consider this, so we must assume that everything always goes // alright and continue processing. setCurrentPos(pos); } while (currentBufferSize() < length) { int oldSize = currentBufferSize(); needData(); m_waitingForData.wait(&m_mutex); // Abort instantly if we got unlocked, whether we got sufficient data or not // is absolutely unimportant at this point. if (!m_locked) { break; } if (oldSize == currentBufferSize()) { // We didn't get any data, check if we are at the end of stream already. if (m_eos) { return GST_FLOW_UNEXPECTED; } } } if (m_mediaObject->state() != Phonon::BufferingState && m_mediaObject->state() != Phonon::LoadingState) { enoughData(); } qMemCopy(buffer, m_buffer.data(), length); m_pos += length; //truncate the buffer m_buffer = m_buffer.mid(length); return GST_FLOW_OK; } void StreamReader::endOfData() { QMutexLocker locker(&m_mutex); DEBUG_BLOCK; m_eos = true; m_waitingForData.wakeAll(); } void StreamReader::start() { QMutexLocker locker(&m_mutex); DEBUG_BLOCK; m_buffer.clear(); m_eos = false; m_locked = true; m_pos = 0; m_seekable = false; m_size = 0; reset(); } void StreamReader::stop() { QMutexLocker locker(&m_mutex); DEBUG_BLOCK; enoughData(); m_waitingForData.wakeAll(); } void StreamReader::unlock() { QMutexLocker locker(&m_mutex); DEBUG_BLOCK; enoughData(); m_locked = false; m_waitingForData.wakeAll(); } void StreamReader::setStreamSize(qint64 newSize) { QMutexLocker locker(&m_mutex); m_size = newSize; } void StreamReader::setStreamSeekable(bool seekable) { QMutexLocker locker(&m_mutex); // if (seekable) { // // The initial stream size of a seekable stream *must* not be 0 or // // GStreamer will refuse to typefind. // m_size = 1; // } m_seekable = seekable; } } } #endif //QT_NO_PHONON_ABSTRACTMEDIASTREAM QT_END_NAMESPACE <|endoftext|>
<commit_before> /** * \file main.cc * \brief Program for giving an indication when a rfid card has been detected, a database connection has been made and a string has been encrypted * \author Tim IJntema, Stefan de Beer, Arco Gelderblom, Rik Honcoop, Koen de Groot, Ricardo Bouwman, Philippe Zwietering, Luuk Steeman, Leo Jenneskens, Jeremy Ruijzenaars * \copyright Copyright (c) 2017, The R2D2 Team * \license See LICENSE */ #include "mysql.hh" #include "mfrc522.hh" #include "led-controller.hh" #include "matrix-keypad.hh" #include "config-file-parser.hh" #include "databasemanager.hh" #include <wiringPi.h> #include <wiringPiSPI.h> #include <iostream> struct MFAuthentData { uint8_t command_code; uint8_t blockAddress; uint8_t sectorKey[5]; uint8_t serialNumber[4]; }; int main(int argc, char **argv) { #define USING_PIN // Comment out this rule if not using a pincode on your application try { std::string ip; std::string username; std::string password; //int encryptionKey; ConfigFileParser factory("database-config.txt"); factory.loadDatabaseSettings(ip, username, password); MySql connection; connection.connectTo(ip, username, password); connection.selectDatabase("R2D2"); std::cout << "Made connection to the database\n"; wiringPiSetup(); wiringPiSPISetup(0, 10000000);//max speed for mfrc522 is 10Mhz MFRC522 rfid; rfid.PCD_Init(); //Keypad pinSetup const int keypadRow[] = {15, 16, 1, 4}; const int keypadColumn[] = {8, 9, 7, 2}; //Keypad objects MatrixKeypad keypad(keypadRow, keypadColumn, 4); LedController led(0); while (true) { delay(1000); std::cout << "\n\nWaiting for rfid tag: \n"; rfid.PICC_IsNewCardPresent(); rfid.PICC_ReadCardSerial(); // Hier moet het database gedeelte komen om te checken of je ID al in de database staat #ifdef USING_PIN MFRC522::MIFARE_Key key = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; if( 1 !=rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)0x05, &key, &rfid.uid)) continue; //read pincode std::string id; for(byte i = 0; i < rfid.uid.size; ++i){ if(rfid.uid.uidByte[i] < 0x10){ id +=(char)rfid.uid.uidByte[i]; std::cout<<"1" ; } else{ id += (char)rfid.uid.uidByte[i]; std::cout<<"2" ; } } std::cout<<"philips" ; DatabaseManager information; if ( information.isCardInDatabase(id)){ std::cout << " id in database"; } byte bufferSize = (byte)18; byte readArray[18] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; rfid.MIFARE_Read((byte)0x05,readArray, &bufferSize); std::cout << "Readarray contains: \n"; for (int i = 0; i < 18; i++){ std::cout <<(int)readArray[i] << '\n'; } //pincode invoeren std::cout << "Input PIN and finish with #\n"; std::string value = keypad.getString(); // write pincode byte writeArray[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; int index = 0; for(auto c :value){ if (c >47 && c < 58 ){ int number = c - 48; writeArray[index++] = (byte)number; } } rfid.MIFARE_Write((byte)0x05, writeArray, (byte)16); for (int i = 0; i < 16; i++){ std::cout <<(int)writeArray[i] << '\n'; } #endif rfid.PCD_StopCrypto1(); for(byte i = 0; i < rfid.uid.size; ++i){ if(rfid.uid.uidByte[i] < 0x10){ printf(" 0"); printf("%X",rfid.uid.uidByte[i]); } else{ printf(" "); printf("%X", rfid.uid.uidByte[i]); } } connection.executeQuery("SELECT * FROM RFID"); // std::cout << "Database information: " // << database.getAllCardIdFromDatabase() // << '\n'; led.blinkLed(1000); } } catch (const std::string &error) { std::cerr << error << '\n'; exit(EXIT_FAILURE); } catch (...) { std::cerr << "Something went wrong\n"; exit(EXIT_FAILURE); } return 0; } <commit_msg>[RFID-03] bug fix<commit_after> /** * \file main.cc * \brief Program for giving an indication when a rfid card has been detected, a database connection has been made and a string has been encrypted * \author Tim IJntema, Stefan de Beer, Arco Gelderblom, Rik Honcoop, Koen de Groot, Ricardo Bouwman, Philippe Zwietering, Luuk Steeman, Leo Jenneskens, Jeremy Ruijzenaars * \copyright Copyright (c) 2017, The R2D2 Team * \license See LICENSE */ #include "mysql.hh" #include "mfrc522.hh" #include "led-controller.hh" #include "matrix-keypad.hh" #include "config-file-parser.hh" #include "databasemanager.hh" #include <wiringPi.h> #include <wiringPiSPI.h> #include <iostream> struct MFAuthentData { uint8_t command_code; uint8_t blockAddress; uint8_t sectorKey[5]; uint8_t serialNumber[4]; }; int main(int argc, char **argv) { #define USING_PIN // Comment out this rule if not using a pincode on your application try { std::string ip; std::string username; std::string password; //int encryptionKey; ConfigFileParser factory("database-config.txt"); factory.loadDatabaseSettings(ip, username, password); MySql connection; connection.connectTo(ip, username, password); connection.selectDatabase("R2D2"); std::cout << "Made connection to the database\n"; wiringPiSetup(); wiringPiSPISetup(0, 10000000);//max speed for mfrc522 is 10Mhz MFRC522 rfid; rfid.PCD_Init(); //Keypad pinSetup const int keypadRow[] = {15, 16, 1, 4}; const int keypadColumn[] = {8, 9, 7, 2}; //Keypad objects MatrixKeypad keypad(keypadRow, keypadColumn, 4); LedController led(0); while (true) { delay(1000); std::cout << "\n\nWaiting for rfid tag: \n"; rfid.PICC_IsNewCardPresent(); rfid.PICC_ReadCardSerial(); // Hier moet het database gedeelte komen om te checken of je ID al in de database staat #ifdef USING_PIN MFRC522::MIFARE_Key key = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; if( 1 !=rfid.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, (byte)0x05, &key, &rfid.uid)) continue; //read pincode std::string id; for(byte i = 0; i < rfid.uid.size; ++i){ std::cout <<"0"; if(rfid.uid.uidByte[i] < 0x10){ id +=(char)rfid.uid.uidByte[i]; std::cout<<"1" ; } else{ id += (char)rfid.uid.uidByte[i]; std::cout<<"2" ; } } std::cout<<"philips " ; DatabaseManager information; if ( information.isCardInDatabase(id)){ std::cout << " id in database"; } byte bufferSize = (byte)18; byte readArray[18] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; rfid.MIFARE_Read((byte)0x05,readArray, &bufferSize); std::cout << "Readarray contains: \n"; for (int i = 0; i < 18; i++){ std::cout <<(int)readArray[i] << '\n'; } //pincode invoeren std::cout << "Input PIN and finish with #\n"; std::string value = keypad.getString(); // write pincode byte writeArray[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; int index = 0; for(auto c :value){ if (c >47 && c < 58 ){ int number = c - 48; writeArray[index++] = (byte)number; } } rfid.MIFARE_Write((byte)0x05, writeArray, (byte)16); for (int i = 0; i < 16; i++){ std::cout <<(int)writeArray[i] << '\n'; } #endif rfid.PCD_StopCrypto1(); for(byte i = 0; i < rfid.uid.size; ++i){ if(rfid.uid.uidByte[i] < 0x10){ printf(" 0"); printf("%X",rfid.uid.uidByte[i]); } else{ printf(" "); printf("%X", rfid.uid.uidByte[i]); } } connection.executeQuery("SELECT * FROM RFID"); // std::cout << "Database information: " // << database.getAllCardIdFromDatabase() // << '\n'; led.blinkLed(1000); } } catch (const std::string &error) { std::cerr << error << '\n'; exit(EXIT_FAILURE); } catch (...) { std::cerr << "Something went wrong\n"; exit(EXIT_FAILURE); } return 0; } <|endoftext|>
<commit_before>#include <string> #include <functional> #include <vector> #include <cassert> #include <Console.h> #include <CPU.h> #include <APU.h> #include <PPU.h> #include <Cart.h> #include <Controller.h> #include <Divider.h> void Console::boot() { ReadBus cpuReadCallback = [this] (uint16_t addr) { return cpuRead(addr); }; WriteBus cpuWriteCallback = [this] (uint16_t addr, uint8_t data) { cpuWrite(addr,data); }; NMI nmiCallback = [this] () {cpu.signalNMI();}; cpu.boot(cpuReadCallback, cpuWriteCallback); ppu.boot(&cart, nmiCallback); } void Console::loadINesFile(std::string fileName) { return cart.loadFile(fileName); } uint32_t *Console::getFrameBuffer() { return ppu.getFrameBuffer(); } std::vector<short> Console::getAvailableSamples() { return apu.getAvailableSamples(); } void Console::runForOneFrame() { do { tick(); } while (!ppu.endOfFrame()); apu.endFrame(); } void Console::tick() { cpuDivider.tick(); if (cpuDivider.hasClocked()) { cpu.tick(); } ppu.tick(); } uint8_t Console::cpuRead(uint16_t addr) { if (addr < 0x2000) { return cpuRam[addr % 0x800]; } else if (addr < 0x4000) { int registerAddr = addr & 0x2007; switch (registerAddr) { case 0x2000: return cpuBusMDR; case 0x2001: return cpuBusMDR; case 0x2002: return ppu.getSTATUS(); case 0x2003: return cpuBusMDR; case 0x2004: return ppu.getOAMDATA(); case 0x2005: return cpuBusMDR; case 0x2006: return cpuBusMDR; case 0x2007: return ppu.getDATA(); } } else if (addr < 0x4018) { switch (addr) { case 0x4015: return apu.getStatus(); case 0x4016: return controller1.poll(); case 0x4017: return 0; // TODO: controller 2 } } else if (addr < 0x4020) { return cpuBusMDR; // disabled/unused APU test registers } else { return cart.readPrg(addr); } assert(!"Invalid code path"); return 0; } void Console::cpuWrite(uint16_t addr, uint8_t value) { cpuBusMDR = value; if (addr < 0x2000) { cpuRam[addr % 0x800] = value; } else if (addr < 0x4000) { int registerAddr = addr & 0x2007; switch (registerAddr) { case 0x2000: ppu.setCTRL(value); break; case 0x2001: ppu.setMASK(value); break; case 0x2002: break; // ppu status, read-only case 0x2003: ppu.setOAMADDR(value); break; case 0x2004: ppu.setOAMDATA(value); break; case 0x2005: ppu.setSCROLL(value); break; case 0x2006: ppu.setADDR(value); break; case 0x2007: ppu.setDATA(value); break; } } else if (addr < 0x4018) { switch (addr) { case 0x4014: { uint16_t startAddr = ((uint16_t)value) << 8; for (int i = 0; i < 256; ++i) { ppu.setOAMDATA(cpuRead(startAddr + i)); } cpu.suspend(514); } break; case 0x4016: controller1.setStrobe(!!(value & 0x1)); break; default: apu.writeRegister(addr, value); break; } } else if (addr < 0x4020) { return; // disabled/unused APU test registers } else { cart.writePrg(addr, value); } } <commit_msg>Replace modulo op with bitwise AND to compute cpuRam indices<commit_after>#include <string> #include <functional> #include <vector> #include <cassert> #include <Console.h> #include <CPU.h> #include <APU.h> #include <PPU.h> #include <Cart.h> #include <Controller.h> #include <Divider.h> void Console::boot() { ReadBus cpuReadCallback = [this] (uint16_t addr) { return cpuRead(addr); }; WriteBus cpuWriteCallback = [this] (uint16_t addr, uint8_t data) { cpuWrite(addr,data); }; NMI nmiCallback = [this] () {cpu.signalNMI();}; cpu.boot(cpuReadCallback, cpuWriteCallback); ppu.boot(&cart, nmiCallback); } void Console::loadINesFile(std::string fileName) { return cart.loadFile(fileName); } uint32_t *Console::getFrameBuffer() { return ppu.getFrameBuffer(); } std::vector<short> Console::getAvailableSamples() { return apu.getAvailableSamples(); } void Console::runForOneFrame() { do { tick(); } while (!ppu.endOfFrame()); apu.endFrame(); } void Console::tick() { cpuDivider.tick(); if (cpuDivider.hasClocked()) { cpu.tick(); } ppu.tick(); } uint8_t Console::cpuRead(uint16_t addr) { if (addr < 0x2000) { return cpuRam[addr & 0x07FF]; } else if (addr < 0x4000) { int registerAddr = addr & 0x2007; switch (registerAddr) { case 0x2000: return cpuBusMDR; case 0x2001: return cpuBusMDR; case 0x2002: return ppu.getSTATUS(); case 0x2003: return cpuBusMDR; case 0x2004: return ppu.getOAMDATA(); case 0x2005: return cpuBusMDR; case 0x2006: return cpuBusMDR; case 0x2007: return ppu.getDATA(); } } else if (addr < 0x4018) { switch (addr) { case 0x4015: return apu.getStatus(); case 0x4016: return controller1.poll(); case 0x4017: return 0; // TODO: controller 2 } } else if (addr < 0x4020) { return cpuBusMDR; // disabled/unused APU test registers } else { return cart.readPrg(addr); } assert(!"Invalid code path"); return 0; } void Console::cpuWrite(uint16_t addr, uint8_t value) { cpuBusMDR = value; if (addr < 0x2000) { cpuRam[addr & 0x07FF] = value; } else if (addr < 0x4000) { int registerAddr = addr & 0x2007; switch (registerAddr) { case 0x2000: ppu.setCTRL(value); break; case 0x2001: ppu.setMASK(value); break; case 0x2002: break; // ppu status, read-only case 0x2003: ppu.setOAMADDR(value); break; case 0x2004: ppu.setOAMDATA(value); break; case 0x2005: ppu.setSCROLL(value); break; case 0x2006: ppu.setADDR(value); break; case 0x2007: ppu.setDATA(value); break; } } else if (addr < 0x4018) { switch (addr) { case 0x4014: { uint16_t startAddr = ((uint16_t)value) << 8; for (int i = 0; i < 256; ++i) { ppu.setOAMDATA(cpuRead(startAddr + i)); } cpu.suspend(514); } break; case 0x4016: controller1.setStrobe(!!(value & 0x1)); break; default: apu.writeRegister(addr, value); break; } } else if (addr < 0x4020) { return; // disabled/unused APU test registers } else { cart.writePrg(addr, value); } } <|endoftext|>
<commit_before>#include <Context.h> #include <cmath> #include <iostream> using namespace std; using namespace canvas; void Context::resize(unsigned int _width, unsigned int _height) { getDefaultSurface().resize(_width, _height, (unsigned int)(_width * getDisplayScale()), (unsigned int)(_height * getDisplayScale()), getDefaultSurface().getFormat()); hit_regions.clear(); } Context & Context::fillRect(double x, double y, double w, double h) { beginPath().rect(x, y, w, h); return fill(); } Context & Context::strokeRect(double x, double y, double w, double h) { beginPath().rect(x, y, w, h); return stroke(); } Context & Context::clearRect(double x, double y, double w, double h) { Path2D path; path.moveTo(currentTransform.multiply(x, y)); path.lineTo(currentTransform.multiply(x + w, y)); path.lineTo(currentTransform.multiply(x + w, y + h)); path.lineTo(currentTransform.multiply(x, y + h)); path.closePath(); Style style(this); style = Color(0.0f, 0.0f, 0.0f, 0.0f); return renderPath(FILL, path, style, COPY); } Context & Context::renderText(RenderMode mode, const Style & style, const std::string & text, const Point & p, Operator op) { if (hasNativeShadows()) { getDefaultSurface().renderText(mode, font, style, textBaseline.getValue(), textAlign.getValue(), text, p, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), shadowBlur.getValue(), shadowOffsetX.getValue(), shadowOffsetY.getValue(), shadowColor.getValue(), clipPath); } else { if (hasShadow()) { float b = shadowBlur.getValue(), bs = shadowBlur.getValue() * getDisplayScale(); int bi = int(ceil(b)); auto shadow = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, R8); auto shadow2 = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, RGBA8); Style shadow_style(this); shadow_style = shadowColor.getValue(); shadow_style.color.alpha = 1.0f; shadow->renderText(mode, font, shadow_style, textBaseline.getValue(), textAlign.getValue(), text, Point(x + shadowOffsetX.getValue() + bi, y + shadowOffsetY.getValue() + bi), lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath); #if 1 shadow->slowBlur(bs, bs); #else shadow->blur(bs); #endif shadow->colorize(shadowColor.getValue(), *shadow2); getDefaultSurface().drawImage(*shadow2, -bi, -bi, shadow2->getActualWidth(), shadow2->getActualHeight(), getDisplayScale(), 1.0f, 0.0f, 0.0f, 0.0f, shadowColor.getValue(), Path2D(), false); } getDefaultSurface().renderText(mode, font, style, textBaseline.getValue(), textAlign.getValue(), text, p, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath); } return *this; } Context & Context::renderPath(RenderMode mode, const Path2D & path, const Style & style, Operator op) { if (hasNativeShadows()) { getDefaultSurface().renderPath(mode, path, style, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), shadowBlur.getValue(), shadowOffsetX.getValue(), shadowOffsetY.getValue(), shadowColor.getValue(), clipPath); } else { if (hasShadow()) { float b = shadowBlur.getValue(), bs = shadowBlur.getValue() * getDisplayScale(); float bi = int(ceil(b)); auto shadow = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, R8); auto shadow2 = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, RGBA8); Style shadow_style(this); shadow_style = shadowColor.getValue(); Path2D tmp_path = path, tmp_clipPath = clipPath; tmp_path.offset(shadowOffsetX.getValue() + bi, shadowOffsetY.getValue() + bi); tmp_clipPath.offset(shadowOffsetX.getValue() + bi, shadowOffsetY.getValue() + bi); shadow->renderPath(mode, tmp_path, shadow_style, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), 0, 0, 0, shadowColor.getValue(), tmp_clipPath); #if 1 shadow->slowBlur(bs, bs); #else shadow->blur(bs); #endif shadow->colorize(shadowColor.getValue(), *shadow2); getDefaultSurface().drawImage(*shadow2, -bi, -bi, shadow2->getActualWidth(), shadow2->getActualHeight(), getDisplayScale(), 1.0f, 0.0f, 0.0f, 0.0f, shadowColor.getValue(), Path2D(), false); } getDefaultSurface().renderPath(mode, path, style, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), 0, 0, 0, shadowColor.getValue(), clipPath); } return *this; } Context & Context::drawImage(Surface & img, double x, double y, double w, double h) { if (hasNativeShadows()) { getDefaultSurface().drawImage(img, x * getDisplayScale(), y * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), shadowBlur.getValue(), shadowOffsetX.getValue(), shadowOffsetY.getValue(), shadowColor.getValue(), clipPath, imageSmoothingEnabled.getValue()); } else { if (hasShadow()) { float b = shadowBlur.getValue(), bs = shadowBlur.getValue() * getDisplayScale(); float bi = int(ceil(b)); auto shadow = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, R8); auto shadow2 = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, RGBA8); shadow->drawImage(img, (x + bi + shadowOffsetX.getValue()) * getDisplayScale(), (y + bi + shadowOffsetY.getValue()) * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath, imageSmoothingEnabled.getValue()); // shadow->colorFill(shadowColor.getValue()); #if 1 shadow->slowBlur(bs, bs); #else shadow->blur(bs); #endif shadow->colorize(shadowColor.getValue(), *shadow2); getDefaultSurface().drawImage(*shadow2, -bi, -bi, shadow2->getActualWidth(), shadow2->getActualHeight(), getDisplayScale(), 1.0f, 0.0f, 0.0f, 0.0f, shadowColor.getValue(), Path2D(), false); } getDefaultSurface().drawImage(img, x * getDisplayScale(), y * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath, imageSmoothingEnabled.getValue()); } return *this; } Context & Context::drawImage(const Image & img, double x, double y, double w, double h) { if (hasNativeShadows()) { getDefaultSurface().drawImage(img, x * getDisplayScale(), y * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), shadowBlur.getValue(), shadowOffsetX.getValue(), shadowOffsetY.getValue(), shadowColor.getValue(), clipPath, imageSmoothingEnabled.getValue()); } else { if (hasShadow()) { float b = shadowBlur.getValue(), bs = shadowBlur.getValue() * getDisplayScale(); float bi = int(ceil(b)); auto shadow = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, R8); auto shadow2 = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, RGBA8); shadow->drawImage(img, (x + bi + shadowOffsetX.getValue()) * getDisplayScale(), (y + bi + shadowOffsetY.getValue()) * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath, imageSmoothingEnabled.getValue()); // shadow->colorFill(shadowColor.getValue()); #if 1 shadow->slowBlur(bs, bs); #else shadow->blur(bs); #endif shadow->colorize(shadowColor.getValue(), *shadow2); getDefaultSurface().drawImage(*shadow2, -bi, -bi, shadow2->getActualWidth(), shadow2->getActualHeight(), getDisplayScale(), 1.0f, 0.0f, 0.0f, 0.0f, shadowColor.getValue(), Path2D(), false); } getDefaultSurface().drawImage(img, x * getDisplayScale(), y * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath, imageSmoothingEnabled.getValue()); } return *this; } Context & Context::save() { restore_stack.push_back(*this); return *this; } Context & Context::restore() { if (!restore_stack.empty()) { *this = restore_stack.back(); restore_stack.pop_back(); } return *this; } <commit_msg>fix bug with position<commit_after>#include <Context.h> #include <cmath> #include <iostream> using namespace std; using namespace canvas; void Context::resize(unsigned int _width, unsigned int _height) { getDefaultSurface().resize(_width, _height, (unsigned int)(_width * getDisplayScale()), (unsigned int)(_height * getDisplayScale()), getDefaultSurface().getFormat()); hit_regions.clear(); } Context & Context::fillRect(double x, double y, double w, double h) { beginPath().rect(x, y, w, h); return fill(); } Context & Context::strokeRect(double x, double y, double w, double h) { beginPath().rect(x, y, w, h); return stroke(); } Context & Context::clearRect(double x, double y, double w, double h) { Path2D path; path.moveTo(currentTransform.multiply(x, y)); path.lineTo(currentTransform.multiply(x + w, y)); path.lineTo(currentTransform.multiply(x + w, y + h)); path.lineTo(currentTransform.multiply(x, y + h)); path.closePath(); Style style(this); style = Color(0.0f, 0.0f, 0.0f, 0.0f); return renderPath(FILL, path, style, COPY); } Context & Context::renderText(RenderMode mode, const Style & style, const std::string & text, const Point & p, Operator op) { if (hasNativeShadows()) { getDefaultSurface().renderText(mode, font, style, textBaseline.getValue(), textAlign.getValue(), text, p, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), shadowBlur.getValue(), shadowOffsetX.getValue(), shadowOffsetY.getValue(), shadowColor.getValue(), clipPath); } else { if (hasShadow()) { float b = shadowBlur.getValue(), bs = shadowBlur.getValue() * getDisplayScale(); int bi = int(ceil(b)); auto shadow = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, R8); auto shadow2 = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, RGBA8); Style shadow_style(this); shadow_style = shadowColor.getValue(); shadow_style.color.alpha = 1.0f; shadow->renderText(mode, font, shadow_style, textBaseline.getValue(), textAlign.getValue(), text, Point(p.x + shadowOffsetX.getValue() + bi, p.y + shadowOffsetY.getValue() + bi), lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath); #if 1 shadow->slowBlur(bs, bs); #else shadow->blur(bs); #endif shadow->colorize(shadowColor.getValue(), *shadow2); getDefaultSurface().drawImage(*shadow2, -bi, -bi, shadow2->getActualWidth(), shadow2->getActualHeight(), getDisplayScale(), 1.0f, 0.0f, 0.0f, 0.0f, shadowColor.getValue(), Path2D(), false); } getDefaultSurface().renderText(mode, font, style, textBaseline.getValue(), textAlign.getValue(), text, p, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath); } return *this; } Context & Context::renderPath(RenderMode mode, const Path2D & path, const Style & style, Operator op) { if (hasNativeShadows()) { getDefaultSurface().renderPath(mode, path, style, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), shadowBlur.getValue(), shadowOffsetX.getValue(), shadowOffsetY.getValue(), shadowColor.getValue(), clipPath); } else { if (hasShadow()) { float b = shadowBlur.getValue(), bs = shadowBlur.getValue() * getDisplayScale(); float bi = int(ceil(b)); auto shadow = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, R8); auto shadow2 = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, RGBA8); Style shadow_style(this); shadow_style = shadowColor.getValue(); Path2D tmp_path = path, tmp_clipPath = clipPath; tmp_path.offset(shadowOffsetX.getValue() + bi, shadowOffsetY.getValue() + bi); tmp_clipPath.offset(shadowOffsetX.getValue() + bi, shadowOffsetY.getValue() + bi); shadow->renderPath(mode, tmp_path, shadow_style, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), 0, 0, 0, shadowColor.getValue(), tmp_clipPath); #if 1 shadow->slowBlur(bs, bs); #else shadow->blur(bs); #endif shadow->colorize(shadowColor.getValue(), *shadow2); getDefaultSurface().drawImage(*shadow2, -bi, -bi, shadow2->getActualWidth(), shadow2->getActualHeight(), getDisplayScale(), 1.0f, 0.0f, 0.0f, 0.0f, shadowColor.getValue(), Path2D(), false); } getDefaultSurface().renderPath(mode, path, style, lineWidth.getValue(), op, getDisplayScale(), globalAlpha.getValue(), 0, 0, 0, shadowColor.getValue(), clipPath); } return *this; } Context & Context::drawImage(Surface & img, double x, double y, double w, double h) { if (hasNativeShadows()) { getDefaultSurface().drawImage(img, x * getDisplayScale(), y * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), shadowBlur.getValue(), shadowOffsetX.getValue(), shadowOffsetY.getValue(), shadowColor.getValue(), clipPath, imageSmoothingEnabled.getValue()); } else { if (hasShadow()) { float b = shadowBlur.getValue(), bs = shadowBlur.getValue() * getDisplayScale(); float bi = int(ceil(b)); auto shadow = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, R8); auto shadow2 = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, RGBA8); shadow->drawImage(img, (x + bi + shadowOffsetX.getValue()) * getDisplayScale(), (y + bi + shadowOffsetY.getValue()) * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath, imageSmoothingEnabled.getValue()); // shadow->colorFill(shadowColor.getValue()); #if 1 shadow->slowBlur(bs, bs); #else shadow->blur(bs); #endif shadow->colorize(shadowColor.getValue(), *shadow2); getDefaultSurface().drawImage(*shadow2, -bi, -bi, shadow2->getActualWidth(), shadow2->getActualHeight(), getDisplayScale(), 1.0f, 0.0f, 0.0f, 0.0f, shadowColor.getValue(), Path2D(), false); } getDefaultSurface().drawImage(img, x * getDisplayScale(), y * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath, imageSmoothingEnabled.getValue()); } return *this; } Context & Context::drawImage(const Image & img, double x, double y, double w, double h) { if (hasNativeShadows()) { getDefaultSurface().drawImage(img, x * getDisplayScale(), y * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), shadowBlur.getValue(), shadowOffsetX.getValue(), shadowOffsetY.getValue(), shadowColor.getValue(), clipPath, imageSmoothingEnabled.getValue()); } else { if (hasShadow()) { float b = shadowBlur.getValue(), bs = shadowBlur.getValue() * getDisplayScale(); float bi = int(ceil(b)); auto shadow = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, R8); auto shadow2 = createSurface(getDefaultSurface().getLogicalWidth() + 2 * bi, getDefaultSurface().getLogicalHeight() + 2 * bi, RGBA8); shadow->drawImage(img, (x + bi + shadowOffsetX.getValue()) * getDisplayScale(), (y + bi + shadowOffsetY.getValue()) * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath, imageSmoothingEnabled.getValue()); // shadow->colorFill(shadowColor.getValue()); #if 1 shadow->slowBlur(bs, bs); #else shadow->blur(bs); #endif shadow->colorize(shadowColor.getValue(), *shadow2); getDefaultSurface().drawImage(*shadow2, -bi, -bi, shadow2->getActualWidth(), shadow2->getActualHeight(), getDisplayScale(), 1.0f, 0.0f, 0.0f, 0.0f, shadowColor.getValue(), Path2D(), false); } getDefaultSurface().drawImage(img, x * getDisplayScale(), y * getDisplayScale(), w * getDisplayScale(), h * getDisplayScale(), getDisplayScale(), globalAlpha.getValue(), 0.0f, 0.0f, 0.0f, shadowColor.getValue(), clipPath, imageSmoothingEnabled.getValue()); } return *this; } Context & Context::save() { restore_stack.push_back(*this); return *this; } Context & Context::restore() { if (!restore_stack.empty()) { *this = restore_stack.back(); restore_stack.pop_back(); } return *this; } <|endoftext|>
<commit_before>// DepthOp.cpp /* * Copyright (c) 2009, Dan Heeks * This program is released under the BSD license. See the file COPYING for * details. */ #include "stdafx.h" #include "DepthOp.h" #include "CNCConfig.h" #include "ProgramCanvas.h" #include "Program.h" #include "interface/PropertyInt.h" #include "interface/PropertyDouble.h" #include "interface/PropertyLength.h" #include "tinyxml/tinyxml.h" #include "interface/Tool.h" CDepthOpParams::CDepthOpParams() { m_tool_number = 0; m_tool_diameter = 0.0; m_clearance_height = 0.0; m_start_depth = 0.0; m_step_down = 0.0; m_final_depth = 0.0; m_rapid_down_to_height = 0.0; m_horizontal_feed_rate = 0.0; m_vertical_feed_rate = 0.0; m_spindle_speed = 0.0; } void CDepthOpParams::set_initial_values() { CNCConfig config; config.Read(_T("DepthOpToolNumber"), &m_tool_number, 1); config.Read(_T("DepthOpToolDiameter"), &m_tool_diameter, 3.0); config.Read(_T("DepthOpClearanceHeight"), &m_clearance_height, 5.0); config.Read(_T("DepthOpStartDepth"), &m_start_depth, 0.0); config.Read(_T("DepthOpStepDown"), &m_step_down, 1.0); config.Read(_T("DepthOpFinalDepth"), &m_final_depth, -1.0); config.Read(_T("DepthOpRapidDown"), &m_rapid_down_to_height, 2.0); config.Read(_T("DepthOpHorizFeed"), &m_horizontal_feed_rate, 100.0); config.Read(_T("DepthOpVertFeed"), &m_vertical_feed_rate, 100.0); config.Read(_T("DepthOpSpindleSpeed"), &m_spindle_speed, 7000); } void CDepthOpParams::write_values_to_config() { CNCConfig config; config.Write(_T("DepthOpToolNumber"), m_tool_number); config.Write(_T("DepthOpToolDiameter"), m_tool_diameter); config.Write(_T("DepthOpClearanceHeight"), m_clearance_height); config.Write(_T("DepthOpStartDepth"), m_start_depth); config.Write(_T("DepthOpStepDown"), m_step_down); config.Write(_T("DepthOpFinalDepth"), m_final_depth); config.Write(_T("DepthOpRapidDown"), m_rapid_down_to_height); config.Write(_T("DepthOpHorizFeed"), m_horizontal_feed_rate); config.Write(_T("DepthOpVertFeed"), m_vertical_feed_rate); config.Write(_T("DepthOpSpindleSpeed"), m_spindle_speed); } static void on_set_tool_number(int value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_number = value;} static void on_set_tool_diameter(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_diameter = value;} static void on_set_clearance_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_clearance_height = value;} static void on_set_step_down(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_step_down = value;} static void on_set_start_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_start_depth = value;} static void on_set_final_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_final_depth = value;} static void on_set_rapid_down_to_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_rapid_down_to_height = value;} static void on_set_horizontal_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_horizontal_feed_rate = value;} static void on_set_vertical_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_vertical_feed_rate = value;} static void on_set_spindle_speed(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_spindle_speed = value;} void CDepthOpParams::GetProperties(CDepthOp* parent, std::list<Property *> *list) { list->push_back(new PropertyInt(_("tool number"), m_tool_number, parent, on_set_tool_number)); list->push_back(new PropertyLength(_("tool diameter"), m_tool_diameter, parent, on_set_tool_diameter)); list->push_back(new PropertyLength(_("clearance height"), m_clearance_height, parent, on_set_clearance_height)); list->push_back(new PropertyLength(_("step down"), m_step_down, parent, on_set_step_down)); list->push_back(new PropertyLength(_("start depth"), m_start_depth, parent, on_set_start_depth)); list->push_back(new PropertyLength(_("final depth"), m_final_depth, parent, on_set_final_depth)); list->push_back(new PropertyLength(_("rapid down to height"), m_rapid_down_to_height, parent, on_set_rapid_down_to_height)); list->push_back(new PropertyDouble(_("horizontal feed rate"), m_horizontal_feed_rate, parent, on_set_horizontal_feed_rate)); list->push_back(new PropertyDouble(_("vertical feed rate"), m_vertical_feed_rate, parent, on_set_vertical_feed_rate)); list->push_back(new PropertyDouble(_("spindle speed"), m_spindle_speed, parent, on_set_spindle_speed)); } void CDepthOpParams::WriteXMLAttributes(TiXmlNode* pElem) { TiXmlElement * element = new TiXmlElement( "depthop" ); pElem->LinkEndChild( element ); element->SetAttribute("tooln", m_tool_number); element->SetDoubleAttribute("toold", m_tool_diameter); element->SetDoubleAttribute("clear", m_clearance_height); element->SetDoubleAttribute("down", m_step_down); element->SetDoubleAttribute("startdepth", m_start_depth); element->SetDoubleAttribute("depth", m_final_depth); element->SetDoubleAttribute("r", m_rapid_down_to_height); element->SetDoubleAttribute("hfeed", m_horizontal_feed_rate); element->SetDoubleAttribute("vfeed", m_vertical_feed_rate); element->SetDoubleAttribute("spin", m_spindle_speed); } void CDepthOpParams::ReadFromXMLElement(TiXmlElement* pElem) { TiXmlElement* depthop = TiXmlHandle(pElem).FirstChildElement("depthop").Element(); if(depthop) { depthop->Attribute("tooln", &m_tool_number); depthop->Attribute("toold", &m_tool_diameter); depthop->Attribute("clear", &m_clearance_height); depthop->Attribute("down", &m_step_down); depthop->Attribute("startdepth", &m_start_depth); depthop->Attribute("depth", &m_final_depth); depthop->Attribute("r", &m_rapid_down_to_height); depthop->Attribute("hfeed", &m_horizontal_feed_rate); depthop->Attribute("vfeed", &m_vertical_feed_rate); depthop->Attribute("spin", &m_spindle_speed); } } void CDepthOp::WriteBaseXML(TiXmlElement *element) { m_depth_op_params.WriteXMLAttributes(element); COp::WriteBaseXML(element); } void CDepthOp::ReadBaseXML(TiXmlElement* element) { m_depth_op_params.ReadFromXMLElement(element); COp::ReadBaseXML(element); } void CDepthOp::GetProperties(std::list<Property *> *list) { m_depth_op_params.GetProperties(this, list); COp::GetProperties(list); } void CDepthOp::AppendTextToProgram() { COp::AppendTextToProgram(); theApp.m_program_canvas->AppendText(_T("clearance = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_clearance_height / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("rapid_down_to_height = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_rapid_down_to_height / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("start_depth = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_start_depth / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("step_down = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_step_down / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("final_depth = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_final_depth / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("tool_diameter = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_diameter / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("spindle(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_spindle_speed); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("feedrate(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_horizontal_feed_rate); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("tool_change(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_number); theApp.m_program_canvas->AppendText(_T(")\n")); } <commit_msg>line 167 should have been vertical feed instead of horizontal<commit_after>// DepthOp.cpp /* * Copyright (c) 2009, Dan Heeks * This program is released under the BSD license. See the file COPYING for * details. */ #include "stdafx.h" #include "DepthOp.h" #include "CNCConfig.h" #include "ProgramCanvas.h" #include "Program.h" #include "interface/PropertyInt.h" #include "interface/PropertyDouble.h" #include "interface/PropertyLength.h" #include "tinyxml/tinyxml.h" #include "interface/Tool.h" CDepthOpParams::CDepthOpParams() { m_tool_number = 0; m_tool_diameter = 0.0; m_clearance_height = 0.0; m_start_depth = 0.0; m_step_down = 0.0; m_final_depth = 0.0; m_rapid_down_to_height = 0.0; m_horizontal_feed_rate = 0.0; m_vertical_feed_rate = 0.0; m_spindle_speed = 0.0; } void CDepthOpParams::set_initial_values() { CNCConfig config; config.Read(_T("DepthOpToolNumber"), &m_tool_number, 1); config.Read(_T("DepthOpToolDiameter"), &m_tool_diameter, 3.0); config.Read(_T("DepthOpClearanceHeight"), &m_clearance_height, 5.0); config.Read(_T("DepthOpStartDepth"), &m_start_depth, 0.0); config.Read(_T("DepthOpStepDown"), &m_step_down, 1.0); config.Read(_T("DepthOpFinalDepth"), &m_final_depth, -1.0); config.Read(_T("DepthOpRapidDown"), &m_rapid_down_to_height, 2.0); config.Read(_T("DepthOpHorizFeed"), &m_horizontal_feed_rate, 100.0); config.Read(_T("DepthOpVertFeed"), &m_vertical_feed_rate, 100.0); config.Read(_T("DepthOpSpindleSpeed"), &m_spindle_speed, 7000); } void CDepthOpParams::write_values_to_config() { CNCConfig config; config.Write(_T("DepthOpToolNumber"), m_tool_number); config.Write(_T("DepthOpToolDiameter"), m_tool_diameter); config.Write(_T("DepthOpClearanceHeight"), m_clearance_height); config.Write(_T("DepthOpStartDepth"), m_start_depth); config.Write(_T("DepthOpStepDown"), m_step_down); config.Write(_T("DepthOpFinalDepth"), m_final_depth); config.Write(_T("DepthOpRapidDown"), m_rapid_down_to_height); config.Write(_T("DepthOpHorizFeed"), m_horizontal_feed_rate); config.Write(_T("DepthOpVertFeed"), m_vertical_feed_rate); config.Write(_T("DepthOpSpindleSpeed"), m_spindle_speed); } static void on_set_tool_number(int value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_number = value;} static void on_set_tool_diameter(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_diameter = value;} static void on_set_clearance_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_clearance_height = value;} static void on_set_step_down(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_step_down = value;} static void on_set_start_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_start_depth = value;} static void on_set_final_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_final_depth = value;} static void on_set_rapid_down_to_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_rapid_down_to_height = value;} static void on_set_horizontal_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_horizontal_feed_rate = value;} static void on_set_vertical_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_vertical_feed_rate = value;} static void on_set_spindle_speed(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_spindle_speed = value;} void CDepthOpParams::GetProperties(CDepthOp* parent, std::list<Property *> *list) { list->push_back(new PropertyInt(_("tool number"), m_tool_number, parent, on_set_tool_number)); list->push_back(new PropertyLength(_("tool diameter"), m_tool_diameter, parent, on_set_tool_diameter)); list->push_back(new PropertyLength(_("clearance height"), m_clearance_height, parent, on_set_clearance_height)); list->push_back(new PropertyLength(_("step down"), m_step_down, parent, on_set_step_down)); list->push_back(new PropertyLength(_("start depth"), m_start_depth, parent, on_set_start_depth)); list->push_back(new PropertyLength(_("final depth"), m_final_depth, parent, on_set_final_depth)); list->push_back(new PropertyLength(_("rapid down to height"), m_rapid_down_to_height, parent, on_set_rapid_down_to_height)); list->push_back(new PropertyDouble(_("horizontal feed rate"), m_horizontal_feed_rate, parent, on_set_horizontal_feed_rate)); list->push_back(new PropertyDouble(_("vertical feed rate"), m_vertical_feed_rate, parent, on_set_vertical_feed_rate)); list->push_back(new PropertyDouble(_("spindle speed"), m_spindle_speed, parent, on_set_spindle_speed)); } void CDepthOpParams::WriteXMLAttributes(TiXmlNode* pElem) { TiXmlElement * element = new TiXmlElement( "depthop" ); pElem->LinkEndChild( element ); element->SetAttribute("tooln", m_tool_number); element->SetDoubleAttribute("toold", m_tool_diameter); element->SetDoubleAttribute("clear", m_clearance_height); element->SetDoubleAttribute("down", m_step_down); element->SetDoubleAttribute("startdepth", m_start_depth); element->SetDoubleAttribute("depth", m_final_depth); element->SetDoubleAttribute("r", m_rapid_down_to_height); element->SetDoubleAttribute("hfeed", m_horizontal_feed_rate); element->SetDoubleAttribute("vfeed", m_vertical_feed_rate); element->SetDoubleAttribute("spin", m_spindle_speed); } void CDepthOpParams::ReadFromXMLElement(TiXmlElement* pElem) { TiXmlElement* depthop = TiXmlHandle(pElem).FirstChildElement("depthop").Element(); if(depthop) { depthop->Attribute("tooln", &m_tool_number); depthop->Attribute("toold", &m_tool_diameter); depthop->Attribute("clear", &m_clearance_height); depthop->Attribute("down", &m_step_down); depthop->Attribute("startdepth", &m_start_depth); depthop->Attribute("depth", &m_final_depth); depthop->Attribute("r", &m_rapid_down_to_height); depthop->Attribute("hfeed", &m_horizontal_feed_rate); depthop->Attribute("vfeed", &m_vertical_feed_rate); depthop->Attribute("spin", &m_spindle_speed); } } void CDepthOp::WriteBaseXML(TiXmlElement *element) { m_depth_op_params.WriteXMLAttributes(element); COp::WriteBaseXML(element); } void CDepthOp::ReadBaseXML(TiXmlElement* element) { m_depth_op_params.ReadFromXMLElement(element); COp::ReadBaseXML(element); } void CDepthOp::GetProperties(std::list<Property *> *list) { m_depth_op_params.GetProperties(this, list); COp::GetProperties(list); } void CDepthOp::AppendTextToProgram() { COp::AppendTextToProgram(); theApp.m_program_canvas->AppendText(_T("clearance = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_clearance_height / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("rapid_down_to_height = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_rapid_down_to_height / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("start_depth = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_start_depth / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("step_down = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_step_down / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("final_depth = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_final_depth / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("tool_diameter = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_diameter / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("spindle(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_spindle_speed); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("feedrate(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_vertical_feed_rate); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("tool_change(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_number); theApp.m_program_canvas->AppendText(_T(")\n")); } <|endoftext|>
<commit_before>// DepthOp.cpp /* * Copyright (c) 2009, Dan Heeks * This program is released under the BSD license. See the file COPYING for * details. */ #include "stdafx.h" #include "DepthOp.h" #include "CNCConfig.h" #include "ProgramCanvas.h" #include "Program.h" #include "interface/PropertyInt.h" #include "interface/PropertyDouble.h" #include "interface/PropertyLength.h" #include "tinyxml/tinyxml.h" #include "interface/Tool.h" CDepthOpParams::CDepthOpParams() { m_tool_number = 0; m_tool_diameter = 0.0; m_clearance_height = 0.0; m_start_depth = 0.0; m_step_down = 0.0; m_final_depth = 0.0; m_rapid_down_to_height = 0.0; m_horizontal_feed_rate = 0.0; m_vertical_feed_rate = 0.0; m_spindle_speed = 0.0; } void CDepthOpParams::set_initial_values() { CNCConfig config; config.Read(_T("DepthOpToolNumber"), &m_tool_number, 1); config.Read(_T("DepthOpToolDiameter"), &m_tool_diameter, 3.0); config.Read(_T("DepthOpClearanceHeight"), &m_clearance_height, 5.0); config.Read(_T("DepthOpStartDepth"), &m_start_depth, 0.0); config.Read(_T("DepthOpStepDown"), &m_step_down, 1.0); config.Read(_T("DepthOpFinalDepth"), &m_final_depth, -1.0); config.Read(_T("DepthOpRapidDown"), &m_rapid_down_to_height, 2.0); config.Read(_T("DepthOpHorizFeed"), &m_horizontal_feed_rate, 100.0); config.Read(_T("DepthOpVertFeed"), &m_vertical_feed_rate, 100.0); config.Read(_T("DepthOpSpindleSpeed"), &m_spindle_speed, 7000); } void CDepthOpParams::write_values_to_config() { CNCConfig config; config.Write(_T("DepthOpToolNumber"), m_tool_number); config.Write(_T("DepthOpToolDiameter"), m_tool_diameter); config.Write(_T("DepthOpClearanceHeight"), m_clearance_height); config.Write(_T("DepthOpStartDepth"), m_start_depth); config.Write(_T("DepthOpStepDown"), m_step_down); config.Write(_T("DepthOpFinalDepth"), m_final_depth); config.Write(_T("DepthOpRapidDown"), m_rapid_down_to_height); config.Write(_T("DepthOpHorizFeed"), m_horizontal_feed_rate); config.Write(_T("DepthOpVertFeed"), m_vertical_feed_rate); config.Write(_T("DepthOpSpindleSpeed"), m_spindle_speed); } static void on_set_tool_number(int value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_number = value;} static void on_set_tool_diameter(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_diameter = value;} static void on_set_clearance_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_clearance_height = value;} static void on_set_step_down(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_step_down = value;} static void on_set_start_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_start_depth = value;} static void on_set_final_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_final_depth = value;} static void on_set_rapid_down_to_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_rapid_down_to_height = value;} static void on_set_horizontal_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_horizontal_feed_rate = value;} static void on_set_vertical_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_vertical_feed_rate = value;} static void on_set_spindle_speed(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_spindle_speed = value;} void CDepthOpParams::GetProperties(CDepthOp* parent, std::list<Property *> *list) { list->push_back(new PropertyInt(_("tool number"), m_tool_number, parent, on_set_tool_number)); list->push_back(new PropertyLength(_("tool diameter"), m_tool_diameter, parent, on_set_tool_diameter)); list->push_back(new PropertyLength(_("clearance height"), m_clearance_height, parent, on_set_clearance_height)); list->push_back(new PropertyLength(_("step down"), m_step_down, parent, on_set_step_down)); list->push_back(new PropertyLength(_("start depth"), m_start_depth, parent, on_set_start_depth)); list->push_back(new PropertyLength(_("final depth"), m_final_depth, parent, on_set_final_depth)); list->push_back(new PropertyLength(_("rapid down to height"), m_rapid_down_to_height, parent, on_set_rapid_down_to_height)); list->push_back(new PropertyDouble(_("horizontal feed rate"), m_horizontal_feed_rate, parent, on_set_horizontal_feed_rate)); list->push_back(new PropertyDouble(_("vertical feed rate"), m_vertical_feed_rate, parent, on_set_vertical_feed_rate)); list->push_back(new PropertyDouble(_("spindle speed"), m_spindle_speed, parent, on_set_spindle_speed)); } void CDepthOpParams::WriteXMLAttributes(TiXmlNode* pElem) { TiXmlElement * element = new TiXmlElement( "depthop" ); pElem->LinkEndChild( element ); element->SetAttribute("tooln", m_tool_number); element->SetDoubleAttribute("toold", m_tool_diameter); element->SetDoubleAttribute("clear", m_clearance_height); element->SetDoubleAttribute("down", m_step_down); element->SetDoubleAttribute("startdepth", m_start_depth); element->SetDoubleAttribute("depth", m_final_depth); element->SetDoubleAttribute("r", m_rapid_down_to_height); element->SetDoubleAttribute("hfeed", m_horizontal_feed_rate); element->SetDoubleAttribute("vfeed", m_vertical_feed_rate); element->SetDoubleAttribute("spin", m_spindle_speed); } void CDepthOpParams::ReadFromXMLElement(TiXmlElement* pElem) { TiXmlElement* depthop = TiXmlHandle(pElem).FirstChildElement("depthop").Element(); if(depthop) { depthop->Attribute("tooln", &m_tool_number); depthop->Attribute("toold", &m_tool_diameter); depthop->Attribute("clear", &m_clearance_height); depthop->Attribute("down", &m_step_down); depthop->Attribute("startdepth", &m_start_depth); depthop->Attribute("depth", &m_final_depth); depthop->Attribute("r", &m_rapid_down_to_height); depthop->Attribute("hfeed", &m_horizontal_feed_rate); depthop->Attribute("vfeed", &m_vertical_feed_rate); depthop->Attribute("spin", &m_spindle_speed); } } void CDepthOp::WriteBaseXML(TiXmlElement *element) { m_depth_op_params.WriteXMLAttributes(element); COp::WriteBaseXML(element); } void CDepthOp::ReadBaseXML(TiXmlElement* element) { m_depth_op_params.ReadFromXMLElement(element); COp::ReadBaseXML(element); } void CDepthOp::GetProperties(std::list<Property *> *list) { m_depth_op_params.GetProperties(this, list); COp::GetProperties(list); } void CDepthOp::AppendTextToProgram() { COp::AppendTextToProgram(); theApp.m_program_canvas->AppendText(_T("clearance = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_clearance_height / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("clearance = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_clearance_height / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("rapid_down_to_height = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_rapid_down_to_height / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("start_depth = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_start_depth / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("step_down = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_step_down / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("final_depth = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_final_depth / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("tool_diameter = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_diameter / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("spindle(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_spindle_speed); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("feedrate(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_horizontal_feed_rate); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("tool_change(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_number); theApp.m_program_canvas->AppendText(_T(")\n")); } <commit_msg>duplicate "clearance" python script written<commit_after>// DepthOp.cpp /* * Copyright (c) 2009, Dan Heeks * This program is released under the BSD license. See the file COPYING for * details. */ #include "stdafx.h" #include "DepthOp.h" #include "CNCConfig.h" #include "ProgramCanvas.h" #include "Program.h" #include "interface/PropertyInt.h" #include "interface/PropertyDouble.h" #include "interface/PropertyLength.h" #include "tinyxml/tinyxml.h" #include "interface/Tool.h" CDepthOpParams::CDepthOpParams() { m_tool_number = 0; m_tool_diameter = 0.0; m_clearance_height = 0.0; m_start_depth = 0.0; m_step_down = 0.0; m_final_depth = 0.0; m_rapid_down_to_height = 0.0; m_horizontal_feed_rate = 0.0; m_vertical_feed_rate = 0.0; m_spindle_speed = 0.0; } void CDepthOpParams::set_initial_values() { CNCConfig config; config.Read(_T("DepthOpToolNumber"), &m_tool_number, 1); config.Read(_T("DepthOpToolDiameter"), &m_tool_diameter, 3.0); config.Read(_T("DepthOpClearanceHeight"), &m_clearance_height, 5.0); config.Read(_T("DepthOpStartDepth"), &m_start_depth, 0.0); config.Read(_T("DepthOpStepDown"), &m_step_down, 1.0); config.Read(_T("DepthOpFinalDepth"), &m_final_depth, -1.0); config.Read(_T("DepthOpRapidDown"), &m_rapid_down_to_height, 2.0); config.Read(_T("DepthOpHorizFeed"), &m_horizontal_feed_rate, 100.0); config.Read(_T("DepthOpVertFeed"), &m_vertical_feed_rate, 100.0); config.Read(_T("DepthOpSpindleSpeed"), &m_spindle_speed, 7000); } void CDepthOpParams::write_values_to_config() { CNCConfig config; config.Write(_T("DepthOpToolNumber"), m_tool_number); config.Write(_T("DepthOpToolDiameter"), m_tool_diameter); config.Write(_T("DepthOpClearanceHeight"), m_clearance_height); config.Write(_T("DepthOpStartDepth"), m_start_depth); config.Write(_T("DepthOpStepDown"), m_step_down); config.Write(_T("DepthOpFinalDepth"), m_final_depth); config.Write(_T("DepthOpRapidDown"), m_rapid_down_to_height); config.Write(_T("DepthOpHorizFeed"), m_horizontal_feed_rate); config.Write(_T("DepthOpVertFeed"), m_vertical_feed_rate); config.Write(_T("DepthOpSpindleSpeed"), m_spindle_speed); } static void on_set_tool_number(int value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_number = value;} static void on_set_tool_diameter(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_tool_diameter = value;} static void on_set_clearance_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_clearance_height = value;} static void on_set_step_down(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_step_down = value;} static void on_set_start_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_start_depth = value;} static void on_set_final_depth(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_final_depth = value;} static void on_set_rapid_down_to_height(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_rapid_down_to_height = value;} static void on_set_horizontal_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_horizontal_feed_rate = value;} static void on_set_vertical_feed_rate(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_vertical_feed_rate = value;} static void on_set_spindle_speed(double value, HeeksObj* object){((CDepthOp*)object)->m_depth_op_params.m_spindle_speed = value;} void CDepthOpParams::GetProperties(CDepthOp* parent, std::list<Property *> *list) { list->push_back(new PropertyInt(_("tool number"), m_tool_number, parent, on_set_tool_number)); list->push_back(new PropertyLength(_("tool diameter"), m_tool_diameter, parent, on_set_tool_diameter)); list->push_back(new PropertyLength(_("clearance height"), m_clearance_height, parent, on_set_clearance_height)); list->push_back(new PropertyLength(_("step down"), m_step_down, parent, on_set_step_down)); list->push_back(new PropertyLength(_("start depth"), m_start_depth, parent, on_set_start_depth)); list->push_back(new PropertyLength(_("final depth"), m_final_depth, parent, on_set_final_depth)); list->push_back(new PropertyLength(_("rapid down to height"), m_rapid_down_to_height, parent, on_set_rapid_down_to_height)); list->push_back(new PropertyDouble(_("horizontal feed rate"), m_horizontal_feed_rate, parent, on_set_horizontal_feed_rate)); list->push_back(new PropertyDouble(_("vertical feed rate"), m_vertical_feed_rate, parent, on_set_vertical_feed_rate)); list->push_back(new PropertyDouble(_("spindle speed"), m_spindle_speed, parent, on_set_spindle_speed)); } void CDepthOpParams::WriteXMLAttributes(TiXmlNode* pElem) { TiXmlElement * element = new TiXmlElement( "depthop" ); pElem->LinkEndChild( element ); element->SetAttribute("tooln", m_tool_number); element->SetDoubleAttribute("toold", m_tool_diameter); element->SetDoubleAttribute("clear", m_clearance_height); element->SetDoubleAttribute("down", m_step_down); element->SetDoubleAttribute("startdepth", m_start_depth); element->SetDoubleAttribute("depth", m_final_depth); element->SetDoubleAttribute("r", m_rapid_down_to_height); element->SetDoubleAttribute("hfeed", m_horizontal_feed_rate); element->SetDoubleAttribute("vfeed", m_vertical_feed_rate); element->SetDoubleAttribute("spin", m_spindle_speed); } void CDepthOpParams::ReadFromXMLElement(TiXmlElement* pElem) { TiXmlElement* depthop = TiXmlHandle(pElem).FirstChildElement("depthop").Element(); if(depthop) { depthop->Attribute("tooln", &m_tool_number); depthop->Attribute("toold", &m_tool_diameter); depthop->Attribute("clear", &m_clearance_height); depthop->Attribute("down", &m_step_down); depthop->Attribute("startdepth", &m_start_depth); depthop->Attribute("depth", &m_final_depth); depthop->Attribute("r", &m_rapid_down_to_height); depthop->Attribute("hfeed", &m_horizontal_feed_rate); depthop->Attribute("vfeed", &m_vertical_feed_rate); depthop->Attribute("spin", &m_spindle_speed); } } void CDepthOp::WriteBaseXML(TiXmlElement *element) { m_depth_op_params.WriteXMLAttributes(element); COp::WriteBaseXML(element); } void CDepthOp::ReadBaseXML(TiXmlElement* element) { m_depth_op_params.ReadFromXMLElement(element); COp::ReadBaseXML(element); } void CDepthOp::GetProperties(std::list<Property *> *list) { m_depth_op_params.GetProperties(this, list); COp::GetProperties(list); } void CDepthOp::AppendTextToProgram() { COp::AppendTextToProgram(); theApp.m_program_canvas->AppendText(_T("clearance = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_clearance_height / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("rapid_down_to_height = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_rapid_down_to_height / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("start_depth = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_start_depth / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("step_down = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_step_down / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("final_depth = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_final_depth / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("tool_diameter = float(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_diameter / theApp.m_program->m_units); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("spindle(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_spindle_speed); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("feedrate(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_horizontal_feed_rate); theApp.m_program_canvas->AppendText(_T(")\n")); theApp.m_program_canvas->AppendText(_T("tool_change(")); theApp.m_program_canvas->AppendText(m_depth_op_params.m_tool_number); theApp.m_program_canvas->AppendText(_T(")\n")); } <|endoftext|>
<commit_before>#include <Element.h> #include <FWPlatform.h> #include <TextLabel.h> #include <LinearLayout.h> #include <Command.h> using namespace std; Element::~Element() { if (isInitialized()) { sendCommand(Command(Command::DELETE_ELEMENT, getParentInternalId(), getInternalId())); } } void Element::initialize(FWPlatform * _platform) { platform = _platform; internal_id = platform->getNextInternalId(); } void Element::sendCommand(const Command & command){ platform->sendCommand(command); } Element & Element::addChild(const std::string & text) { return addChild(make_shared<TextLabel>(text)); } LinearLayout & Element::addHorizontalLayout() { auto l = make_shared<LinearLayout>(FW_HORIZONTAL); addChild(l); return *l; } LinearLayout & Element::addVerticalLayout() { auto l = make_shared<LinearLayout>(FW_VERTICAL); addChild(l); return *l; } void Element::onEvent(EventBase & ev) { if (parent && !ev.isHandled()) { ev.dispatch(*parent); } } void Element::showMessageDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_MESSAGE_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); } std::string Element::showInputDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_INPUT_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); return platform->getModalResultText(); } <commit_msg>add assertion<commit_after>#include <Element.h> #include <FWPlatform.h> #include <TextLabel.h> #include <LinearLayout.h> #include <Command.h> #include <cassert> using namespace std; Element::~Element() { if (isInitialized()) { sendCommand(Command(Command::DELETE_ELEMENT, getParentInternalId(), getInternalId())); } } void Element::initialize(FWPlatform * _platform) { platform = _platform; internal_id = platform->getNextInternalId(); } void Element::sendCommand(const Command & command){ assert(this != platform); platform->sendCommand(command); } Element & Element::addChild(const std::string & text) { return addChild(make_shared<TextLabel>(text)); } LinearLayout & Element::addHorizontalLayout() { auto l = make_shared<LinearLayout>(FW_HORIZONTAL); addChild(l); return *l; } LinearLayout & Element::addVerticalLayout() { auto l = make_shared<LinearLayout>(FW_VERTICAL); addChild(l); return *l; } void Element::onEvent(EventBase & ev) { if (parent && !ev.isHandled()) { ev.dispatch(*parent); } } void Element::showMessageDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_MESSAGE_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); } std::string Element::showInputDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_INPUT_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); return platform->getModalResultText(); } <|endoftext|>
<commit_before>#include "FastPID.h" #include <Arduino.h> FastPID::~FastPID() { } void FastPID::clear() { _last_sp = 0; _last_out = 0; _sum = 0; _last_err = 0; _cfg_err = false; } bool FastPID::setCoefficients(float kp, float ki, float kd, float hz) { _p = floatToParam(kp); _i = floatToParam(ki / hz); _d = floatToParam(kd * hz); return ! _cfg_err; } bool FastPID::setOutputConfig(int bits, bool sign) { // Set output bits if (bits > 16 || bits < 1) { setCfgErr(); } else { if (bits == 16) { _outmax = (0xFFFFULL >> (17 - bits)) * PARAM_MULT; } else{ _outmax = (0xFFFFULL >> (16 - bits)) * PARAM_MULT; } if (sign) { _outmin = -((0xFFFFULL >> (17 - bits)) + 1) * PARAM_MULT; } else { _outmin = 0; } } return ! _cfg_err; } bool FastPID::setOutputRange(int16_t min, int16_t max) { if (min >= max) { setCfgErr(); return ! _cfg_err; } _outmin = int64_t(min) * PARAM_MULT; _outmax = int64_t(max) * PARAM_MULT; return ! _cfg_err; } bool FastPID::configure(float kp, float ki, float kd, float hz, int bits, bool sign) { clear(); setCoefficients(kp, ki, kd, hz); setOutputConfig(bits, sign); return ! _cfg_err; } uint32_t FastPID::floatToParam(float in) { if (in > PARAM_MAX || in < 0) { _cfg_err = true; return 0; } uint32_t param = in * PARAM_MULT; if (in != 0 && param == 0) { _cfg_err = true; return 0; } return param; } int16_t FastPID::step(int16_t sp, int16_t fb) { // int16 + int16 = int17 int32_t err = int32_t(sp) - int32_t(fb); int32_t P = 0, I = 0; int32_t D = 0; if (_p) { // uint16 * int16 = int32 P = int32_t(_p) * int32_t(err); } if (_i) { // int17 * int16 = int33 _sum += int64_t(err) * int64_t(_i); // Limit sum to 32-bit signed value so that it saturates, never overflows. if (_sum > INTEG_MAX) _sum = INTEG_MAX; else if (_sum < INTEG_MIN) _sum = INTEG_MIN; // int32 I = _sum; } if (_d) { // (int17 - int16) - (int16 - int16) = int19 int32_t deriv = (err - _last_err) - int32_t(sp - _last_sp); _last_sp = sp; _last_err = err; // Limit the derivative to 16-bit signed value. if (deriv > DERIV_MAX) deriv = DERIV_MAX; else if (deriv < DERIV_MIN) deriv = DERIV_MIN; // int16 * int16 = int32 D = int32_t(_d) * int32_t(deriv); } // int32 (P) + int32 (I) + int32 (D) = int34 int64_t out = int64_t(P) + int64_t(I) + int64_t(D); // Make the output saturate if (out > _outmax) out = _outmax; else if (out < _outmin) out = _outmin; // Remove the integer scaling factor. int16_t rval = out >> PARAM_SHIFT; // Fair rounding. if (out & (0x1ULL << (PARAM_SHIFT - 1))) { rval++; } return rval; } void FastPID::setCfgErr() { _cfg_err = true; _p = _i = _d = 0; } <commit_msg>The clear() funciton should not reset the error flag.<commit_after>#include "FastPID.h" #include <Arduino.h> FastPID::~FastPID() { } void FastPID::clear() { _last_sp = 0; _last_out = 0; _sum = 0; _last_err = 0; } bool FastPID::setCoefficients(float kp, float ki, float kd, float hz) { _p = floatToParam(kp); _i = floatToParam(ki / hz); _d = floatToParam(kd * hz); return ! _cfg_err; } bool FastPID::setOutputConfig(int bits, bool sign) { // Set output bits if (bits > 16 || bits < 1) { setCfgErr(); } else { if (bits == 16) { _outmax = (0xFFFFULL >> (17 - bits)) * PARAM_MULT; } else{ _outmax = (0xFFFFULL >> (16 - bits)) * PARAM_MULT; } if (sign) { _outmin = -((0xFFFFULL >> (17 - bits)) + 1) * PARAM_MULT; } else { _outmin = 0; } } return ! _cfg_err; } bool FastPID::setOutputRange(int16_t min, int16_t max) { if (min >= max) { setCfgErr(); return ! _cfg_err; } _outmin = int64_t(min) * PARAM_MULT; _outmax = int64_t(max) * PARAM_MULT; return ! _cfg_err; } bool FastPID::configure(float kp, float ki, float kd, float hz, int bits, bool sign) { clear(); _cfg_err = false; setCoefficients(kp, ki, kd, hz); setOutputConfig(bits, sign); return ! _cfg_err; } uint32_t FastPID::floatToParam(float in) { if (in > PARAM_MAX || in < 0) { _cfg_err = true; return 0; } uint32_t param = in * PARAM_MULT; if (in != 0 && param == 0) { _cfg_err = true; return 0; } return param; } int16_t FastPID::step(int16_t sp, int16_t fb) { // int16 + int16 = int17 int32_t err = int32_t(sp) - int32_t(fb); int32_t P = 0, I = 0; int32_t D = 0; if (_p) { // uint16 * int16 = int32 P = int32_t(_p) * int32_t(err); } if (_i) { // int17 * int16 = int33 _sum += int64_t(err) * int64_t(_i); // Limit sum to 32-bit signed value so that it saturates, never overflows. if (_sum > INTEG_MAX) _sum = INTEG_MAX; else if (_sum < INTEG_MIN) _sum = INTEG_MIN; // int32 I = _sum; } if (_d) { // (int17 - int16) - (int16 - int16) = int19 int32_t deriv = (err - _last_err) - int32_t(sp - _last_sp); _last_sp = sp; _last_err = err; // Limit the derivative to 16-bit signed value. if (deriv > DERIV_MAX) deriv = DERIV_MAX; else if (deriv < DERIV_MIN) deriv = DERIV_MIN; // int16 * int16 = int32 D = int32_t(_d) * int32_t(deriv); } // int32 (P) + int32 (I) + int32 (D) = int34 int64_t out = int64_t(P) + int64_t(I) + int64_t(D); // Make the output saturate if (out > _outmax) out = _outmax; else if (out < _outmin) out = _outmin; // Remove the integer scaling factor. int16_t rval = out >> PARAM_SHIFT; // Fair rounding. if (out & (0x1ULL << (PARAM_SHIFT - 1))) { rval++; } return rval; } void FastPID::setCfgErr() { _cfg_err = true; _p = _i = _d = 0; } <|endoftext|>
<commit_before>#include <getopt.h> #include "dlib/bam_util.h" int usage(char **argv, int retcode=EXIT_FAILURE) { fprintf(stderr, "MASKRIPPER version %s.\n" "Usage: maskripper <opts> in.bam out.bam\n" "Flags:\n-m: Minimum trimmed read length. Default: 0.\n" "-n: Skip reads composed of all Ns. Default: False.\n" "-l: output compression level. Default: 6.\n" "-S: output in sam format.\n" "-s: perform single-end analysis. This option results in imbalanced pairs on paired-end data.\n" "Use - for stdin or stdout.\n", MASKRIPPER_VERSION); return retcode; } struct opts_t { uint8_t *data; uint32_t l_data:16; uint32_t m_data:16; uint32_t min_trimmed_len:8; uint32_t skip_all_ns:1; ~opts_t() {if(data) free(data);} opts_t(): data(nullptr), l_data(0), m_data(0), min_trimmed_len(0), skip_all_ns(0) {} void resize(uint32_t new_min) { if(new_min > m_data) { m_data = new_min; kroundup32(m_data); data = (uint8_t *)realloc(data, m_data * sizeof(uint8_t)); } } }; static int trim_ns(bam1_t *b, void *data) { int ret = 0; opts_t *op((opts_t *)data); std::vector<uint8_t> aux(bam_get_aux(b), bam_get_aux(b) + bam_get_l_aux(b)); int tmp; uint8_t *const seq(bam_get_seq(b)); uint32_t *const cigar(bam_get_cigar(b)); //op->n_cigar = b->core.n_cigar; op->resize(b->l_data); // Make sure it's big enough to hold everything. memcpy(op->data, b->data, b->core.l_qname); // Get #Ns at the beginning for(tmp = 0; bam_seqi(seq, tmp) == dlib::htseq::HTS_N; ++tmp); const int n_start(tmp); if(tmp == b->core.l_qseq - 1) // all bases are N -- garbage read ret |= op->skip_all_ns; // Get #Ns at the end for(tmp = b->core.l_qseq - 1; bam_seqi(seq, tmp) == dlib::htseq::HTS_N; --tmp); const int n_end(b->core.l_qseq - 1 - tmp); // Get new length for read int final_len(b->core.l_qseq - n_end - n_start); if(final_len < 0) final_len = 0; if(final_len < op->min_trimmed_len) // Too short. ret |= 1; // Copy in qual and all of aux. if(n_end) { if((tmp = bam_cigar_oplen(cigar[b->core.n_cigar - 1]) - n_end) == 0) { LOG_DEBUG("Entire cigar operation is the softclip. Decrease the number of new cigar operations.\n"); --b->core.n_cigar; } else { LOG_DEBUG("Updating second cigar operation in-place.\n"); cigar[b->core.n_cigar - 1] = bam_cigar_gen(tmp, BAM_CSOFT_CLIP); } } // Get new n_cigar. if((tmp = bam_cigar_oplen(*cigar) - n_start) == 0) { memcpy(op->data + b->core.l_qname, cigar + 1, (--b->core.n_cigar) << 2); // << 2 for 4 bit per cigar op } else { if(n_start) *cigar = bam_cigar_gen(tmp, BAM_CSOFT_CLIP); memcpy(op->data + b->core.l_qname, cigar, b->core.n_cigar << 2); } uint8_t *opseq(op->data + b->core.l_qname + (b->core.n_cigar << 2)); // Pointer to the seq region of new data field. for(tmp = 0; tmp < final_len >> 1; ++tmp) opseq[tmp] = (bam_seqi(seq, ((tmp << 1) + n_start)) << 4) | (bam_seqi(seq, (tmp << 1) + n_start + 1)); if(final_len & 1) opseq[tmp] = (bam_seqi(seq, ((tmp << 1) + n_start)) << 4); tmp = bam_get_l_aux(b); memcpy(opseq + ((final_len + 1) >> 1), bam_get_qual(b) + n_start, final_len + tmp); // Switch data strings std::swap(op->data, b->data); b->core.l_qseq = final_len; memcpy(bam_get_aux(b), aux.data(), aux.size()); b->l_data = (bam_get_aux(b) - b->data) + aux.size(); if(n_end) bam_aux_append(b, "NE", 'i', sizeof(int), (uint8_t *)&n_end); if(n_start) bam_aux_append(b, "NS", 'i', sizeof(int), (uint8_t *)&n_start); const uint32_t *pvar((uint32_t *)dlib::array_tag(b, "PV")); tmp = b->core.flag & BAM_FREVERSE ? n_end: n_start; if(pvar) { std::vector<uint32_t>pvals(pvar + tmp, pvar + final_len + tmp); bam_aux_del(b, (uint8_t *)(pvar) - 6); dlib::bam_aux_array_append(b, "PV", 'I', sizeof(uint32_t), final_len, (uint8_t *)pvals.data()); } const uint32_t *fvar((uint32_t *)dlib::array_tag(b, "FA")); if(fvar) { std::vector<uint32_t>fvals(fvar + tmp, fvar + final_len + tmp); bam_aux_del(b, (uint8_t *)(fvar) - 6); dlib::bam_aux_array_append(b, "FA", 'I', sizeof(uint32_t), final_len, (uint8_t *)fvals.data()); } return ret; } static int pe_trim_ns(bam1_t *b1, bam1_t *b2, void *aux) { return trim_ns(b1, aux) & trim_ns(b2, aux); } int main(int argc, char *argv[]) { if(argc < 3) return usage(argv); if(strcmp(argv[1], "--help") == 0) return usage(argv, EXIT_SUCCESS); int c; int is_se{0}; char out_mode[4] = "wb"; opts_t opts; while((c = getopt(argc, argv, "m:l:h?sSn")) > -1) { switch(c) { case 'm': opts.min_trimmed_len = (uint32_t)atoi(optarg); break; case 'l': out_mode[2] = *optarg; break; case 's': is_se = 1; break; case 'S': sprintf(out_mode, "w"); break; case 'n': opts.skip_all_ns = 1; break; case 'h': case '?': return usage(argv, EXIT_SUCCESS); } } if(argc - 2 != optind) LOG_EXIT("Required: precisely two positional arguments (in bam, out bam).\n"); dlib::BamHandle inHandle(argv[optind]); dlib::BamHandle outHandle(argv[optind + 1], inHandle.header, out_mode); is_se ? dlib::abstract_single_iter(inHandle.fp, inHandle.header, outHandle.fp, &trim_ns, (void *)&opts) : dlib::abstract_pair_iter(inHandle.fp, inHandle.header, outHandle.fp, &pe_trim_ns, (void *)&opts); return EXIT_SUCCESS; } <commit_msg>Update usage<commit_after>#include <getopt.h> #include "dlib/bam_util.h" int usage(char **argv, int retcode=EXIT_FAILURE) { fprintf(stderr, "MASKRIPPER version %s.\n NOTE: for paired-end usage, the bam must be name-sorted.\n" "Usage: maskripper <opts> in.bam out.bam\n" "Flags:\n-m: Minimum trimmed read length. Default: 0.\n" "-n: Skip reads composed of all Ns. Default: False.\n" "-l: output compression level. Default: 6.\n" "-S: output in sam format.\n" "-s: perform single-end analysis. This option results in imbalanced pairs on paired-end data.\n" "Use - for stdin or stdout.\n", MASKRIPPER_VERSION); return retcode; } struct opts_t { uint8_t *data; uint32_t l_data:16; uint32_t m_data:16; uint32_t min_trimmed_len:8; uint32_t skip_all_ns:1; ~opts_t() {if(data) free(data);} opts_t(): data(nullptr), l_data(0), m_data(0), min_trimmed_len(0), skip_all_ns(0) {} void resize(uint32_t new_min) { if(new_min > m_data) { m_data = new_min; kroundup32(m_data); data = (uint8_t *)realloc(data, m_data * sizeof(uint8_t)); } } }; static int trim_ns(bam1_t *b, void *data) { int ret = 0; opts_t *op((opts_t *)data); std::vector<uint8_t> aux(bam_get_aux(b), bam_get_aux(b) + bam_get_l_aux(b)); int tmp; uint8_t *const seq(bam_get_seq(b)); uint32_t *const cigar(bam_get_cigar(b)); //op->n_cigar = b->core.n_cigar; op->resize(b->l_data); // Make sure it's big enough to hold everything. memcpy(op->data, b->data, b->core.l_qname); // Get #Ns at the beginning for(tmp = 0; bam_seqi(seq, tmp) == dlib::htseq::HTS_N; ++tmp); const int n_start(tmp); if(tmp == b->core.l_qseq - 1) // all bases are N -- garbage read ret |= op->skip_all_ns; // Get #Ns at the end for(tmp = b->core.l_qseq - 1; bam_seqi(seq, tmp) == dlib::htseq::HTS_N; --tmp); const int n_end(b->core.l_qseq - 1 - tmp); // Get new length for read int final_len(b->core.l_qseq - n_end - n_start); if(final_len < 0) final_len = 0; if(final_len < op->min_trimmed_len) // Too short. ret |= 1; // Copy in qual and all of aux. if(n_end) { if((tmp = bam_cigar_oplen(cigar[b->core.n_cigar - 1]) - n_end) == 0) { LOG_DEBUG("Entire cigar operation is the softclip. Decrease the number of new cigar operations.\n"); --b->core.n_cigar; } else { LOG_DEBUG("Updating second cigar operation in-place.\n"); cigar[b->core.n_cigar - 1] = bam_cigar_gen(tmp, BAM_CSOFT_CLIP); } } // Get new n_cigar. if((tmp = bam_cigar_oplen(*cigar) - n_start) == 0) { memcpy(op->data + b->core.l_qname, cigar + 1, (--b->core.n_cigar) << 2); // << 2 for 4 bit per cigar op } else { if(n_start) *cigar = bam_cigar_gen(tmp, BAM_CSOFT_CLIP); memcpy(op->data + b->core.l_qname, cigar, b->core.n_cigar << 2); } uint8_t *opseq(op->data + b->core.l_qname + (b->core.n_cigar << 2)); // Pointer to the seq region of new data field. for(tmp = 0; tmp < final_len >> 1; ++tmp) opseq[tmp] = (bam_seqi(seq, ((tmp << 1) + n_start)) << 4) | (bam_seqi(seq, (tmp << 1) + n_start + 1)); if(final_len & 1) opseq[tmp] = (bam_seqi(seq, ((tmp << 1) + n_start)) << 4); tmp = bam_get_l_aux(b); memcpy(opseq + ((final_len + 1) >> 1), bam_get_qual(b) + n_start, final_len + tmp); // Switch data strings std::swap(op->data, b->data); b->core.l_qseq = final_len; memcpy(bam_get_aux(b), aux.data(), aux.size()); b->l_data = (bam_get_aux(b) - b->data) + aux.size(); if(n_end) bam_aux_append(b, "NE", 'i', sizeof(int), (uint8_t *)&n_end); if(n_start) bam_aux_append(b, "NS", 'i', sizeof(int), (uint8_t *)&n_start); const uint32_t *pvar((uint32_t *)dlib::array_tag(b, "PV")); tmp = b->core.flag & BAM_FREVERSE ? n_end: n_start; if(pvar) { std::vector<uint32_t>pvals(pvar + tmp, pvar + final_len + tmp); bam_aux_del(b, (uint8_t *)(pvar) - 6); dlib::bam_aux_array_append(b, "PV", 'I', sizeof(uint32_t), final_len, (uint8_t *)pvals.data()); } const uint32_t *fvar((uint32_t *)dlib::array_tag(b, "FA")); if(fvar) { std::vector<uint32_t>fvals(fvar + tmp, fvar + final_len + tmp); bam_aux_del(b, (uint8_t *)(fvar) - 6); dlib::bam_aux_array_append(b, "FA", 'I', sizeof(uint32_t), final_len, (uint8_t *)fvals.data()); } return ret; } static int pe_trim_ns(bam1_t *b1, bam1_t *b2, void *aux) { return trim_ns(b1, aux) & trim_ns(b2, aux); } int main(int argc, char *argv[]) { if(argc < 3) return usage(argv); int c; int is_se{0}; char out_mode[4] = "wb"; opts_t opts; while((c = getopt(argc, argv, "m:l:h?sSn")) > -1) { switch(c) { case 'm': opts.min_trimmed_len = (uint32_t)atoi(optarg); break; case 'l': out_mode[2] = *optarg; break; case 's': is_se = 1; break; case 'S': sprintf(out_mode, "w"); break; case 'n': opts.skip_all_ns = 1; break; case 'h': case '?': return usage(argv, EXIT_SUCCESS); } } if(argc - 2 != optind) LOG_EXIT("Required: precisely two positional arguments (in bam, out bam).\n"); dlib::BamHandle inHandle(argv[optind]); dlib::BamHandle outHandle(argv[optind + 1], inHandle.header, out_mode); is_se ? dlib::abstract_single_iter(inHandle.fp, inHandle.header, outHandle.fp, &trim_ns, (void *)&opts) : dlib::abstract_pair_iter(inHandle.fp, inHandle.header, outHandle.fp, &pe_trim_ns, (void *)&opts); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*** DEVSIM Copyright 2013 Devsim LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ***/ #ifndef DS_NEWTON_HH #define DS_NEWTON_HH #include "MatrixEntries.hh" #include "dsMathTypes.hh" #include "MathEnum.hh" #include <cstddef> #include <vector> #include <complex> #include <map> class PermutationEntry; class ObjectHolder; typedef std::map<std::string, ObjectHolder> ObjectHolderMap_t; class Device; /// This is the outer nonlinear solver namespace dsMath { enum class CompressionType; template <typename DoubleType> class Matrix; template <typename DoubleType> class LinearSolver; namespace TimeMethods { enum class TimeMethod_t {DCONLY, INTEGRATEDC, INTEGRATETR, INTEGRATEBDF1, INTEGRATEBDF2}; template <typename DoubleType> struct TimeParams { TimeParams(TimeMethod_t tm, DoubleType ts, DoubleType g) : method(tm), tstep(ts), gamma(g), tdelta(0.0), a0(0.0), a1(0.0), a2(0.0), b0(1.0), b1(0.0), b2(0.0) { } // strictly dc bool IsDCOnly() const { return (method == TimeMethod_t::DCONLY); } // could be dc transient too. bool IsDCMethod() const { return (method == TimeMethod_t::DCONLY) || (method == TimeMethod_t::INTEGRATEDC); } // can be dc transient too bool IsTransient() const { return (method != TimeMethod_t::DCONLY); } bool IsIntegration() const { return (method == TimeMethod_t::INTEGRATEBDF1) || (method == TimeMethod_t::INTEGRATETR) || (method == TimeMethod_t::INTEGRATEBDF2); } TimeMethod_t method; DoubleType tstep; DoubleType gamma; DoubleType tdelta; DoubleType a0; DoubleType a1; DoubleType a2; DoubleType b0; DoubleType b1; DoubleType b2; }; template <typename DoubleType> struct DCOnly : public TimeParams<DoubleType> { DCOnly() : TimeParams<DoubleType>(TimeMethod_t::DCONLY, 0.0, 0.0) { TimeParams<DoubleType>::b0 = 1.0; } }; template <typename DoubleType> struct TransientDC : public TimeParams<DoubleType> { TransientDC() : TimeParams<DoubleType>(TimeMethod_t::INTEGRATEDC, 0.0, 0.0) { TimeParams<DoubleType>::b0 = 1.0; } }; template <typename DoubleType> struct BDF1 : public TimeParams<DoubleType> { BDF1(DoubleType tstep, DoubleType gamma) : TimeParams<DoubleType>(TimeMethod_t::INTEGRATEBDF1, tstep, gamma) { tdelta = gamma * tstep; const DoubleType tf = 1.0 / tdelta; a0 = tf; a1 = -tf; b0 = 1.0; } using TimeParams<DoubleType>::tdelta; using TimeParams<DoubleType>::a0; using TimeParams<DoubleType>::a1; using TimeParams<DoubleType>::b0; }; template <typename DoubleType> struct BDF2 : public TimeParams<DoubleType> { BDF2(DoubleType tstep, DoubleType gamma) : TimeParams<DoubleType>(TimeMethod_t::INTEGRATEBDF2, tstep, gamma) { //// td for first order projection tdelta = (1.0 - gamma) * tstep; a0 = (2.0 - gamma) / tdelta; a1 = (-1.0) / (gamma * tdelta); a2 = (1.0 - gamma) / (gamma * tstep); b0 = 1.0; } using TimeParams<DoubleType>::tdelta; using TimeParams<DoubleType>::a0; using TimeParams<DoubleType>::a1; using TimeParams<DoubleType>::a2; using TimeParams<DoubleType>::b0; }; template <typename DoubleType> struct TR : public TimeParams<DoubleType> { TR(DoubleType tstep, DoubleType gamma) : TimeParams<DoubleType>(TimeMethod_t::INTEGRATETR, tstep, gamma) { tdelta = gamma * tstep; const DoubleType tf = 2.0 / tdelta; a0 = tf; a1 = -tf; b0 = 1.0; b1 = -1.0; } using TimeParams<DoubleType>::tdelta; using TimeParams<DoubleType>::a0; using TimeParams<DoubleType>::a1; using TimeParams<DoubleType>::b0; using TimeParams<DoubleType>::b1; }; } template <typename DoubleType> class Newton { public: typedef std::vector<PermutationEntry> permvec_t; /// Newton takes on linear solver /// near solver selects Preconditioner Newton(); ~Newton(); //// INTEGRATE_DC means that we are just gonna Assemble I, Q when done void GetMatrixAndRHSForExternalUse(CompressionType /*ct*/, ObjectHolderMap_t & /*ohm*/); bool Solve(LinearSolver<DoubleType> &, const TimeMethods::TimeParams<DoubleType> &, ObjectHolderMap_t *ohm); bool ACSolve(LinearSolver<DoubleType> &, DoubleType); bool NoiseSolve(const std::string &, LinearSolver<DoubleType> &, DoubleType); //Newton(LinearSolver<DoubleType> &iterator); void SetAbsError(DoubleType x) { absLimit = x; } void SetRelError(DoubleType x) { relLimit = x; } void SetQRelError(DoubleType x) { qrelLimit = x; } void SetMaxIter(size_t x) { maxiter = x; } protected: template <typename T> void LoadIntoMatrix(const RealRowColValueVec<DoubleType> &rcv, Matrix<DoubleType> &matrix, T scl = 1.0, size_t offset = 0); template <typename T> void LoadIntoMatrixPermutated(const RealRowColValueVec<DoubleType> &rcv, Matrix<DoubleType> &matrix, const permvec_t &, T scl = 1.0, size_t offset = 0); template <typename T> void LoadIntoRHS(const RHSEntryVec<DoubleType> &, std::vector<T> &, T scl = 1.0, size_t offset = 0); template <typename T> void LoadIntoRHSPermutated(const RHSEntryVec<DoubleType> &, std::vector<T> &, const permvec_t &, T scl = 1.0, size_t offset = 0); private: void InitializeTransientAssemble(const TimeMethods::TimeParams<DoubleType> &, size_t, std::vector<DoubleType> &); bool CheckTransientProjection(const TimeMethods::TimeParams<DoubleType> &, const std::vector<DoubleType> &, ObjectHolderMap_t *ohm); void UpdateTransientCurrent(const TimeMethods::TimeParams<DoubleType> &, size_t, const std::vector<DoubleType> &, const std::vector<DoubleType> &); void PrintDeviceErrors(const Device &device, ObjectHolderMap_t *); void PrintCircuitErrors(ObjectHolderMap_t *); void PrintNumberEquations(size_t, ObjectHolderMap_t *); void PrintIteration(size_t, ObjectHolderMap_t *); size_t NumberEquationsAndSetDimension(bool); void BackupSolutions(); void RestoreSolutions(); template <typename T> void LoadMatrixAndRHS(Matrix<DoubleType> &, std::vector<T> &, permvec_t &, dsMathEnum::WhatToLoad, dsMathEnum::TimeMode, T); void LoadMatrixAndRHSAC(Matrix<DoubleType> &, std::vector<std::complex<DoubleType>> &, permvec_t &, DoubleType); void LoadCircuitRHSAC(std::vector<std::complex<DoubleType>> &); void LoadMatrixAndRHSOnCircuit(RealRowColValueVec<DoubleType> &, RHSEntryVec<DoubleType> &rhs, dsMathEnum::WhatToLoad, dsMathEnum::TimeMode); void AssembleContactsAndInterfaces(RealRowColValueVec<DoubleType> &, RHSEntryVec<DoubleType> &, permvec_t &, Device &, dsMathEnum::WhatToLoad, dsMathEnum::TimeMode); void AssembleBulk(RealRowColValueVec<DoubleType> &, RHSEntryVec<DoubleType> &, Device &, dsMathEnum::WhatToLoad, dsMathEnum::TimeMode); void AssembleTclEquation(const std::string &name, ObjectHolder &, ObjectHolder &, RealRowColValueVec<DoubleType> &, RHSEntryVec<DoubleType> &, dsMathEnum::WhatToLoad); void AssembleTclEquations(RealRowColValueVec<DoubleType> &, RHSEntryVec<DoubleType> &, RealRowColValueVec<DoubleType> &, RHSEntryVec<DoubleType> &, dsMathEnum::WhatToLoad, dsMathEnum::TimeMode); static const size_t DefaultMaxIter; static const DoubleType DefaultAbsError; static const DoubleType DefaultRelError; static const DoubleType DefaultQRelError; Newton(const Newton &); size_t maxiter; /// The maximum number of iterations DoubleType absLimit; /// The calculated abs error (maybe come on per device or per region basis) DoubleType relLimit; /// The calculated rel error DoubleType qrelLimit; size_t dimension; static const DoubleType rhssign; }; } #endif <commit_msg>potential sign mistake<commit_after>/*** DEVSIM Copyright 2013 Devsim LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ***/ #ifndef DS_NEWTON_HH #define DS_NEWTON_HH #include "MatrixEntries.hh" #include "dsMathTypes.hh" #include "MathEnum.hh" #include <cstddef> #include <vector> #include <complex> #include <map> class PermutationEntry; class ObjectHolder; typedef std::map<std::string, ObjectHolder> ObjectHolderMap_t; class Device; /// This is the outer nonlinear solver namespace dsMath { enum class CompressionType; template <typename DoubleType> class Matrix; template <typename DoubleType> class LinearSolver; namespace TimeMethods { enum class TimeMethod_t {DCONLY, INTEGRATEDC, INTEGRATETR, INTEGRATEBDF1, INTEGRATEBDF2}; template <typename DoubleType> struct TimeParams { TimeParams(TimeMethod_t tm, DoubleType ts, DoubleType g) : method(tm), tstep(ts), gamma(g), tdelta(0.0), a0(0.0), a1(0.0), a2(0.0), b0(1.0), b1(0.0), b2(0.0) { } // strictly dc bool IsDCOnly() const { return (method == TimeMethod_t::DCONLY); } // could be dc transient too. bool IsDCMethod() const { return (method == TimeMethod_t::DCONLY) || (method == TimeMethod_t::INTEGRATEDC); } // can be dc transient too bool IsTransient() const { return (method != TimeMethod_t::DCONLY); } bool IsIntegration() const { return (method == TimeMethod_t::INTEGRATEBDF1) || (method == TimeMethod_t::INTEGRATETR) || (method == TimeMethod_t::INTEGRATEBDF2); } TimeMethod_t method; DoubleType tstep; DoubleType gamma; DoubleType tdelta; DoubleType a0; DoubleType a1; DoubleType a2; DoubleType b0; DoubleType b1; DoubleType b2; }; template <typename DoubleType> struct DCOnly : public TimeParams<DoubleType> { DCOnly() : TimeParams<DoubleType>(TimeMethod_t::DCONLY, 0.0, 0.0) { TimeParams<DoubleType>::b0 = 1.0; } }; template <typename DoubleType> struct TransientDC : public TimeParams<DoubleType> { TransientDC() : TimeParams<DoubleType>(TimeMethod_t::INTEGRATEDC, 0.0, 0.0) { TimeParams<DoubleType>::b0 = 1.0; } }; template <typename DoubleType> struct BDF1 : public TimeParams<DoubleType> { BDF1(DoubleType tstep, DoubleType gamma) : TimeParams<DoubleType>(TimeMethod_t::INTEGRATEBDF1, tstep, gamma) { tdelta = gamma * tstep; const DoubleType tf = 1.0 / tdelta; a0 = tf; a1 = -tf; b0 = 1.0; } using TimeParams<DoubleType>::tdelta; using TimeParams<DoubleType>::a0; using TimeParams<DoubleType>::a1; using TimeParams<DoubleType>::b0; }; template <typename DoubleType> struct BDF2 : public TimeParams<DoubleType> { BDF2(DoubleType tstep, DoubleType gamma) : TimeParams<DoubleType>(TimeMethod_t::INTEGRATEBDF2, tstep, gamma) { //// td for first order projection tdelta = (1.0 - gamma) * tstep; a0 = (2.0 - gamma) / tdelta; a1 = (-1.0) / (gamma * tdelta); a2 = (1.0 - gamma) / (gamma * tstep); b0 = 1.0; } using TimeParams<DoubleType>::tdelta; using TimeParams<DoubleType>::a0; using TimeParams<DoubleType>::a1; using TimeParams<DoubleType>::a2; using TimeParams<DoubleType>::b0; }; template <typename DoubleType> struct TR : public TimeParams<DoubleType> { TR(DoubleType tstep, DoubleType gamma) : TimeParams<DoubleType>(TimeMethod_t::INTEGRATETR, tstep, gamma) { tdelta = gamma * tstep; const DoubleType tf = 2.0 / tdelta; a0 = tf; a1 = -tf; b0 = 1.0; b1 = 1.0; } using TimeParams<DoubleType>::tdelta; using TimeParams<DoubleType>::a0; using TimeParams<DoubleType>::a1; using TimeParams<DoubleType>::b0; using TimeParams<DoubleType>::b1; }; } template <typename DoubleType> class Newton { public: typedef std::vector<PermutationEntry> permvec_t; /// Newton takes on linear solver /// near solver selects Preconditioner Newton(); ~Newton(); //// INTEGRATE_DC means that we are just gonna Assemble I, Q when done void GetMatrixAndRHSForExternalUse(CompressionType /*ct*/, ObjectHolderMap_t & /*ohm*/); bool Solve(LinearSolver<DoubleType> &, const TimeMethods::TimeParams<DoubleType> &, ObjectHolderMap_t *ohm); bool ACSolve(LinearSolver<DoubleType> &, DoubleType); bool NoiseSolve(const std::string &, LinearSolver<DoubleType> &, DoubleType); //Newton(LinearSolver<DoubleType> &iterator); void SetAbsError(DoubleType x) { absLimit = x; } void SetRelError(DoubleType x) { relLimit = x; } void SetQRelError(DoubleType x) { qrelLimit = x; } void SetMaxIter(size_t x) { maxiter = x; } protected: template <typename T> void LoadIntoMatrix(const RealRowColValueVec<DoubleType> &rcv, Matrix<DoubleType> &matrix, T scl = 1.0, size_t offset = 0); template <typename T> void LoadIntoMatrixPermutated(const RealRowColValueVec<DoubleType> &rcv, Matrix<DoubleType> &matrix, const permvec_t &, T scl = 1.0, size_t offset = 0); template <typename T> void LoadIntoRHS(const RHSEntryVec<DoubleType> &, std::vector<T> &, T scl = 1.0, size_t offset = 0); template <typename T> void LoadIntoRHSPermutated(const RHSEntryVec<DoubleType> &, std::vector<T> &, const permvec_t &, T scl = 1.0, size_t offset = 0); private: void InitializeTransientAssemble(const TimeMethods::TimeParams<DoubleType> &, size_t, std::vector<DoubleType> &); bool CheckTransientProjection(const TimeMethods::TimeParams<DoubleType> &, const std::vector<DoubleType> &, ObjectHolderMap_t *ohm); void UpdateTransientCurrent(const TimeMethods::TimeParams<DoubleType> &, size_t, const std::vector<DoubleType> &, const std::vector<DoubleType> &); void PrintDeviceErrors(const Device &device, ObjectHolderMap_t *); void PrintCircuitErrors(ObjectHolderMap_t *); void PrintNumberEquations(size_t, ObjectHolderMap_t *); void PrintIteration(size_t, ObjectHolderMap_t *); size_t NumberEquationsAndSetDimension(bool); void BackupSolutions(); void RestoreSolutions(); template <typename T> void LoadMatrixAndRHS(Matrix<DoubleType> &, std::vector<T> &, permvec_t &, dsMathEnum::WhatToLoad, dsMathEnum::TimeMode, T); void LoadMatrixAndRHSAC(Matrix<DoubleType> &, std::vector<std::complex<DoubleType>> &, permvec_t &, DoubleType); void LoadCircuitRHSAC(std::vector<std::complex<DoubleType>> &); void LoadMatrixAndRHSOnCircuit(RealRowColValueVec<DoubleType> &, RHSEntryVec<DoubleType> &rhs, dsMathEnum::WhatToLoad, dsMathEnum::TimeMode); void AssembleContactsAndInterfaces(RealRowColValueVec<DoubleType> &, RHSEntryVec<DoubleType> &, permvec_t &, Device &, dsMathEnum::WhatToLoad, dsMathEnum::TimeMode); void AssembleBulk(RealRowColValueVec<DoubleType> &, RHSEntryVec<DoubleType> &, Device &, dsMathEnum::WhatToLoad, dsMathEnum::TimeMode); void AssembleTclEquation(const std::string &name, ObjectHolder &, ObjectHolder &, RealRowColValueVec<DoubleType> &, RHSEntryVec<DoubleType> &, dsMathEnum::WhatToLoad); void AssembleTclEquations(RealRowColValueVec<DoubleType> &, RHSEntryVec<DoubleType> &, RealRowColValueVec<DoubleType> &, RHSEntryVec<DoubleType> &, dsMathEnum::WhatToLoad, dsMathEnum::TimeMode); static const size_t DefaultMaxIter; static const DoubleType DefaultAbsError; static const DoubleType DefaultRelError; static const DoubleType DefaultQRelError; Newton(const Newton &); size_t maxiter; /// The maximum number of iterations DoubleType absLimit; /// The calculated abs error (maybe come on per device or per region basis) DoubleType relLimit; /// The calculated rel error DoubleType qrelLimit; size_t dimension; static const DoubleType rhssign; }; } #endif <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "primitives/block.h" #include "hash.h" #include "tinyformat.h" #include "utilstrencodings.h" #include "crypto/common.h" #include "compat/endian.h" #include "main.h" namespace { #pragma pack(push, 1) /** * The Keccak-256 hash of this structure is used as input for egihash * It is a truncated block header with a deterministic encoding * All integer values are little endian * Hashes are the nul-terminated hex encoded representation as if ToString() was called */ struct CBlockHeaderTruncatedLE { int32_t nVersion; char hashPrevBlock[65]; char hashMerkleRoot[65]; uint32_t nTime; uint32_t nBits; uint32_t nHeight; CBlockHeaderTruncatedLE(CBlockHeader const & h) : nVersion(htole32(h.nVersion)) , hashPrevBlock{0} , hashMerkleRoot{0} , nTime(htole32(h.nTime)) , nBits(htole32(h.nBits)) , nHeight(htole32(h.nHeight)) { auto prevHash = h.hashPrevBlock.ToString(); memcpy(hashPrevBlock, prevHash.c_str(), (std::min)(prevHash.size(), sizeof(hashPrevBlock))); auto merkleRoot = h.hashMerkleRoot.ToString(); memcpy(hashMerkleRoot, merkleRoot.c_str(), (std::min)(merkleRoot.size(), sizeof(hashMerkleRoot))); } }; #pragma pack(pop) } uint256 CBlockHeader::GetHash() const { CBlockHeaderTruncatedLE truncatedBlockHeader(*this); egihash::h256_t headerHash(&truncatedBlockHeader, sizeof(truncatedBlockHeader)); egihash::result_t ret; // if we have a DAG loaded, use it if (dagActive && ((nHeight / egihash::constants::EPOCH_LENGTH) == dagActive->epoch())) { ret = egihash::full::hash(*dagActive, headerHash, nNonce); } else // otherwise all we can do is generate a light hash { // TODO: pre-load caches and seed hashes ret = egihash::light::hash(egihash::cache_t(nHeight, egihash::get_seedhash(nHeight)), headerHash, nNonce); } hashMix = uint256(ret.mixhash); return uint256(ret.value); } std::string CBlock::ToString() const { std::stringstream s; s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nHeight=%u, hashMix=%s, nNonce=%u, vtx=%u)\n", GetHash().ToString(), nVersion, hashPrevBlock.ToString(), hashMerkleRoot.ToString(), nTime, nBits, nHeight, hashMix.ToString(), nNonce, vtx.size()); for (unsigned int i = 0; i < vtx.size(); i++) { s << " " << vtx[i].ToString() << "\n"; } return s.str(); } <commit_msg>updating GetHash() function for new dag singleton<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "primitives/block.h" #include "hash.h" #include "tinyformat.h" #include "utilstrencodings.h" #include "crypto/common.h" #include "compat/endian.h" #include "dag_singleton.h" namespace { #pragma pack(push, 1) /** * The Keccak-256 hash of this structure is used as input for egihash * It is a truncated block header with a deterministic encoding * All integer values are little endian * Hashes are the nul-terminated hex encoded representation as if ToString() was called */ struct CBlockHeaderTruncatedLE { int32_t nVersion; char hashPrevBlock[65]; char hashMerkleRoot[65]; uint32_t nTime; uint32_t nBits; uint32_t nHeight; CBlockHeaderTruncatedLE(CBlockHeader const & h) : nVersion(htole32(h.nVersion)) , hashPrevBlock{0} , hashMerkleRoot{0} , nTime(htole32(h.nTime)) , nBits(htole32(h.nBits)) , nHeight(htole32(h.nHeight)) { auto prevHash = h.hashPrevBlock.ToString(); memcpy(hashPrevBlock, prevHash.c_str(), (std::min)(prevHash.size(), sizeof(hashPrevBlock))); auto merkleRoot = h.hashMerkleRoot.ToString(); memcpy(hashMerkleRoot, merkleRoot.c_str(), (std::min)(merkleRoot.size(), sizeof(hashMerkleRoot))); } }; #pragma pack(pop) } uint256 CBlockHeader::GetHash() const { CBlockHeaderTruncatedLE truncatedBlockHeader(*this); egihash::h256_t headerHash(&truncatedBlockHeader, sizeof(truncatedBlockHeader)); egihash::result_t ret; // if we have a DAG loaded, use it auto const & dag = ActiveDAG(); if (dag && ((nHeight / egihash::constants::EPOCH_LENGTH) == dag->epoch())) { ret = egihash::full::hash(*dag, headerHash, nNonce); } else // otherwise all we can do is generate a light hash { // TODO: pre-load caches and seed hashes ret = egihash::light::hash(egihash::cache_t(nHeight, egihash::get_seedhash(nHeight)), headerHash, nNonce); } hashMix = uint256(ret.mixhash); return uint256(ret.value); } std::string CBlock::ToString() const { std::stringstream s; s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nHeight=%u, hashMix=%s, nNonce=%u, vtx=%u)\n", GetHash().ToString(), nVersion, hashPrevBlock.ToString(), hashMerkleRoot.ToString(), nTime, nBits, nHeight, hashMix.ToString(), nNonce, vtx.size()); for (unsigned int i = 0; i < vtx.size(); i++) { s << " " << vtx[i].ToString() << "\n"; } return s.str(); } <|endoftext|>
<commit_before>//================================================ // @title mx_fwht.cpp // @author Jonathan Hadida // @contact Jonathan.hadida [at] dtc.ox.ac.uk //================================================ #include "fwht.h" #include "mexArray.h" #include <algorithm> #define SEQUENCY_ORDER false /******************** ********** ********************/ /******************** ********** ********************/ /** * Dependency to MexArray (see https://github.com/Sheljohn/MexArray). * Use the script start_matlab.sh to start Matlab, and compile with: * mex CXXFLAGS="\$CXXFLAGS -std=c++0x -Wall -O2" mx_fwht.cpp */ void mexFunction( int nargout, mxArray *out[], int nargin, const mxArray *in[] ) { if ( nargin != 1 ) { mexErrMsgTxt("Usage: w = mx_fwht(sequence);"); return; } ndArray<const double,2> input(in[0]); ndArray<double,2> output; std::vector<double> d( input.begin(), input.end() ); fwht( d, SEQUENCY_ORDER ); int size[2]; size[0] = 1; size[1] = d.size(); out[0] = mxCreateNumericArray( 2, size, mx_type<double>::id, mxREAL ); output.assign( out[0] ); std::copy( d.begin(), d.end(), output.begin() ); }<commit_msg>Update dependency<commit_after>//================================================ // @title mx_fwht.cpp // @author Jonathan Hadida // @contact Jonathan.hadida [at] dtc.ox.ac.uk //================================================ #include "fwht.h" #include "ndArray.h" #include <algorithm> #define SEQUENCY_ORDER false /******************** ********** ********************/ /******************** ********** ********************/ /** * Dependency to ndArray (see https://github.com/Sheljohn/ndArray). * Use the script start_matlab.sh to start Matlab, and compile with: * mex CXXFLAGS="\$CXXFLAGS -std=c++0x -Wall -O2" mx_fwht.cpp */ void mexFunction( int nargout, mxArray *out[], int nargin, const mxArray *in[] ) { if ( nargin != 1 ) { mexErrMsgTxt("Usage: w = mx_fwht(sequence);"); return; } ndArray<const double,2> input(in[0]); ndArray<double,2> output; std::vector<double> d( input.begin(), input.end() ); fwht( d, SEQUENCY_ORDER ); int size[2]; size[0] = 1; size[1] = d.size(); out[0] = mxCreateNumericArray( 2, size, mx_type<double>::id, mxREAL ); output.assign( out[0] ); std::copy( d.begin(), d.end(), output.begin() ); }<|endoftext|>
<commit_before>#include "V3DInstance.h" V3D_RESULT V3DCreateInstance(const V3DInstanceDesc& instanceDesc, IV3DInstance** ppInstance) { if (V3DInstance::IsCreated() == true) { return V3D_ERROR_FAIL; } // ---------------------------------------------------------------------------------------------------- // ̏ // ---------------------------------------------------------------------------------------------------- if (((instanceDesc.memory.pAllocateFunction == nullptr) && (instanceDesc.memory.pReallocateFunction == nullptr) && (instanceDesc.memory.pFreeFunction == nullptr)) || ((instanceDesc.memory.pAllocateFunction != nullptr) && (instanceDesc.memory.pReallocateFunction != nullptr) && (instanceDesc.memory.pFreeFunction != nullptr))) { ; } else { return V3D_ERROR_INVALID_ARGUMENT; } V3D_MEM_INIT(instanceDesc.memory.pAllocateFunction, instanceDesc.memory.pReallocateFunction, instanceDesc.memory.pFreeFunction, instanceDesc.memory.pUserData); // ---------------------------------------------------------------------------------------------------- // CX^X̍쐬 // ---------------------------------------------------------------------------------------------------- V3DInstance* pInstance = V3DInstance::Create(); if (pInstance == nullptr) { return V3D_ERROR_OUT_OF_HOST_MEMORY; } V3D_RESULT result = pInstance->Initialize(instanceDesc); if (result != V3D_OK) { V3D_RELEASE(pInstance); return result; } (*ppInstance) = pInstance; // ---------------------------------------------------------------------------------------------------- return V3D_OK; } <commit_msg>レイヤーが使用できるかどうかを確認する関数を追加<commit_after>#include "V3DInstance.h" V3D_RESULT V3DCheckLayer(V3D_LAYER layer) { uint32_t vLayerPropCount; std::vector<VkLayerProperties> vLayerProps; VkResult vResult = vkEnumerateInstanceLayerProperties(&vLayerPropCount, nullptr); if (vResult != VK_SUCCESS) { return V3D_ERROR_FAIL; } vLayerProps.resize(vLayerPropCount); vResult = vkEnumerateInstanceLayerProperties(&vLayerPropCount, vLayerProps.data()); if (vResult != VK_SUCCESS) { return V3D_ERROR_FAIL; } const char* pLayerName = nullptr; switch (layer) { case V3D_LAYER_STANDARD: pLayerName = V3D_LAYER_LUNARG_standard_validation; break; case V3D_LAYER_NSIGHT: pLayerName = V3D_LAYER_NV_nsight; break; case V3D_LAYER_RENDERDOC: pLayerName = V3D_LAYER_RENDERDOC_Capture; break; } if ((pLayerName == nullptr) || (std::find_if(vLayerProps.begin(), vLayerProps.end(), V3DFindLayer(pLayerName)) == vLayerProps.end())) { return V3D_ERROR_NOT_SUPPORTED; } return V3D_OK; } V3D_RESULT V3DCreateInstance(const V3DInstanceDesc& instanceDesc, IV3DInstance** ppInstance) { if (V3DInstance::IsCreated() == true) { return V3D_ERROR_FAIL; } // ---------------------------------------------------------------------------------------------------- // ̏ // ---------------------------------------------------------------------------------------------------- if (((instanceDesc.memory.pAllocateFunction == nullptr) && (instanceDesc.memory.pReallocateFunction == nullptr) && (instanceDesc.memory.pFreeFunction == nullptr)) || ((instanceDesc.memory.pAllocateFunction != nullptr) && (instanceDesc.memory.pReallocateFunction != nullptr) && (instanceDesc.memory.pFreeFunction != nullptr))) { ; } else { return V3D_ERROR_INVALID_ARGUMENT; } V3D_MEM_INIT(instanceDesc.memory.pAllocateFunction, instanceDesc.memory.pReallocateFunction, instanceDesc.memory.pFreeFunction, instanceDesc.memory.pUserData); // ---------------------------------------------------------------------------------------------------- // CX^X̍쐬 // ---------------------------------------------------------------------------------------------------- V3DInstance* pInstance = V3DInstance::Create(); if (pInstance == nullptr) { return V3D_ERROR_OUT_OF_HOST_MEMORY; } V3D_RESULT result = pInstance->Initialize(instanceDesc); if (result != V3D_OK) { V3D_RELEASE(pInstance); return result; } (*ppInstance) = pInstance; // ---------------------------------------------------------------------------------------------------- return V3D_OK; } <|endoftext|>
<commit_before>#include "Hueckel.h" #include "RunStatus.h" #include <boost/spirit/include/classic.hpp> #include <vector> #include <sstream> #include <string> #include <cstdio> using namespace hmo; using namespace boost::spirit::classic; using namespace std; /* E.g. C1==C2 \ C3==C4 coordinates: C -5.08058762 1.31970094 -0.11574781 C -4.40138351 2.49241097 -0.11574781 C -2.86138495 2.49030529 -0.11574781 C -2.18218084 3.66301532 -0.11574781 fullmatrix: 1100 1110 0111 0011 adjacencymatrix, u_or_p = 'U' or 'u' 1100110111 adjacencymatrix, u_or_p = 'L' or 'l' 1110110011 */ Hueckel::Hueckel(const string& coordinates, double bondingthreshold, int charge) { istringstream iss(coordinates); string tstr; vector<double> xcoords; vector<double> ycoords; vector<double> zcoords; natoms = 0; // Read coordinates double tx, ty, tz; const rule<> RULE_coords =(*blank_p)>>(*graph_p) >>(*blank_p)>>(real_p)[assign(tx)] >>(*blank_p)>>(real_p)[assign(ty)] >>(*blank_p)>>(real_p)[assign(tz)] >>(*blank_p); while(getline(iss, tstr, '\n')) { if(parse(tstr.c_str(), RULE_coords).full) { xcoords.push_back(tx); ycoords.push_back(ty); zcoords.push_back(tz); ++natoms; } else { RunStatus::ErrorTermination("Cannot parse coordinates near \" %s \".", tstr.c_str()); } } // Construct adjacencymatrix upperadjacencymatrix.clear(); double squarebondingthreshold = bondingthreshold*bondingthreshold; for(int i = 0; i < natoms; ++i) { for(int j = i; j < natoms; ++j) { double dx = xcoords[i]-xcoords[j]; double dy = ycoords[i]-ycoords[j]; double dz = zcoords[i]-zcoords[j]; double dist = dx*dx+dy*dy+dz*dz; double me = (dist < squarebondingthreshold) ? 1.0000 : 0.0000; upperadjacencymatrix.push_back(me); } } // Orbitals nels = natoms-charge; if(nels < 0) { RunStatus::ErrorTermination("The number of electrons is negative, implying that charge = %d is unresonable!", charge); } if(nels > natoms*2) { RunStatus::ErrorTermination("The number of electrons (%d) cannot be accomadated by the available orbitals (%d), implying that charge = %d is unresonable!", nels, natoms, charge); } } Hueckel::Hueckel(const string& adjacencymatrix, char u_or_l) { int nam = adjacencymatrix.size(); natoms = (sqrt(8.0*adjacencymatrix.size()+1)-1)/2; if(natoms*(natoms+1)/2 != nam) { RunStatus::ErrorTermination("The dimension of the adjecency matrix ( %d ) is invalid: It must be like n*(n+1)/2.", nam); } // Construct the adjacencymatrix upperadjacencymatrix.clear(); for(int i = 0; i < natoms; ++i) { for(int j = i; j < natoms; ++j) { int idx; switch(u_or_l) { case 'U': case 'u': { idx = (2*natoms+1-i)*i/2+j-i; break; } case 'L': case 'l': { idx = (j+1)*j/2+i; break; } default: { RunStatus::ErrorTermination("Cannot parse \"%c\". It should be \"U\", \"u\", \"L\" or \"l\".", u_or_l); break; } } double me; switch(adjacencymatrix[idx]) { case '0': { me = 0.0000; break; } case '1': { me = 1.0000; break; } default: { RunStatus::ErrorTermination("Cannot parse \"%c\".", adjacencymatrix[idx]); break; } } upperadjacencymatrix.push_back(me); } } } Hueckel::~Hueckel(void) { /* Nothing to do */ } int Hueckel::GetNAtoms(void) const { return natoms; } int Hueckel::GetNElectrons(void) const { return nels; } const vector<double>& Hueckel::GetAdjacencyMatrix(void) const { return upperadjacencymatrix; } int Hueckel::Solve(vector<double>& energies, vector<vector<double> >& orbitals, vector<double>& eletrondensities, vector<double>& bondorders, vector<double>& pivalence, const string& outfnprefix) const { // Solve the matrix equation. vector<double> tenergies; vector<double> torbitals; int info = dsyev(natoms, upperadjacencymatrix, tenergies, torbitals); energies.clear(); energies.reserve(natoms); for(int i = natoms-1; i >= 0; --i) { energies.push_back(tenergies[i]); } orbitals.clear(); orbitals.assign(natoms, vector<double>()); for(int i = natoms-1; i >= 0; --i) { for(int j = 0; j < natoms; ++j) { orbitals[natoms-1-i].push_back(torbitals[i*natoms+j]); } } // Calculate the properties. eletrondensities.clear(); for(int i = 0; i < natoms; ++i) { double tdensity = 0.; for(int j = 0; j < natoms; ++j) { int occ = 0; if(j+1 <= nels/2) occ = 2; if((j+1 == nels/2+1) && (nels%2 == 1)) occ = 1; tdensity += orbitals[j][i]*orbitals[j][i]*occ; } eletrondensities.push_back(tdensity); } // Bond orders. bondorders.clear(); for(int i = 0; i < natoms; ++i) { for(int j = i; j < natoms; ++j) { double tbondorder = 0.; for(int k = 0; k < natoms; ++k) { int occ = 0; if(k+1 <= nels/2) occ = 2; if((k+1 == nels/2+1) && (nels%2 == 1)) occ = 1; tbondorder += orbitals[k][i]*orbitals[k][j]*occ; } bondorders.push_back(tbondorder); } } // Free valence. pivalence.clear(); for(int i = 0; i < natoms; ++i) { double tpivalence = 0.; for(int j = 0; j < natoms; ++j) { const int ij = (j >= i) ? (2*natoms+1-i)*i/2+j-i : (2*natoms+1-j)*j/2+i-j ; if((i != j) && (upperadjacencymatrix[ij] != 0)) { tpivalence += bondorders[ij]; } } pivalence.push_back(tpivalence); } // Draw a molecular graph. GenerateMolecularGraph(outfnprefix, eletrondensities, bondorders); return info; } void Hueckel::GenerateMolecularGraph(const string& fnprefix, const vector<double>& eletrondensities, const vector<double>& bondorders) const { string fndot(fnprefix+".dot"); FILE* fd = fopen(fndot.c_str(), "w"); if(fd == NULL) { RunStatus::ErrorTermination("Cannot open file [ %s ] to write molecular graph.", fndot.c_str()); } fprintf(fd, "graph MDGraph {\n"); fprintf(fd, " rankdir = LR;\n"); fprintf(fd, " // Atom definitions\n"); for(int i = 0; i < natoms; ++i) { const double electrondensity = eletrondensities[i]; fprintf(fd, " \"C%d\" [label=\"%d (%.5f)\", shape=circle];\n", i+1, i+1, electrondensity); } fprintf(fd, " // Connection information\n"); for(int i = 0, ij = 0; i < natoms; ++i) { for(int j = i; j < natoms; ++j, ++ij) { if((i != j) && (upperadjacencymatrix[ij] != 0)) { const double bondorder = bondorders[ij]; fprintf(fd, " \"C%d\" -- \"C%d\" [label=\"%.5f\", color=black];\n", i+1, j+1, bondorder); } } } fprintf(fd, "}\n"); fclose(fd); } // Diagolization // // Input: A: a11, a12, a13, ... a22, a23, ... // Output: eigenvalues: lambda1, lambda2, lambda3, ... // eigenvectors: v1, v2, v3, ... // Return: info int Hueckel::dsyev(int m, const vector<double>& A, vector<double>& eigenvalues, vector<double>& eigenvectors) const { char jobz = 'V'; char uplo = 'U'; int n = m; vector<double> ta; int lda = m; vector<double> tw; int lwork; double dwork; vector<double> work; int info; unsigned int dimA = n*(n+1)/2; if(A.size() != dimA) { RunStatus::ErrorTermination("The parameter m ( %d ) and size of A ( %d ) in dsyev are incompatible.", m, A.size()); } // Copy the data int ncounter = 0; unsigned int dimta = m*m; ta.clear(); ta.assign(dimta, 0.0000); int idx = 0; for(int i = 0; i < m; ++i) { for(int j = i; j < m; ++j) { ta[j*m+i] = A[idx]; ++idx; } } // Detect the optimal lwork lwork = -1; dsyev_(&jobz, &uplo, &n, &(ta[0]), &lda, &(tw[0]), &dwork, &lwork, &info); lwork = (int)dwork; work.assign(lwork, 0.0000); // Diagonaization tw.clear(); tw.assign(m, 0.0000); dsyev_(&jobz, &uplo, &n, &(ta[0]), &lda, &(tw[0]), &(work[0]), &lwork, &info); eigenvectors.clear(); eigenvectors.assign(ta.begin(), ta.end()); eigenvalues.clear(); eigenvalues.assign(tw.begin(), tw.end()); return info; } <commit_msg>Increase the font size of the Graphviz file.<commit_after>#include "Hueckel.h" #include "RunStatus.h" #include <boost/spirit/include/classic.hpp> #include <vector> #include <sstream> #include <string> #include <cstdio> using namespace hmo; using namespace boost::spirit::classic; using namespace std; /* E.g. C1==C2 \ C3==C4 coordinates: C -5.08058762 1.31970094 -0.11574781 C -4.40138351 2.49241097 -0.11574781 C -2.86138495 2.49030529 -0.11574781 C -2.18218084 3.66301532 -0.11574781 fullmatrix: 1100 1110 0111 0011 adjacencymatrix, u_or_p = 'U' or 'u' 1100110111 adjacencymatrix, u_or_p = 'L' or 'l' 1110110011 */ Hueckel::Hueckel(const string& coordinates, double bondingthreshold, int charge) { istringstream iss(coordinates); string tstr; vector<double> xcoords; vector<double> ycoords; vector<double> zcoords; natoms = 0; // Read coordinates double tx, ty, tz; const rule<> RULE_coords =(*blank_p)>>(*graph_p) >>(*blank_p)>>(real_p)[assign(tx)] >>(*blank_p)>>(real_p)[assign(ty)] >>(*blank_p)>>(real_p)[assign(tz)] >>(*blank_p); while(getline(iss, tstr, '\n')) { if(parse(tstr.c_str(), RULE_coords).full) { xcoords.push_back(tx); ycoords.push_back(ty); zcoords.push_back(tz); ++natoms; } else { RunStatus::ErrorTermination("Cannot parse coordinates near \" %s \".", tstr.c_str()); } } // Construct adjacencymatrix upperadjacencymatrix.clear(); double squarebondingthreshold = bondingthreshold*bondingthreshold; for(int i = 0; i < natoms; ++i) { for(int j = i; j < natoms; ++j) { double dx = xcoords[i]-xcoords[j]; double dy = ycoords[i]-ycoords[j]; double dz = zcoords[i]-zcoords[j]; double dist = dx*dx+dy*dy+dz*dz; double me = (dist < squarebondingthreshold) ? 1.0000 : 0.0000; upperadjacencymatrix.push_back(me); } } // Orbitals nels = natoms-charge; if(nels < 0) { RunStatus::ErrorTermination("The number of electrons is negative, implying that charge = %d is unresonable!", charge); } if(nels > natoms*2) { RunStatus::ErrorTermination("The number of electrons (%d) cannot be accomadated by the available orbitals (%d), implying that charge = %d is unresonable!", nels, natoms, charge); } } Hueckel::Hueckel(const string& adjacencymatrix, char u_or_l) { int nam = adjacencymatrix.size(); natoms = (sqrt(8.0*adjacencymatrix.size()+1)-1)/2; if(natoms*(natoms+1)/2 != nam) { RunStatus::ErrorTermination("The dimension of the adjecency matrix ( %d ) is invalid: It must be like n*(n+1)/2.", nam); } // Construct the adjacencymatrix upperadjacencymatrix.clear(); for(int i = 0; i < natoms; ++i) { for(int j = i; j < natoms; ++j) { int idx; switch(u_or_l) { case 'U': case 'u': { idx = (2*natoms+1-i)*i/2+j-i; break; } case 'L': case 'l': { idx = (j+1)*j/2+i; break; } default: { RunStatus::ErrorTermination("Cannot parse \"%c\". It should be \"U\", \"u\", \"L\" or \"l\".", u_or_l); break; } } double me; switch(adjacencymatrix[idx]) { case '0': { me = 0.0000; break; } case '1': { me = 1.0000; break; } default: { RunStatus::ErrorTermination("Cannot parse \"%c\".", adjacencymatrix[idx]); break; } } upperadjacencymatrix.push_back(me); } } } Hueckel::~Hueckel(void) { /* Nothing to do */ } int Hueckel::GetNAtoms(void) const { return natoms; } int Hueckel::GetNElectrons(void) const { return nels; } const vector<double>& Hueckel::GetAdjacencyMatrix(void) const { return upperadjacencymatrix; } int Hueckel::Solve(vector<double>& energies, vector<vector<double> >& orbitals, vector<double>& eletrondensities, vector<double>& bondorders, vector<double>& pivalence, const string& outfnprefix) const { // Solve the matrix equation. vector<double> tenergies; vector<double> torbitals; int info = dsyev(natoms, upperadjacencymatrix, tenergies, torbitals); energies.clear(); energies.reserve(natoms); for(int i = natoms-1; i >= 0; --i) { energies.push_back(tenergies[i]); } orbitals.clear(); orbitals.assign(natoms, vector<double>()); for(int i = natoms-1; i >= 0; --i) { for(int j = 0; j < natoms; ++j) { orbitals[natoms-1-i].push_back(torbitals[i*natoms+j]); } } // Calculate the properties. eletrondensities.clear(); for(int i = 0; i < natoms; ++i) { double tdensity = 0.; for(int j = 0; j < natoms; ++j) { int occ = 0; if(j+1 <= nels/2) occ = 2; if((j+1 == nels/2+1) && (nels%2 == 1)) occ = 1; tdensity += orbitals[j][i]*orbitals[j][i]*occ; } eletrondensities.push_back(tdensity); } // Bond orders. bondorders.clear(); for(int i = 0; i < natoms; ++i) { for(int j = i; j < natoms; ++j) { double tbondorder = 0.; for(int k = 0; k < natoms; ++k) { int occ = 0; if(k+1 <= nels/2) occ = 2; if((k+1 == nels/2+1) && (nels%2 == 1)) occ = 1; tbondorder += orbitals[k][i]*orbitals[k][j]*occ; } bondorders.push_back(tbondorder); } } // Free valence. pivalence.clear(); for(int i = 0; i < natoms; ++i) { double tpivalence = 0.; for(int j = 0; j < natoms; ++j) { const int ij = (j >= i) ? (2*natoms+1-i)*i/2+j-i : (2*natoms+1-j)*j/2+i-j ; if((i != j) && (upperadjacencymatrix[ij] != 0)) { tpivalence += bondorders[ij]; } } pivalence.push_back(tpivalence); } // Draw a molecular graph. GenerateMolecularGraph(outfnprefix, eletrondensities, bondorders); return info; } void Hueckel::GenerateMolecularGraph(const string& fnprefix, const vector<double>& eletrondensities, const vector<double>& bondorders) const { string fndot(fnprefix+".dot"); FILE* fd = fopen(fndot.c_str(), "w"); if(fd == NULL) { RunStatus::ErrorTermination("Cannot open file [ %s ] to write molecular graph.", fndot.c_str()); } fprintf(fd, "graph MDGraph {\n"); fprintf(fd, " rankdir = LR;\n"); fprintf(fd, " // Atom definitions\n"); for(int i = 0; i < natoms; ++i) { const double electrondensity = eletrondensities[i]; fprintf(fd, " \"C%d\" [label=\"%d (%.5f)\", fontsize=15, width=1.3, shape=circle];\n", i+1, i+1, electrondensity); } fprintf(fd, " // Connection information\n"); for(int i = 0, ij = 0; i < natoms; ++i) { for(int j = i; j < natoms; ++j, ++ij) { if((i != j) && (upperadjacencymatrix[ij] != 0)) { const double bondorder = bondorders[ij]; fprintf(fd, " \"C%d\" -- \"C%d\" [label=\"%.5f\", fontsize=15, color=black];\n", i+1, j+1, bondorder); } } } fprintf(fd, "}\n"); fclose(fd); } // Diagolization // // Input: A: a11, a12, a13, ... a22, a23, ... // Output: eigenvalues: lambda1, lambda2, lambda3, ... // eigenvectors: v1, v2, v3, ... // Return: info int Hueckel::dsyev(int m, const vector<double>& A, vector<double>& eigenvalues, vector<double>& eigenvectors) const { char jobz = 'V'; char uplo = 'U'; int n = m; vector<double> ta; int lda = m; vector<double> tw; int lwork; double dwork; vector<double> work; int info; unsigned int dimA = n*(n+1)/2; if(A.size() != dimA) { RunStatus::ErrorTermination("The parameter m ( %d ) and size of A ( %d ) in dsyev are incompatible.", m, A.size()); } // Copy the data int ncounter = 0; unsigned int dimta = m*m; ta.clear(); ta.assign(dimta, 0.0000); int idx = 0; for(int i = 0; i < m; ++i) { for(int j = i; j < m; ++j) { ta[j*m+i] = A[idx]; ++idx; } } // Detect the optimal lwork lwork = -1; dsyev_(&jobz, &uplo, &n, &(ta[0]), &lda, &(tw[0]), &dwork, &lwork, &info); lwork = (int)dwork; work.assign(lwork, 0.0000); // Diagonaization tw.clear(); tw.assign(m, 0.0000); dsyev_(&jobz, &uplo, &n, &(ta[0]), &lda, &(tw[0]), &(work[0]), &lwork, &info); eigenvectors.clear(); eigenvectors.assign(ta.begin(), ta.end()); eigenvalues.clear(); eigenvalues.assign(tw.begin(), tw.end()); return info; } <|endoftext|>
<commit_before>// Copyright 2017 Global Phasing Ltd. // // Functions for transparent reading of gzipped files. Uses zlib. #ifndef GEMMI_GZ_HPP_ #define GEMMI_GZ_HPP_ #include <cassert> #include <cstdio> // fseek, ftell, fread #include <climits> // INT_MAX #include <memory> #include <string> #include <zlib.h> #include "fail.hpp" // fail #include "fileutil.hpp" // file_open #include "input.hpp" // BasicInput #include "util.hpp" // iends_with namespace gemmi { // Throws if the size is not found or if it is suspicious. // Anything outside of the arbitrary limits from 1 to 10x of the compressed // size looks suspicious to us. inline size_t estimate_uncompressed_size(const std::string& path) { fileptr_t f = file_open(path.c_str(), "rb"); if (std::fseek(f.get(), -4, SEEK_END) != 0) fail("fseek() failed (empty file?): " + path); long pos = std::ftell(f.get()); if (pos <= 0) fail("ftell() failed on " + path); size_t gzipped_size = pos + 4; unsigned char buf[4]; if (std::fread(buf, 1, 4, f.get()) != 4) fail("Failed to read last 4 bytes of: " + path); unsigned orig_size = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf[0]; if (orig_size + 100 < gzipped_size || orig_size > 100 * gzipped_size) fail("Cannot determine uncompressed size of " + path + "\nWould it be " + std::to_string(gzipped_size) + " -> " + std::to_string(orig_size) + " bytes?"); return orig_size; } inline size_t big_gzread(gzFile file, void* buf, size_t len) { // In zlib >= 1.2.9 we could use gzfread() // return gzfread(buf, len, 1, f) == 1; size_t read_bytes = 0; while (len > INT_MAX) { int ret = gzread(file, buf, INT_MAX); read_bytes += ret; if (ret != INT_MAX) return read_bytes; len -= INT_MAX; buf = (char*) buf + INT_MAX; } read_bytes += gzread(file, buf, (unsigned) len); return read_bytes; } class MaybeGzipped : public BasicInput { public: struct GzStream { gzFile f; char* gets(char* line, int size) { return gzgets(f, line, size); } int getc() { return gzgetc(f); } bool read(void* buf, size_t len) { return big_gzread(f, buf, len) == len; } }; explicit MaybeGzipped(const std::string& path) : BasicInput(path), memory_size_(0), file_(nullptr) {} ~MaybeGzipped() { if (file_) #if ZLIB_VERNUM >= 0x1235 gzclose_r(file_); #else gzclose(file_); #endif } size_t gzread_checked(void* buf, size_t len) { size_t read_bytes = big_gzread(file_, buf, len); if (read_bytes != len && !gzeof(file_)) { int errnum; std::string err_str = gzerror(file_, &errnum); if (errnum) fail("Error reading " + path() + ": " + err_str); } if (read_bytes > len) // should never happen fail("Error reading " + path()); return read_bytes; } bool is_compressed() const { return iends_with(path(), ".gz"); } std::string basepath() const { return is_compressed() ? path().substr(0, path().size() - 3) : path(); } size_t memory_size() const { return memory_size_; } std::unique_ptr<char[]> memory() { if (!is_compressed()) return BasicInput::memory(); memory_size_ = estimate_uncompressed_size(path()); open(); if (memory_size_ > 3221225471) fail("For now gz files above 3 GiB uncompressed are not supported."); std::unique_ptr<char[]> mem(new char[memory_size_]); size_t read_bytes = gzread_checked(mem.get(), memory_size_); // if the file is shorter than the size from header, adjust memory_size_ if (read_bytes < memory_size_) { memory_size_ = read_bytes; } else { // read_bytes == memory_size_ // if the file is longer than the size from header, read in the rest int next_char; while (!gzeof(file_) && (next_char = gzgetc(file_)) != -1) { if (memory_size_ > 3221225471) fail("For now gz files above 3 GiB uncompressed are not supported."); gzungetc(next_char, file_); std::unique_ptr<char[]> mem2(new char[2 * memory_size_]); std::memcpy(mem2.get(), mem.get(), memory_size_); memory_size_ += gzread_checked(mem2.get() + memory_size_, memory_size_); mem2.swap(mem); } } return mem; } GzStream get_uncompressing_stream() { assert(is_compressed()); open(); #if ZLIB_VERNUM >= 0x1235 gzbuffer(file_, 64*1024); #endif return GzStream{file_}; } private: size_t memory_size_; gzFile file_; void open() { file_ = gzopen(path().c_str(), "rb"); if (!file_) fail("Failed to gzopen: " + path()); } }; } // namespace gemmi #endif <commit_msg>gz.hpp: more informative error message<commit_after>// Copyright 2017 Global Phasing Ltd. // // Functions for transparent reading of gzipped files. Uses zlib. #ifndef GEMMI_GZ_HPP_ #define GEMMI_GZ_HPP_ #include <cassert> #include <cstdio> // fseek, ftell, fread #include <climits> // INT_MAX #include <memory> #include <string> #include <zlib.h> #include "fail.hpp" // fail #include "fileutil.hpp" // file_open #include "input.hpp" // BasicInput #include "util.hpp" // iends_with namespace gemmi { // Throws if the size is not found or if it is suspicious. // Anything outside of the arbitrary limits from 1 to 10x of the compressed // size looks suspicious to us. inline size_t estimate_uncompressed_size(const std::string& path) { fileptr_t f = file_open(path.c_str(), "rb"); if (std::fseek(f.get(), -4, SEEK_END) != 0) fail("fseek() failed (empty file?): " + path); long pos = std::ftell(f.get()); if (pos <= 0) fail("ftell() failed on " + path); size_t gzipped_size = pos + 4; unsigned char buf[4]; if (std::fread(buf, 1, 4, f.get()) != 4) fail("Failed to read last 4 bytes of: " + path); unsigned orig_size = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf[0]; if (orig_size + 100 < gzipped_size || orig_size > 100 * gzipped_size) fail("Cannot determine uncompressed size of " + path + "\nWould it be " + std::to_string(gzipped_size) + " -> " + std::to_string(orig_size) + " bytes?"); return orig_size; } inline size_t big_gzread(gzFile file, void* buf, size_t len) { // In zlib >= 1.2.9 we could use gzfread() // return gzfread(buf, len, 1, f) == 1; size_t read_bytes = 0; while (len > INT_MAX) { int ret = gzread(file, buf, INT_MAX); read_bytes += ret; if (ret != INT_MAX) return read_bytes; len -= INT_MAX; buf = (char*) buf + INT_MAX; } read_bytes += gzread(file, buf, (unsigned) len); return read_bytes; } class MaybeGzipped : public BasicInput { public: struct GzStream { gzFile f; char* gets(char* line, int size) { return gzgets(f, line, size); } int getc() { return gzgetc(f); } bool read(void* buf, size_t len) { return big_gzread(f, buf, len) == len; } }; explicit MaybeGzipped(const std::string& path) : BasicInput(path), memory_size_(0), file_(nullptr) {} ~MaybeGzipped() { if (file_) #if ZLIB_VERNUM >= 0x1235 gzclose_r(file_); #else gzclose(file_); #endif } size_t gzread_checked(void* buf, size_t len) { size_t read_bytes = big_gzread(file_, buf, len); if (read_bytes != len && !gzeof(file_)) { int errnum; std::string err_str = gzerror(file_, &errnum); if (errnum) fail("Error reading " + path() + ": " + err_str); } if (read_bytes > len) // should never happen fail("Error reading " + path()); return read_bytes; } bool is_compressed() const { return iends_with(path(), ".gz"); } std::string basepath() const { return is_compressed() ? path().substr(0, path().size() - 3) : path(); } size_t memory_size() const { return memory_size_; } std::unique_ptr<char[]> memory() { if (!is_compressed()) return BasicInput::memory(); memory_size_ = estimate_uncompressed_size(path()); open(); if (memory_size_ > 3221225471) fail("For now gz files above 3 GiB uncompressed are not supported.\n" "To read " + path() + " first uncompress it."); std::unique_ptr<char[]> mem(new char[memory_size_]); size_t read_bytes = gzread_checked(mem.get(), memory_size_); // if the file is shorter than the size from header, adjust memory_size_ if (read_bytes < memory_size_) { memory_size_ = read_bytes; } else { // read_bytes == memory_size_ // if the file is longer than the size from header, read in the rest int next_char; while (!gzeof(file_) && (next_char = gzgetc(file_)) != -1) { if (memory_size_ > 3221225471) fail("For now gz files above 3 GiB uncompressed are not supported.\n" "To read " + path() + " first uncompress it."); gzungetc(next_char, file_); std::unique_ptr<char[]> mem2(new char[2 * memory_size_]); std::memcpy(mem2.get(), mem.get(), memory_size_); memory_size_ += gzread_checked(mem2.get() + memory_size_, memory_size_); mem2.swap(mem); } } return mem; } GzStream get_uncompressing_stream() { assert(is_compressed()); open(); #if ZLIB_VERNUM >= 0x1235 gzbuffer(file_, 64*1024); #endif return GzStream{file_}; } private: size_t memory_size_; gzFile file_; void open() { file_ = gzopen(path().c_str(), "rb"); if (!file_) fail("Failed to gzopen: " + path()); } }; } // namespace gemmi #endif <|endoftext|>
<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/session.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace libtorrent; void bind_session_settings() { class_<session_settings>("session_settings") .def_readwrite("user_agent", &session_settings::user_agent) .def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout) .def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout) .def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length) .def_readwrite("piece_timeout", &session_settings::piece_timeout) .def_readwrite("request_queue_time", &session_settings::request_queue_time) .def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue) .def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue) .def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold) .def_readwrite("peer_timeout", &session_settings::peer_timeout) .def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout) .def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size) .def_readwrite("file_pool_size", &session_settings::file_pool_size) .def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip) .def_readwrite("max_failcount", &session_settings::max_failcount) .def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time) .def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout) .def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network) .def_readwrite("connection_speed", &session_settings::connection_speed) .def_readwrite("send_redundant_have", &session_settings::send_redundant_have) .def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields) .def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout) .def_readwrite("unchoke_interval", &session_settings::unchoke_interval) .def_readwrite("active_downloads", &session_settings::active_downloads) .def_readwrite("active_seeds", &session_settings::active_seeds) .def_readwrite("active_limit", &session_settings::active_limit) .def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents) .def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval) .def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit) .def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit) .def_readwrite("seed_time_limit", &session_settings::seed_time_limit) .def_readwrite("auto_scraped_interval", &session_settings::auto_scrape_interval) #ifndef TORRENT_DISABLE_DHT .def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback) #endif ; enum_<proxy_settings::proxy_type>("proxy_type") .value("none", proxy_settings::none) .value("socks4", proxy_settings::socks4) .value("socks5", proxy_settings::socks5) .value("socks5_pw", proxy_settings::socks5_pw) .value("http", proxy_settings::http) .value("http_pw", proxy_settings::http_pw) ; class_<proxy_settings>("proxy_settings") .def_readwrite("hostname", &proxy_settings::hostname) .def_readwrite("port", &proxy_settings::port) .def_readwrite("password", &proxy_settings::password) .def_readwrite("username", &proxy_settings::username) .def_readwrite("type", &proxy_settings::type) ; #ifndef TORRENT_DISABLE_ENCRYPTION enum_<pe_settings::enc_policy>("enc_policy") .value("forced", pe_settings::forced) .value("enabled", pe_settings::enabled) .value("disabled", pe_settings::disabled) ; enum_<pe_settings::enc_level>("enc_level") .value("rc4", pe_settings::rc4) .value("plaintext", pe_settings::plaintext) .value("both", pe_settings::both) ; class_<pe_settings>("pe_settings") .def_readwrite("out_enc_policy", &pe_settings::out_enc_policy) .def_readwrite("in_enc_policy", &pe_settings::in_enc_policy) .def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level) .def_readwrite("prefer_rc4", &pe_settings::prefer_rc4) ; #endif } <commit_msg>Add session_settings::peer_tos to bindings<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/session.hpp> #include <boost/python.hpp> using namespace boost::python; using namespace libtorrent; void bind_session_settings() { class_<session_settings>("session_settings") .def_readwrite("user_agent", &session_settings::user_agent) .def_readwrite("tracker_completion_timeout", &session_settings::tracker_completion_timeout) .def_readwrite("tracker_receive_timeout", &session_settings::tracker_receive_timeout) .def_readwrite("tracker_maximum_response_length", &session_settings::tracker_maximum_response_length) .def_readwrite("piece_timeout", &session_settings::piece_timeout) .def_readwrite("request_queue_time", &session_settings::request_queue_time) .def_readwrite("max_allowed_in_request_queue", &session_settings::max_allowed_in_request_queue) .def_readwrite("max_out_request_queue", &session_settings::max_out_request_queue) .def_readwrite("whole_pieces_threshold", &session_settings::whole_pieces_threshold) .def_readwrite("peer_timeout", &session_settings::peer_timeout) .def_readwrite("urlseed_timeout", &session_settings::urlseed_timeout) .def_readwrite("urlseed_pipeline_size", &session_settings::urlseed_pipeline_size) .def_readwrite("file_pool_size", &session_settings::file_pool_size) .def_readwrite("allow_multiple_connections_per_ip", &session_settings::allow_multiple_connections_per_ip) .def_readwrite("max_failcount", &session_settings::max_failcount) .def_readwrite("min_reconnect_time", &session_settings::min_reconnect_time) .def_readwrite("peer_connect_timeout", &session_settings::peer_connect_timeout) .def_readwrite("ignore_limits_on_local_network", &session_settings::ignore_limits_on_local_network) .def_readwrite("connection_speed", &session_settings::connection_speed) .def_readwrite("send_redundant_have", &session_settings::send_redundant_have) .def_readwrite("lazy_bitfields", &session_settings::lazy_bitfields) .def_readwrite("inactivity_timeout", &session_settings::inactivity_timeout) .def_readwrite("unchoke_interval", &session_settings::unchoke_interval) .def_readwrite("active_downloads", &session_settings::active_downloads) .def_readwrite("active_seeds", &session_settings::active_seeds) .def_readwrite("active_limit", &session_settings::active_limit) .def_readwrite("dont_count_slow_torrents", &session_settings::dont_count_slow_torrents) .def_readwrite("auto_manage_interval", &session_settings::auto_manage_interval) .def_readwrite("share_ratio_limit", &session_settings::share_ratio_limit) .def_readwrite("seed_time_ratio_limit", &session_settings::seed_time_ratio_limit) .def_readwrite("seed_time_limit", &session_settings::seed_time_limit) .def_readwrite("auto_scraped_interval", &session_settings::auto_scrape_interval) .def_readwrite("peer_tos", &session_settings::peer_tos) #ifndef TORRENT_DISABLE_DHT .def_readwrite("use_dht_as_fallback", &session_settings::use_dht_as_fallback) #endif ; enum_<proxy_settings::proxy_type>("proxy_type") .value("none", proxy_settings::none) .value("socks4", proxy_settings::socks4) .value("socks5", proxy_settings::socks5) .value("socks5_pw", proxy_settings::socks5_pw) .value("http", proxy_settings::http) .value("http_pw", proxy_settings::http_pw) ; class_<proxy_settings>("proxy_settings") .def_readwrite("hostname", &proxy_settings::hostname) .def_readwrite("port", &proxy_settings::port) .def_readwrite("password", &proxy_settings::password) .def_readwrite("username", &proxy_settings::username) .def_readwrite("type", &proxy_settings::type) ; #ifndef TORRENT_DISABLE_ENCRYPTION enum_<pe_settings::enc_policy>("enc_policy") .value("forced", pe_settings::forced) .value("enabled", pe_settings::enabled) .value("disabled", pe_settings::disabled) ; enum_<pe_settings::enc_level>("enc_level") .value("rc4", pe_settings::rc4) .value("plaintext", pe_settings::plaintext) .value("both", pe_settings::both) ; class_<pe_settings>("pe_settings") .def_readwrite("out_enc_policy", &pe_settings::out_enc_policy) .def_readwrite("in_enc_policy", &pe_settings::in_enc_policy) .def_readwrite("allowed_enc_level", &pe_settings::allowed_enc_level) .def_readwrite("prefer_rc4", &pe_settings::prefer_rc4) ; #endif } <|endoftext|>
<commit_before>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" // This is a GR test #if SK_SUPPORT_GPU #include "GrContextFactory.h" #include "SkGpuDevice.h" #include "../../src/gpu/GrClipMaskManager.h" static const int X_SIZE = 12; static const int Y_SIZE = 12; //////////////////////////////////////////////////////////////////////////////// // note: this is unused static GrTexture* createTexture(GrContext* context) { unsigned char textureData[X_SIZE][Y_SIZE][4]; memset(textureData, 0, 4* X_SIZE * Y_SIZE); GrTextureDesc desc; // let Skia know we will be using this texture as a render target desc.fFlags = kRenderTarget_GrTextureFlagBit; desc.fConfig = kSkia8888_GrPixelConfig; desc.fWidth = X_SIZE; desc.fHeight = Y_SIZE; // We are initializing the texture with zeros here GrTexture* texture = context->createUncachedTexture(desc, textureData, 0); if (!texture) { return NULL; } return texture; } // Ensure that the 'getConservativeBounds' calls are returning bounds clamped // to the render target static void test_clip_bounds(skiatest::Reporter* reporter, GrContext* context) { static const int kXSize = 100; static const int kYSize = 100; GrTextureDesc desc; desc.fFlags = kRenderTarget_GrTextureFlagBit; desc.fConfig = kAlpha_8_GrPixelConfig; desc.fWidth = kXSize; desc.fHeight = kYSize; GrTexture* texture = context->createUncachedTexture(desc, NULL, 0); if (!texture) { return; } GrAutoUnref au(texture); SkIRect intScreen = SkIRect::MakeWH(kXSize, kYSize); SkRect screen = SkRect::MakeWH(SkIntToScalar(kXSize), SkIntToScalar(kYSize)); SkRect clipRect(screen); clipRect.outset(10, 10); // create a clip stack that will (trivially) reduce to a single rect that // is larger than the screen SkClipStack stack; stack.clipDevRect(clipRect, SkRegion::kReplace_Op, false); bool isIntersectionOfRects = true; SkRect devStackBounds; stack.getConservativeBounds(0, 0, kXSize, kYSize, &devStackBounds, &isIntersectionOfRects); // make sure that the SkClipStack is behaving itself REPORTER_ASSERT(reporter, screen == devStackBounds); REPORTER_ASSERT(reporter, isIntersectionOfRects); // wrap the SkClipStack in a GrClipData GrClipData clipData; clipData.fClipStack = &stack; SkIRect devGrClipDataBound; clipData.getConservativeBounds(texture, &devGrClipDataBound, &isIntersectionOfRects); // make sure that GrClipData is behaving itself REPORTER_ASSERT(reporter, intScreen == devGrClipDataBound); REPORTER_ASSERT(reporter, isIntersectionOfRects); } //////////////////////////////////////////////////////////////////////////////// // verify that the top state of the stack matches the passed in state static void check_state(skiatest::Reporter* reporter, const GrClipMaskCache& cache, const SkClipStack& clip, GrTexture* mask, const GrIRect& bound) { SkClipStack cacheClip; REPORTER_ASSERT(reporter, clip.getTopmostGenID() == cache.getLastClipGenID()); REPORTER_ASSERT(reporter, mask == cache.getLastMask()); GrIRect cacheBound; cache.getLastBound(&cacheBound); REPORTER_ASSERT(reporter, bound == cacheBound); } //////////////////////////////////////////////////////////////////////////////// // basic test of the cache's base functionality: // push, pop, set, canReuse & getters static void test_cache(skiatest::Reporter* reporter, GrContext* context) { if (false) { // avoid bit rot, suppress warning createTexture(context); } GrClipMaskCache cache; cache.setContext(context); SkClipStack emptyClip; emptyClip.reset(); GrIRect emptyBound; emptyBound.setEmpty(); // check initial state check_state(reporter, cache, emptyClip, NULL, emptyBound); // set the current state GrIRect bound1; bound1.set(0, 0, 100, 100); SkClipStack clip1(bound1); GrTextureDesc desc; desc.fFlags = kRenderTarget_GrTextureFlagBit; desc.fWidth = X_SIZE; desc.fHeight = Y_SIZE; desc.fConfig = kSkia8888_GrPixelConfig; cache.acquireMask(clip1.getTopmostGenID(), desc, bound1); GrTexture* texture1 = cache.getLastMask(); REPORTER_ASSERT(reporter, texture1); if (NULL == texture1) { return; } // check that the set took check_state(reporter, cache, clip1, texture1, bound1); REPORTER_ASSERT(reporter, texture1->getRefCnt()); // push the state cache.push(); // verify that the pushed state is initially empty check_state(reporter, cache, emptyClip, NULL, emptyBound); REPORTER_ASSERT(reporter, texture1->getRefCnt()); // modify the new state GrIRect bound2; bound2.set(-10, -10, 10, 10); SkClipStack clip2(bound2); cache.acquireMask(clip2.getTopmostGenID(), desc, bound2); GrTexture* texture2 = cache.getLastMask(); REPORTER_ASSERT(reporter, texture2); if (NULL == texture2) { return; } // check that the changes took check_state(reporter, cache, clip2, texture2, bound2); REPORTER_ASSERT(reporter, texture1->getRefCnt()); REPORTER_ASSERT(reporter, texture2->getRefCnt()); // check to make sure canReuse works REPORTER_ASSERT(reporter, cache.canReuse(clip2.getTopmostGenID(), bound2)); REPORTER_ASSERT(reporter, !cache.canReuse(clip1.getTopmostGenID(), bound1)); // pop the state cache.pop(); // verify that the old state is restored check_state(reporter, cache, clip1, texture1, bound1); REPORTER_ASSERT(reporter, texture1->getRefCnt()); REPORTER_ASSERT(reporter, texture2->getRefCnt()); // manually clear the state cache.reset(); // verify it is now empty check_state(reporter, cache, emptyClip, NULL, emptyBound); REPORTER_ASSERT(reporter, texture1->getRefCnt()); REPORTER_ASSERT(reporter, texture2->getRefCnt()); // pop again - so there is no state cache.pop(); #if !defined(SK_DEBUG) // verify that the getters don't crash // only do in release since it generates asserts in debug check_state(reporter, cache, emptyClip, NULL, emptyBound); #endif REPORTER_ASSERT(reporter, texture1->getRefCnt()); REPORTER_ASSERT(reporter, texture2->getRefCnt()); } //////////////////////////////////////////////////////////////////////////////// static void TestClipCache(skiatest::Reporter* reporter, GrContextFactory* factory) { for (int type = 0; type < GrContextFactory::kLastGLContextType; ++type) { GrContextFactory::GLContextType glType = static_cast<GrContextFactory::GLContextType>(type); if (!GrContextFactory::IsRenderingGLContext(glType)) { continue; } GrContext* context = factory->get(glType); if (NULL == context) { continue; } test_cache(reporter, context); test_clip_bounds(reporter, context); } } //////////////////////////////////////////////////////////////////////////////// #include "TestClassDef.h" DEFINE_GPUTESTCLASS("ClipCache", ClipCacheTestClass, TestClipCache) #endif <commit_msg>Fix Mac 10.8 64-bit Release ClipCacheTest issue<commit_after>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" // This is a GR test #if SK_SUPPORT_GPU #include "GrContextFactory.h" #include "SkGpuDevice.h" #include "../../src/gpu/GrClipMaskManager.h" static const int X_SIZE = 12; static const int Y_SIZE = 12; //////////////////////////////////////////////////////////////////////////////// // note: this is unused static GrTexture* createTexture(GrContext* context) { unsigned char textureData[X_SIZE][Y_SIZE][4]; memset(textureData, 0, 4* X_SIZE * Y_SIZE); GrTextureDesc desc; // let Skia know we will be using this texture as a render target desc.fFlags = kRenderTarget_GrTextureFlagBit; desc.fConfig = kSkia8888_GrPixelConfig; desc.fWidth = X_SIZE; desc.fHeight = Y_SIZE; // We are initializing the texture with zeros here GrTexture* texture = context->createUncachedTexture(desc, textureData, 0); if (!texture) { return NULL; } return texture; } // Ensure that the 'getConservativeBounds' calls are returning bounds clamped // to the render target static void test_clip_bounds(skiatest::Reporter* reporter, GrContext* context) { static const int kXSize = 100; static const int kYSize = 100; GrTextureDesc desc; desc.fFlags = kRenderTarget_GrTextureFlagBit; desc.fConfig = kAlpha_8_GrPixelConfig; desc.fWidth = kXSize; desc.fHeight = kYSize; GrTexture* texture = context->createUncachedTexture(desc, NULL, 0); if (!texture) { return; } GrAutoUnref au(texture); SkIRect intScreen = SkIRect::MakeWH(kXSize, kYSize); SkRect screen; screen = SkRect::MakeWH(SkIntToScalar(kXSize), SkIntToScalar(kYSize)); SkRect clipRect(screen); clipRect.outset(10, 10); // create a clip stack that will (trivially) reduce to a single rect that // is larger than the screen SkClipStack stack; stack.clipDevRect(clipRect, SkRegion::kReplace_Op, false); bool isIntersectionOfRects = true; SkRect devStackBounds; stack.getConservativeBounds(0, 0, kXSize, kYSize, &devStackBounds, &isIntersectionOfRects); // make sure that the SkClipStack is behaving itself REPORTER_ASSERT(reporter, screen == devStackBounds); REPORTER_ASSERT(reporter, isIntersectionOfRects); // wrap the SkClipStack in a GrClipData GrClipData clipData; clipData.fClipStack = &stack; SkIRect devGrClipDataBound; clipData.getConservativeBounds(texture, &devGrClipDataBound, &isIntersectionOfRects); // make sure that GrClipData is behaving itself REPORTER_ASSERT(reporter, intScreen == devGrClipDataBound); REPORTER_ASSERT(reporter, isIntersectionOfRects); } //////////////////////////////////////////////////////////////////////////////// // verify that the top state of the stack matches the passed in state static void check_state(skiatest::Reporter* reporter, const GrClipMaskCache& cache, const SkClipStack& clip, GrTexture* mask, const GrIRect& bound) { SkClipStack cacheClip; REPORTER_ASSERT(reporter, clip.getTopmostGenID() == cache.getLastClipGenID()); REPORTER_ASSERT(reporter, mask == cache.getLastMask()); GrIRect cacheBound; cache.getLastBound(&cacheBound); REPORTER_ASSERT(reporter, bound == cacheBound); } //////////////////////////////////////////////////////////////////////////////// // basic test of the cache's base functionality: // push, pop, set, canReuse & getters static void test_cache(skiatest::Reporter* reporter, GrContext* context) { if (false) { // avoid bit rot, suppress warning createTexture(context); } GrClipMaskCache cache; cache.setContext(context); SkClipStack emptyClip; emptyClip.reset(); GrIRect emptyBound; emptyBound.setEmpty(); // check initial state check_state(reporter, cache, emptyClip, NULL, emptyBound); // set the current state GrIRect bound1; bound1.set(0, 0, 100, 100); SkClipStack clip1(bound1); GrTextureDesc desc; desc.fFlags = kRenderTarget_GrTextureFlagBit; desc.fWidth = X_SIZE; desc.fHeight = Y_SIZE; desc.fConfig = kSkia8888_GrPixelConfig; cache.acquireMask(clip1.getTopmostGenID(), desc, bound1); GrTexture* texture1 = cache.getLastMask(); REPORTER_ASSERT(reporter, texture1); if (NULL == texture1) { return; } // check that the set took check_state(reporter, cache, clip1, texture1, bound1); REPORTER_ASSERT(reporter, texture1->getRefCnt()); // push the state cache.push(); // verify that the pushed state is initially empty check_state(reporter, cache, emptyClip, NULL, emptyBound); REPORTER_ASSERT(reporter, texture1->getRefCnt()); // modify the new state GrIRect bound2; bound2.set(-10, -10, 10, 10); SkClipStack clip2(bound2); cache.acquireMask(clip2.getTopmostGenID(), desc, bound2); GrTexture* texture2 = cache.getLastMask(); REPORTER_ASSERT(reporter, texture2); if (NULL == texture2) { return; } // check that the changes took check_state(reporter, cache, clip2, texture2, bound2); REPORTER_ASSERT(reporter, texture1->getRefCnt()); REPORTER_ASSERT(reporter, texture2->getRefCnt()); // check to make sure canReuse works REPORTER_ASSERT(reporter, cache.canReuse(clip2.getTopmostGenID(), bound2)); REPORTER_ASSERT(reporter, !cache.canReuse(clip1.getTopmostGenID(), bound1)); // pop the state cache.pop(); // verify that the old state is restored check_state(reporter, cache, clip1, texture1, bound1); REPORTER_ASSERT(reporter, texture1->getRefCnt()); REPORTER_ASSERT(reporter, texture2->getRefCnt()); // manually clear the state cache.reset(); // verify it is now empty check_state(reporter, cache, emptyClip, NULL, emptyBound); REPORTER_ASSERT(reporter, texture1->getRefCnt()); REPORTER_ASSERT(reporter, texture2->getRefCnt()); // pop again - so there is no state cache.pop(); #if !defined(SK_DEBUG) // verify that the getters don't crash // only do in release since it generates asserts in debug check_state(reporter, cache, emptyClip, NULL, emptyBound); #endif REPORTER_ASSERT(reporter, texture1->getRefCnt()); REPORTER_ASSERT(reporter, texture2->getRefCnt()); } //////////////////////////////////////////////////////////////////////////////// static void TestClipCache(skiatest::Reporter* reporter, GrContextFactory* factory) { for (int type = 0; type < GrContextFactory::kLastGLContextType; ++type) { GrContextFactory::GLContextType glType = static_cast<GrContextFactory::GLContextType>(type); if (!GrContextFactory::IsRenderingGLContext(glType)) { continue; } GrContext* context = factory->get(glType); if (NULL == context) { continue; } test_cache(reporter, context); test_clip_bounds(reporter, context); } } //////////////////////////////////////////////////////////////////////////////// #include "TestClassDef.h" DEFINE_GPUTESTCLASS("ClipCache", ClipCacheTestClass, TestClipCache) #endif <|endoftext|>
<commit_before>#pragma once //=========================================================================// /*! @file @brief UDP Protocol 全体管理 @n Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=========================================================================// #include "net2/udp.hpp" namespace net { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief UDP マネージメント・クラス @param[in] ETHER イーサーネット・ドライバー・クラス @param[in] NMAX 管理最大数 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template<class ETHER, uint32_t NMAX> class udp_manage { ETHER& eth_; udp udp_[NMAX]; struct frame_t { eth_h eh_; ipv4_h ipv4_; udp_h udp_; } __attribute__((__packed__)); struct csum_h { // UDP checksum header ip_adrs src_; ip_adrs dst_; uint16_t fix_; uint16_t len_; }; public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] eth イーサーネット・ドライバー */ //-----------------------------------------------------------------// udp_manage(ETHER& eth) : eth_(eth) { } //-----------------------------------------------------------------// /*! @brief 格納可能な最大サイズを返す @return 格納可能な最大サイズ */ //-----------------------------------------------------------------// uint32_t capacity() const noexcept { return NMAX; } //-----------------------------------------------------------------// /*! @brief オープン @param[in] adrs アドレス @param[in] sport 転送元ポート @param[in] dport 転送先ポート @return ディスクリプタ */ //-----------------------------------------------------------------// int open(const ip_adrs& adrs, uint16_t sport, uint16_t dport) { int ds = 0; for(uint32_t i = 0; i < NMAX; ++i) { if(udp_[i].empty()) { udp_[i].open(adrs, sport, dport); return i; } } return -1; } //-----------------------------------------------------------------// /*! @brief プロセス(割り込みから呼ばれる) @param[in] eh イーサーネット・ヘッダー @param[in] ih IPV4 ヘッダー @param[in] msg メッセージ先頭 @param[in] len メッセージ長 @return エラーが無い場合「true」 */ //-----------------------------------------------------------------// bool process(const eth_h& eh, const ipv4_h& ih, const void* msg, int32_t len) { return true; } //-----------------------------------------------------------------// /*! @brief サービス(10ms毎に呼ぶ) */ //-----------------------------------------------------------------// void service() { for(udp& u : udp_) { /// u.service(); } } }; } <commit_msg>update manage context<commit_after>#pragma once //=========================================================================// /*! @file @brief UDP Protocol 全体管理 @n Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=========================================================================// #include "net2/udp.hpp" #include "common/fixed_block.hpp" namespace net { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief UDP マネージメント・クラス @param[in] ETHER イーサーネット・ドライバー・クラス @param[in] NMAX 管理最大数 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template<class ETHER, uint32_t NMAX> class udp_manage { ETHER& eth_; typedef utils::fixed_block<udp, NMAX> UDP_BLOCK; UDP_BLOCK udps_; struct frame_t { eth_h eh_; ipv4_h ipv4_; udp_h udp_; } __attribute__((__packed__)); struct csum_h { // UDP checksum header ip_adrs src_; ip_adrs dst_; uint16_t fix_; uint16_t len_; }; public: //-----------------------------------------------------------------// /*! @brief コンストラクター @param[in] eth イーサーネット・ドライバー */ //-----------------------------------------------------------------// udp_manage(ETHER& eth) : eth_(eth) { } //-----------------------------------------------------------------// /*! @brief 格納可能な最大サイズを返す @return 格納可能な最大サイズ */ //-----------------------------------------------------------------// uint32_t capacity() const noexcept { return NMAX; } //-----------------------------------------------------------------// /*! @brief オープン @param[in] adrs アドレス @param[in] sport 転送元ポート @param[in] dport 転送先ポート @return ディスクリプタ */ //-----------------------------------------------------------------// int open(const ip_adrs& adrs, uint16_t sport, uint16_t dport) { uint32_t idx = udps_.alloc(); if(udps_.is_alloc(idx)) { udps_.at(idx).open(adrs, sport, dport); return idx; } return -1; } //-----------------------------------------------------------------// /*! @brief プロセス(割り込みから呼ばれる) @param[in] eh イーサーネット・ヘッダー @param[in] ih IPV4 ヘッダー @param[in] msg メッセージ先頭 @param[in] len メッセージ長 @return エラーが無い場合「true」 */ //-----------------------------------------------------------------// bool process(const eth_h& eh, const ipv4_h& ih, const void* msg, int32_t len) { return true; } //-----------------------------------------------------------------// /*! @brief サービス(10ms毎に呼ぶ) */ //-----------------------------------------------------------------// void service() { } }; } <|endoftext|>
<commit_before>#include "WsaSocket.h" #include "WsaException.h" WsaSocket::WsaSocket(int family, int type, int protocol) { _socket = socket(family, type, protocol); if (_socket == INVALID_SOCKET) { throw WsaException("Error at socket()", WSAGetLastError()); } } WsaSocket::~WsaSocket() { if (_connected) { closesocket(_socket); } } void WsaSocket::connect(addrinfo &address) { auto result = ::connect(_socket, address.ai_addr, address.ai_addrlen); _connected = true; if (result == SOCKET_ERROR) { throw WsaException("Connection error", WSAGetLastError()); } } void WsaSocket::send(const char *bytes, int length) { auto result = ::send(_socket, bytes, length, 0); if (result == SOCKET_ERROR) { throw WsaException("Sending error", WSAGetLastError()); } } void WsaSocket::send(std::uint32_t data) { const auto size = sizeof(std::uint32_t); char buffer[4] = {}; auto networkOrderData = static_cast<std::uint32_t>(::htonl(data)); ::memcpy(buffer, &networkOrderData, size); send(buffer, size); } void WsaSocket::send(const std::string &string) { send(string.c_str(), string.length()); } SOCKET WsaSocket::handle() const { return _socket; } <commit_msg>Rewrite conversion without memcpy.<commit_after>#include "WsaSocket.h" #include "WsaException.h" WsaSocket::WsaSocket(int family, int type, int protocol) { _socket = socket(family, type, protocol); if (_socket == INVALID_SOCKET) { throw WsaException("Error at socket()", WSAGetLastError()); } } WsaSocket::~WsaSocket() { if (_connected) { closesocket(_socket); } } void WsaSocket::connect(addrinfo &address) { auto result = ::connect(_socket, address.ai_addr, address.ai_addrlen); _connected = true; if (result == SOCKET_ERROR) { throw WsaException("Connection error", WSAGetLastError()); } } void WsaSocket::send(const char *bytes, int length) { auto result = ::send(_socket, bytes, length, 0); if (result == SOCKET_ERROR) { throw WsaException("Sending error", WSAGetLastError()); } } void WsaSocket::send(std::uint32_t data) { const auto size = sizeof(std::uint32_t); union { std::uint32_t data; char bytes[size]; } converter; converter.data = static_cast<std::uint32_t>(::htonl(data)); send(converter.bytes, size); } void WsaSocket::send(const std::string &string) { send(string.c_str(), string.length()); } SOCKET WsaSocket::handle() const { return _socket; } <|endoftext|>
<commit_before>#pragma once /** @file @brief functions for T[] @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #include <cybozu/bit_operation.hpp> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4456) #pragma warning(disable : 4459) #endif namespace mcl { namespace fp { // some environments do not have utility template<class T> T abs_(T x) { return x < 0 ? -x : x; } template<class T> T min_(T x, T y) { return x < y ? x : y; } template<class T> T max_(T x, T y) { return x < y ? y : x; } template<class T> void swap_(T& x, T& y) { T t; t = x; x = y; y = t; } /* get pp such that p * pp = -1 mod M, where p is prime and M = 1 << 64(or 32). @param pLow [in] p mod M */ template<class T> T getMontgomeryCoeff(T pLow) { T ret = 0; T t = 0; T x = 1; for (size_t i = 0; i < sizeof(T) * 8; i++) { if ((t & 1) == 0) { t += pLow; ret += x; } t >>= 1; x <<= 1; } return ret; } template<class T> int compareArray(const T* x, const T* y, size_t n) { for (size_t i = n - 1; i != size_t(-1); i--) { T a = x[i]; T b = y[i]; if (a != b) return a < b ? -1 : 1; } return 0; } template<class T> bool isLessArray(const T *x, const T* y, size_t n) { for (size_t i = n - 1; i != size_t(-1); i--) { T a = x[i]; T b = y[i]; if (a != b) return a < b; } return false; } template<class T> bool isGreaterOrEqualArray(const T *x, const T* y, size_t n) { return !isLessArray(x, y, n); } template<class T> bool isLessOrEqualArray(const T *x, const T* y, size_t n) { for (size_t i = n - 1; i != size_t(-1); i--) { T a = x[i]; T b = y[i]; if (a != b) return a < b; } return true; } template<class T> bool isGreaterArray(const T *x, const T* y, size_t n) { return !isLessOrEqualArray(x, y, n); } template<class T> bool isEqualArray(const T* x, const T* y, size_t n) { for (size_t i = 0; i < n; i++) { if (x[i] != y[i]) return false; } return true; } template<class T> bool isZeroArray(const T *x, size_t n) { for (size_t i = 0; i < n; i++) { if (x[i]) return false; } return true; } template<class T> void clearArray(T *x, size_t begin, size_t end) { for (size_t i = begin; i < end; i++) x[i] = 0; } template<class T> void copyArray(T *y, const T *x, size_t n) { for (size_t i = 0; i < n; i++) y[i] = x[i]; } /* x &= (1 << bitSize) - 1 */ template<class T> void maskArray(T *x, size_t n, size_t bitSize) { const size_t TbitSize = sizeof(T) * 8; assert(bitSize <= TbitSize * n); const size_t q = bitSize / TbitSize; const size_t r = bitSize % TbitSize; if (r) { x[q] &= (T(1) << r) - 1; clearArray(x, q + 1, n); } else { clearArray(x, q, n); } } /* return non zero size of x[] return 1 if x[] == 0 */ template<class T> size_t getNonZeroArraySize(const T *x, size_t n) { while (n > 0) { if (x[n - 1]) return n; n--; } return 1; } template<class T> class BitIterator { const T *x_; size_t bitPos_; size_t bitSize_; static const size_t TbitSize = sizeof(T) * 8; public: BitIterator(const T *x, size_t n) : x_(x) , bitPos_(0) { assert(n > 0); n = getNonZeroArraySize(x, n); if (n == 1 && x[0] == 0) { bitSize_ = 1; } else { assert(x_[n - 1]); bitSize_ = (n - 1) * sizeof(T) * 8 + 1 + cybozu::bsr<T>(x_[n - 1]); } } bool hasNext() const { return bitPos_ < bitSize_; } T getNext(size_t w) { assert(0 < w && w <= TbitSize); assert(hasNext()); const size_t q = bitPos_ / TbitSize; const size_t r = bitPos_ % TbitSize; const size_t remain = bitSize_ - bitPos_; if (w > remain) w = remain; T v = x_[q] >> r; if (r + w > TbitSize) { v |= x_[q + 1] << (TbitSize - r); } bitPos_ += w; return v & mask(w); } // whethere next bit is 1 or 0 (bitPos is not moved) bool peekBit() const { assert(hasNext()); const size_t q = bitPos_ / TbitSize; const size_t r = bitPos_ % TbitSize; return (x_[q] >> r) & 1; } void skipBit() { assert(hasNext()); bitPos_++; } T mask(size_t w) const { assert(w <= TbitSize); return (w == TbitSize ? T(0) : (T(1) << w)) - 1; } }; /* @param out [inout] : set element of G ; out = x^y[] @param x [in] @param y [in] @param n [in] size of y[] @param limitBit [in] const time version if the value is positive @note &out != x and out = the unit element of G */ template<class G, class Mul, class Sqr, class T> void powGeneric(G& out, const G& x, const T *y, size_t n, const Mul& mul, const Sqr& sqr, void normalize(G&, const G&), size_t limitBit = 0) { assert(&out != &x); G tbl[4]; // tbl = { discard, x, x^2, x^3 } T v; bool constTime = limitBit > 0; int maxBit = 0; int m = 0; while (n > 0) { if (y[n - 1]) break; n--; } if (n == 0) { if (constTime) goto DummyLoop; return; } if (!constTime && n == 1) { switch (y[0]) { case 1: out = x; return; case 2: sqr(out, x); return; case 3: sqr(out, x); mul(out, out, x); return; case 4: sqr(out, x); sqr(out, out); return; } } if (normalize != 0) { normalize(tbl[0], x); } else { tbl[0] = x; } tbl[1] = tbl[0]; sqr(tbl[2], tbl[1]); if (normalize != 0) { normalize(tbl[2], tbl[2]); } mul(tbl[3], tbl[2], x); if (normalize != 0) { normalize(tbl[3], tbl[3]); } v = y[n - 1]; assert(v); m = cybozu::bsr<T>(v); maxBit = int(m + (n - 1) * sizeof(T) * 8); if (m & 1) { m--; T idx = (v >> m) & 3; assert(idx > 0); out = tbl[idx]; } else { out = x; } for (int i = (int)n - 1; i >= 0; i--) { T v = y[i]; for (int j = m - 2; j >= 0; j -= 2) { sqr(out, out); sqr(out, out); T idx = (v >> j) & 3; if (idx == 0) { if (constTime) mul(tbl[0], tbl[0], tbl[1]); } else { mul(out, out, tbl[idx]); } } m = (int)sizeof(T) * 8; } DummyLoop: if (!constTime) return; G D = out; for (size_t i = maxBit + 1; i < limitBit; i += 2) { sqr(D, D); sqr(D, D); mul(D, D, tbl[1]); } } /* shortcut of multiplication by Unit */ template<class T, class U> bool mulSmallUnit(T& z, const T& x, U y) { switch (y) { case 0: z.clear(); break; case 1: z = x; break; case 2: T::add(z, x, x); break; case 3: { T t; T::add(t, x, x); T::add(z, t, x); break; } case 4: T::add(z, x, x); T::add(z, z, z); break; case 5: { T t; T::add(t, x, x); T::add(t, t, t); T::add(z, t, x); break; } case 6: { T t; T::add(t, x, x); T::add(t, t, x); T::add(z, t, t); break; } case 7: { T t; T::add(t, x, x); T::add(t, t, t); T::add(t, t, t); T::sub(z, t, x); break; } case 8: T::add(z, x, x); T::add(z, z, z); T::add(z, z, z); break; case 9: { T t; T::add(t, x, x); T::add(t, t, t); T::add(t, t, t); T::add(z, t, x); break; } case 10: { T t; T::add(t, x, x); T::add(t, t, t); T::add(t, t, x); T::add(z, t, t); break; } default: return false; } return true; } } } // mcl::fp #ifdef _MSC_VER #pragma warning(pop) #endif <commit_msg>remove warning of vc<commit_after>#pragma once /** @file @brief functions for T[] @author MITSUNARI Shigeo(@herumi) @license modified new BSD license http://opensource.org/licenses/BSD-3-Clause */ #include <cybozu/bit_operation.hpp> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4456) #pragma warning(disable : 4459) #endif namespace mcl { namespace fp { // some environments do not have utility template<class T> T abs_(T x) { return x < 0 ? -x : x; } template<class T> T min_(T x, T y) { return x < y ? x : y; } template<class T> T max_(T x, T y) { return x < y ? y : x; } template<class T> void swap_(T& x, T& y) { T t; t = x; x = y; y = t; } /* get pp such that p * pp = -1 mod M, where p is prime and M = 1 << 64(or 32). @param pLow [in] p mod M */ template<class T> T getMontgomeryCoeff(T pLow) { T ret = 0; T t = 0; T x = 1; for (size_t i = 0; i < sizeof(T) * 8; i++) { if ((t & 1) == 0) { t += pLow; ret += x; } t >>= 1; x <<= 1; } return ret; } template<class T> int compareArray(const T* x, const T* y, size_t n) { for (size_t i = n - 1; i != size_t(-1); i--) { T a = x[i]; T b = y[i]; if (a != b) return a < b ? -1 : 1; } return 0; } template<class T> bool isLessArray(const T *x, const T* y, size_t n) { for (size_t i = n - 1; i != size_t(-1); i--) { T a = x[i]; T b = y[i]; if (a != b) return a < b; } return false; } template<class T> bool isGreaterOrEqualArray(const T *x, const T* y, size_t n) { return !isLessArray(x, y, n); } template<class T> bool isLessOrEqualArray(const T *x, const T* y, size_t n) { for (size_t i = n - 1; i != size_t(-1); i--) { T a = x[i]; T b = y[i]; if (a != b) return a < b; } return true; } template<class T> bool isGreaterArray(const T *x, const T* y, size_t n) { return !isLessOrEqualArray(x, y, n); } template<class T> bool isEqualArray(const T* x, const T* y, size_t n) { for (size_t i = 0; i < n; i++) { if (x[i] != y[i]) return false; } return true; } template<class T> bool isZeroArray(const T *x, size_t n) { for (size_t i = 0; i < n; i++) { if (x[i]) return false; } return true; } template<class T> void clearArray(T *x, size_t begin, size_t end) { for (size_t i = begin; i < end; i++) x[i] = 0; } template<class T> void copyArray(T *y, const T *x, size_t n) { for (size_t i = 0; i < n; i++) y[i] = x[i]; } /* x &= (1 << bitSize) - 1 */ template<class T> void maskArray(T *x, size_t n, size_t bitSize) { const size_t TbitSize = sizeof(T) * 8; assert(bitSize <= TbitSize * n); const size_t q = bitSize / TbitSize; const size_t r = bitSize % TbitSize; if (r) { x[q] &= (T(1) << r) - 1; clearArray(x, q + 1, n); } else { clearArray(x, q, n); } } /* return non zero size of x[] return 1 if x[] == 0 */ template<class T> size_t getNonZeroArraySize(const T *x, size_t n) { while (n > 0) { if (x[n - 1]) return n; n--; } return 1; } template<class T> class BitIterator { const T *x_; size_t bitPos_; size_t bitSize_; static const size_t TbitSize = sizeof(T) * 8; public: BitIterator(const T *x, size_t n) : x_(x) , bitPos_(0) { assert(n > 0); n = getNonZeroArraySize(x, n); if (n == 1 && x[0] == 0) { bitSize_ = 1; } else { assert(x_[n - 1]); bitSize_ = (n - 1) * sizeof(T) * 8 + 1 + cybozu::bsr<T>(x_[n - 1]); } } bool hasNext() const { return bitPos_ < bitSize_; } T getNext(size_t w) { assert(0 < w && w <= TbitSize); assert(hasNext()); const size_t q = bitPos_ / TbitSize; const size_t r = bitPos_ % TbitSize; const size_t remain = bitSize_ - bitPos_; if (w > remain) w = remain; T v = x_[q] >> r; if (r + w > TbitSize) { v |= x_[q + 1] << (TbitSize - r); } bitPos_ += w; return v & mask(w); } // whethere next bit is 1 or 0 (bitPos is not moved) bool peekBit() const { assert(hasNext()); const size_t q = bitPos_ / TbitSize; const size_t r = bitPos_ % TbitSize; return (x_[q] >> r) & 1; } void skipBit() { assert(hasNext()); bitPos_++; } T mask(size_t w) const { assert(w <= TbitSize); return (w == TbitSize ? T(0) : (T(1) << w)) - 1; } }; /* @param out [inout] : set element of G ; out = x^y[] @param x [in] @param y [in] @param n [in] size of y[] @param limitBit [in] const time version if the value is positive @note &out != x and out = the unit element of G */ template<class G, class Mul, class Sqr, class T> void powGeneric(G& out, const G& x, const T *y, size_t n, const Mul& mul, const Sqr& sqr, void normalize(G&, const G&), size_t limitBit = 0) { assert(&out != &x); G tbl[4]; // tbl = { discard, x, x^2, x^3 } T v; bool constTime = limitBit > 0; int maxBit = 0; int m = 0; while (n > 0) { if (y[n - 1]) break; n--; } if (n == 0) { if (constTime) goto DummyLoop; return; } if (!constTime && n == 1) { switch (y[0]) { case 1: out = x; return; case 2: sqr(out, x); return; case 3: sqr(out, x); mul(out, out, x); return; case 4: sqr(out, x); sqr(out, out); return; } } if (normalize != 0) { normalize(tbl[0], x); } else { tbl[0] = x; } tbl[1] = tbl[0]; sqr(tbl[2], tbl[1]); if (normalize != 0) { normalize(tbl[2], tbl[2]); } mul(tbl[3], tbl[2], x); if (normalize != 0) { normalize(tbl[3], tbl[3]); } v = y[n - 1]; assert(v); m = cybozu::bsr<T>(v); maxBit = int(m + (n - 1) * sizeof(T) * 8); if (m & 1) { m--; T idx = (v >> m) & 3; assert(idx > 0); out = tbl[idx]; } else { out = x; } for (int i = (int)n - 1; i >= 0; i--) { v = y[i]; for (int j = m - 2; j >= 0; j -= 2) { sqr(out, out); sqr(out, out); T idx = (v >> j) & 3; if (idx == 0) { if (constTime) mul(tbl[0], tbl[0], tbl[1]); } else { mul(out, out, tbl[idx]); } } m = (int)sizeof(T) * 8; } DummyLoop: if (!constTime) return; G D = out; for (size_t i = maxBit + 1; i < limitBit; i += 2) { sqr(D, D); sqr(D, D); mul(D, D, tbl[1]); } } /* shortcut of multiplication by Unit */ template<class T, class U> bool mulSmallUnit(T& z, const T& x, U y) { switch (y) { case 0: z.clear(); break; case 1: z = x; break; case 2: T::add(z, x, x); break; case 3: { T t; T::add(t, x, x); T::add(z, t, x); break; } case 4: T::add(z, x, x); T::add(z, z, z); break; case 5: { T t; T::add(t, x, x); T::add(t, t, t); T::add(z, t, x); break; } case 6: { T t; T::add(t, x, x); T::add(t, t, x); T::add(z, t, t); break; } case 7: { T t; T::add(t, x, x); T::add(t, t, t); T::add(t, t, t); T::sub(z, t, x); break; } case 8: T::add(z, x, x); T::add(z, z, z); T::add(z, z, z); break; case 9: { T t; T::add(t, x, x); T::add(t, t, t); T::add(t, t, t); T::add(z, t, x); break; } case 10: { T t; T::add(t, x, x); T::add(t, t, t); T::add(t, t, x); T::add(z, t, t); break; } default: return false; } return true; } } } // mcl::fp #ifdef _MSC_VER #pragma warning(pop) #endif <|endoftext|>
<commit_before>//---------------------------- reference.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 1998, 1999, 2000, 2001 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- reference.cc --------------------------- #include <fstream> #include <base/subscriptor.h> #include <base/smartpointer.h> #include <base/logstream.h> class Test : public Subscriptor { const char* name; public: Test(const char* n) : name(n) { deallog << "Construct " << name << std::endl; } ~Test() { deallog << "Destruct " << name << std::endl; } void f() { deallog << "mutable" << std::endl; } void f() const { deallog << "const" << std::endl; } }; int main() { std::ofstream logfile("reference.output"); deallog.attach(logfile); deallog.depth_console(0); Test a("A"); const Test b("B"); SmartPointer<Test> r=&a; SmartPointer<const Test> s=&a; // SmartPointer<Test> t=&b; // this one should not work SmartPointer<Test> t=const_cast<Test*>(&b); SmartPointer<const Test> u=&b; deallog << "a "; a.f(); // should print "mutable", since #a# is not const deallog << "b "; b.f(); // should print "const", since #b# is const deallog << "r "; r->f(); // should print "mutable", since it points to the non-const #a# deallog << "s "; s->f(); // should print "const", since it points to the const #b# // but we made it const deallog << "t "; t->f(); // should print "mutable", since #b# is const, but // we casted the constness away deallog << "u "; u->f(); // should print "const" since #b# is const // Now try if subscriptor works { Test c("C"); r = &c; Test d("D"); r = &d; } } <commit_msg>Undo previous change, as it modifies the output of the test. Nevertheless, things can't remain as they are now as cerr is not assignable. There may be a way to redirect is, however, by binding it to stdout...<commit_after>//---------------------------- reference.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 1998, 1999, 2000, 2001 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- reference.cc --------------------------- #include <fstream> #include <base/subscriptor.h> #include <base/smartpointer.h> #include <base/logstream.h> class Test : public Subscriptor { const char* name; public: Test(const char* n) : name(n) { deallog << "Construct " << name << std::endl; } ~Test() { deallog << "Destruct " << name << std::endl; } void f() { deallog << "mutable" << std::endl; } void f() const { deallog << "const" << std::endl; } }; int main() { std::ofstream logfile("reference.output"); deallog.attach(logfile); deallog.depth_console(0); std::cerr = logfile; Test a("A"); const Test b("B"); SmartPointer<Test> r=&a; SmartPointer<const Test> s=&a; // SmartPointer<Test> t=&b; // this one should not work SmartPointer<Test> t=const_cast<Test*>(&b); SmartPointer<const Test> u=&b; deallog << "a "; a.f(); // should print "mutable", since #a# is not const deallog << "b "; b.f(); // should print "const", since #b# is const deallog << "r "; r->f(); // should print "mutable", since it points to the non-const #a# deallog << "s "; s->f(); // should print "const", since it points to the const #b# // but we made it const deallog << "t "; t->f(); // should print "mutable", since #b# is const, but // we casted the constness away deallog << "u "; u->f(); // should print "const" since #b# is const // Now try if subscriptor works { Test c("C"); r = &c; Test d("D"); r = &d; } } <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file LexInno.cxx ** Lexer for Inno Setup scripts. **/ // Written by Friedrich Vedder <fvedd@t-online.de>, using code from LexOthers.cxx. // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static void ColouriseInnoDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor &styler) { int state = SCE_INNO_DEFAULT; char chPrev; char ch = 0; char chNext = styler[startPos]; int lengthDoc = startPos + length; char *buffer = new char[length]; int bufferCount = 0; bool isBOL, isEOL, isWS, isBOLWS = 0; WordList &sectionKeywords = *keywordLists[0]; WordList &standardKeywords = *keywordLists[1]; WordList &parameterKeywords = *keywordLists[2]; WordList &preprocessorKeywords = *keywordLists[3]; WordList &pascalKeywords = *keywordLists[4]; WordList &userKeywords = *keywordLists[5]; // Go through all provided text segment // using the hand-written state machine shown below styler.StartAt(startPos); styler.StartSegment(startPos); for (int i = startPos; i < lengthDoc; i++) { chPrev = ch; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); if (styler.IsLeadByte(ch)) { chNext = styler.SafeGetCharAt(i + 2); i++; continue; } isBOL = (chPrev == 0) || (chPrev == '\n') || (chPrev == '\r' && ch != '\n'); isBOLWS = (isBOL) ? 1 : (isBOLWS && (chPrev == ' ' || chPrev == '\t')); isEOL = (ch == '\n' || ch == '\r'); isWS = (ch == ' ' || ch == '\t'); switch(state) { case SCE_INNO_DEFAULT: if (ch == ';' && isBOLWS) { // Start of a comment state = SCE_INNO_COMMENT; } else if (ch == '[' && isBOLWS) { // Start of a section name bufferCount = 0; state = SCE_INNO_SECTION; } else if (ch == '#' && isBOLWS) { // Start of a preprocessor directive state = SCE_INNO_PREPROC; } else if (ch == '{' && chNext == '#') { // Start of a preprocessor inline directive state = SCE_INNO_PREPROC_INLINE; } else if ((ch == '{' && (chNext == ' ' || chNext == '\t')) || (ch == '(' && chNext == '*')) { // Start of a Pascal comment state = SCE_INNO_COMMENT_PASCAL; } else if (ch == '"') { // Start of a double-quote string state = SCE_INNO_STRING_DOUBLE; } else if (ch == '\'') { // Start of a single-quote string state = SCE_INNO_STRING_SINGLE; } else if (isascii(ch) && (isalpha(ch) || (ch == '_'))) { // Start of an identifier bufferCount = 0; buffer[bufferCount++] = static_cast<char>(tolower(ch)); state = SCE_INNO_IDENTIFIER; } else { // Style it the default style styler.ColourTo(i,SCE_INNO_DEFAULT); } break; case SCE_INNO_COMMENT: if (isEOL) { state = SCE_INNO_DEFAULT; styler.ColourTo(i,SCE_INNO_COMMENT); } break; case SCE_INNO_IDENTIFIER: if (isascii(ch) && (isalnum(ch) || (ch == '_'))) { buffer[bufferCount++] = static_cast<char>(tolower(ch)); } else { state = SCE_INNO_DEFAULT; buffer[bufferCount] = '\0'; // Check if the buffer contains a keyword if (standardKeywords.InList(buffer)) { styler.ColourTo(i-1,SCE_INNO_KEYWORD); } else if (parameterKeywords.InList(buffer)) { styler.ColourTo(i-1,SCE_INNO_PARAMETER); } else if (pascalKeywords.InList(buffer)) { styler.ColourTo(i-1,SCE_INNO_KEYWORD_PASCAL); } else if (userKeywords.InList(buffer)) { styler.ColourTo(i-1,SCE_INNO_KEYWORD_USER); } else { styler.ColourTo(i-1,SCE_INNO_DEFAULT); } // Push back the faulty character chNext = styler[i--]; ch = chPrev; } break; case SCE_INNO_SECTION: if (ch == ']') { state = SCE_INNO_DEFAULT; buffer[bufferCount] = '\0'; // Check if the buffer contains a section name if (sectionKeywords.InList(buffer)) { styler.ColourTo(i,SCE_INNO_SECTION); } else { styler.ColourTo(i,SCE_INNO_DEFAULT); } } else if (isascii(ch) && (isalnum(ch) || (ch == '_'))) { buffer[bufferCount++] = static_cast<char>(tolower(ch)); } else { state = SCE_INNO_DEFAULT; styler.ColourTo(i,SCE_INNO_DEFAULT); } break; case SCE_INNO_PREPROC: if (isWS || isEOL) { if (isascii(chPrev) && isalpha(chPrev)) { state = SCE_INNO_DEFAULT; buffer[bufferCount] = '\0'; // Check if the buffer contains a preprocessor directive if (preprocessorKeywords.InList(buffer)) { styler.ColourTo(i-1,SCE_INNO_PREPROC); } else { styler.ColourTo(i-1,SCE_INNO_DEFAULT); } // Push back the faulty character chNext = styler[i--]; ch = chPrev; } } else if (isascii(ch) && isalpha(ch)) { if (chPrev == '#' || chPrev == ' ' || chPrev == '\t') bufferCount = 0; buffer[bufferCount++] = static_cast<char>(tolower(ch)); } break; case SCE_INNO_STRING_DOUBLE: if (ch == '"' || isEOL) { state = SCE_INNO_DEFAULT; styler.ColourTo(i,SCE_INNO_DEFAULT); } break; case SCE_INNO_STRING_SINGLE: if (ch == '\'' || isEOL) { state = SCE_INNO_DEFAULT; styler.ColourTo(i,SCE_INNO_DEFAULT); } break; case SCE_INNO_PREPROC_INLINE: if (ch == '}') { state = SCE_INNO_DEFAULT; styler.ColourTo(i,SCE_INNO_PREPROC_INLINE); } else if (isEOL) { state = SCE_INNO_DEFAULT; styler.ColourTo(i,SCE_INNO_DEFAULT); } break; case SCE_INNO_COMMENT_PASCAL: if (ch == '}' || (ch == ')' && chPrev == '*')) { state = SCE_INNO_DEFAULT; styler.ColourTo(i,SCE_INNO_COMMENT_PASCAL); } else if (isEOL) { state = SCE_INNO_DEFAULT; styler.ColourTo(i,SCE_INNO_DEFAULT); } break; } } delete []buffer; } static const char * const innoWordListDesc[] = { "Sections", "Keywords", "Parameters", "Preprocessor directives", "Pascal keywords", "User defined keywords", 0 }; static void FoldInnoDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) { bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; unsigned int endPos = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); bool headerPoint = false; int lev; for (unsigned int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler[i+1]; int style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (style == SCE_INNO_SECTION) headerPoint = true; if (atEOL) { lev = SC_FOLDLEVELBASE; if (lineCurrent > 0) { int levelPrevious = styler.LevelAt(lineCurrent - 1); if (levelPrevious & SC_FOLDLEVELHEADERFLAG) lev = SC_FOLDLEVELBASE + 1; else lev = levelPrevious & SC_FOLDLEVELNUMBERMASK; } if (headerPoint) lev = SC_FOLDLEVELBASE; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if (headerPoint) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) styler.SetLevel(lineCurrent, lev); lineCurrent++; visibleChars = 0; headerPoint = false; } if (!isspacechar(ch)) visibleChars++; } if (lineCurrent > 0) { int levelPrevious = styler.LevelAt(lineCurrent - 1); if (levelPrevious & SC_FOLDLEVELHEADERFLAG) lev = SC_FOLDLEVELBASE + 1; else lev = levelPrevious & SC_FOLDLEVELNUMBERMASK; } else { lev = SC_FOLDLEVELBASE; } int flagsNext = styler.LevelAt(lineCurrent); styler.SetLevel(lineCurrent, lev | flagsNext & ~SC_FOLDLEVELNUMBERMASK); } LexerModule lmInno(SCLEX_INNOSETUP, ColouriseInnoDoc, "inno", FoldInnoDoc, innoWordListDesc); <commit_msg>Feature request #1593709 adds colouring for strings, both single and double quoted.<commit_after>// Scintilla source code edit control /** @file LexInno.cxx ** Lexer for Inno Setup scripts. **/ // Written by Friedrich Vedder <fvedd@t-online.de>, using code from LexOthers.cxx. // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #include <stdarg.h> #include "Platform.h" #include "PropSet.h" #include "Accessor.h" #include "StyleContext.h" #include "KeyWords.h" #include "Scintilla.h" #include "SciLexer.h" static void ColouriseInnoDoc(unsigned int startPos, int length, int, WordList *keywordLists[], Accessor &styler) { int state = SCE_INNO_DEFAULT; char chPrev; char ch = 0; char chNext = styler[startPos]; int lengthDoc = startPos + length; char *buffer = new char[length]; int bufferCount = 0; bool isBOL, isEOL, isWS, isBOLWS = 0; WordList &sectionKeywords = *keywordLists[0]; WordList &standardKeywords = *keywordLists[1]; WordList &parameterKeywords = *keywordLists[2]; WordList &preprocessorKeywords = *keywordLists[3]; WordList &pascalKeywords = *keywordLists[4]; WordList &userKeywords = *keywordLists[5]; // Go through all provided text segment // using the hand-written state machine shown below styler.StartAt(startPos); styler.StartSegment(startPos); for (int i = startPos; i < lengthDoc; i++) { chPrev = ch; ch = chNext; chNext = styler.SafeGetCharAt(i + 1); if (styler.IsLeadByte(ch)) { chNext = styler.SafeGetCharAt(i + 2); i++; continue; } isBOL = (chPrev == 0) || (chPrev == '\n') || (chPrev == '\r' && ch != '\n'); isBOLWS = (isBOL) ? 1 : (isBOLWS && (chPrev == ' ' || chPrev == '\t')); isEOL = (ch == '\n' || ch == '\r'); isWS = (ch == ' ' || ch == '\t'); switch(state) { case SCE_INNO_DEFAULT: if (ch == ';' && isBOLWS) { // Start of a comment state = SCE_INNO_COMMENT; } else if (ch == '[' && isBOLWS) { // Start of a section name bufferCount = 0; state = SCE_INNO_SECTION; } else if (ch == '#' && isBOLWS) { // Start of a preprocessor directive state = SCE_INNO_PREPROC; } else if (ch == '{' && chNext == '#') { // Start of a preprocessor inline directive state = SCE_INNO_PREPROC_INLINE; } else if ((ch == '{' && (chNext == ' ' || chNext == '\t')) || (ch == '(' && chNext == '*')) { // Start of a Pascal comment state = SCE_INNO_COMMENT_PASCAL; } else if (ch == '"') { // Start of a double-quote string state = SCE_INNO_STRING_DOUBLE; } else if (ch == '\'') { // Start of a single-quote string state = SCE_INNO_STRING_SINGLE; } else if (isascii(ch) && (isalpha(ch) || (ch == '_'))) { // Start of an identifier bufferCount = 0; buffer[bufferCount++] = static_cast<char>(tolower(ch)); state = SCE_INNO_IDENTIFIER; } else { // Style it the default style styler.ColourTo(i,SCE_INNO_DEFAULT); } break; case SCE_INNO_COMMENT: if (isEOL) { state = SCE_INNO_DEFAULT; styler.ColourTo(i,SCE_INNO_COMMENT); } break; case SCE_INNO_IDENTIFIER: if (isascii(ch) && (isalnum(ch) || (ch == '_'))) { buffer[bufferCount++] = static_cast<char>(tolower(ch)); } else { state = SCE_INNO_DEFAULT; buffer[bufferCount] = '\0'; // Check if the buffer contains a keyword if (standardKeywords.InList(buffer)) { styler.ColourTo(i-1,SCE_INNO_KEYWORD); } else if (parameterKeywords.InList(buffer)) { styler.ColourTo(i-1,SCE_INNO_PARAMETER); } else if (pascalKeywords.InList(buffer)) { styler.ColourTo(i-1,SCE_INNO_KEYWORD_PASCAL); } else if (userKeywords.InList(buffer)) { styler.ColourTo(i-1,SCE_INNO_KEYWORD_USER); } else { styler.ColourTo(i-1,SCE_INNO_DEFAULT); } // Push back the faulty character chNext = styler[i--]; ch = chPrev; } break; case SCE_INNO_SECTION: if (ch == ']') { state = SCE_INNO_DEFAULT; buffer[bufferCount] = '\0'; // Check if the buffer contains a section name if (sectionKeywords.InList(buffer)) { styler.ColourTo(i,SCE_INNO_SECTION); } else { styler.ColourTo(i,SCE_INNO_DEFAULT); } } else if (isascii(ch) && (isalnum(ch) || (ch == '_'))) { buffer[bufferCount++] = static_cast<char>(tolower(ch)); } else { state = SCE_INNO_DEFAULT; styler.ColourTo(i,SCE_INNO_DEFAULT); } break; case SCE_INNO_PREPROC: if (isWS || isEOL) { if (isascii(chPrev) && isalpha(chPrev)) { state = SCE_INNO_DEFAULT; buffer[bufferCount] = '\0'; // Check if the buffer contains a preprocessor directive if (preprocessorKeywords.InList(buffer)) { styler.ColourTo(i-1,SCE_INNO_PREPROC); } else { styler.ColourTo(i-1,SCE_INNO_DEFAULT); } // Push back the faulty character chNext = styler[i--]; ch = chPrev; } } else if (isascii(ch) && isalpha(ch)) { if (chPrev == '#' || chPrev == ' ' || chPrev == '\t') bufferCount = 0; buffer[bufferCount++] = static_cast<char>(tolower(ch)); } break; case SCE_INNO_STRING_DOUBLE: if (ch == '"' || isEOL) { state = SCE_INNO_DEFAULT; styler.ColourTo(i,SCE_INNO_STRING_DOUBLE); } break; case SCE_INNO_STRING_SINGLE: if (ch == '\'' || isEOL) { state = SCE_INNO_DEFAULT; styler.ColourTo(i,SCE_INNO_STRING_SINGLE); } break; case SCE_INNO_PREPROC_INLINE: if (ch == '}') { state = SCE_INNO_DEFAULT; styler.ColourTo(i,SCE_INNO_PREPROC_INLINE); } else if (isEOL) { state = SCE_INNO_DEFAULT; styler.ColourTo(i,SCE_INNO_DEFAULT); } break; case SCE_INNO_COMMENT_PASCAL: if (ch == '}' || (ch == ')' && chPrev == '*')) { state = SCE_INNO_DEFAULT; styler.ColourTo(i,SCE_INNO_COMMENT_PASCAL); } else if (isEOL) { state = SCE_INNO_DEFAULT; styler.ColourTo(i,SCE_INNO_DEFAULT); } break; } } delete []buffer; } static const char * const innoWordListDesc[] = { "Sections", "Keywords", "Parameters", "Preprocessor directives", "Pascal keywords", "User defined keywords", 0 }; static void FoldInnoDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) { bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; unsigned int endPos = startPos + length; int visibleChars = 0; int lineCurrent = styler.GetLine(startPos); char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); bool headerPoint = false; int lev; for (unsigned int i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler[i+1]; int style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (style == SCE_INNO_SECTION) headerPoint = true; if (atEOL) { lev = SC_FOLDLEVELBASE; if (lineCurrent > 0) { int levelPrevious = styler.LevelAt(lineCurrent - 1); if (levelPrevious & SC_FOLDLEVELHEADERFLAG) lev = SC_FOLDLEVELBASE + 1; else lev = levelPrevious & SC_FOLDLEVELNUMBERMASK; } if (headerPoint) lev = SC_FOLDLEVELBASE; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if (headerPoint) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) styler.SetLevel(lineCurrent, lev); lineCurrent++; visibleChars = 0; headerPoint = false; } if (!isspacechar(ch)) visibleChars++; } if (lineCurrent > 0) { int levelPrevious = styler.LevelAt(lineCurrent - 1); if (levelPrevious & SC_FOLDLEVELHEADERFLAG) lev = SC_FOLDLEVELBASE + 1; else lev = levelPrevious & SC_FOLDLEVELNUMBERMASK; } else { lev = SC_FOLDLEVELBASE; } int flagsNext = styler.LevelAt(lineCurrent); styler.SetLevel(lineCurrent, lev | flagsNext & ~SC_FOLDLEVELNUMBERMASK); } LexerModule lmInno(SCLEX_INNOSETUP, ColouriseInnoDoc, "inno", FoldInnoDoc, innoWordListDesc); <|endoftext|>
<commit_before>/* RawSpeed - RAW file decoder. Copyright (C) 2009 Klaus Post This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ #include <rawstudio.h> #include "StdAfx.h" #include "FileReader.h" #include "TiffParser.h" #include "RawDecoder.h" #include "CameraMetaData.h" #include "rawstudio-plugin-api.h" extern "C" { RS_IMAGE16 * load_rawspeed(const gchar *filename) { static CameraMetaData *c = NULL; if (!c) { gchar *path = g_build_filename(rs_confdir_get(), "cameras.xml", NULL); c = new CameraMetaData(path); g_free(path); } RS_IMAGE16 *image = NULL; FileReader f((char *) filename); RawDecoder *d = 0; FileMap* m = 0; try { m = f.readFile(); TiffParser t(m); t.parseData(); d = t.getDecompressor(); try { gint col, row; gint cpp; GTimer *gt = g_timer_new(); d->decodeRaw(); d->decodeMetaData(c); printf("%s: %.03f\n", filename, g_timer_elapsed(gt, NULL)); g_timer_destroy(gt); for (guint i = 0; i < d->errors.size(); i++) printf("Error Encountered:%s\n", d->errors[i]); RawImage r = d->mRaw; r->scaleBlackWhite(); cpp = r->getCpp(); if (cpp == 1) image = rs_image16_new(r->dim.x, r->dim.y, cpp, cpp); else if (cpp == 3) image = rs_image16_new(r->dim.x, r->dim.y, 3, 3); else { printf("Unsupported component per pixel count"); return NULL; } if (r->isCFA) image->filters = r->cfa.getDcrawFilter(); if (r->isCFA) { printf("DCRAW filter:%x\n",r->cfa.getDcrawFilter()); printf("%s", r->cfa.asString().c_str()); } if (cpp == 1) { BitBlt((guchar *)(GET_PIXEL(image,0,0)),image->pitch*2, r->getData(0,0), r->pitch, r->dim.x*2, r->dim.y); } else { for(row=0;row<image->h;row++) { gushort *inpixel = (gushort*)&r->getData()[row*r->pitch]; gushort *outpixel = GET_PIXEL(image, 0, row); for(col=0;col<image->w;col++) { *outpixel++ = *inpixel++; *outpixel++ = *inpixel++; *outpixel++ = *inpixel++; outpixel++; } } } } catch (RawDecoderException e) { printf("RawDecoderException: %s\n", e.what()); } } catch (TiffParserException e) { printf("TiffParserException: %s\n", e.what()); } if (d) delete d; if (m) delete m; return image; } } /* extern "C" */ <commit_msg>- Really fixed bitblit in load_rawspeed() :).<commit_after>/* RawSpeed - RAW file decoder. Copyright (C) 2009 Klaus Post This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA http://www.klauspost.com */ #include <rawstudio.h> #include "StdAfx.h" #include "FileReader.h" #include "TiffParser.h" #include "RawDecoder.h" #include "CameraMetaData.h" #include "rawstudio-plugin-api.h" extern "C" { RS_IMAGE16 * load_rawspeed(const gchar *filename) { static CameraMetaData *c = NULL; if (!c) { gchar *path = g_build_filename(rs_confdir_get(), "cameras.xml", NULL); c = new CameraMetaData(path); g_free(path); } RS_IMAGE16 *image = NULL; FileReader f((char *) filename); RawDecoder *d = 0; FileMap* m = 0; try { m = f.readFile(); TiffParser t(m); t.parseData(); d = t.getDecompressor(); try { gint col, row; gint cpp; GTimer *gt = g_timer_new(); d->decodeRaw(); d->decodeMetaData(c); printf("%s: %.03f\n", filename, g_timer_elapsed(gt, NULL)); g_timer_destroy(gt); for (guint i = 0; i < d->errors.size(); i++) printf("Error Encountered:%s\n", d->errors[i]); RawImage r = d->mRaw; r->scaleBlackWhite(); cpp = r->getCpp(); if (cpp == 1) image = rs_image16_new(r->dim.x, r->dim.y, cpp, cpp); else if (cpp == 3) image = rs_image16_new(r->dim.x, r->dim.y, 3, 3); else { printf("Unsupported component per pixel count"); return NULL; } if (r->isCFA) image->filters = r->cfa.getDcrawFilter(); if (r->isCFA) { printf("DCRAW filter:%x\n",r->cfa.getDcrawFilter()); printf("%s", r->cfa.asString().c_str()); } if (cpp == 1) { BitBlt((guchar *)(GET_PIXEL(image,0,0)),image->pitch*2, r->getData(0,0), r->pitch, r->bpp*r->dim.x, r->dim.y); } else { for(row=0;row<image->h;row++) { gushort *inpixel = (gushort*)&r->getData()[row*r->pitch]; gushort *outpixel = GET_PIXEL(image, 0, row); for(col=0;col<image->w;col++) { *outpixel++ = *inpixel++; *outpixel++ = *inpixel++; *outpixel++ = *inpixel++; outpixel++; } } } } catch (RawDecoderException e) { printf("RawDecoderException: %s\n", e.what()); } } catch (TiffParserException e) { printf("TiffParserException: %s\n", e.what()); } if (d) delete d; if (m) delete m; return image; } } /* extern "C" */ <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <folly/memory/ReentrantAllocator.h> #include <memory> #include <thread> #include <tuple> #include <vector> #include <folly/Utility.h> #include <folly/portability/GTest.h> class ReentrantAllocatorTest : public testing::Test {}; TEST_F(ReentrantAllocatorTest, equality) { folly::reentrant_allocator<void> a{folly::reentrant_allocator_options{}}; folly::reentrant_allocator<void> b{folly::reentrant_allocator_options{}}; EXPECT_TRUE(a == a); EXPECT_FALSE(a == b); EXPECT_FALSE(a != a); EXPECT_TRUE(a != b); folly::reentrant_allocator<int> a2{a}; folly::reentrant_allocator<int> b2{b}; EXPECT_TRUE(a2 == a); EXPECT_FALSE(a2 == b); EXPECT_TRUE(a2 == a2); EXPECT_FALSE(a2 == b2); EXPECT_FALSE(a2 != a); EXPECT_TRUE(a2 != b); EXPECT_FALSE(a2 != a2); EXPECT_TRUE(a2 != b2); } TEST_F(ReentrantAllocatorTest, small) { folly::reentrant_allocator<void> alloc{folly::reentrant_allocator_options{}}; std::vector<size_t, folly::reentrant_allocator<size_t>> vec{alloc}; for (auto i = 0u; i < (1u << 16); ++i) { vec.push_back(i); } for (auto i = 0u; i < (1u << 16); ++i) { EXPECT_EQ(i, vec.at(i)); } } TEST_F(ReentrantAllocatorTest, large) { constexpr size_t const large_size_lg = 6; struct alignas(1u << large_size_lg) type : std::tuple<size_t> {}; auto const opts = folly::reentrant_allocator_options{} // .large_size_lg(large_size_lg); folly::reentrant_allocator<void> alloc{opts}; std::vector<type, folly::reentrant_allocator<type>> vec{alloc}; for (auto i = 0u; i < (1u << 16); ++i) { vec.push_back(type{i}); } for (auto i = 0u; i < (1u << 16); ++i) { EXPECT_EQ(i, std::get<0>(vec.at(i))); } } TEST_F(ReentrantAllocatorTest, zero) { folly::reentrant_allocator<int> a{folly::reentrant_allocator_options{}}; a.deallocate(nullptr, 0); auto ptr = a.allocate(0); EXPECT_NE(nullptr, ptr); a.deallocate(ptr, 0); } TEST_F(ReentrantAllocatorTest, self_assignment) { folly::reentrant_allocator<int> a{folly::reentrant_allocator_options{}}; auto& i = *a.allocate(1); ::new (&i) int(7); EXPECT_EQ(7, i); a = folly::as_const(a); EXPECT_EQ(7, i); a.deallocate(&i, 1); } TEST_F(ReentrantAllocatorTest, stress) { struct alignas(256) big {}; folly::reentrant_allocator<void> a{folly::reentrant_allocator_options{}}; std::vector<std::thread> threads{4}; std::atomic<bool> done{false}; for (auto& th : threads) { th = std::thread([&done, a] { while (!done.load(std::memory_order_relaxed)) { std::allocate_shared<big>(a); } }); } /* sleep override */ std::this_thread::sleep_for(std::chrono::seconds(1)); done.store(true, std::memory_order_relaxed); for (auto& th : threads) { th.join(); } } <commit_msg>Fix gcc-specific problem in reentrant_allocator test<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <folly/memory/ReentrantAllocator.h> #include <memory> #include <thread> #include <tuple> #include <vector> #include <folly/Utility.h> #include <folly/portability/GTest.h> class ReentrantAllocatorTest : public testing::Test {}; TEST_F(ReentrantAllocatorTest, equality) { folly::reentrant_allocator<void> a{folly::reentrant_allocator_options{}}; folly::reentrant_allocator<void> b{folly::reentrant_allocator_options{}}; EXPECT_TRUE(a == a); EXPECT_FALSE(a == b); EXPECT_FALSE(a != a); EXPECT_TRUE(a != b); folly::reentrant_allocator<int> a2{a}; folly::reentrant_allocator<int> b2{b}; EXPECT_TRUE(a2 == a); EXPECT_FALSE(a2 == b); EXPECT_TRUE(a2 == a2); EXPECT_FALSE(a2 == b2); EXPECT_FALSE(a2 != a); EXPECT_TRUE(a2 != b); EXPECT_FALSE(a2 != a2); EXPECT_TRUE(a2 != b2); } TEST_F(ReentrantAllocatorTest, small) { folly::reentrant_allocator<void> alloc{folly::reentrant_allocator_options{}}; std::vector<size_t, folly::reentrant_allocator<size_t>> vec{alloc}; for (auto i = 0u; i < (1u << 16); ++i) { vec.push_back(i); } for (auto i = 0u; i < (1u << 16); ++i) { EXPECT_EQ(i, vec.at(i)); } } TEST_F(ReentrantAllocatorTest, large) { constexpr size_t const large_size_lg = 6; struct alignas(1u << large_size_lg) type : std::tuple<size_t> { using std::tuple<size_t>::tuple; }; auto const opts = folly::reentrant_allocator_options{} // .large_size_lg(large_size_lg); folly::reentrant_allocator<void> alloc{opts}; std::vector<type, folly::reentrant_allocator<type>> vec{alloc}; for (auto i = 0u; i < (1u << 16); ++i) { vec.push_back({i}); } for (auto i = 0u; i < (1u << 16); ++i) { EXPECT_EQ(i, std::get<0>(vec.at(i))); } } TEST_F(ReentrantAllocatorTest, zero) { folly::reentrant_allocator<int> a{folly::reentrant_allocator_options{}}; a.deallocate(nullptr, 0); auto ptr = a.allocate(0); EXPECT_NE(nullptr, ptr); a.deallocate(ptr, 0); } TEST_F(ReentrantAllocatorTest, self_assignment) { folly::reentrant_allocator<int> a{folly::reentrant_allocator_options{}}; auto& i = *a.allocate(1); ::new (&i) int(7); EXPECT_EQ(7, i); a = folly::as_const(a); EXPECT_EQ(7, i); a.deallocate(&i, 1); } TEST_F(ReentrantAllocatorTest, stress) { struct alignas(256) big {}; folly::reentrant_allocator<void> a{folly::reentrant_allocator_options{}}; std::vector<std::thread> threads{4}; std::atomic<bool> done{false}; for (auto& th : threads) { th = std::thread([&done, a] { while (!done.load(std::memory_order_relaxed)) { std::allocate_shared<big>(a); } }); } /* sleep override */ std::this_thread::sleep_for(std::chrono::seconds(1)); done.store(true, std::memory_order_relaxed); for (auto& th : threads) { th.join(); } } <|endoftext|>
<commit_before>#include "channel.hpp" #include "types.hpp" #include "transporthandler.hpp" #include "utils.hpp" #include "net.hpp" #include <string> #include <arpa/inet.h> #include <phosphor-logging/log.hpp> #include <phosphor-logging/elog-errors.hpp> #include "xyz/openbmc_project/Common/error.hpp" constexpr auto ipv4Protocol = "xyz.openbmc_project.Network.IP.Protocol.IPv4"; using namespace phosphor::logging; using namespace sdbusplus::xyz::openbmc_project::Common::Error; /** @struct SetChannelAccessRequest * * IPMI payload for Set Channel access command request. */ struct SetChannelAccessRequest { uint8_t channelNumber; //!< Channel number. uint8_t setting; //!< The setting values. uint8_t privilegeLevelLimit; //!< The Privilege Level Limit } __attribute__((packed)); /** @struct GetChannelAccessRequest * * IPMI payload for Get Channel access command request. */ struct GetChannelAccessRequest { uint8_t channelNumber; //!< Channel number. uint8_t volatileSetting; //!< Get non-volatile or the volatile setting. } __attribute__((packed)); /** @struct GetChannelAccessResponse * * IPMI payload for Get Channel access command response. */ struct GetChannelAccessResponse { uint8_t settings; //!< Channel settings. uint8_t privilegeLimit; //!< Channel privilege level limit. } __attribute__((packed)); ipmi_ret_t ipmi_set_channel_access(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { ipmi_ret_t rc = IPMI_CC_OK; std::string ipaddress; std::string gateway; uint8_t prefix {}; uint32_t vlanID {}; std::string networkInterfacePath; ipmi::DbusObjectInfo ipObject; ipmi::DbusObjectInfo systemObject; if (*data_len < sizeof(SetChannelAccessRequest)) { return IPMI_CC_INVALID; } auto requestData = reinterpret_cast<const SetChannelAccessRequest*> (request); int channel = requestData->channelNumber & CHANNEL_MASK; auto ethdevice = ipmi::network::ChanneltoEthernet(channel); if (ethdevice.empty()) { return IPMI_CC_INVALID_FIELD_REQUEST; } auto ethIp = ethdevice + "/" + ipmi::network::IP_TYPE; auto channelConf = getChannelConfig(channel); // Todo: parse the request data if needed. // Using Set Channel cmd to apply changes of Set Lan Cmd. try { sdbusplus::bus::bus bus(ipmid_get_sd_bus_connection()); log<level::INFO>("Network data from Cache", entry("PREFIX=%s", channelConf->netmask.c_str()), entry("ADDRESS=%s", channelConf->ipaddr.c_str()), entry("GATEWAY=%s", channelConf->gateway.c_str()), entry("VLAN=%d", channelConf->vlanID), entry("IPSRC=%d", channelConf->ipsrc)); if (channelConf->vlanID != ipmi::network::VLAN_ID_MASK) { //get the first twelve bits which is vlan id //not interested in rest of the bits. channelConf->vlanID = le32toh(channelConf->vlanID); vlanID = channelConf->vlanID & ipmi::network::VLAN_ID_MASK; } // if the asked ip src is DHCP then not interested in // any given data except vlan. if (channelConf->ipsrc != ipmi::network::IPOrigin::DHCP) { // always get the system object systemObject = ipmi::getDbusObject( bus, ipmi::network::SYSTEMCONFIG_INTERFACE, ipmi::network::ROOT); // the below code is to determine the mode of the interface // as the handling is same, if the system is configured with // DHCP or user has given all the data. try { ipmi::ObjectTree ancestorMap; ipmi::InterfaceList interfaces { ipmi::network::ETHERNET_INTERFACE }; // if the system is having ip object,then // get the IP object. ipObject = ipmi::getDbusObject(bus, ipmi::network::IP_INTERFACE, ipmi::network::ROOT, ethIp); // Get the parent interface of the IP object. try { ancestorMap = ipmi::getAllAncestors(bus, ipObject.first, std::move(interfaces)); } catch (InternalFailure& e) { // if unable to get the parent interface // then commit the error and return. log<level::ERR>("Unable to get the parent interface", entry("PATH=%s", ipObject.first.c_str()), entry("INTERFACE=%s", ipmi::network::ETHERNET_INTERFACE)); commit<InternalFailure>(); rc = IPMI_CC_UNSPECIFIED_ERROR; channelConf->clear(); return rc; } networkInterfacePath = ancestorMap.begin()->first; } catch (InternalFailure& e) { // TODO Currently IPMI supports single interface,need to handle // Multiple interface through // https://github.com/openbmc/openbmc/issues/2138 // if there is no ip configured on the system,then // get the network interface object. auto networkInterfaceObject = ipmi::getDbusObject( bus, ipmi::network::ETHERNET_INTERFACE, ipmi::network::ROOT, ethdevice); networkInterfacePath = std::move(networkInterfaceObject.first); } // get the configured mode on the system. auto enableDHCP = ipmi::getDbusProperty( bus, ipmi::network::SERVICE, networkInterfacePath, ipmi::network::ETHERNET_INTERFACE, "DHCPEnabled").get<bool>(); // check whether user has given all the data // or the configured system interface is dhcp enabled, // in both of the cases get the values from the cache. if ((!channelConf->ipaddr.empty() && !channelConf->netmask.empty() && !channelConf->gateway.empty()) || (enableDHCP)) // configured system interface mode = DHCP { //convert mask into prefix ipaddress = channelConf->ipaddr; prefix = ipmi::network::toPrefix(AF_INET, channelConf->netmask); gateway = channelConf->gateway; if (channelConf->vlanID != ipmi::network::VLAN_ID_MASK) { //get the first twelve bits which is vlan id //not interested in rest of the bits. channelConf->vlanID = le32toh(channelConf->vlanID); vlanID = channelConf->vlanID & ipmi::network::VLAN_ID_MASK; } else { vlanID = ipmi::network::getVLAN(networkInterfacePath); } } else // asked ip src = static and configured system src = static // or partially given data. { // We have partial filled cache so get the remaining // info from the system. // Get the network data from the system as user has // not given all the data then use the data fetched from the // system but it is implementation dependent,IPMI spec doesn't // force it. // if system is not having any ip object don't throw error, try { auto properties = ipmi::getAllDbusProperties( bus, ipObject.second, ipObject.first, ipmi::network::IP_INTERFACE); ipaddress = channelConf->ipaddr.empty() ? properties["Address"].get<std::string>() : channelConf->ipaddr; prefix = channelConf->netmask.empty() ? properties["PrefixLength"].get<uint8_t>() : ipmi::network::toPrefix(AF_INET, channelConf->netmask); } catch (InternalFailure& e) { log<level::INFO>("Failed to get IP object which matches", entry("INTERFACE=%s", ipmi::network::IP_INTERFACE), entry("MATCH=%s", ethIp)); } auto systemProperties = ipmi::getAllDbusProperties( bus, systemObject.second, systemObject.first, ipmi::network::SYSTEMCONFIG_INTERFACE); gateway = channelConf->gateway.empty() ? systemProperties["DefaultGateway"].get<std::string>() : channelConf->gateway; } } // Currently network manager doesn't support purging of all the // ip addresses and the vlan interfaces from the parent interface, // TODO once the support is there, will make the change here. // https://github.com/openbmc/openbmc/issues/2141. // TODO Currently IPMI supports single interface,need to handle // Multiple interface through // https://github.com/openbmc/openbmc/issues/2138 // instead of deleting all the vlan interfaces and // all the ipv4 address,we will call reset method. //delete all the vlan interfaces ipmi::deleteAllDbusObjects(bus, ipmi::network::ROOT, ipmi::network::VLAN_INTERFACE); // set the interface mode to static auto networkInterfaceObject = ipmi::getDbusObject( bus, ipmi::network::ETHERNET_INTERFACE, ipmi::network::ROOT, ethdevice); // setting the physical interface mode to static. ipmi::setDbusProperty(bus, ipmi::network::SERVICE, networkInterfaceObject.first, ipmi::network::ETHERNET_INTERFACE, "DHCPEnabled", false); networkInterfacePath = networkInterfaceObject.first; //delete all the ipv4 addresses ipmi::deleteAllDbusObjects(bus, ipmi::network::ROOT, ipmi::network::IP_INTERFACE, ethIp); if (vlanID) { ipmi::network::createVLAN(bus, ipmi::network::SERVICE, ipmi::network::ROOT, ethdevice, vlanID); auto networkInterfaceObject = ipmi::getDbusObject( bus, ipmi::network::VLAN_INTERFACE, ipmi::network::ROOT); networkInterfacePath = networkInterfaceObject.first; } if (channelConf->ipsrc == ipmi::network::IPOrigin::DHCP) { ipmi::setDbusProperty(bus, ipmi::network::SERVICE, networkInterfacePath, ipmi::network::ETHERNET_INTERFACE, "DHCPEnabled", true); } else { //change the mode to static ipmi::setDbusProperty(bus, ipmi::network::SERVICE, networkInterfacePath, ipmi::network::ETHERNET_INTERFACE, "DHCPEnabled", false); if (!ipaddress.empty()) { ipmi::network::createIP(bus, ipmi::network::SERVICE, networkInterfacePath, ipv4Protocol, ipaddress, prefix); } if (!gateway.empty()) { ipmi::setDbusProperty(bus, systemObject.second, systemObject.first, ipmi::network::SYSTEMCONFIG_INTERFACE, "DefaultGateway", std::string(gateway)); } } } catch (InternalFailure& e) { log<level::ERR>("Failed to set network data", entry("PREFIX=%d", prefix), entry("ADDRESS=%s", ipaddress.c_str()), entry("GATEWAY=%s", gateway.c_str()), entry("VLANID=%d", vlanID), entry("IPSRC=%d", channelConf->ipsrc)); commit<InternalFailure>(); rc = IPMI_CC_UNSPECIFIED_ERROR; } channelConf->clear(); return rc; } ipmi_ret_t ipmi_get_channel_access(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { auto requestData = reinterpret_cast<const GetChannelAccessRequest*> (request); std::vector<uint8_t> outPayload(sizeof(GetChannelAccessResponse)); auto responseData = reinterpret_cast<GetChannelAccessResponse*> (outPayload.data()); /* * The value Eh is used as a way to identify the current channel that * the command is being received from. */ constexpr auto channelE = 0x0E; int channel = requestData->channelNumber; auto ethdevice = ipmi::network::ChanneltoEthernet(channel); if (channel != channelE && ethdevice.empty()) { *data_len = 0; return IPMI_CC_INVALID_FIELD_REQUEST; } /* * [7:6] - reserved * [5] - 1b = Alerting disabled * [4] - 1b = per message authentication disabled * [3] - 0b = User level authentication enabled * [2:0] - 2h = always available */ constexpr auto channelSetting = 0x32; responseData->settings = channelSetting; //Defaulting the channel privilege to administrator level. responseData->privilegeLimit = PRIVILEGE_ADMIN; *data_len = outPayload.size(); memcpy(response, outPayload.data(), *data_len); return IPMI_CC_OK; } // ATTENTION: This ipmi function is very hardcoded on purpose // OpenBMC does not fully support IPMI. This command is useful // to have around because it enables testing of interfaces with // the IPMI tool. #define GET_CHANNEL_INFO_CHANNEL_OFFSET 0 // IPMI Table 6-2 #define IPMI_CHANNEL_TYPE_IPMB 1 // IPMI Table 6-3 #define IPMI_CHANNEL_MEDIUM_TYPE_OTHER 6 ipmi_ret_t ipmi_app_channel_info(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { ipmi_ret_t rc = IPMI_CC_OK; uint8_t resp[] = { 1, IPMI_CHANNEL_MEDIUM_TYPE_OTHER, IPMI_CHANNEL_TYPE_IPMB, 1,0x41,0xA7,0x00,0,0}; uint8_t *p = (uint8_t*) request; int channel = (*p) & CHANNEL_MASK; std::string ethdevice = ipmi::network::ChanneltoEthernet(channel); printf("IPMI APP GET CHANNEL INFO\n"); // The supported channels numbers are those which are configured. // Channel Number E is used as way to identify the current channel // that the command is being is received from. if (channel != 0xe && ethdevice.empty()) { rc = IPMI_CC_PARM_OUT_OF_RANGE; *data_len = 0; } else { *data_len = sizeof(resp); memcpy(response, resp, *data_len); } return rc; } <commit_msg>LANConf: Minor Fixes<commit_after>#include "channel.hpp" #include "types.hpp" #include "transporthandler.hpp" #include "utils.hpp" #include "net.hpp" #include <string> #include <arpa/inet.h> #include <phosphor-logging/log.hpp> #include <phosphor-logging/elog-errors.hpp> #include "xyz/openbmc_project/Common/error.hpp" constexpr auto ipv4Protocol = "xyz.openbmc_project.Network.IP.Protocol.IPv4"; using namespace phosphor::logging; using namespace sdbusplus::xyz::openbmc_project::Common::Error; /** @struct SetChannelAccessRequest * * IPMI payload for Set Channel access command request. */ struct SetChannelAccessRequest { uint8_t channelNumber; //!< Channel number. uint8_t setting; //!< The setting values. uint8_t privilegeLevelLimit; //!< The Privilege Level Limit } __attribute__((packed)); /** @struct GetChannelAccessRequest * * IPMI payload for Get Channel access command request. */ struct GetChannelAccessRequest { uint8_t channelNumber; //!< Channel number. uint8_t volatileSetting; //!< Get non-volatile or the volatile setting. } __attribute__((packed)); /** @struct GetChannelAccessResponse * * IPMI payload for Get Channel access command response. */ struct GetChannelAccessResponse { uint8_t settings; //!< Channel settings. uint8_t privilegeLimit; //!< Channel privilege level limit. } __attribute__((packed)); ipmi_ret_t ipmi_set_channel_access(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { ipmi_ret_t rc = IPMI_CC_OK; std::string ipaddress; std::string gateway; uint8_t prefix {}; uint32_t vlanID {}; std::string networkInterfacePath; ipmi::DbusObjectInfo ipObject; ipmi::DbusObjectInfo systemObject; if (*data_len < sizeof(SetChannelAccessRequest)) { return IPMI_CC_INVALID; } auto requestData = reinterpret_cast<const SetChannelAccessRequest*> (request); int channel = requestData->channelNumber & CHANNEL_MASK; auto ethdevice = ipmi::network::ChanneltoEthernet(channel); if (ethdevice.empty()) { return IPMI_CC_INVALID_FIELD_REQUEST; } auto ethIp = ethdevice + "/" + ipmi::network::IP_TYPE; auto channelConf = getChannelConfig(channel); // Todo: parse the request data if needed. // Using Set Channel cmd to apply changes of Set Lan Cmd. try { sdbusplus::bus::bus bus(ipmid_get_sd_bus_connection()); log<level::INFO>("Network data from Cache", entry("PREFIX=%s", channelConf->netmask.c_str()), entry("ADDRESS=%s", channelConf->ipaddr.c_str()), entry("GATEWAY=%s", channelConf->gateway.c_str()), entry("VLAN=%d", channelConf->vlanID), entry("IPSRC=%d", channelConf->ipsrc)); if (channelConf->vlanID != ipmi::network::VLAN_ID_MASK) { //get the first twelve bits which is vlan id //not interested in rest of the bits. channelConf->vlanID = le32toh(channelConf->vlanID); vlanID = channelConf->vlanID & ipmi::network::VLAN_ID_MASK; } // if the asked ip src is DHCP then not interested in // any given data except vlan. if (channelConf->ipsrc != ipmi::network::IPOrigin::DHCP) { // always get the system object systemObject = ipmi::getDbusObject( bus, ipmi::network::SYSTEMCONFIG_INTERFACE, ipmi::network::ROOT); // the below code is to determine the mode of the interface // as the handling is same, if the system is configured with // DHCP or user has given all the data. try { ipmi::ObjectTree ancestorMap; ipmi::InterfaceList interfaces { ipmi::network::ETHERNET_INTERFACE }; // if the system is having ip object,then // get the IP object. ipObject = ipmi::getDbusObject(bus, ipmi::network::IP_INTERFACE, ipmi::network::ROOT, ethIp); // Get the parent interface of the IP object. try { ancestorMap = ipmi::getAllAncestors(bus, ipObject.first, std::move(interfaces)); } catch (InternalFailure& e) { // if unable to get the parent interface // then commit the error and return. log<level::ERR>("Unable to get the parent interface", entry("PATH=%s", ipObject.first.c_str()), entry("INTERFACE=%s", ipmi::network::ETHERNET_INTERFACE)); commit<InternalFailure>(); rc = IPMI_CC_UNSPECIFIED_ERROR; channelConf->clear(); return rc; } networkInterfacePath = ancestorMap.begin()->first; } catch (InternalFailure& e) { // TODO Currently IPMI supports single interface,need to handle // Multiple interface through // https://github.com/openbmc/openbmc/issues/2138 // if there is no ip configured on the system,then // get the network interface object. auto networkInterfaceObject = ipmi::getDbusObject( bus, ipmi::network::ETHERNET_INTERFACE, ipmi::network::ROOT, ethdevice); networkInterfacePath = std::move(networkInterfaceObject.first); } // get the configured mode on the system. auto enableDHCP = ipmi::getDbusProperty( bus, ipmi::network::SERVICE, networkInterfacePath, ipmi::network::ETHERNET_INTERFACE, "DHCPEnabled").get<bool>(); // if ip address source is not given then get the ip source mode // from the system so that it can be applied later. if (channelConf->ipsrc == ipmi::network::IPOrigin::UNSPECIFIED) { channelConf->ipsrc = (enableDHCP) ? ipmi::network::IPOrigin::DHCP : ipmi::network::IPOrigin::STATIC; } // check whether user has given all the data // or the configured system interface is dhcp enabled, // in both of the cases get the values from the cache. if ((!channelConf->ipaddr.empty() && !channelConf->netmask.empty() && !channelConf->gateway.empty()) || (enableDHCP)) // configured system interface mode = DHCP { //convert mask into prefix ipaddress = channelConf->ipaddr; prefix = ipmi::network::toPrefix(AF_INET, channelConf->netmask); gateway = channelConf->gateway; } else // asked ip src = static and configured system src = static // or partially given data. { // We have partial filled cache so get the remaining // info from the system. // Get the network data from the system as user has // not given all the data then use the data fetched from the // system but it is implementation dependent,IPMI spec doesn't // force it. // if system is not having any ip object don't throw error, try { auto properties = ipmi::getAllDbusProperties( bus, ipObject.second, ipObject.first, ipmi::network::IP_INTERFACE); ipaddress = channelConf->ipaddr.empty() ? properties["Address"].get<std::string>() : channelConf->ipaddr; prefix = channelConf->netmask.empty() ? properties["PrefixLength"].get<uint8_t>() : ipmi::network::toPrefix(AF_INET, channelConf->netmask); } catch (InternalFailure& e) { log<level::INFO>("Failed to get IP object which matches", entry("INTERFACE=%s", ipmi::network::IP_INTERFACE), entry("MATCH=%s", ethIp)); } auto systemProperties = ipmi::getAllDbusProperties( bus, systemObject.second, systemObject.first, ipmi::network::SYSTEMCONFIG_INTERFACE); gateway = channelConf->gateway.empty() ? systemProperties["DefaultGateway"].get<std::string>() : channelConf->gateway; } } // Currently network manager doesn't support purging of all the // ip addresses and the vlan interfaces from the parent interface, // TODO once the support is there, will make the change here. // https://github.com/openbmc/openbmc/issues/2141. // TODO Currently IPMI supports single interface,need to handle // Multiple interface through // https://github.com/openbmc/openbmc/issues/2138 // instead of deleting all the vlan interfaces and // all the ipv4 address,we will call reset method. //delete all the vlan interfaces ipmi::deleteAllDbusObjects(bus, ipmi::network::ROOT, ipmi::network::VLAN_INTERFACE); // set the interface mode to static auto networkInterfaceObject = ipmi::getDbusObject( bus, ipmi::network::ETHERNET_INTERFACE, ipmi::network::ROOT, ethdevice); // setting the physical interface mode to static. ipmi::setDbusProperty(bus, ipmi::network::SERVICE, networkInterfaceObject.first, ipmi::network::ETHERNET_INTERFACE, "DHCPEnabled", false); networkInterfacePath = networkInterfaceObject.first; //delete all the ipv4 addresses ipmi::deleteAllDbusObjects(bus, ipmi::network::ROOT, ipmi::network::IP_INTERFACE, ethIp); if (vlanID) { ipmi::network::createVLAN(bus, ipmi::network::SERVICE, ipmi::network::ROOT, ethdevice, vlanID); auto networkInterfaceObject = ipmi::getDbusObject( bus, ipmi::network::VLAN_INTERFACE, ipmi::network::ROOT); networkInterfacePath = networkInterfaceObject.first; } if (channelConf->ipsrc == ipmi::network::IPOrigin::DHCP) { ipmi::setDbusProperty(bus, ipmi::network::SERVICE, networkInterfacePath, ipmi::network::ETHERNET_INTERFACE, "DHCPEnabled", true); } else { //change the mode to static ipmi::setDbusProperty(bus, ipmi::network::SERVICE, networkInterfacePath, ipmi::network::ETHERNET_INTERFACE, "DHCPEnabled", false); if (!ipaddress.empty()) { ipmi::network::createIP(bus, ipmi::network::SERVICE, networkInterfacePath, ipv4Protocol, ipaddress, prefix); } if (!gateway.empty()) { ipmi::setDbusProperty(bus, systemObject.second, systemObject.first, ipmi::network::SYSTEMCONFIG_INTERFACE, "DefaultGateway", std::string(gateway)); } } } catch (InternalFailure& e) { log<level::ERR>("Failed to set network data", entry("PREFIX=%d", prefix), entry("ADDRESS=%s", ipaddress.c_str()), entry("GATEWAY=%s", gateway.c_str()), entry("VLANID=%d", vlanID), entry("IPSRC=%d", channelConf->ipsrc)); commit<InternalFailure>(); rc = IPMI_CC_UNSPECIFIED_ERROR; } channelConf->clear(); return rc; } ipmi_ret_t ipmi_get_channel_access(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { auto requestData = reinterpret_cast<const GetChannelAccessRequest*> (request); std::vector<uint8_t> outPayload(sizeof(GetChannelAccessResponse)); auto responseData = reinterpret_cast<GetChannelAccessResponse*> (outPayload.data()); /* * The value Eh is used as a way to identify the current channel that * the command is being received from. */ constexpr auto channelE = 0x0E; int channel = requestData->channelNumber; auto ethdevice = ipmi::network::ChanneltoEthernet(channel); if (channel != channelE && ethdevice.empty()) { *data_len = 0; return IPMI_CC_INVALID_FIELD_REQUEST; } /* * [7:6] - reserved * [5] - 1b = Alerting disabled * [4] - 1b = per message authentication disabled * [3] - 0b = User level authentication enabled * [2:0] - 2h = always available */ constexpr auto channelSetting = 0x32; responseData->settings = channelSetting; //Defaulting the channel privilege to administrator level. responseData->privilegeLimit = PRIVILEGE_ADMIN; *data_len = outPayload.size(); memcpy(response, outPayload.data(), *data_len); return IPMI_CC_OK; } // ATTENTION: This ipmi function is very hardcoded on purpose // OpenBMC does not fully support IPMI. This command is useful // to have around because it enables testing of interfaces with // the IPMI tool. #define GET_CHANNEL_INFO_CHANNEL_OFFSET 0 // IPMI Table 6-2 #define IPMI_CHANNEL_TYPE_IPMB 1 // IPMI Table 6-3 #define IPMI_CHANNEL_MEDIUM_TYPE_OTHER 6 ipmi_ret_t ipmi_app_channel_info(ipmi_netfn_t netfn, ipmi_cmd_t cmd, ipmi_request_t request, ipmi_response_t response, ipmi_data_len_t data_len, ipmi_context_t context) { ipmi_ret_t rc = IPMI_CC_OK; uint8_t resp[] = { 1, IPMI_CHANNEL_MEDIUM_TYPE_OTHER, IPMI_CHANNEL_TYPE_IPMB, 1,0x41,0xA7,0x00,0,0}; uint8_t *p = (uint8_t*) request; int channel = (*p) & CHANNEL_MASK; std::string ethdevice = ipmi::network::ChanneltoEthernet(channel); printf("IPMI APP GET CHANNEL INFO\n"); // The supported channels numbers are those which are configured. // Channel Number E is used as way to identify the current channel // that the command is being is received from. if (channel != 0xe && ethdevice.empty()) { rc = IPMI_CC_PARM_OUT_OF_RANGE; *data_len = 0; } else { *data_len = sizeof(resp); memcpy(response, resp, *data_len); } return rc; } <|endoftext|>