text
stringlengths
54
60.6k
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// /// \file hardware_concurrency.hpp /// ------------------------------ /// /// (c) Copyright Domagoj Saric 2016 - 2019. /// /// Use, modification and distribution are 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) /// /// See http://www.boost.org for most recent version. /// //////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------ #ifndef hardware_concurrency_hpp__070F2563_7F3C_40D5_85C9_1289E8DEEDC8 #define hardware_concurrency_hpp__070F2563_7F3C_40D5_85C9_1289E8DEEDC8 #pragma once //------------------------------------------------------------------------------ #ifndef BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY # if defined( __ANDROID__ ) # if defined( __aarch64__ ) # define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 32 // SGS6 8, Meizu PRO 6 10 cores # elif defined( __arm__ ) # define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 8 # endif // arch # elif defined( __APPLE__ ) # if defined( __aarch64__ ) # define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 8 // iPad 2 Air 3, iPhone 8 6 cores # elif defined( __arm__ ) # define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 2 # else # define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 0 // desktop or simulator # endif // arch # elif defined(__WINDOWS_PHONE__) # define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 2 # else # define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 0 # endif // platform #endif // BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY #ifdef __ANDROID__ # include <unistd.h> #endif // __ANDROID__ #ifdef __linux__ # include <sys/sysinfo.h> #endif // __linux__ #ifdef _MSC_VER # include <yvals.h> # pragma detect_mismatch( "BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY", _STRINGIZE( BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY ) ) #endif // _MSC_VER #include <cstdint> #include <thread> //------------------------------------------------------------------------------ #ifdef __ANDROID__ // https://android.googlesource.com/platform/bionic/+/HEAD/docs/status.md __attribute__(( weak )) int get_nprocs () { return static_cast< int >( ::sysconf( _SC_NPROCESSORS_ONLN ) ); } __attribute__(( weak )) int get_nprocs_conf() { return static_cast< int >( ::sysconf( _SC_NPROCESSORS_CONF ) ); } #endif // __ANDROID__ //------------------------------------------------------------------------------ namespace boost { //------------------------------------------------------------------------------ namespace sweater { //------------------------------------------------------------------------------ #if defined( __arm__ ) || defined( __aarch64__ ) || defined( __ANDROID__ ) || defined( __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ ) using hardware_concurrency_t = std::uint_fast8_t; #else using hardware_concurrency_t = std::uint_fast16_t; // e.g. Intel MIC #endif namespace detail { inline auto get_hardware_concurrency_max() noexcept { return static_cast<hardware_concurrency_t> ( # ifdef __linux__ // libcpp std::thread::hardware_concurrency() returns the dynamic number of active cores. get_nprocs_conf() # else std::thread::hardware_concurrency() # endif ); } } // namespace detail #ifdef __GNUC__ // http://clang-developers.42468.n3.nabble.com/Clang-equivalent-to-attribute-init-priority-td4034229.html // https://gcc.gnu.org/ml/gcc-help/2011-05/msg00221.html // "can only use 'init_priority' attribute on file-scope definitions of objects of class type" struct hardware_concurrency_max_t { hardware_concurrency_t const value = detail::get_hardware_concurrency_max(); operator hardware_concurrency_t() const noexcept { return value; } } const hardware_concurrency_max __attribute__(( init_priority( 101 ) )); #else inline auto const hardware_concurrency_max( detail::get_hardware_concurrency_max() ); #endif // compiler inline auto hardware_concurrency_current() noexcept { return static_cast<hardware_concurrency_t> ( # ifdef __linux__ get_nprocs() # else std::thread::hardware_concurrency() # endif ); } //------------------------------------------------------------------------------ } // namespace sweater //------------------------------------------------------------------------------ } // namespace boost //------------------------------------------------------------------------------ #endif // hardware_concurrency_hpp <commit_msg>GCC&co.: fixed multiple initializers getting generated for hardware_concurrency_max.<commit_after>//////////////////////////////////////////////////////////////////////////////// /// /// \file hardware_concurrency.hpp /// ------------------------------ /// /// (c) Copyright Domagoj Saric 2016 - 2019. /// /// Use, modification and distribution are 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) /// /// See http://www.boost.org for most recent version. /// //////////////////////////////////////////////////////////////////////////////// //------------------------------------------------------------------------------ #ifndef hardware_concurrency_hpp__070F2563_7F3C_40D5_85C9_1289E8DEEDC8 #define hardware_concurrency_hpp__070F2563_7F3C_40D5_85C9_1289E8DEEDC8 #pragma once //------------------------------------------------------------------------------ #ifndef BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY # if defined( __ANDROID__ ) # if defined( __aarch64__ ) # define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 32 // SGS6 8, Meizu PRO 6 10 cores # elif defined( __arm__ ) # define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 8 # endif // arch # elif defined( __APPLE__ ) # if defined( __aarch64__ ) # define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 8 // iPad 2 Air 3, iPhone 8 6 cores # elif defined( __arm__ ) # define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 2 # else # define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 0 // desktop or simulator # endif // arch # elif defined(__WINDOWS_PHONE__) # define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 2 # else # define BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY 0 # endif // platform #endif // BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY #ifdef __ANDROID__ # include <unistd.h> #endif // __ANDROID__ #ifdef __linux__ # include <sys/sysinfo.h> #endif // __linux__ #ifdef _MSC_VER # include <yvals.h> # pragma detect_mismatch( "BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY", _STRINGIZE( BOOST_SWEATER_MAX_HARDWARE_CONCURRENCY ) ) #endif // _MSC_VER #include <cstdint> #include <thread> //------------------------------------------------------------------------------ #ifdef __ANDROID__ // https://android.googlesource.com/platform/bionic/+/HEAD/docs/status.md __attribute__(( weak )) int get_nprocs () { return static_cast< int >( ::sysconf( _SC_NPROCESSORS_ONLN ) ); } __attribute__(( weak )) int get_nprocs_conf() { return static_cast< int >( ::sysconf( _SC_NPROCESSORS_CONF ) ); } #endif // __ANDROID__ //------------------------------------------------------------------------------ namespace boost { //------------------------------------------------------------------------------ namespace sweater { //------------------------------------------------------------------------------ #if defined( __arm__ ) || defined( __aarch64__ ) || defined( __ANDROID__ ) || defined( __ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__ ) using hardware_concurrency_t = std::uint_fast8_t; #else using hardware_concurrency_t = std::uint_fast16_t; // e.g. Intel MIC #endif namespace detail { inline auto get_hardware_concurrency_max() noexcept { return static_cast<hardware_concurrency_t> ( # ifdef __linux__ // libcpp std::thread::hardware_concurrency() returns the dynamic number of active cores. get_nprocs_conf() # else std::thread::hardware_concurrency() # endif ); } } // namespace detail #ifdef __GNUC__ // http://clang-developers.42468.n3.nabble.com/Clang-equivalent-to-attribute-init-priority-td4034229.html // https://gcc.gnu.org/ml/gcc-help/2011-05/msg00221.html // "can only use 'init_priority' attribute on file-scope definitions of objects of class type" inline struct hardware_concurrency_max_t { hardware_concurrency_t const value = detail::get_hardware_concurrency_max(); operator hardware_concurrency_t() const noexcept { return value; } } const hardware_concurrency_max __attribute__(( init_priority( 101 ) )); #else inline auto const hardware_concurrency_max( detail::get_hardware_concurrency_max() ); #endif // compiler inline auto hardware_concurrency_current() noexcept { return static_cast<hardware_concurrency_t> ( # ifdef __linux__ get_nprocs() # else std::thread::hardware_concurrency() # endif ); } //------------------------------------------------------------------------------ } // namespace sweater //------------------------------------------------------------------------------ } // namespace boost //------------------------------------------------------------------------------ #endif // hardware_concurrency_hpp <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2017 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_SVG_PATH_GRAMMAR_X3_DEF_HPP #define MAPNIK_SVG_PATH_GRAMMAR_X3_DEF_HPP // mapnik #include <mapnik/config.hpp> #include <mapnik/svg/svg_path_grammar_x3.hpp> #include <mapnik/util/math.hpp> #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/fusion/adapted/std_tuple.hpp> #pragma GCC diagnostic pop namespace mapnik { namespace svg { namespace grammar { namespace x3 = boost::spirit::x3; using x3::lit; using x3::double_; using x3::int_; using x3::no_case; using coord_type = std::tuple<double,double>; template <typename Context> svg_converter_type & extract_path(Context const& ctx) { return x3::get<svg_path_tag>(ctx); } template <typename Context> bool & extract_relative(Context const& ctx) { return x3::get<relative_tag>(ctx); } auto const move_to = [] (auto const& ctx) { extract_path(ctx).move_to(std::get<0>(_attr(ctx)), std::get<1>(_attr(ctx)), x3::get<relative_tag>(ctx)); }; auto const line_to = [] (auto const & ctx) { extract_path(ctx).line_to(std::get<0>(_attr(ctx)), std::get<1>(_attr(ctx)), x3::get<relative_tag>(ctx)); }; auto const hline_to = [] (auto const& ctx) { extract_path(ctx).hline_to(_attr(ctx), x3::get<relative_tag>(ctx)); }; auto const vline_to = [] (auto const& ctx) { extract_path(ctx).vline_to(_attr(ctx), x3::get<relative_tag>(ctx)); }; auto const curve4 = [] (auto const& ctx) { auto const& attr = _attr(ctx); auto const& p0 = boost::fusion::at_c<0>(attr); auto const& p1 = boost::fusion::at_c<1>(attr); auto const& p2 = boost::fusion::at_c<2>(attr); extract_path(ctx).curve4(std::get<0>(p0),std::get<1>(p0), std::get<0>(p1),std::get<1>(p1), std::get<0>(p2),std::get<1>(p2), x3::get<relative_tag>(ctx)); }; auto const curve4_smooth = [] (auto const& ctx) { auto const& attr = _attr(ctx); auto const& p0 = boost::fusion::at_c<0>(attr); auto const& p1 = boost::fusion::at_c<1>(attr); extract_path(ctx).curve4(std::get<0>(p0),std::get<1>(p0), std::get<0>(p1),std::get<1>(p1), x3::get<relative_tag>(ctx)); }; auto const curve3 = [] (auto const& ctx) { auto const& attr = _attr(ctx); auto const& p0 = boost::fusion::at_c<0>(attr); auto const& p1 = boost::fusion::at_c<1>(attr); extract_path(ctx).curve3(std::get<0>(p0),std::get<1>(p0), std::get<0>(p1),std::get<1>(p1), x3::get<relative_tag>(ctx)); }; auto const curve3_smooth = [] (auto const& ctx) { auto const& attr = _attr(ctx); extract_path(ctx).curve3(std::get<0>(attr),std::get<1>(attr), x3::get<relative_tag>(ctx)); }; auto const arc_to = [] (auto & ctx) { auto const& attr = _attr(ctx); auto const& p = boost::fusion::at_c<0>(attr); double angle = boost::fusion::at_c<1>(attr); int large_arc_flag = boost::fusion::at_c<2>(attr); int sweep_flag = boost::fusion::at_c<3>(attr); auto const& v = boost::fusion::at_c<4>(attr); x3::get<svg_path_tag>(ctx).arc_to(std::get<0>(p),std::get<1>(p), util::radians(angle), large_arc_flag, sweep_flag, std::get<0>(v),std::get<1>(v), x3::get<relative_tag>(ctx)); }; auto const close_path = [] (auto const& ctx) { extract_path(ctx).close_subpath(); }; auto const relative = [] (auto const& ctx) { extract_relative(ctx) = true; }; auto const absolute = [] (auto const& ctx) { extract_relative(ctx) = false; }; // exported rules svg_path_grammar_type const svg_path = "SVG Path"; svg_points_grammar_type const svg_points = "SVG_Points"; // rules auto const coord = x3::rule<class coord_tag, coord_type>{} = double_ > -lit(',') > double_; auto const svg_points_def = coord[move_to] // move_to > *(-lit(',') >> coord[line_to]); // *line_to auto const M = x3::rule<class M_tag> {} = (lit('M')[absolute] | lit('m')[relative]) > svg_points ; auto const H = x3::rule<class H_tag> {} = (lit('H')[absolute] | lit('h')[relative]) > (double_[ hline_to] % -lit(',')) ; // +hline_to auto const V = x3::rule<class V_tag> {} = (lit('V')[absolute] | lit('v')[relative]) > (double_[ vline_to] % -lit(',')) ; // +vline_to auto const L = x3::rule<class L_tag> {} = (lit('L')[absolute] | lit('l')[relative]) > (coord [line_to] % -lit(',')); // +line_to auto const C = x3::rule<class C_tag> {} = (lit('C')[absolute] | lit('c')[relative]) > ((coord > -lit(',') > coord > -lit(',') > coord)[curve4] % -lit(',')); // +curve4 auto const S = x3::rule<class S_tag> {} = (lit('S')[absolute] | lit('s')[relative]) > ((coord > -lit(',') > coord) [curve4_smooth] % -lit(',')); // +curve4_smooth (smooth curveto) auto const Q = x3::rule<class Q_tag> {} = (lit('Q')[absolute] | lit('q')[relative]) > ((coord > -lit(',') > coord) [curve3] % -lit(',')); // +curve3 (quadratic-bezier-curveto) auto const T = x3::rule<class T_tag> {} = (lit('T')[absolute] | lit('t')[relative]) > ((coord ) [curve3_smooth] % -lit(',')); // +curve3_smooth (smooth-quadratic-bezier-curveto) auto const A = x3::rule<class A_tag> {} = (lit('A')[absolute] | lit('a')[relative]) > ((coord > -lit(',') > double_ > -lit(',') > int_ > -lit(',') > int_ > -lit(',') > coord) [arc_to] % -lit(',')); // arc_to; auto const Z = x3::rule<class Z_tag>{} = no_case[lit('z')] [close_path]; // close path auto const drawto_cmd = x3::rule<class drawto_cmd_tag> {} = L | H | V | C | S | Q | T | A | Z; auto const cmd = x3::rule<class cmd_tag> {} = M > *drawto_cmd ; auto const svg_path_def = +cmd; #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> BOOST_SPIRIT_DEFINE( svg_path, svg_points ); #pragma GCC diagnostic pop } grammar::svg_path_grammar_type const& svg_path_grammar() { return grammar::svg_path; } grammar::svg_points_grammar_type const& svg_points_grammar() { return grammar::svg_points; } }} #endif // MAPNIK_SVG_PATH_GRAMMAR_X3_HPP <commit_msg>Revert "opps, adding lost change (re: boost>=1.67)"<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2017 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_SVG_PATH_GRAMMAR_X3_DEF_HPP #define MAPNIK_SVG_PATH_GRAMMAR_X3_DEF_HPP // mapnik #include <mapnik/config.hpp> #include <mapnik/svg/svg_path_grammar_x3.hpp> #include <mapnik/util/math.hpp> #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/fusion/adapted/std_tuple.hpp> #pragma GCC diagnostic pop namespace mapnik { namespace svg { namespace grammar { namespace x3 = boost::spirit::x3; using x3::lit; using x3::double_; using x3::int_; using x3::no_case; using coord_type = std::tuple<double,double>; template <typename Context> svg_converter_type & extract_path(Context const& ctx) { return x3::get<svg_path_tag>(ctx); } template <typename Context> bool & extract_relative(Context const& ctx) { return x3::get<relative_tag>(ctx); } auto const move_to = [] (auto const& ctx) { extract_path(ctx).move_to(std::get<0>(_attr(ctx)), std::get<1>(_attr(ctx)), x3::get<relative_tag>(ctx)); }; auto const line_to = [] (auto const & ctx) { extract_path(ctx).line_to(std::get<0>(_attr(ctx)), std::get<1>(_attr(ctx)), x3::get<relative_tag>(ctx)); }; auto const hline_to = [] (auto const& ctx) { extract_path(ctx).hline_to(_attr(ctx), x3::get<relative_tag>(ctx)); }; auto const vline_to = [] (auto const& ctx) { extract_path(ctx).vline_to(_attr(ctx), x3::get<relative_tag>(ctx)); }; auto const curve4 = [] (auto const& ctx) { auto const& attr = _attr(ctx); auto const& p0 = boost::fusion::at_c<0>(attr); auto const& p1 = boost::fusion::at_c<1>(attr); auto const& p2 = boost::fusion::at_c<2>(attr); extract_path(ctx).curve4(std::get<0>(p0),std::get<1>(p0), std::get<0>(p1),std::get<1>(p1), std::get<0>(p2),std::get<1>(p2), x3::get<relative_tag>(ctx)); }; auto const curve4_smooth = [] (auto const& ctx) { auto const& attr = _attr(ctx); auto const& p0 = boost::fusion::at_c<0>(attr); auto const& p1 = boost::fusion::at_c<1>(attr); extract_path(ctx).curve4(std::get<0>(p0),std::get<1>(p0), std::get<0>(p1),std::get<1>(p1), x3::get<relative_tag>(ctx)); }; auto const curve3 = [] (auto const& ctx) { auto const& attr = _attr(ctx); auto const& p0 = boost::fusion::at_c<0>(attr); auto const& p1 = boost::fusion::at_c<1>(attr); extract_path(ctx).curve3(std::get<0>(p0),std::get<1>(p0), std::get<0>(p1),std::get<1>(p1), x3::get<relative_tag>(ctx)); }; auto const curve3_smooth = [] (auto const& ctx) { auto const& attr = _attr(ctx); extract_path(ctx).curve3(std::get<0>(attr),std::get<1>(attr), x3::get<relative_tag>(ctx)); }; auto const arc_to = [] (auto & ctx) { auto const& attr = _attr(ctx); auto const& p = boost::fusion::at_c<0>(attr); double angle = boost::fusion::at_c<1>(attr); int large_arc_flag = boost::fusion::at_c<2>(attr); int sweep_flag = boost::fusion::at_c<3>(attr); auto const& v = boost::fusion::at_c<4>(attr); x3::get<svg_path_tag>(ctx).get().arc_to(std::get<0>(p),std::get<1>(p), util::radians(angle), large_arc_flag, sweep_flag, std::get<0>(v),std::get<1>(v), x3::get<relative_tag>(ctx)); }; auto const close_path = [] (auto const& ctx) { extract_path(ctx).close_subpath(); }; auto const relative = [] (auto const& ctx) { extract_relative(ctx) = true; }; auto const absolute = [] (auto const& ctx) { extract_relative(ctx) = false; }; // exported rules svg_path_grammar_type const svg_path = "SVG Path"; svg_points_grammar_type const svg_points = "SVG_Points"; // rules auto const coord = x3::rule<class coord_tag, coord_type>{} = double_ > -lit(',') > double_; auto const svg_points_def = coord[move_to] // move_to > *(-lit(',') >> coord[line_to]); // *line_to auto const M = x3::rule<class M_tag> {} = (lit('M')[absolute] | lit('m')[relative]) > svg_points ; auto const H = x3::rule<class H_tag> {} = (lit('H')[absolute] | lit('h')[relative]) > (double_[ hline_to] % -lit(',')) ; // +hline_to auto const V = x3::rule<class V_tag> {} = (lit('V')[absolute] | lit('v')[relative]) > (double_[ vline_to] % -lit(',')) ; // +vline_to auto const L = x3::rule<class L_tag> {} = (lit('L')[absolute] | lit('l')[relative]) > (coord [line_to] % -lit(',')); // +line_to auto const C = x3::rule<class C_tag> {} = (lit('C')[absolute] | lit('c')[relative]) > ((coord > -lit(',') > coord > -lit(',') > coord)[curve4] % -lit(',')); // +curve4 auto const S = x3::rule<class S_tag> {} = (lit('S')[absolute] | lit('s')[relative]) > ((coord > -lit(',') > coord) [curve4_smooth] % -lit(',')); // +curve4_smooth (smooth curveto) auto const Q = x3::rule<class Q_tag> {} = (lit('Q')[absolute] | lit('q')[relative]) > ((coord > -lit(',') > coord) [curve3] % -lit(',')); // +curve3 (quadratic-bezier-curveto) auto const T = x3::rule<class T_tag> {} = (lit('T')[absolute] | lit('t')[relative]) > ((coord ) [curve3_smooth] % -lit(',')); // +curve3_smooth (smooth-quadratic-bezier-curveto) auto const A = x3::rule<class A_tag> {} = (lit('A')[absolute] | lit('a')[relative]) > ((coord > -lit(',') > double_ > -lit(',') > int_ > -lit(',') > int_ > -lit(',') > coord) [arc_to] % -lit(',')); // arc_to; auto const Z = x3::rule<class Z_tag>{} = no_case[lit('z')] [close_path]; // close path auto const drawto_cmd = x3::rule<class drawto_cmd_tag> {} = L | H | V | C | S | Q | T | A | Z; auto const cmd = x3::rule<class cmd_tag> {} = M > *drawto_cmd ; auto const svg_path_def = +cmd; #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> BOOST_SPIRIT_DEFINE( svg_path, svg_points ); #pragma GCC diagnostic pop } grammar::svg_path_grammar_type const& svg_path_grammar() { return grammar::svg_path; } grammar::svg_points_grammar_type const& svg_points_grammar() { return grammar::svg_points; } }} #endif // MAPNIK_SVG_PATH_GRAMMAR_X3_HPP <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: framelistanalyzer.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kz $ $Date: 2005-03-01 19:35:00 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "classes/framelistanalyzer.hxx" //_______________________________________________ // my own includes #ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_ #include <threadhelp/writeguard.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_ #include <threadhelp/readguard.hxx> #endif #ifndef __FRAMEWORK_TARGETS_H_ #include <targets.h> #endif #ifndef __FRAMEWORK_PROPERTIES_H_ #include <properties.h> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include <services.h> #endif //_______________________________________________ // interface includes #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_ #include <com/sun/star/frame/XModuleManager.hpp> #endif //_______________________________________________ // includes of other projects #ifndef _UNOTOOLS_PROCESSFACTORY_HXX_ #include <unotools/processfactory.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif //_______________________________________________ // namespace namespace framework{ //_______________________________________________ // non exported const //_______________________________________________ // non exported definitions //_______________________________________________ // declarations //_______________________________________________ /** */ FrameListAnalyzer::FrameListAnalyzer( const css::uno::Reference< css::frame::XFramesSupplier >& xSupplier , const css::uno::Reference< css::frame::XFrame >& xReferenceFrame , sal_uInt32 eDetectMode ) : m_xSupplier (xSupplier ) , m_xReferenceFrame(xReferenceFrame) , m_eDetectMode (eDetectMode ) { impl_analyze(); } //_______________________________________________ /** */ FrameListAnalyzer::~FrameListAnalyzer() { } //_______________________________________________ /** returns an analyzed list of all currently opened (top!) frames inside the desktop tree. We try to get a snapshot of all opened frames, which are part of the desktop frame container. Of course we can't access frames, which stands outside of this tree. But it's neccessary to collect top frames here only. Otherwhise we interpret closing of last frame wrong. Further we analyze this list and split into different parts. E.g. for "CloseDoc" we must know, which frames of the given list referr to the same model. These frames must be closed then. But all other frames must be untouched. In case the request was "CloseWin" these splitted lists can be used too, to decide if the last window or document was closed. Then we have to initialize the backing window ... Last but not least we must know something about our special help frame. It must be handled seperatly. And last but not least - the backing component frame must be detected too. */ void FrameListAnalyzer::impl_analyze() { // reset all members to get a consistent state m_bReferenceIsHidden = sal_False; m_bReferenceIsHelp = sal_False; m_bReferenceIsBacking = sal_False; m_xHelp = css::uno::Reference< css::frame::XFrame >(); m_xBackingComponent = css::uno::Reference< css::frame::XFrame >(); // try to get the task container by using the given supplier css::uno::Reference< css::container::XIndexAccess > xFrameContainer(m_xSupplier->getFrames(), css::uno::UNO_QUERY); // All return list get an initial size to include all possible frames. // They will be packed at the end of this method ... using the actual step positions then. sal_Int32 nVisibleStep = 0; sal_Int32 nHiddenStep = 0; sal_Int32 nModelStep = 0; sal_Int32 nCount = xFrameContainer->getCount(); m_lOtherVisibleFrames.realloc(nCount); m_lOtherHiddenFrames.realloc(nCount); m_lModelFrames.realloc(nCount); // ask for the model of the given reference frame. // It must be compared with the model of every frame of the container // to sort it into the list of frames with the same model. // Supress this step, if right detect mode isn't set. css::uno::Reference< css::frame::XModel > xReferenceModel; if ((m_eDetectMode & E_MODEL) == E_MODEL ) { css::uno::Reference< css::frame::XController > xReferenceController = m_xReferenceFrame->getController(); if (xReferenceController.is()) xReferenceModel = xReferenceController->getModel(); } // check, if the reference frame is in hidden mode. // But look, if this analyze step is realy needed. css::uno::Reference< css::beans::XPropertySet > xSet(m_xReferenceFrame, css::uno::UNO_QUERY); if ( ((m_eDetectMode & E_HIDDEN) == E_HIDDEN) && (xSet.is() ) ) { css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN); aValue >>= m_bReferenceIsHidden; } // check, if the reference frame includes the backing component. // But look, if this analyze step is realy needed. if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT) { try { css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::utl::getProcessServiceFactory(); css::uno::Reference< css::frame::XModuleManager > xModuleMgr(xSMGR->createInstance(SERVICENAME_MODULEMANAGER), css::uno::UNO_QUERY); ::rtl::OUString sModule = xModuleMgr->identify(m_xReferenceFrame); m_bReferenceIsBacking = (sModule.equals(SERVICENAME_STARTMODULE)); } catch(const css::uno::Exception&) {} } // check, if the reference frame includes the help module. // But look, if this analyze step is realy needed. if ( ((m_eDetectMode & E_HELP) == E_HELP ) && (m_xReferenceFrame.is() ) && (m_xReferenceFrame->getName() == SPECIALTARGET_HELPTASK) ) { m_bReferenceIsHelp = sal_True; } try { // Step over all frames of the desktop frame container and analyze it. for (sal_Int32 i=0; i<nCount; ++i) { // Ignore invalid items ... and of course the reference frame. // It will be a member of the given frame list too - but it was already // analyzed before! css::uno::Reference< css::frame::XFrame > xFrame; if ( !(xFrameContainer->getByIndex(i) >>= xFrame) || !(xFrame.is() ) || (xFrame==m_xReferenceFrame ) ) continue; #ifdef ENABLE_WARNINGS if ( ((m_eDetectMode & E_ZOMBIE) == E_ZOMBIE) && ( (!xFrame->getContainerWindow().is()) || (!xFrame->getComponentWindow().is()) ) ) { LOG_WARNING("FrameListAnalyzer::impl_analyze()", "ZOMBIE!") } #endif // ------------------------------------------------- // a) Is it the special help task? // Return it seperated from any return list. if ( ((m_eDetectMode & E_HELP) == E_HELP ) && (xFrame->getName()==SPECIALTARGET_HELPTASK) ) { m_xHelp = xFrame; continue; } // ------------------------------------------------- // b) Or is includes this task the special backing component? // Return it seperated from any return list. // But check if the reference task itself is the backing frame. // Our user mst know it to decide right. if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT) { try { css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::utl::getProcessServiceFactory(); css::uno::Reference< css::frame::XModuleManager > xModuleMgr(xSMGR->createInstance(SERVICENAME_MODULEMANAGER), css::uno::UNO_QUERY); ::rtl::OUString sModule = xModuleMgr->identify(xFrame); if (sModule.equals(SERVICENAME_STARTMODULE)) { m_xBackingComponent = xFrame; continue; } } catch(const css::uno::Exception&) {} } // ------------------------------------------------- // c) Or is it the a task, which uses the specified model? // Add it to the list of "model frames". if ((m_eDetectMode & E_MODEL) == E_MODEL) { css::uno::Reference< css::frame::XController > xController = xFrame->getController(); css::uno::Reference< css::frame::XModel > xModel ; if (xController.is()) xModel = xController->getModel(); if (xModel==xReferenceModel) { m_lModelFrames[nModelStep] = xFrame; ++nModelStep; continue; } } // ------------------------------------------------- // d) Or is it the a task, which use another or no model at all? // Add it to the list of "other frames". But look for it's // visible state ... if it's allowed to do so. // ------------------------------------------------- sal_Bool bHidden = sal_False; if ((m_eDetectMode & E_HIDDEN) == E_HIDDEN ) { xSet = css::uno::Reference< css::beans::XPropertySet >(xFrame, css::uno::UNO_QUERY); if (xSet.is()) { css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN); aValue >>= bHidden; } } if (bHidden) { m_lOtherHiddenFrames[nHiddenStep] = xFrame; ++nHiddenStep; } else { m_lOtherVisibleFrames[nVisibleStep] = xFrame; ++nVisibleStep; } } } catch(css::lang::IndexOutOfBoundsException) { // stop copying if index seams to be wrong. // This interface can't realy guarantee its count for multithreaded // environments. So it can occure! } // Pack both lists by using the actual step positions. // All empty or ignorable items should exist at the end of these lists // behind the position pointers. So they will be removed by a reallocation. m_lOtherVisibleFrames.realloc(nVisibleStep); m_lOtherHiddenFrames.realloc(nHiddenStep); m_lModelFrames.realloc(nModelStep); } } // namespace framework <commit_msg>INTEGRATION: CWS fwk16 (1.5.82); FILE MERGED 2005/07/07 11:20:30 as 1.5.82.1: #120310# close dispatcher detects disposed frames now and handle it more gracefully<commit_after>/************************************************************************* * * $RCSfile: framelistanalyzer.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2005-07-12 14:13:53 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "classes/framelistanalyzer.hxx" //_______________________________________________ // my own includes #ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_ #include <threadhelp/writeguard.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_ #include <threadhelp/readguard.hxx> #endif #ifndef __FRAMEWORK_TARGETS_H_ #include <targets.h> #endif #ifndef __FRAMEWORK_PROPERTIES_H_ #include <properties.h> #endif #ifndef __FRAMEWORK_SERVICES_H_ #include <services.h> #endif //_______________________________________________ // interface includes #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_ #include <com/sun/star/frame/XModuleManager.hpp> #endif //_______________________________________________ // includes of other projects #ifndef _UNOTOOLS_PROCESSFACTORY_HXX_ #include <unotools/processfactory.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif //_______________________________________________ // namespace namespace framework{ //_______________________________________________ // non exported const //_______________________________________________ // non exported definitions //_______________________________________________ // declarations //_______________________________________________ /** */ FrameListAnalyzer::FrameListAnalyzer( const css::uno::Reference< css::frame::XFramesSupplier >& xSupplier , const css::uno::Reference< css::frame::XFrame >& xReferenceFrame , sal_uInt32 eDetectMode ) : m_xSupplier (xSupplier ) , m_xReferenceFrame(xReferenceFrame) , m_eDetectMode (eDetectMode ) { impl_analyze(); } //_______________________________________________ /** */ FrameListAnalyzer::~FrameListAnalyzer() { } //_______________________________________________ /** returns an analyzed list of all currently opened (top!) frames inside the desktop tree. We try to get a snapshot of all opened frames, which are part of the desktop frame container. Of course we can't access frames, which stands outside of this tree. But it's neccessary to collect top frames here only. Otherwhise we interpret closing of last frame wrong. Further we analyze this list and split into different parts. E.g. for "CloseDoc" we must know, which frames of the given list referr to the same model. These frames must be closed then. But all other frames must be untouched. In case the request was "CloseWin" these splitted lists can be used too, to decide if the last window or document was closed. Then we have to initialize the backing window ... Last but not least we must know something about our special help frame. It must be handled seperatly. And last but not least - the backing component frame must be detected too. */ void FrameListAnalyzer::impl_analyze() { // reset all members to get a consistent state m_bReferenceIsHidden = sal_False; m_bReferenceIsHelp = sal_False; m_bReferenceIsBacking = sal_False; m_xHelp = css::uno::Reference< css::frame::XFrame >(); m_xBackingComponent = css::uno::Reference< css::frame::XFrame >(); // try to get the task container by using the given supplier css::uno::Reference< css::container::XIndexAccess > xFrameContainer(m_xSupplier->getFrames(), css::uno::UNO_QUERY); // All return list get an initial size to include all possible frames. // They will be packed at the end of this method ... using the actual step positions then. sal_Int32 nVisibleStep = 0; sal_Int32 nHiddenStep = 0; sal_Int32 nModelStep = 0; sal_Int32 nCount = xFrameContainer->getCount(); m_lOtherVisibleFrames.realloc(nCount); m_lOtherHiddenFrames.realloc(nCount); m_lModelFrames.realloc(nCount); // ask for the model of the given reference frame. // It must be compared with the model of every frame of the container // to sort it into the list of frames with the same model. // Supress this step, if right detect mode isn't set. css::uno::Reference< css::frame::XModel > xReferenceModel; if ((m_eDetectMode & E_MODEL) == E_MODEL ) { css::uno::Reference< css::frame::XController > xReferenceController; if (m_xReferenceFrame.is()) xReferenceController = m_xReferenceFrame->getController(); if (xReferenceController.is()) xReferenceModel = xReferenceController->getModel(); } // check, if the reference frame is in hidden mode. // But look, if this analyze step is realy needed. css::uno::Reference< css::beans::XPropertySet > xSet(m_xReferenceFrame, css::uno::UNO_QUERY); if ( ((m_eDetectMode & E_HIDDEN) == E_HIDDEN) && (xSet.is() ) ) { css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN); aValue >>= m_bReferenceIsHidden; } // check, if the reference frame includes the backing component. // But look, if this analyze step is realy needed. if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT) { try { css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::utl::getProcessServiceFactory(); css::uno::Reference< css::frame::XModuleManager > xModuleMgr(xSMGR->createInstance(SERVICENAME_MODULEMANAGER), css::uno::UNO_QUERY); ::rtl::OUString sModule = xModuleMgr->identify(m_xReferenceFrame); m_bReferenceIsBacking = (sModule.equals(SERVICENAME_STARTMODULE)); } catch(const css::uno::Exception&) {} } // check, if the reference frame includes the help module. // But look, if this analyze step is realy needed. if ( ((m_eDetectMode & E_HELP) == E_HELP ) && (m_xReferenceFrame.is() ) && (m_xReferenceFrame->getName() == SPECIALTARGET_HELPTASK) ) { m_bReferenceIsHelp = sal_True; } try { // Step over all frames of the desktop frame container and analyze it. for (sal_Int32 i=0; i<nCount; ++i) { // Ignore invalid items ... and of course the reference frame. // It will be a member of the given frame list too - but it was already // analyzed before! css::uno::Reference< css::frame::XFrame > xFrame; if ( !(xFrameContainer->getByIndex(i) >>= xFrame) || !(xFrame.is() ) || (xFrame==m_xReferenceFrame ) ) continue; #ifdef ENABLE_WARNINGS if ( ((m_eDetectMode & E_ZOMBIE) == E_ZOMBIE) && ( (!xFrame->getContainerWindow().is()) || (!xFrame->getComponentWindow().is()) ) ) { LOG_WARNING("FrameListAnalyzer::impl_analyze()", "ZOMBIE!") } #endif // ------------------------------------------------- // a) Is it the special help task? // Return it seperated from any return list. if ( ((m_eDetectMode & E_HELP) == E_HELP ) && (xFrame->getName()==SPECIALTARGET_HELPTASK) ) { m_xHelp = xFrame; continue; } // ------------------------------------------------- // b) Or is includes this task the special backing component? // Return it seperated from any return list. // But check if the reference task itself is the backing frame. // Our user mst know it to decide right. if ((m_eDetectMode & E_BACKINGCOMPONENT) == E_BACKINGCOMPONENT) { try { css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = ::utl::getProcessServiceFactory(); css::uno::Reference< css::frame::XModuleManager > xModuleMgr(xSMGR->createInstance(SERVICENAME_MODULEMANAGER), css::uno::UNO_QUERY); ::rtl::OUString sModule = xModuleMgr->identify(xFrame); if (sModule.equals(SERVICENAME_STARTMODULE)) { m_xBackingComponent = xFrame; continue; } } catch(const css::uno::Exception&) {} } // ------------------------------------------------- // c) Or is it the a task, which uses the specified model? // Add it to the list of "model frames". if ((m_eDetectMode & E_MODEL) == E_MODEL) { css::uno::Reference< css::frame::XController > xController = xFrame->getController(); css::uno::Reference< css::frame::XModel > xModel ; if (xController.is()) xModel = xController->getModel(); if (xModel==xReferenceModel) { m_lModelFrames[nModelStep] = xFrame; ++nModelStep; continue; } } // ------------------------------------------------- // d) Or is it the a task, which use another or no model at all? // Add it to the list of "other frames". But look for it's // visible state ... if it's allowed to do so. // ------------------------------------------------- sal_Bool bHidden = sal_False; if ((m_eDetectMode & E_HIDDEN) == E_HIDDEN ) { xSet = css::uno::Reference< css::beans::XPropertySet >(xFrame, css::uno::UNO_QUERY); if (xSet.is()) { css::uno::Any aValue = xSet->getPropertyValue(FRAME_PROPNAME_ISHIDDEN); aValue >>= bHidden; } } if (bHidden) { m_lOtherHiddenFrames[nHiddenStep] = xFrame; ++nHiddenStep; } else { m_lOtherVisibleFrames[nVisibleStep] = xFrame; ++nVisibleStep; } } } catch(css::lang::IndexOutOfBoundsException) { // stop copying if index seams to be wrong. // This interface can't realy guarantee its count for multithreaded // environments. So it can occure! } // Pack both lists by using the actual step positions. // All empty or ignorable items should exist at the end of these lists // behind the position pointers. So they will be removed by a reallocation. m_lOtherVisibleFrames.realloc(nVisibleStep); m_lOtherHiddenFrames.realloc(nHiddenStep); m_lModelFrames.realloc(nModelStep); } } // namespace framework <|endoftext|>
<commit_before>// Copyright (c) 2014-2016 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/ #ifndef PEGTL_INTERNAL_FILE_MAPPER_HH #define PEGTL_INTERNAL_FILE_MAPPER_HH #include <unistd.h> #include <sys/mman.h> #include "file_opener.hh" #include "../input_error.hh" namespace pegtl { namespace internal { class file_mapper { public: explicit file_mapper( const std::string & filename ) : file_mapper( file_opener( filename ) ) { } explicit file_mapper( const file_opener & reader ) : m_size( reader.size() ), m_data( static_cast< const char * >( ::mmap( nullptr, m_size, PROT_READ, MAP_FILE | MAP_PRIVATE, reader.m_fd, 0 ) ) ) { if ( m_size && intptr_t( m_data ) == -1 ) { PEGTL_THROW_INPUT_ERROR( "unable to mmap() file " << reader.m_source << " descriptor " << reader.m_fd ); } } ~file_mapper() { ::munmap( const_cast< char * >( m_data ), m_size ); // Legacy C interface requires pointer-to-mutable but does not write through the pointer. } file_mapper( const file_mapper & ) = delete; void operator= ( const file_mapper & ) = delete; bool empty() const { return m_size == 0; } std::size_t size() const { return m_size; } using iterator = const char *; using const_iterator = const char *; iterator data() const { return m_data; } iterator begin() const { return m_data; } iterator end() const { return m_data + m_size; } std::string string() const { return std::string( m_data, m_size ); } private: const std::size_t m_size; const char * const m_data; }; } // namespace internal } // namespace pegtl #endif <commit_msg>Update file_mapper.hh<commit_after>// Copyright (c) 2014-2016 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/ #ifndef PEGTL_INTERNAL_FILE_MAPPER_HH #define PEGTL_INTERNAL_FILE_MAPPER_HH #include <unistd.h> #include <sys/mman.h> #include "file_opener.hh" #include "../input_error.hh" namespace pegtl { namespace internal { class file_mapper { public: explicit file_mapper( const std::string & filename ) : file_mapper( file_opener( filename ) ) { } explicit file_mapper( const file_opener & reader ) : m_size( reader.size() ), m_data( static_cast< const char * >( ::mmap( nullptr, m_size, PROT_READ, MAP_FILE | MAP_PRIVATE, reader.m_fd, 0 ) ) ) { if ( m_size && ( intptr_t( m_data ) == -1 ) ) { PEGTL_THROW_INPUT_ERROR( "unable to mmap() file " << reader.m_source << " descriptor " << reader.m_fd ); } } ~file_mapper() { ::munmap( const_cast< char * >( m_data ), m_size ); // Legacy C interface requires pointer-to-mutable but does not write through the pointer. } file_mapper( const file_mapper & ) = delete; void operator= ( const file_mapper & ) = delete; bool empty() const { return m_size == 0; } std::size_t size() const { return m_size; } using iterator = const char *; using const_iterator = const char *; iterator data() const { return m_data; } iterator begin() const { return m_data; } iterator end() const { return m_data + m_size; } std::string string() const { return std::string( m_data, m_size ); } private: const std::size_t m_size; const char * const m_data; }; } // namespace internal } // namespace pegtl #endif <|endoftext|>
<commit_before>#include "dialog.h" #include <Tempest/SystemAPI> #include <Tempest/Window> #include <Tempest/Layout> #include <Tempest/Application> using namespace Tempest; struct Dialog::LayShadow : Tempest::Layout { void applyLayout(){ for(Widget* w:widgets()){ Point pos = w->pos(); if(w->x()+w->w()>owner()->w()) pos.x = owner()->w()-w->w(); if(w->y()+w->h()>owner()->h()) pos.y = owner()->h()-w->h(); if(pos.x<=0) pos.x = 0; if(pos.y<=0) pos.y = 0; w->setPosition(pos); } } }; struct Dialog::Overlay : public Tempest::WindowOverlay { bool isModal = true; Dialog * dlg = nullptr; void mouseDownEvent(MouseEvent& e){ e.accept(); } void mouseWheelEvent(MouseEvent& e){ e.accept(); } void paintEvent(PaintEvent& e){ dlg->paintShadow(e); paintNested(e); } }; Dialog::Dialog() : owner_ov(nullptr) { resize(300,200); setDragable(1); } Dialog::~Dialog() { close(); } int Dialog::exec() { if(!owner_ov){ owner_ov = new Overlay(); owner_ov->dlg = this; T_ASSERT( SystemAPI::instance().addOverlay( owner_ov )!=0 ); owner_ov->setLayout( new LayShadow() ); owner_ov->layout().add( this ); } setPosition( (owner_ov->w()-w())/2, (owner_ov->h()-h())/2 ); while( owner_ov && !Application::isQuit() ) { Application::processEvents(); } return 0; } void Dialog::close() { if( owner_ov ){ Tempest::WindowOverlay* ov = owner_ov; owner_ov = 0; setVisible(0); CloseEvent e; this->closeEvent(e); ov->layout().take(this); ov->deleteLater(); } } void Dialog::setModal(bool m) { if(owner_ov) owner_ov->isModal = m; } bool Dialog::isModal() const { return owner_ov ? owner_ov->isModal : false; } void Dialog::closeEvent( CloseEvent & ) { close(); } void Dialog::paintShadow(PaintEvent &e) { if(!owner_ov) return; Painter p(e); p.setBlendMode(alphaBlend); p.setColor(0,0,0,0.5); p.drawRect(0,0,owner_ov->w(),owner_ov->h()); } <commit_msg>fix dialog close event<commit_after>#include "dialog.h" #include <Tempest/SystemAPI> #include <Tempest/Window> #include <Tempest/Layout> #include <Tempest/Application> using namespace Tempest; struct Dialog::LayShadow : Tempest::Layout { void applyLayout(){ for(Widget* w:widgets()){ Point pos = w->pos(); if(w->x()+w->w()>owner()->w()) pos.x = owner()->w()-w->w(); if(w->y()+w->h()>owner()->h()) pos.y = owner()->h()-w->h(); if(pos.x<=0) pos.x = 0; if(pos.y<=0) pos.y = 0; w->setPosition(pos); } } }; struct Dialog::Overlay : public Tempest::WindowOverlay { bool isModal = true; Dialog * dlg = nullptr; void mouseDownEvent(MouseEvent& e){ e.accept(); } void mouseWheelEvent(MouseEvent& e){ e.accept(); } void paintEvent(PaintEvent& e){ dlg->paintShadow(e); paintNested(e); } }; Dialog::Dialog() : owner_ov(nullptr) { resize(300,200); setDragable(1); } Dialog::~Dialog() { close(); } int Dialog::exec() { if(!owner_ov){ owner_ov = new Overlay(); owner_ov->dlg = this; T_ASSERT( SystemAPI::instance().addOverlay( owner_ov )!=0 ); owner_ov->setLayout( new LayShadow() ); owner_ov->layout().add( this ); } setPosition( (owner_ov->w()-w())/2, (owner_ov->h()-h())/2 ); while( owner_ov && !Application::isQuit() ) { Application::processEvents(); } return 0; } void Dialog::close() { if( owner_ov ){ Tempest::WindowOverlay* ov = owner_ov; owner_ov = 0; setVisible(0); CloseEvent e; this->closeEvent(e); ov->layout().take(this); ov->deleteLater(); } } void Dialog::setModal(bool m) { if(owner_ov) owner_ov->isModal = m; } bool Dialog::isModal() const { return owner_ov ? owner_ov->isModal : false; } void Dialog::closeEvent( CloseEvent & e ) { if(!owner_ov) e.ignore(); else close(); } void Dialog::paintShadow(PaintEvent &e) { if(!owner_ov) return; Painter p(e); p.setBlendMode(alphaBlend); p.setColor(0,0,0,0.5); p.drawRect(0,0,owner_ov->w(),owner_ov->h()); } <|endoftext|>
<commit_before><commit_msg>ThirdParty: Fix quarternion to euler conversion bug (#6241)<commit_after><|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "scriptingcomponent.h" #include "scriptingcomponentprivate.h" REGISTER_OBJECTTYPE(GluonEngine, ScriptingComponent) using namespace GluonEngine; ScriptingComponent::ScriptingComponent(QObject* parent) : Component(parent) , d(new ScriptingComponentPrivate) { } ScriptingComponent::ScriptingComponent(const ScriptingComponent& other) : d(other.d) { } ScriptingComponent::~ScriptingComponent() { } QString ScriptingComponent::category() const { return QString("Other"); } void ScriptingComponent::initialize() { GluonEngine::Component::initialize(); } void ScriptingComponent::start() { GluonEngine::Component::start(); } void ScriptingComponent::update(int elapsedMilliseconds) { GluonEngine::Component::update(elapsedMilliseconds); } void ScriptingComponent::draw(int timeLapse) { GluonEngine::Component::draw(); } void ScriptingComponent::stop() { GluonEngine::Component::stop(); } void ScriptingComponent::cleanup() { GluonEngine::Component::cleanup(); } #include "scriptingcomponent.moc" <commit_msg>fix some linker errors for Adopta - why did this not get hit for me?!<commit_after>/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "scriptingcomponent.h" #include "scriptingcomponentprivate.h" REGISTER_OBJECTTYPE(GluonEngine, ScriptingComponent) using namespace GluonEngine; ScriptingComponent::ScriptingComponent(QObject* parent) : Component(parent) , d(new ScriptingComponentPrivate) { } ScriptingComponent::ScriptingComponent(const ScriptingComponent& other) : d(other.d) { } ScriptingComponent::~ScriptingComponent() { } QString ScriptingComponent::category() const { return QString("Other"); } ScriptingAsset* ScriptingComponent::script() const { } void ScriptingComponent::setScript(const GluonEngine::ScriptingAsset* newAsset) { } void ScriptingComponent::initialize() { GluonEngine::Component::initialize(); } void ScriptingComponent::start() { GluonEngine::Component::start(); } void ScriptingComponent::update(int elapsedMilliseconds) { GluonEngine::Component::update(elapsedMilliseconds); } void ScriptingComponent::draw(int timeLapse) { GluonEngine::Component::draw(); } void ScriptingComponent::stop() { GluonEngine::Component::stop(); } void ScriptingComponent::cleanup() { GluonEngine::Component::cleanup(); } #include "scriptingcomponent.moc" <|endoftext|>
<commit_before>// Copyright 2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "elang/compiler/analysis/name_tree_builder.h" #include "base/logging.h" #include "elang/compiler/analysis/analysis_editor.h" #include "elang/compiler/ast/class.h" #include "elang/compiler/ast/enum.h" #include "elang/compiler/ast/expressions.h" #include "elang/compiler/ast/factory.h" #include "elang/compiler/ast/method.h" #include "elang/compiler/ast/namespace.h" #include "elang/compiler/ast/types.h" #include "elang/compiler/compilation_session.h" #include "elang/compiler/public/compiler_error_code.h" #include "elang/compiler/semantics/factory.h" #include "elang/compiler/semantics/nodes.h" #include "elang/compiler/token_type.h" namespace elang { namespace compiler { NameTreeBuilder::NameTreeBuilder(CompilationSession* session, AnalysisEditor* editor) : CompilationSessionUser(session), editor_(editor) { } NameTreeBuilder::~NameTreeBuilder() { } sm::Factory* NameTreeBuilder::factory() const { return session()->semantic_factory(); } sm::Class* NameTreeBuilder::NewClass(ast::ClassBody* node) { auto const outer = SemanticOf(node->parent()); if (node->owner()->is_class()) return factory()->NewClass(outer, node->modifiers(), node->name()); if (node->owner()->is_interface()) return factory()->NewInterface(outer, node->modifiers(), node->name()); if (node->owner()->is_struct()) return factory()->NewStruct(outer, node->modifiers(), node->name()); NOTREACHED() << node; return nullptr; } void NameTreeBuilder::ProcessNamespaceBody(ast::NamespaceBody* node) { if (node->loaded_) return; if (node->owner() == session()->global_namespace()) { editor_->SetSemanticOf(node, factory()->global_namespace()); return; } auto const outer = SemanticOf(node->outer())->as<sm::Namespace>(); DCHECK(outer->is<sm::Namespace>()) << outer; if (auto const present = outer->FindMember(node->name())) { DCHECK(present->is<sm::Namespace>()) << present; editor_->SetSemanticOf(node, present); return; } auto const ns = factory()->NewNamespace(outer, node->name()); editor_->SetSemanticOf(node, ns); editor_->SetSemanticOf(node->owner(), ns); } void NameTreeBuilder::Run() { Traverse(session()->global_namespace_body()); for (auto const alias : aliases_) { auto const outer = SemanticOf(alias->parent()); auto const present = outer->FindMember(alias->name()); if (!present) continue; Error(ErrorCode::NameTreeAliasConflict, alias->name(), present->name()); } } sm::Semantic* NameTreeBuilder::SemanticOf(ast::Node* node) const { return editor_->SemanticOf(node); } // NameTreeBuilder - ast::Visitor void NameTreeBuilder::VisitAlias(ast::Alias* node) { aliases_.push_back(node); } void NameTreeBuilder::VisitClassBody(ast::ClassBody* node) { if (auto const ns = node->parent()->as<ast::NamespaceBody>()) { if (ns->loaded_) return ast::Visitor::VisitClassBody(node); } auto const outer = SemanticOf(node->parent()); auto const present = outer->FindMember(node->name()); if (!present) { editor_->SetSemanticOf(node, NewClass(node)); ast::Visitor::VisitClassBody(node); return; } if (auto const present_class = present->as<sm::Class>()) { if (!present_class->has_base() && node->IsPartial() && present_class->IsPartial()) { editor_->SetSemanticOf(node, present_class); return ast::Visitor::VisitClassBody(node); } return Error(ErrorCode::NameTreeClassDuplicate, node, present->name()); } Error(ErrorCode::NameTreeClassConflict, node, present->name()); } void NameTreeBuilder::VisitConst(ast::Const* node) { auto const owner = SemanticOf(node->parent()->as<ast::ClassBody>())->as<sm::Class>(); auto const present = owner->FindMember(node->name()); if (!present) { editor_->SetSemanticOf(node, factory()->NewConst(owner, node->name())); return; } if (present->is<sm::Const>()) { return Error(ErrorCode::NameTreeConstDuplicate, node, present->name()); } Error(ErrorCode::NameTreeConstConflict, node, present->name()); } void NameTreeBuilder::VisitEnum(ast::Enum* node) { if (auto const ns = node->parent()->as<ast::NamespaceBody>()) { if (ns->loaded_) return; } auto const outer = SemanticOf(node->parent()); auto const present = outer->FindMember(node->name()); if (present) { if (present->is<sm::Enum>()) return Error(ErrorCode::NameTreeEnumDuplicate, node, present->name()); return Error(ErrorCode::NameTreeEnumConflict, node, present->name()); } auto const enum_type = factory()->NewEnum(outer, node->name()); for (auto const member : node->members()) { editor_->SetSemanticOf(member, factory()->NewEnumMember(enum_type, member->name())); } editor_->SetSemanticOf(node, enum_type); } void NameTreeBuilder::VisitField(ast::Field* node) { auto const owner = SemanticOf(node->parent()->as<ast::ClassBody>())->as<sm::Class>(); auto const present = owner->FindMember(node->name()); if (!present) { editor_->SetSemanticOf(node, factory()->NewField(owner, node->name())); return; } if (present->is<sm::Field>()) return Error(ErrorCode::NameTreeFieldDuplicate, node, present->name()); Error(ErrorCode::NameTreeFieldConflict, node, present->name()); } void NameTreeBuilder::VisitMethod(ast::Method* node) { auto const owner = SemanticOf(node->parent()->as<ast::ClassBody>())->as<sm::Class>(); auto const present = owner->FindMember(node->name()); if (!present) { factory()->NewMethodGroup(owner, node->name()); return; } if (present->is<sm::MethodGroup>()) return; Error(ErrorCode::NameTreeMethodConflict, node->name()); } void NameTreeBuilder::VisitNamespaceBody(ast::NamespaceBody* node) { ProcessNamespaceBody(node); ast::Visitor::VisitNamespaceBody(node); } } // namespace compiler } // namespace elang <commit_msg>elang/compiler/analysis: Make |NameTreeBuilder| not to traverse external AST tree.<commit_after>// Copyright 2015 Project Vogue. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "elang/compiler/analysis/name_tree_builder.h" #include "base/logging.h" #include "elang/compiler/analysis/analysis_editor.h" #include "elang/compiler/ast/class.h" #include "elang/compiler/ast/enum.h" #include "elang/compiler/ast/expressions.h" #include "elang/compiler/ast/factory.h" #include "elang/compiler/ast/method.h" #include "elang/compiler/ast/namespace.h" #include "elang/compiler/ast/types.h" #include "elang/compiler/compilation_session.h" #include "elang/compiler/public/compiler_error_code.h" #include "elang/compiler/semantics/factory.h" #include "elang/compiler/semantics/nodes.h" #include "elang/compiler/token_type.h" namespace elang { namespace compiler { NameTreeBuilder::NameTreeBuilder(CompilationSession* session, AnalysisEditor* editor) : CompilationSessionUser(session), editor_(editor) { } NameTreeBuilder::~NameTreeBuilder() { } sm::Factory* NameTreeBuilder::factory() const { return session()->semantic_factory(); } sm::Class* NameTreeBuilder::NewClass(ast::ClassBody* node) { auto const outer = SemanticOf(node->parent()); if (node->owner()->is_class()) return factory()->NewClass(outer, node->modifiers(), node->name()); if (node->owner()->is_interface()) return factory()->NewInterface(outer, node->modifiers(), node->name()); if (node->owner()->is_struct()) return factory()->NewStruct(outer, node->modifiers(), node->name()); NOTREACHED() << node; return nullptr; } void NameTreeBuilder::ProcessNamespaceBody(ast::NamespaceBody* node) { if (node->loaded_) return; if (node->owner() == session()->global_namespace()) { editor_->SetSemanticOf(node, factory()->global_namespace()); return; } auto const outer = SemanticOf(node->outer())->as<sm::Namespace>(); DCHECK(outer->is<sm::Namespace>()) << outer; if (auto const present = outer->FindMember(node->name())) { DCHECK(present->is<sm::Namespace>()) << present; editor_->SetSemanticOf(node, present); return; } auto const ns = factory()->NewNamespace(outer, node->name()); editor_->SetSemanticOf(node, ns); editor_->SetSemanticOf(node->owner(), ns); } void NameTreeBuilder::Run() { Traverse(session()->global_namespace_body()); for (auto const alias : aliases_) { auto const outer = SemanticOf(alias->parent()); auto const present = outer->FindMember(alias->name()); if (!present) continue; Error(ErrorCode::NameTreeAliasConflict, alias->name(), present->name()); } } sm::Semantic* NameTreeBuilder::SemanticOf(ast::Node* node) const { return editor_->SemanticOf(node); } // NameTreeBuilder - ast::Visitor void NameTreeBuilder::VisitAlias(ast::Alias* node) { aliases_.push_back(node); } void NameTreeBuilder::VisitClassBody(ast::ClassBody* node) { if (auto const ns = node->parent()->as<ast::NamespaceBody>()) { if (ns->loaded_) return; } auto const outer = SemanticOf(node->parent()); auto const present = outer->FindMember(node->name()); if (!present) { editor_->SetSemanticOf(node, NewClass(node)); ast::Visitor::VisitClassBody(node); return; } if (auto const present_class = present->as<sm::Class>()) { if (!present_class->has_base() && node->IsPartial() && present_class->IsPartial()) { editor_->SetSemanticOf(node, present_class); return ast::Visitor::VisitClassBody(node); } return Error(ErrorCode::NameTreeClassDuplicate, node, present->name()); } Error(ErrorCode::NameTreeClassConflict, node, present->name()); } void NameTreeBuilder::VisitConst(ast::Const* node) { auto const owner = SemanticOf(node->parent()->as<ast::ClassBody>())->as<sm::Class>(); auto const present = owner->FindMember(node->name()); if (!present) { editor_->SetSemanticOf(node, factory()->NewConst(owner, node->name())); return; } if (present->is<sm::Const>()) { return Error(ErrorCode::NameTreeConstDuplicate, node, present->name()); } Error(ErrorCode::NameTreeConstConflict, node, present->name()); } void NameTreeBuilder::VisitEnum(ast::Enum* node) { if (auto const ns = node->parent()->as<ast::NamespaceBody>()) { if (ns->loaded_) return; } auto const outer = SemanticOf(node->parent()); auto const present = outer->FindMember(node->name()); if (present) { if (present->is<sm::Enum>()) return Error(ErrorCode::NameTreeEnumDuplicate, node, present->name()); return Error(ErrorCode::NameTreeEnumConflict, node, present->name()); } auto const enum_type = factory()->NewEnum(outer, node->name()); for (auto const member : node->members()) { editor_->SetSemanticOf(member, factory()->NewEnumMember(enum_type, member->name())); } editor_->SetSemanticOf(node, enum_type); } void NameTreeBuilder::VisitField(ast::Field* node) { auto const owner = SemanticOf(node->parent()->as<ast::ClassBody>())->as<sm::Class>(); auto const present = owner->FindMember(node->name()); if (!present) { editor_->SetSemanticOf(node, factory()->NewField(owner, node->name())); return; } if (present->is<sm::Field>()) return Error(ErrorCode::NameTreeFieldDuplicate, node, present->name()); Error(ErrorCode::NameTreeFieldConflict, node, present->name()); } void NameTreeBuilder::VisitMethod(ast::Method* node) { auto const owner = SemanticOf(node->parent()->as<ast::ClassBody>())->as<sm::Class>(); auto const present = owner->FindMember(node->name()); if (!present) { factory()->NewMethodGroup(owner, node->name()); return; } if (present->is<sm::MethodGroup>()) return; Error(ErrorCode::NameTreeMethodConflict, node->name()); } void NameTreeBuilder::VisitNamespaceBody(ast::NamespaceBody* node) { ProcessNamespaceBody(node); ast::Visitor::VisitNamespaceBody(node); } } // namespace compiler } // namespace elang <|endoftext|>
<commit_before>/* ============================================================================== Copyright (c) 2016, Daniel Walz All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ============================================================================== LayoutItemView.cpp Created: 24 Apr 2016 10:47:36pm Author: Daniel Walz ============================================================================== */ #include "../JuceLibraryCode/JuceHeader.h" #include "LayoutEditorApplication.h" #include "LayoutXMLEditor.h" #include "LayoutTreeView.h" #include "LayoutTreeViewItem.h" LayoutTreeViewItem::LayoutTreeViewItem (ValueTree _state, LayoutXMLEditor* _editor) : state (_state), editor (_editor) { setState (state, editor); } void LayoutTreeViewItem::setState (ValueTree _state, LayoutXMLEditor* _editor) { OpennessRestorer restorer (*this); state = _state; editor = _editor; LayoutItem item (state); clearSubItems(); if (item.isSubLayout()) { for (int i=0; i<state.getNumChildren(); ++i) { addSubItem (new LayoutTreeViewItem (state.getChild (i), editor)); } } } String LayoutTreeViewItem::getUniqueName () const { String name = state.getType().toString(); if (state.getType() == LayoutItem::itemTypeSubLayout) { name += ":" + state.getProperty (LayoutItem::propOrientation).toString(); } if (state.hasProperty (LayoutItem::propComponentID)) { name += ":" + state.getProperty (LayoutItem::propComponentID).toString(); } if (state.hasProperty (LayoutItem::propComponentName)) { name += ":" + state.getProperty (LayoutItem::propComponentName).toString(); } return name; } void LayoutTreeViewItem::paintItem (Graphics &g, int width, int height) { Graphics::ScopedSaveState save (g); LayoutItem item (state); if (item.isSubLayout()) { g.setColour (Colours::black); g.drawText (LayoutItem::getNameFromOrientation (item.getOrientation()).toString(), 0, 0, width, height, Justification::left); } else if (item.isSplitterItem()) { g.setColour (Colours::darkblue); g.drawText (TRANS ("Splitter"), 0, 0, width, height, Justification::left); } else if (item.isSpacerItem()) { g.setColour (Colours::darkgreen); g.drawText (TRANS ("Spacer"), 0, 0, width, height, Justification::left); } else if (item.isComponentItem()) { g.setColour (Colours::darkred); String componentID = item.getComponentID(); if (!componentID.isEmpty()) { g.drawText (String ("ID:") + componentID, 0, 0, width, height, Justification::left); } else { String labelText = state.getProperty ("labelText", ""); Font f = g.getCurrentFont(); f.setItalic (true); g.setFont (f); g.drawText (String ("\"") + labelText + String ("\""), 0, 0, width, height, Justification::left); } } } bool LayoutTreeViewItem::mightContainSubItems () { LayoutItem item (state); return item.isSubLayout(); } void LayoutTreeViewItem::itemSelectionChanged (bool isNowSelected) { if (editor && isNowSelected) { editor->updatePropertiesView (state); } } void LayoutTreeViewItem::itemClicked (const MouseEvent& event) { if (event.mods.isRightButtonDown()) { ApplicationCommandManager* cm = LayoutEditorApplication::getApp()->getCommandManager(); PopupMenu menu; menu.addCommandItem (cm, LayoutXMLEditor::CMDLayoutEditor_InsertLayout); menu.addCommandItem (cm, LayoutXMLEditor::CMDLayoutEditor_InsertComponent); menu.addCommandItem (cm, LayoutXMLEditor::CMDLayoutEditor_InsertSplitter); menu.addCommandItem (cm, LayoutXMLEditor::CMDLayoutEditor_InsertSpacer); menu.addSeparator(); menu.addCommandItem (cm, StandardApplicationCommandIDs::del); menu.show(); } } var LayoutTreeViewItem::getDragSourceDescription () { String name; ValueTree item = state; ValueTree parent = item.getParent(); while (parent.isValid()) { name = String (parent.indexOf (item)) + ";" + name; item = parent; parent = item.getParent(); } return name; } bool LayoutTreeViewItem::isInterestedInDragSource (const DragAndDropTarget::SourceDetails& dragSourceDetails) { if (state.getType() == LayoutItem::itemTypeSubLayout) { return true; } return false; } void LayoutTreeViewItem::itemDropped (const DragAndDropTarget::SourceDetails& dragSourceDetails, int insertIndex) { DBG ("Drop Item: " + dragSourceDetails.description.toString()); LayoutTreeView* treeView = dynamic_cast<LayoutTreeView*> (dragSourceDetails.sourceComponent.get()); if (treeView != nullptr) { if (LayoutTreeViewItem* dragged = dynamic_cast<LayoutTreeViewItem*> (treeView->getSelectedItem (0))) { ValueTree movedNode = dragged->state; if (movedNode.getParent().isValid()) { movedNode.getParent().removeChild (movedNode, nullptr); state.addChild (movedNode, insertIndex, nullptr); } } } } <commit_msg>Avoid inserting node to itself<commit_after>/* ============================================================================== Copyright (c) 2016, Daniel Walz All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ============================================================================== LayoutItemView.cpp Created: 24 Apr 2016 10:47:36pm Author: Daniel Walz ============================================================================== */ #include "../JuceLibraryCode/JuceHeader.h" #include "LayoutEditorApplication.h" #include "LayoutXMLEditor.h" #include "LayoutTreeView.h" #include "LayoutTreeViewItem.h" LayoutTreeViewItem::LayoutTreeViewItem (ValueTree _state, LayoutXMLEditor* _editor) : state (_state), editor (_editor) { setState (state, editor); } void LayoutTreeViewItem::setState (ValueTree _state, LayoutXMLEditor* _editor) { OpennessRestorer restorer (*this); state = _state; editor = _editor; LayoutItem item (state); clearSubItems(); if (item.isSubLayout()) { for (int i=0; i<state.getNumChildren(); ++i) { addSubItem (new LayoutTreeViewItem (state.getChild (i), editor)); } } } String LayoutTreeViewItem::getUniqueName () const { String name = state.getType().toString(); if (state.getType() == LayoutItem::itemTypeSubLayout) { name += ":" + state.getProperty (LayoutItem::propOrientation).toString(); } if (state.hasProperty (LayoutItem::propComponentID)) { name += ":" + state.getProperty (LayoutItem::propComponentID).toString(); } if (state.hasProperty (LayoutItem::propComponentName)) { name += ":" + state.getProperty (LayoutItem::propComponentName).toString(); } return name; } void LayoutTreeViewItem::paintItem (Graphics &g, int width, int height) { Graphics::ScopedSaveState save (g); LayoutItem item (state); if (item.isSubLayout()) { g.setColour (Colours::black); g.drawText (LayoutItem::getNameFromOrientation (item.getOrientation()).toString(), 0, 0, width, height, Justification::left); } else if (item.isSplitterItem()) { g.setColour (Colours::darkblue); g.drawText (TRANS ("Splitter"), 0, 0, width, height, Justification::left); } else if (item.isSpacerItem()) { g.setColour (Colours::darkgreen); g.drawText (TRANS ("Spacer"), 0, 0, width, height, Justification::left); } else if (item.isComponentItem()) { g.setColour (Colours::darkred); String componentID = item.getComponentID(); if (!componentID.isEmpty()) { g.drawText (String ("ID:") + componentID, 0, 0, width, height, Justification::left); } else { String labelText = state.getProperty ("labelText", ""); Font f = g.getCurrentFont(); f.setItalic (true); g.setFont (f); g.drawText (String ("\"") + labelText + String ("\""), 0, 0, width, height, Justification::left); } } } bool LayoutTreeViewItem::mightContainSubItems () { LayoutItem item (state); return item.isSubLayout(); } void LayoutTreeViewItem::itemSelectionChanged (bool isNowSelected) { if (editor && isNowSelected) { editor->updatePropertiesView (state); } } void LayoutTreeViewItem::itemClicked (const MouseEvent& event) { if (event.mods.isRightButtonDown()) { ApplicationCommandManager* cm = LayoutEditorApplication::getApp()->getCommandManager(); PopupMenu menu; menu.addCommandItem (cm, LayoutXMLEditor::CMDLayoutEditor_InsertLayout); menu.addCommandItem (cm, LayoutXMLEditor::CMDLayoutEditor_InsertComponent); menu.addCommandItem (cm, LayoutXMLEditor::CMDLayoutEditor_InsertSplitter); menu.addCommandItem (cm, LayoutXMLEditor::CMDLayoutEditor_InsertSpacer); menu.addSeparator(); menu.addCommandItem (cm, StandardApplicationCommandIDs::del); menu.show(); } } var LayoutTreeViewItem::getDragSourceDescription () { String name; ValueTree item = state; ValueTree parent = item.getParent(); while (parent.isValid()) { name = String (parent.indexOf (item)) + ";" + name; item = parent; parent = item.getParent(); } return name; } bool LayoutTreeViewItem::isInterestedInDragSource (const DragAndDropTarget::SourceDetails& dragSourceDetails) { if (state.getType() == LayoutItem::itemTypeSubLayout) { return true; } return false; } void LayoutTreeViewItem::itemDropped (const DragAndDropTarget::SourceDetails& dragSourceDetails, int insertIndex) { DBG ("Drop Item: " + dragSourceDetails.description.toString()); LayoutTreeView* treeView = dynamic_cast<LayoutTreeView*> (dragSourceDetails.sourceComponent.get()); if (treeView != nullptr) { if (LayoutTreeViewItem* dragged = dynamic_cast<LayoutTreeViewItem*> (treeView->getSelectedItem (0))) { ValueTree movedNode = dragged->state; if (movedNode.getParent().isValid()) { if (state.isAChildOf (movedNode)) { return; } movedNode.getParent().removeChild (movedNode, nullptr); state.addChild (movedNode, insertIndex, nullptr); } } } } <|endoftext|>
<commit_before>/* Copyright (c) 2007 Tobias Koenig <tokoe@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "addressbookcombobox.h" #include "collectionfiltermodel_p.h" #include <akonadi/collectionfetchscope.h> #include <akonadi/entitytreemodel.h> #include <akonadi/entityfilterproxymodel.h> #include <akonadi/monitor.h> #include <akonadi/session.h> #include <kabc/addressee.h> #include <kabc/contactgroup.h> #include <kdescendantsproxymodel.h> #include <QtCore/QAbstractItemModel> #include <QtGui/QComboBox> #include <QtGui/QVBoxLayout> using namespace Akonadi; class AddressBookComboBox::Private { public: Private( AddressBookComboBox::Type type, AddressBookComboBox *parent ) : mParent( parent ) { mComboBox = new QComboBox; QStringList contentTypes; switch ( type ) { case AddressBookComboBox::ContactsOnly: contentTypes << KABC::Addressee::mimeType(); break; case AddressBookComboBox::ContactGroupsOnly: contentTypes << KABC::ContactGroup::mimeType(); break; case AddressBookComboBox::All: contentTypes << KABC::Addressee::mimeType() << KABC::ContactGroup::mimeType(); break; } mMonitor = new Akonadi::Monitor; mMonitor->fetchCollection( true ); mMonitor->setCollectionMonitored( Akonadi::Collection::root() ); mMonitor->collectionFetchScope().setContentMimeTypes( contentTypes ); foreach ( const QString &mimeType, contentTypes ) mMonitor->setMimeTypeMonitored( mimeType, true ); mModel = new EntityTreeModel( Session::defaultSession(), mMonitor ); mModel->setItemPopulationStrategy(EntityTreeModel::NoItemPopulation); KDescendantsProxyModel *descProxy = new KDescendantsProxyModel( parent ); descProxy->setSourceModel( mModel ); // filter for collections that support saving of contacts / contact groups CollectionFilterModel *filterModel = new CollectionFilterModel( mParent ); foreach ( const QString &contentMimeType, contentTypes ) filterModel->addContentMimeTypeFilter( contentMimeType ); filterModel->setRightsFilter( Akonadi::Collection::CanCreateItem ); filterModel->setSourceModel( descProxy ); mComboBox->setModel( filterModel ); } ~Private() { delete mModel; delete mMonitor; } void activated( int index ); AddressBookComboBox *mParent; QComboBox *mComboBox; Monitor *mMonitor; EntityTreeModel *mModel; }; void AddressBookComboBox::Private::activated( int index ) { const QModelIndex modelIndex = mComboBox->model()->index( index, 0 ); if ( modelIndex.isValid() ) emit mParent->selectionChanged( modelIndex.data( EntityTreeModel::CollectionRole).value<Collection>() ); } AddressBookComboBox::AddressBookComboBox( Type type, QWidget *parent ) : QWidget( parent ), d( new Private( type, this ) ) { QVBoxLayout *layout = new QVBoxLayout( this ); layout->setMargin( 0 ); layout->setSpacing( 0 ); layout->addWidget( d->mComboBox ); d->mComboBox->setCurrentIndex( 0 ); connect( d->mComboBox, SIGNAL( activated( int ) ), SLOT( activated( int ) ) ); } AddressBookComboBox::~AddressBookComboBox() { delete d->mComboBox; // delete as long as the model still exists, crashs otherwise delete d; } Akonadi::Collection AddressBookComboBox::selectedAddressBook() const { Q_ASSERT_X( d->mComboBox->model() != 0, "AddressBookComboBox::selectedAddressBook", "No model set!" ); const int index = d->mComboBox->currentIndex(); const QModelIndex modelIndex = d->mComboBox->model()->index( index, 0 ); if ( modelIndex.isValid() ) return modelIndex.data( Akonadi::EntityTreeModel::CollectionRole ).value<Collection>(); else return Akonadi::Collection(); } #include "addressbookcombobox.moc" <commit_msg>SVN_SILENT coding style cleanup<commit_after>/* Copyright (c) 2007 Tobias Koenig <tokoe@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "addressbookcombobox.h" #include "collectionfiltermodel_p.h" #include <akonadi/collectionfetchscope.h> #include <akonadi/entitytreemodel.h> #include <akonadi/entityfilterproxymodel.h> #include <akonadi/monitor.h> #include <akonadi/session.h> #include <kabc/addressee.h> #include <kabc/contactgroup.h> #include <kdescendantsproxymodel.h> #include <QtCore/QAbstractItemModel> #include <QtGui/QComboBox> #include <QtGui/QVBoxLayout> using namespace Akonadi; class AddressBookComboBox::Private { public: Private( AddressBookComboBox::Type type, AddressBookComboBox *parent ) : mParent( parent ) { mComboBox = new QComboBox; QStringList contentTypes; switch ( type ) { case AddressBookComboBox::ContactsOnly: contentTypes << KABC::Addressee::mimeType(); break; case AddressBookComboBox::ContactGroupsOnly: contentTypes << KABC::ContactGroup::mimeType(); break; case AddressBookComboBox::All: contentTypes << KABC::Addressee::mimeType() << KABC::ContactGroup::mimeType(); break; } mMonitor = new Akonadi::Monitor; mMonitor->fetchCollection( true ); mMonitor->setCollectionMonitored( Akonadi::Collection::root() ); mMonitor->collectionFetchScope().setContentMimeTypes( contentTypes ); foreach ( const QString &mimeType, contentTypes ) mMonitor->setMimeTypeMonitored( mimeType, true ); mModel = new EntityTreeModel( Session::defaultSession(), mMonitor ); mModel->setItemPopulationStrategy( EntityTreeModel::NoItemPopulation ); KDescendantsProxyModel *proxyModel = new KDescendantsProxyModel( parent ); proxyModel->setSourceModel( mModel ); // filter for collections that support saving of contacts / contact groups CollectionFilterModel *filterModel = new CollectionFilterModel( mParent ); foreach ( const QString &contentMimeType, contentTypes ) filterModel->addContentMimeTypeFilter( contentMimeType ); filterModel->setRightsFilter( Akonadi::Collection::CanCreateItem ); filterModel->setSourceModel( proxyModel ); mComboBox->setModel( filterModel ); } ~Private() { delete mModel; delete mMonitor; } void activated( int index ); AddressBookComboBox *mParent; QComboBox *mComboBox; Monitor *mMonitor; EntityTreeModel *mModel; }; void AddressBookComboBox::Private::activated( int index ) { const QModelIndex modelIndex = mComboBox->model()->index( index, 0 ); if ( modelIndex.isValid() ) emit mParent->selectionChanged( modelIndex.data( EntityTreeModel::CollectionRole).value<Collection>() ); } AddressBookComboBox::AddressBookComboBox( Type type, QWidget *parent ) : QWidget( parent ), d( new Private( type, this ) ) { QVBoxLayout *layout = new QVBoxLayout( this ); layout->setMargin( 0 ); layout->setSpacing( 0 ); layout->addWidget( d->mComboBox ); d->mComboBox->setCurrentIndex( 0 ); connect( d->mComboBox, SIGNAL( activated( int ) ), SLOT( activated( int ) ) ); } AddressBookComboBox::~AddressBookComboBox() { delete d->mComboBox; // delete as long as the model still exists, crashs otherwise delete d; } Akonadi::Collection AddressBookComboBox::selectedAddressBook() const { Q_ASSERT_X( d->mComboBox->model() != 0, "AddressBookComboBox::selectedAddressBook", "No model set!" ); const int index = d->mComboBox->currentIndex(); const QModelIndex modelIndex = d->mComboBox->model()->index( index, 0 ); if ( modelIndex.isValid() ) return modelIndex.data( Akonadi::EntityTreeModel::CollectionRole ).value<Collection>(); else return Akonadi::Collection(); } #include "addressbookcombobox.moc" <|endoftext|>
<commit_before>/* * %CopyrightBegin% * * Copyright Ericsson AB 2020-2020. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * %CopyrightEnd% */ #include "beam_asm.hpp" #ifdef HAVE_LINUX_PERF_SUPPORT # ifdef HAVE_ELF_H # include <elf.h> # define HAVE_LINUX_PERF_DUMP_SUPPORT 1 class JitPerfDump { FILE *file = nullptr; Uint64 code_index = 0; enum PerfDumpId { JIT_CODE_LOAD = 0, /* record describing a jitted function */ JIT_CODE_MOVE = 1, /* record describing an already jitted function which is moved */ JIT_CODE_DEBUG_INFO = 2, /* record describing the debug information for a jitted function */ JIT_CODE_CLOSE = 3, /* record marking the end of the jit runtime (optional) */ JIT_CODE_UNWINDING_INFO = 4 /* record describing a function unwinding information */ }; struct FileHeader { Uint32 magic; Uint32 version; Uint32 total_size; Uint32 elf_mach; Uint32 pad1; Uint32 pid; Uint64 timestamp; Uint64 flags; FileHeader() { magic = 0x4A695444; /* "JiTD" as numbers */ version = 1; total_size = sizeof(FileHeader); elf_mach = EM_X86_64; pad1 = 0; pid = getpid(); timestamp = erts_os_monotonic_time(); flags = 0; ERTS_CT_ASSERT(sizeof(FileHeader) == 4 * 10); } }; struct RecordHeader { Uint32 id; Uint32 total_size; Uint64 timestamp; }; struct JitCodeLoadRecord { RecordHeader header; Uint32 pid; Uint32 tid; Uint64 vma; Uint64 code_addr; Uint64 code_size; Uint64 code_index; /* Null terminated M:F/A */ /* Native code */ JitCodeLoadRecord() { header.id = JIT_CODE_LOAD; pid = getpid(); tid = erts_thr_self(); } }; public: bool init() { char name[MAXPATHLEN]; FileHeader header; /* LLVM places this file in ~/.debug/jit/ maybe we should do that to? */ erts_snprintf(name, sizeof(name), "/tmp/jit-%d.dump", getpid()); file = fopen(name, "w+"); if (file) { fwrite(&header, sizeof(header), 1, file); /* inform perf of the location of the dump file */ void *addr = mmap(NULL, sizeof(header), PROT_READ | PROT_EXEC, MAP_PRIVATE, fileno(file), 0); if (addr == MAP_FAILED) { int saved_errno = errno; erts_dsprintf_buf_t *dsbuf = erts_create_logger_dsbuf(); erts_dsprintf(dsbuf, "perf: mmap of %s(%d) failed: %d\r\n", name, fileno(file), saved_errno); erts_send_error_to_logger_nogl(dsbuf); fclose(file); file = nullptr; return false; } } else { int saved_errno = errno; erts_dsprintf_buf_t *dsbuf = erts_create_logger_dsbuf(); erts_dsprintf(dsbuf, "perf: Failed to open %s (%d)", name, saved_errno); erts_send_error_to_logger_nogl(dsbuf); return false; } return true; } void update_perf_info(std::string modulename, std::vector<BeamAssembler::AsmRange> &ranges) { JitCodeLoadRecord record; for (BeamAssembler::AsmRange &r : ranges) { size_t nameLen = r.name.size(); ptrdiff_t codeSize = (char *)r.stop - (char *)r.start; record.header.total_size = sizeof(record) + nameLen + 1 + codeSize; record.vma = (Uint64)r.start; record.code_addr = (Uint64)r.start; record.code_size = (Uint64)codeSize; record.code_index = ++code_index; record.header.timestamp = erts_os_monotonic_time(); fwrite(&record, sizeof(record), 1, file); fwrite(r.name.c_str(), nameLen + 1, 1, file); fwrite(r.start, codeSize, 1, file); } } }; # endif class JitPerfMap { FILE *file = nullptr; public: bool init() { char name[MAXPATHLEN]; snprintf(name, sizeof(name), "/tmp/perf-%i.map", getpid()); file = fopen(name, "w"); if (!file) { int saved_errno = errno; erts_dsprintf_buf_t *dsbuf = erts_create_logger_dsbuf(); erts_dsprintf(dsbuf, "perf: Failed to open %s (%d)", name, saved_errno); erts_send_error_to_logger_nogl(dsbuf); return false; } return true; } void update_perf_info(std::string modulename, std::vector<BeamAssembler::AsmRange> &ranges) { for (BeamAssembler::AsmRange &r : ranges) { char *start = (char *)r.start, *stop = (char *)r.stop; ptrdiff_t size = stop - start; fprintf(file, "%p %tx $%s\n", start, size, r.name.c_str()); } } }; class JitPerfSupport { enum PerfModes { NONE = 0, MAP = (1 << 0), DUMP = (1 << 1) }; int modes; erts_mtx_t mutex; # ifdef HAVE_LINUX_PERF_DUMP_SUPPORT JitPerfDump perf_dump; # endif JitPerfMap perf_map; public: JitPerfSupport() : modes(NONE) { } void init() { modes = JitPerfSupport::NONE; # ifdef HAVE_LINUX_PERF_DUMP_SUPPORT if ((erts_jit_perf_support & BEAMASM_PERF_DUMP) && perf_dump.init()) { modes |= JitPerfSupport::DUMP; } # endif if ((erts_jit_perf_support & BEAMASM_PERF_MAP) && perf_map.init()) { modes |= JitPerfSupport::MAP; } erts_mtx_init(&mutex, "perf", NIL, ERTS_LOCK_FLAGS_PROPERTY_STATIC | ERTS_LOCK_FLAGS_CATEGORY_GENERIC); } void update_perf_info(std::string modulename, std::vector<BeamAssembler::AsmRange> &ranges) { if (modes) { erts_mtx_lock(&mutex); # ifdef HAVE_LINUX_PERF_DUMP_SUPPORT if (modes & DUMP) { perf_dump.update_perf_info(modulename, ranges); } # endif if (modes & MAP) { perf_map.update_perf_info(modulename, ranges); } erts_mtx_unlock(&mutex); } } }; static JitPerfSupport perf; void beamasm_init_perf() { perf.init(); } void beamasm_update_perf_info(std::string modulename, std::vector<BeamAssembler::AsmRange> &ranges) { perf.update_perf_info(modulename, ranges); } #else void beamasm_init_perf() { } void beamasm_update_perf_info(std::string modulename, std::vector<BeamAssembler::AsmRange> &ranges) { } #endif <commit_msg>jit: Flush perf logs after module is added<commit_after>/* * %CopyrightBegin% * * Copyright Ericsson AB 2020-2020. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * %CopyrightEnd% */ #include "beam_asm.hpp" #ifdef HAVE_LINUX_PERF_SUPPORT # ifdef HAVE_ELF_H # include <elf.h> # define HAVE_LINUX_PERF_DUMP_SUPPORT 1 class JitPerfDump { FILE *file = nullptr; Uint64 code_index = 0; enum PerfDumpId { JIT_CODE_LOAD = 0, /* record describing a jitted function */ JIT_CODE_MOVE = 1, /* record describing an already jitted function which is moved */ JIT_CODE_DEBUG_INFO = 2, /* record describing the debug information for a jitted function */ JIT_CODE_CLOSE = 3, /* record marking the end of the jit runtime (optional) */ JIT_CODE_UNWINDING_INFO = 4 /* record describing a function unwinding information */ }; struct FileHeader { Uint32 magic; Uint32 version; Uint32 total_size; Uint32 elf_mach; Uint32 pad1; Uint32 pid; Uint64 timestamp; Uint64 flags; FileHeader() { magic = 0x4A695444; /* "JiTD" as numbers */ version = 1; total_size = sizeof(FileHeader); elf_mach = EM_X86_64; pad1 = 0; pid = getpid(); timestamp = erts_os_monotonic_time(); flags = 0; ERTS_CT_ASSERT(sizeof(FileHeader) == 4 * 10); } }; struct RecordHeader { Uint32 id; Uint32 total_size; Uint64 timestamp; }; struct JitCodeLoadRecord { RecordHeader header; Uint32 pid; Uint32 tid; Uint64 vma; Uint64 code_addr; Uint64 code_size; Uint64 code_index; /* Null terminated M:F/A */ /* Native code */ JitCodeLoadRecord() { header.id = JIT_CODE_LOAD; pid = getpid(); tid = erts_thr_self(); } }; public: bool init() { char name[MAXPATHLEN]; FileHeader header; /* LLVM places this file in ~/.debug/jit/ maybe we should do that to? */ erts_snprintf(name, sizeof(name), "/tmp/jit-%d.dump", getpid()); file = fopen(name, "w+"); if (file) { fwrite(&header, sizeof(header), 1, file); /* inform perf of the location of the dump file */ void *addr = mmap(NULL, sizeof(header), PROT_READ | PROT_EXEC, MAP_PRIVATE, fileno(file), 0); if (addr == MAP_FAILED) { int saved_errno = errno; erts_dsprintf_buf_t *dsbuf = erts_create_logger_dsbuf(); erts_dsprintf(dsbuf, "perf: mmap of %s(%d) failed: %d\r\n", name, fileno(file), saved_errno); erts_send_error_to_logger_nogl(dsbuf); fclose(file); file = nullptr; return false; } } else { int saved_errno = errno; erts_dsprintf_buf_t *dsbuf = erts_create_logger_dsbuf(); erts_dsprintf(dsbuf, "perf: Failed to open %s (%d)", name, saved_errno); erts_send_error_to_logger_nogl(dsbuf); return false; } return true; } void update_perf_info(std::string modulename, std::vector<BeamAssembler::AsmRange> &ranges) { JitCodeLoadRecord record; for (BeamAssembler::AsmRange &r : ranges) { size_t nameLen = r.name.size(); ptrdiff_t codeSize = (char *)r.stop - (char *)r.start; ASSERT(codeSize > 0); record.header.total_size = sizeof(record) + nameLen + 1 + codeSize; record.vma = (Uint64)r.start; record.code_addr = (Uint64)r.start; record.code_size = (Uint64)codeSize; record.code_index = ++code_index; record.header.timestamp = erts_os_monotonic_time(); fwrite(&record, sizeof(record), 1, file); fwrite(r.name.c_str(), nameLen + 1, 1, file); fwrite(r.start, codeSize, 1, file); } } }; # endif class JitPerfMap { FILE *file = nullptr; public: bool init() { char name[MAXPATHLEN]; snprintf(name, sizeof(name), "/tmp/perf-%i.map", getpid()); file = fopen(name, "w"); if (!file) { int saved_errno = errno; erts_dsprintf_buf_t *dsbuf = erts_create_logger_dsbuf(); erts_dsprintf(dsbuf, "perf: Failed to open %s (%d)", name, saved_errno); erts_send_error_to_logger_nogl(dsbuf); return false; } return true; } void update_perf_info(std::string modulename, std::vector<BeamAssembler::AsmRange> &ranges) { for (BeamAssembler::AsmRange &r : ranges) { char *start = (char *)r.start, *stop = (char *)r.stop; ptrdiff_t size = stop - start; fprintf(file, "%p %tx $%s\n", start, size, r.name.c_str()); } fflush(file); } }; class JitPerfSupport { enum PerfModes { NONE = 0, MAP = (1 << 0), DUMP = (1 << 1) }; int modes; erts_mtx_t mutex; # ifdef HAVE_LINUX_PERF_DUMP_SUPPORT JitPerfDump perf_dump; # endif JitPerfMap perf_map; public: JitPerfSupport() : modes(NONE) { } void init() { modes = JitPerfSupport::NONE; # ifdef HAVE_LINUX_PERF_DUMP_SUPPORT if ((erts_jit_perf_support & BEAMASM_PERF_DUMP) && perf_dump.init()) { modes |= JitPerfSupport::DUMP; } # endif if ((erts_jit_perf_support & BEAMASM_PERF_MAP) && perf_map.init()) { modes |= JitPerfSupport::MAP; } erts_mtx_init(&mutex, "perf", NIL, ERTS_LOCK_FLAGS_PROPERTY_STATIC | ERTS_LOCK_FLAGS_CATEGORY_GENERIC); } void update_perf_info(std::string modulename, std::vector<BeamAssembler::AsmRange> &ranges) { if (modes) { erts_mtx_lock(&mutex); # ifdef HAVE_LINUX_PERF_DUMP_SUPPORT if (modes & DUMP) { perf_dump.update_perf_info(modulename, ranges); } # endif if (modes & MAP) { perf_map.update_perf_info(modulename, ranges); } erts_mtx_unlock(&mutex); } } }; static JitPerfSupport perf; void beamasm_init_perf() { perf.init(); } void beamasm_update_perf_info(std::string modulename, std::vector<BeamAssembler::AsmRange> &ranges) { perf.update_perf_info(modulename, ranges); } #else void beamasm_init_perf() { } void beamasm_update_perf_info(std::string modulename, std::vector<BeamAssembler::AsmRange> &ranges) { } #endif <|endoftext|>
<commit_before>#ifndef ETS2_TELEMETRY_COMMON_HPP #define ETS2_TELEMETRY_COMMON_HPP // This file contains "Common definitions" for this ETS2 telemetry plug-in. // This includes: // - Debug logging detail options // - Shared memory map struct layout // - [..] #define ETS2_PLUGIN_REVID 1 #define ETS2_PLUGIN_LOGGING_ON 1 #define ETS2_PLUGIN_LOGGING_SHAREDMEMORY 1 #define ETS2_PLUGIN_FILENAME_PREFIX "C:\ets2telem_" #if ETS2_PLUGIN_LOGGING_ON == 1 #define SDK_ENABLE_LOGGING #endif #define ETS2_PLUGIN_MMF_NAME TEXT("Local\\SimTelemetryETS2") #define ETS2_PLUGIN_MMF_SIZE (16*1024) #define TRUCK_STRING_OFFSET 15*1024 #define TRAILER_STRING_OFFSET TRUCK_STRING_OFFSET+64 typedef struct ets2TelemetryMap_s { unsigned int time; unsigned int paused; struct { unsigned int ets2_telemetry_plugin_revision; unsigned int ets2_version_major; unsigned int ets2_version_minor; } tel_revId; // All variables per revision are packed into 1 struct. // Newer revisions must contain identical struct layouts/lengths, even if variabeles become deprecated. // Replaced/new variabeles should be added in seperate structs struct { bool engine_enabled; bool trailer_attached; // vehicle dynamics float speed; float accelerationX; float accelerationY; float accelerationZ; float coordinateX; float coordinateY; float coordinateZ; float rotationX; float rotationY; float rotationZ; // drivetrain essentials int gear; int gears; int gearRanges; int gearRangeActive; float engineRpm; float engineRpmMax; float fuel; float fuelCapacity; float fuelRate; // ! Not working float fuelAvgConsumption; // user input float userSteer; float userThrottle; float userBrake; float userClutch; float gameSteer; float gameThrottle; float gameBrake; float gameClutch; // truck & trailer float truckWeight; float trailerWeight; int modelType[2]; int trailerType[2]; // ! deprecated } tel_rev1; struct { long time_abs; int gears_reverse; // Trailer ID & display name float trailerMass; char trailerId[64]; char trailerName[64]; // Job information int jobIncome; int time_abs_delivery; char citySrc[64]; char cityDst[64]; char compSrc[64]; char compDst[64]; } tel_rev2; } ets2TelemetryMap_t; #endif<commit_msg>Increased revision number.<commit_after>#ifndef ETS2_TELEMETRY_COMMON_HPP #define ETS2_TELEMETRY_COMMON_HPP // This file contains "Common definitions" for this ETS2 telemetry plug-in. // This includes: // - Debug logging detail options // - Shared memory map struct layout // - [..] #define ETS2_PLUGIN_REVID 2 #define ETS2_PLUGIN_LOGGING_ON 0 #define ETS2_PLUGIN_LOGGING_SHAREDMEMORY 1 #define ETS2_PLUGIN_FILENAME_PREFIX "C:\ets2telem_" #if ETS2_PLUGIN_LOGGING_ON == 1 #define SDK_ENABLE_LOGGING #endif #define ETS2_PLUGIN_MMF_NAME TEXT("Local\\SimTelemetryETS2") #define ETS2_PLUGIN_MMF_SIZE (16*1024) #define TRUCK_STRING_OFFSET 15*1024 #define TRAILER_STRING_OFFSET TRUCK_STRING_OFFSET+64 typedef struct ets2TelemetryMap_s { unsigned int time; unsigned int paused; struct { unsigned int ets2_telemetry_plugin_revision; unsigned int ets2_version_major; unsigned int ets2_version_minor; } tel_revId; // All variables per revision are packed into 1 struct. // Newer revisions must contain identical struct layouts/lengths, even if variabeles become deprecated. // Replaced/new variabeles should be added in seperate structs struct { bool engine_enabled; bool trailer_attached; // vehicle dynamics float speed; float accelerationX; float accelerationY; float accelerationZ; float coordinateX; float coordinateY; float coordinateZ; float rotationX; float rotationY; float rotationZ; // drivetrain essentials int gear; int gears; int gearRanges; int gearRangeActive; float engineRpm; float engineRpmMax; float fuel; float fuelCapacity; float fuelRate; // ! Not working float fuelAvgConsumption; // user input float userSteer; float userThrottle; float userBrake; float userClutch; float gameSteer; float gameThrottle; float gameBrake; float gameClutch; // truck & trailer float truckWeight; float trailerWeight; int modelType[2]; int trailerType[2]; // ! deprecated } tel_rev1; struct { long time_abs; int gears_reverse; // Trailer ID & display name float trailerMass; char trailerId[64]; char trailerName[64]; // Job information int jobIncome; int time_abs_delivery; char citySrc[64]; char cityDst[64]; char compSrc[64]; char compDst[64]; } tel_rev2; } ets2TelemetryMap_t; #endif<|endoftext|>
<commit_before>/* * Copyright (c) 2016 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * @file text-scrolling-example.cpp * @brief Shows text labels with scrolling text and allows a text label and text field control to be scrolled vertically */ // EXTERNAL INCLUDES #include <dali-toolkit/dali-toolkit.h> using namespace Dali; using namespace Dali::Toolkit; namespace { const char* DESKTOP_IMAGE( DEMO_IMAGE_DIR "woodEffect.jpg" ); const Vector2 DESKTOP_SIZE( Vector2( 1440.f, 1600.f ) ); const Vector2 BOX_SIZE( Vector2(330.0f, 80.0f ) ); const Vector2 SCROLLING_BOX_SIZE( Vector2(330.0f, 40.0f ) ); const float MAX_OFFSCREEN_RENDERING_SIZE = 2048.f; const float SCREEN_BORDER = 5.0f; // Border around screen that Popups and handles will not exceed enum Labels { SMALL = 1u, RTL = 1u << 1, LARGE = 1u << 2, RTL_LONG = 1u << 4, NONE = 1u << 6, }; } /** * @brief The main class of the demo. */ class TextScrollingExample : public ConnectionTracker { public: TextScrollingExample( Application& application ) : mApplication( application ), mTargetActorPosition(), mTargetActorSize() { // Connect to the Application's Init signal mApplication.InitSignal().Connect( this, &TextScrollingExample::Create ); } ~TextScrollingExample() { // Nothing to do here. } void CreateBox( const std::string& name, Actor& box, Actor parent, const Vector2& size ) { box.SetName(name); box.SetAnchorPoint( AnchorPoint::CENTER ); box.SetParentOrigin( ParentOrigin::CENTER ); box.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::HEIGHT ); box.SetResizePolicy( ResizePolicy::FIXED, Dimension::WIDTH ); box.SetSize( size.width, 0.f ); parent.Add( box ); Dali::Property::Map border; border.Insert( Visual::Property::TYPE, Visual::BORDER ); border.Insert( BorderVisual::Property::COLOR, Color::WHITE ); border.Insert( BorderVisual::Property::SIZE, 1.f ); box.SetProperty( Control::Property::BACKGROUND, border ); } void CreateLabel( Actor& label, const std::string text, Actor parent, bool scrollOnStart, PushButton button ) { label = TextLabel::New( text ); label.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH ); label.SetResizePolicy( ResizePolicy::DIMENSION_DEPENDENCY, Dimension::HEIGHT ); label.SetPadding( Padding( 1.0f, 1.0f, 1.0f, 1.0f ) ); label.SetAnchorPoint( AnchorPoint::CENTER ); label.SetParentOrigin( ParentOrigin::CENTER ); parent.Add( label ); if ( scrollOnStart ) { label.SetProperty(TextLabel::Property::ENABLE_AUTO_SCROLL, true); } button.SetResizePolicy( ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS ); button.SetSize(BOX_SIZE.height,BOX_SIZE.height); button.SetParentOrigin( ParentOrigin::TOP_RIGHT ); button.SetAnchorPoint( AnchorPoint::TOP_LEFT ); parent.Add(button); } /** * One-time setup in response to Application InitSignal. */ void Create( Application& application ) { Stage stage = Stage::GetCurrent(); mStageSize = stage.GetSize(); stage.KeyEventSignal().Connect(this, &TextScrollingExample::OnKeyEvent); // Create Root actor Actor rootActor = Actor::New(); rootActor.SetName("rootActor"); rootActor.SetResizePolicy( ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS ); rootActor.SetSize( mStageSize ); rootActor.SetAnchorPoint( AnchorPoint::TOP_LEFT ); stage.Add( rootActor ); const Size mTargetActorSize( mStageSize.width, DESKTOP_SIZE.height ); // Create Desktop ImageView desktop = ImageView::New(); Property::Map imageMap; imageMap[ "url" ] = DESKTOP_IMAGE; imageMap[ "synchronousLoading" ] = true; desktop.SetProperty( ImageView::Property::IMAGE, imageMap ); desktop.SetName("desktopActor"); desktop.SetAnchorPoint( AnchorPoint::TOP_LEFT ); desktop.SetResizePolicy( ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS ); desktop.SetSize( mTargetActorSize ); rootActor.Add( desktop ); // Add desktop (content) to offscreen actor // Create Boxes Control boxA = Control::New(); Control boxB = Control::New(); Control boxC = Control::New(); Control boxD = Control::New(); Control boxE = Control::New(); CreateBox( "boxA", boxA, desktop, BOX_SIZE ); boxA.SetPosition( 0.0f, -500.0f, 1.0f ); // Create TextField TextField field = TextField::New(); field.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS ); field.SetPadding( Padding( 1.0f, 1.0f, 1.0f, 1.0f ) ); field.SetAnchorPoint( AnchorPoint::TOP_LEFT ); field.SetProperty( TextField::Property::PLACEHOLDER_TEXT, "Enter Folder Name" ); field.SetProperty( TextField::Property::DECORATION_BOUNDING_BOX, Rect<int>( SCREEN_BORDER, SCREEN_BORDER, mStageSize.width - SCREEN_BORDER*2, mStageSize.height - SCREEN_BORDER*2 ) ); boxA.Add( field ); boxA.SetSize(BOX_SIZE); CreateBox( "boxB", boxB, desktop, SCROLLING_BOX_SIZE ); boxB.SetPosition( 0.0f, -400.0f, 1.0f ); Toolkit::PushButton scrollLargeButton = Toolkit::PushButton::New(); scrollLargeButton.ClickedSignal().Connect( this, &TextScrollingExample::OnButtonClickedLarge ); CreateLabel( mLargeLabel, "A Quick Brown Fox Jumps Over The Lazy Dog", boxB, false ,scrollLargeButton ); CreateBox( "boxC", boxC, desktop, SCROLLING_BOX_SIZE ); boxC.SetPosition( 0.0f, -300.0f, 1.0f ); Toolkit::PushButton scrollSmallButton = Toolkit::PushButton::New(); scrollSmallButton.ClickedSignal().Connect( this, &TextScrollingExample::OnButtonClickedSmall ); CreateLabel( mSmallLabel, "A Quick Brown Fox", boxC , true, scrollSmallButton ); mSmallLabel.SetProperty( TextLabel::Property::TEXT_COLOR, Color::WHITE ); mSmallLabel.SetProperty( TextLabel::Property::SHADOW_OFFSET, Vector2( 1.0f, 1.0f ) ); mSmallLabel.SetProperty( TextLabel::Property::SHADOW_COLOR, Color::BLACK ); CreateBox( "boxD", boxD, desktop, SCROLLING_BOX_SIZE ); boxD.SetPosition( 0.0f, -200.0f, 1.0f ); Toolkit::PushButton scrollRtlButton = Toolkit::PushButton::New(); scrollRtlButton.ClickedSignal().Connect( this, &TextScrollingExample::OnButtonClickedRtl ); CreateLabel( mRtlLabel, "مرحبا بالعالم", boxD , true, scrollRtlButton ); CreateBox( "boxE", boxE, desktop, SCROLLING_BOX_SIZE ); boxE.SetPosition( 0.0f, -100.0f, 1.0f ); Toolkit::PushButton scrollRtlLongButton = Toolkit::PushButton::New(); scrollRtlLongButton.ClickedSignal().Connect( this, &TextScrollingExample::OnButtonClickedRtlLong ); CreateLabel( mRtlLongLabel, " مرحبا بالعالم مرحبا بالعالم مرحبا بالعالم", boxE , false, scrollRtlLongButton ); mPanGestureDetector = PanGestureDetector::New(); mPanGestureDetector.DetectedSignal().Connect(this, &TextScrollingExample::OnPanGesture ); mPanGestureDetector.Attach( desktop ); } void EnableScrolling( Labels labels ) { Actor label; switch( labels ) { case LARGE: { label = mLargeLabel; break; } case RTL: { label = mRtlLabel; break; } case SMALL: { label = mSmallLabel; break; } case RTL_LONG: { label = mRtlLongLabel; break; } case NONE: { return; } } if ( labels != NONE ) { Property::Value value = label.GetProperty( TextLabel::Property::ENABLE_AUTO_SCROLL); if (value.Get< bool >()) { label.SetProperty( TextLabel::Property::ENABLE_AUTO_SCROLL, false ); } else { label.SetProperty( TextLabel::Property::ENABLE_AUTO_SCROLL, true ); } } } bool OnButtonClickedSmall( Toolkit::Button button ) { EnableScrolling( SMALL ); return true; } bool OnButtonClickedLarge( Toolkit::Button button ) { EnableScrolling( LARGE ); return true; } bool OnButtonClickedRtl( Toolkit::Button button ) { EnableScrolling( RTL ); return true; } bool OnButtonClickedRtlLong( Toolkit::Button button ) { EnableScrolling( RTL_LONG ); return true; } /** * Main key event handler */ void OnKeyEvent(const KeyEvent& event) { if(event.state == KeyEvent::Down) { if( IsKey( event, DALI_KEY_ESCAPE) || IsKey( event, DALI_KEY_BACK ) ) { mApplication.Quit(); } } } void OnPanGesture( Actor actor, const PanGesture& gesture ) { if( gesture.state == Gesture::Continuing ) { Vector2 position = Vector2( gesture.displacement ); mTargetActorPosition.y = mTargetActorPosition.y + position.y; mTargetActorPosition.y = std::min( mTargetActorPosition.y, -mTargetActorSize.height ); mTargetActorPosition.y = std::max( mTargetActorPosition.y, ( mTargetActorSize.height - mStageSize.height*0.25f ) ); actor.SetPosition( 0.0f, mTargetActorPosition.y ); } } private: Application& mApplication; PanGestureDetector mPanGestureDetector; Vector2 mTargetActorPosition; Vector2 mTargetActorSize; Vector2 mStageSize; TextLabel mLargeLabel; TextLabel mSmallLabel; TextLabel mRtlLabel; TextLabel mRtlLongLabel; }; void RunTest( Application& application ) { TextScrollingExample test( application ); application.MainLoop(); } /** Entry point for Linux & Tizen applications */ int DALI_EXPORT_API main( int argc, char **argv ) { Application application = Application::New( &argc, &argv, DEMO_THEME_PATH ); RunTest( application ); return 0; } <commit_msg>TextScrolling example allows text color changes<commit_after>/* * Copyright (c) 2017 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /** * @file text-scrolling-example.cpp * @brief Shows text labels with scrolling text and allows a text label and text field control to be scrolled vertically */ // EXTERNAL INCLUDES #include <dali-toolkit/dali-toolkit.h> #include <dali-toolkit/devel-api/controls/buttons/button-devel.h> using namespace Dali; using namespace Dali::Toolkit; namespace { const Vector2 DESKTOP_SIZE( Vector2( 1440.f, 1600.f ) ); const Vector2 BOX_SIZE( Vector2(330.0f, 80.0f ) ); const Vector2 SCROLLING_BOX_SIZE( Vector2(330.0f, 40.0f ) ); const float MAX_OFFSCREEN_RENDERING_SIZE = 2048.f; const float SCREEN_BORDER = 5.0f; // Border around screen that Popups and handles will not exceed enum Labels { SMALL = 1u, RTL = 1u << 1, LARGE = 1u << 2, RTL_LONG = 1u << 4, NONE = 1u << 6, }; } /** * @brief The main class of the demo. */ class TextScrollingExample : public ConnectionTracker { public: TextScrollingExample( Application& application ) : mApplication( application ), mTargetActorPosition(), mTargetActorSize(), mToggleColor( false ) { // Connect to the Application's Init signal mApplication.InitSignal().Connect( this, &TextScrollingExample::Create ); } ~TextScrollingExample() { // Nothing to do here. } void CreateBox( const std::string& name, Actor& box, Actor parent, const Vector2& size ) { box.SetName(name); box.SetAnchorPoint( AnchorPoint::CENTER ); box.SetParentOrigin( ParentOrigin::CENTER ); box.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::HEIGHT ); box.SetResizePolicy( ResizePolicy::FIXED, Dimension::WIDTH ); box.SetSize( size.width, 0.f ); parent.Add( box ); Dali::Property::Map border; border.Insert( Visual::Property::TYPE, Visual::BORDER ); border.Insert( BorderVisual::Property::COLOR, Color::BLUE ); border.Insert( BorderVisual::Property::SIZE, 1.f ); box.SetProperty( Control::Property::BACKGROUND, border ); } void CreateLabel( Actor& label, const std::string text, Actor parent, bool scrollOnStart, PushButton button ) { label = TextLabel::New( text ); label.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::WIDTH ); label.SetResizePolicy( ResizePolicy::DIMENSION_DEPENDENCY, Dimension::HEIGHT ); label.SetPadding( Padding( 1.0f, 1.0f, 1.0f, 1.0f ) ); label.SetAnchorPoint( AnchorPoint::CENTER ); label.SetParentOrigin( ParentOrigin::CENTER ); parent.Add( label ); if ( scrollOnStart ) { label.SetProperty(TextLabel::Property::ENABLE_AUTO_SCROLL, true); } button.SetResizePolicy( ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS ); button.SetSize(BOX_SIZE.height,BOX_SIZE.height); button.SetParentOrigin( ParentOrigin::TOP_RIGHT ); button.SetAnchorPoint( AnchorPoint::TOP_LEFT ); parent.Add(button); } /** * One-time setup in response to Application InitSignal. */ void Create( Application& application ) { Stage stage = Stage::GetCurrent(); mStageSize = stage.GetSize(); stage.KeyEventSignal().Connect(this, &TextScrollingExample::OnKeyEvent); // Create Root actor Actor rootActor = Actor::New(); rootActor.SetName("rootActor"); rootActor.SetResizePolicy( ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS ); rootActor.SetSize( mStageSize ); rootActor.SetAnchorPoint( AnchorPoint::TOP_LEFT ); stage.Add( rootActor ); mAnimation = Animation::New( 1.0f ); const Size mTargetActorSize( mStageSize.width, DESKTOP_SIZE.height ); // Create Desktop Control desktop = Control::New(); desktop.SetBackgroundColor( Color::WHITE ); desktop.SetName("desktopActor"); desktop.SetAnchorPoint( AnchorPoint::TOP_LEFT ); desktop.SetResizePolicy( ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS ); desktop.SetSize( mTargetActorSize ); rootActor.Add( desktop ); // Add desktop (content) to offscreen actor // Create Boxes Control boxA = Control::New(); Control boxB = Control::New(); Control boxC = Control::New(); Control boxD = Control::New(); Control boxE = Control::New(); CreateBox( "boxA", boxA, desktop, BOX_SIZE ); boxA.SetPosition( 0.0f, -500.0f, 1.0f ); // Create TextField TextField field = TextField::New(); field.SetResizePolicy( ResizePolicy::FILL_TO_PARENT, Dimension::ALL_DIMENSIONS ); field.SetPadding( Padding( 1.0f, 1.0f, 1.0f, 1.0f ) ); field.SetAnchorPoint( AnchorPoint::TOP_LEFT ); field.SetProperty( TextField::Property::PLACEHOLDER_TEXT, "Enter Folder Name" ); field.SetProperty( TextField::Property::DECORATION_BOUNDING_BOX, Rect<int>( SCREEN_BORDER, SCREEN_BORDER, mStageSize.width - SCREEN_BORDER*2, mStageSize.height - SCREEN_BORDER*2 ) ); boxA.Add( field ); boxA.SetSize(BOX_SIZE); CreateBox( "boxB", boxB, desktop, SCROLLING_BOX_SIZE ); boxB.SetPosition( 0.0f, -400.0f, 1.0f ); Toolkit::PushButton scrollLargeButton = Toolkit::PushButton::New(); scrollLargeButton.ClickedSignal().Connect( this, &TextScrollingExample::OnButtonClickedLarge ); CreateLabel( mLargeLabel, "A Quick Brown Fox Jumps Over The Lazy Dog", boxB, false ,scrollLargeButton ); CreateBox( "boxC", boxC, desktop, SCROLLING_BOX_SIZE ); boxC.SetPosition( 0.0f, -300.0f, 1.0f ); Toolkit::PushButton scrollSmallButton = Toolkit::PushButton::New(); scrollSmallButton.ClickedSignal().Connect( this, &TextScrollingExample::OnButtonClickedSmall ); CreateLabel( mSmallLabel, "A Quick Brown Fox", boxC , true, scrollSmallButton ); mSmallLabel.SetProperty( TextLabel::Property::TEXT_COLOR, Color::BLACK ); mSmallLabel.SetProperty( TextLabel::Property::SHADOW_OFFSET, Vector2( 1.0f, 1.0f ) ); mSmallLabel.SetProperty( TextLabel::Property::SHADOW_COLOR, Color::CYAN ); CreateBox( "boxD", boxD, desktop, SCROLLING_BOX_SIZE ); boxD.SetPosition( 0.0f, -200.0f, 1.0f ); Toolkit::PushButton scrollRtlButton = Toolkit::PushButton::New(); scrollRtlButton.ClickedSignal().Connect( this, &TextScrollingExample::OnButtonClickedRtl ); CreateLabel( mRtlLabel, "مرحبا بالعالم", boxD , true, scrollRtlButton ); CreateBox( "boxE", boxE, desktop, SCROLLING_BOX_SIZE ); boxE.SetPosition( 0.0f, -100.0f, 1.0f ); Toolkit::PushButton scrollRtlLongButton = Toolkit::PushButton::New(); scrollRtlLongButton.ClickedSignal().Connect( this, &TextScrollingExample::OnButtonClickedRtlLong ); CreateLabel( mRtlLongLabel, " مرحبا بالعالم مرحبا بالعالم مرحبا بالعالم مرحبا بالعالم مرحبا بالعالم مرحبا بالعالم مرحبا بالعالم مرحبا بالعالم مرحبا بالعالم", boxE , false, scrollRtlLongButton ); mRtlLongLabel.SetProperty(TextLabel::Property::AUTO_SCROLL_SPEED, 500); mRtlLongLabel.SetProperty(TextLabel::Property::AUTO_SCROLL_GAP, 500); mRtlLongLabel.SetProperty(TextLabel::Property::AUTO_SCROLL_LOOP_COUNT, 3); mPanGestureDetector = PanGestureDetector::New(); mPanGestureDetector.DetectedSignal().Connect(this, &TextScrollingExample::OnPanGesture ); mPanGestureDetector.Attach( desktop ); Toolkit::PushButton colorButton = Toolkit::PushButton::New(); colorButton.SetProperty( Button::Property::TOGGLABLE, true ); colorButton.SetProperty( DevelButton::Property::UNSELECTED_BACKGROUND_VISUAL, Property::Map().Add ( Visual::Property::TYPE, Visual::COLOR ).Add( ColorVisual::Property::MIX_COLOR, Color::RED ) ); colorButton.SetProperty( DevelButton::Property::SELECTED_BACKGROUND_VISUAL, Property::Map().Add ( Visual::Property::TYPE, Visual::COLOR ).Add( ColorVisual::Property::MIX_COLOR, Color::BLACK ) ); colorButton.SetAnchorPoint( AnchorPoint::BOTTOM_CENTER ); colorButton.SetParentOrigin( ParentOrigin::BOTTOM_CENTER ); colorButton.SetResizePolicy( ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS ); colorButton.SetSize(BOX_SIZE.height,BOX_SIZE.height); colorButton.ClickedSignal().Connect( this, &TextScrollingExample::OnColorButtonClicked ); rootActor.Add( colorButton ); } void EnableScrolling( Labels labels ) { Actor label; switch( labels ) { case LARGE: { label = mLargeLabel; break; } case RTL: { label = mRtlLabel; break; } case SMALL: { label = mSmallLabel; break; } case RTL_LONG: { label = mRtlLongLabel; break; } case NONE: { return; } } if ( labels != NONE ) { Property::Value value = label.GetProperty( TextLabel::Property::ENABLE_AUTO_SCROLL); if (value.Get< bool >()) { label.SetProperty( TextLabel::Property::ENABLE_AUTO_SCROLL, false ); } else { label.SetProperty( TextLabel::Property::ENABLE_AUTO_SCROLL, true ); } } } bool OnButtonClickedSmall( Toolkit::Button button ) { EnableScrolling( SMALL ); return true; } bool OnButtonClickedLarge( Toolkit::Button button ) { EnableScrolling( LARGE ); return true; } bool OnButtonClickedRtl( Toolkit::Button button ) { EnableScrolling( RTL ); return true; } bool OnButtonClickedRtlLong( Toolkit::Button button ) { EnableScrolling( RTL_LONG ); return true; } bool OnColorButtonClicked( Toolkit::Button button ) { Vector4 color = Color::RED; if ( mToggleColor ) { color = Color::BLACK; mToggleColor = false; } else { mToggleColor = true; } mSmallLabel.SetProperty( TextLabel::Property::SHADOW_COLOR, Color::BLACK ); mSmallLabel.SetProperty( TextLabel::Property::TEXT_COLOR, color ); mLargeLabel.SetProperty( TextLabel::Property::TEXT_COLOR, color ); mRtlLongLabel.SetProperty( TextLabel::Property::TEXT_COLOR, color ); return true; } /** * Main key event handler */ void OnKeyEvent(const KeyEvent& event) { if(event.state == KeyEvent::Down) { if( IsKey( event, DALI_KEY_ESCAPE) || IsKey( event, DALI_KEY_BACK ) ) { mApplication.Quit(); } else { if ( event.keyPressedName == "2" ) { mAnimation.AnimateTo( Property( mSmallLabel, Actor::Property::SCALE ), Vector3(1.2f, 1.2f, 0.0f), AlphaFunction::BOUNCE, TimePeriod( 1.0f, 1.0f ) ); mAnimation.AnimateTo( Property( mLargeLabel, Actor::Property::SCALE ), Vector3(1.2f, 1.2f, 0.0f), AlphaFunction::BOUNCE, TimePeriod( 1.0f, 1.0f ) ); mAnimation.AnimateTo( Property( mRtlLabel, Actor::Property::SCALE ), Vector3(1.2f, 1.2f, 0.0f), AlphaFunction::BOUNCE, TimePeriod( 1.0f, 1.0f ) ); mAnimation.AnimateTo( Property( mRtlLongLabel, Actor::Property::SCALE ), Vector3(1.2f, 1.2f, 0.0f), AlphaFunction::BOUNCE, TimePeriod( 1.0f, 1.0f ) ); mAnimation.Play(); } } } } void OnPanGesture( Actor actor, const PanGesture& gesture ) { if( gesture.state == Gesture::Continuing ) { Vector2 position = Vector2( gesture.displacement ); mTargetActorPosition.y = mTargetActorPosition.y + position.y; mTargetActorPosition.y = std::min( mTargetActorPosition.y, -mTargetActorSize.height ); mTargetActorPosition.y = std::max( mTargetActorPosition.y, ( mTargetActorSize.height - mStageSize.height*0.25f ) ); actor.SetPosition( 0.0f, mTargetActorPosition.y ); } } private: Application& mApplication; PanGestureDetector mPanGestureDetector; Vector2 mTargetActorPosition; Vector2 mTargetActorSize; Vector2 mStageSize; TextLabel mLargeLabel; TextLabel mSmallLabel; TextLabel mRtlLabel; TextLabel mRtlLongLabel; Animation mAnimation; bool mToggleColor; }; void RunTest( Application& application ) { TextScrollingExample test( application ); application.MainLoop(); } /** Entry point for Linux & Tizen applications */ int DALI_EXPORT_API main( int argc, char **argv ) { Application application = Application::New( &argc, &argv, DEMO_THEME_PATH ); RunTest( application ); return 0; } <|endoftext|>
<commit_before>// GLAD will not include windows.h for APIENTRY if it was previously defined #ifdef _WIN32 #define APIENTRY __stdcall #endif #include <glad/glad.h> #include <GLFW/glfw3.h> // confirm that neither GLAD nor GLFW didn't include windows.h #ifdef _WINDOWS_ #error windows.h was included! #endif #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <cstdlib> #include <string> #include <cassert> #include <fstream> #include <sstream> #include <iostream> #include <vector> const int WIDTH = 1280; const int HEIGHT = 720; float greenOffset = 0.6f; float blueOffset = 0.92f; bool keys[512]; const float SIZE = 50.f; glm::vec2 topLeftPosition = glm::vec2(WIDTH / 2 - SIZE, HEIGHT / 2 - SIZE); std::string readTextFile(const std::string& path); void processInput(); int main(int argc, char* argv[]) { if (!glfwInit()) { std::cout << "Failed to initialize GLFW" << std::endl; return EXIT_FAILURE; } // glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "Fuzzy", nullptr, nullptr); if (!window) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return EXIT_FAILURE; } GLFWmonitor* monitor = glfwGetPrimaryMonitor(); const GLFWvidmode* vidmode = glfwGetVideoMode(monitor); glfwSetWindowPos(window, (vidmode->width - WIDTH) / 2, (vidmode->height - HEIGHT) / 2); glfwSetKeyCallback(window, [](GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, GLFW_TRUE); } if (action == GLFW_PRESS) { keys[key] = true; } else if (action == GLFW_RELEASE) { keys[key] = false; } }); glfwSetFramebufferSizeCallback(window, [](GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); }); glfwMakeContextCurrent(window); glfwSwapInterval(1); if (!gladLoadGLLoader((GLADloadproc) glfwGetProcAddress)) { std::cout << "Failed to initialize OpenGL context" << std::endl; return EXIT_FAILURE; } std::cout << glGetString(GL_VERSION) << std::endl; glViewport(0, 0, WIDTH, HEIGHT); float vertices[] = { 0.f, 0.f, 0.f, 1.0f, 1.0f, 0.f, 1.0f, 1.0f }; GLuint VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // vertex shader GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); std::string vertexShaderSource = readTextFile("shaders/basic.vert"); const GLchar* vertexShaderSourcePtr = vertexShaderSource.c_str(); glShaderSource(vertexShader, 1, &vertexShaderSourcePtr, nullptr); glCompileShader(vertexShader); GLint isVertexShaderCompiled; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &isVertexShaderCompiled); if (!isVertexShaderCompiled) { GLint LOG_LENGTH; glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &LOG_LENGTH); std::vector<GLchar> errorLog(LOG_LENGTH); glGetShaderInfoLog(vertexShader, LOG_LENGTH, nullptr, &errorLog[0]); std::cerr << "Vertex shader compilation failed:" << std::endl << &errorLog[0] << std::endl; } assert(isVertexShaderCompiled); // fragment shader GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); std::string fragmentShaderSource = readTextFile("shaders/basic.frag"); const GLchar* fragmentShaderSourcePtr = fragmentShaderSource.c_str(); glShaderSource(fragmentShader, 1, &fragmentShaderSourcePtr, nullptr); glCompileShader(fragmentShader); GLint isFragmentShaderCompiled; glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &isFragmentShaderCompiled); if (!isFragmentShaderCompiled) { GLint LOG_LENGTH; glGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &LOG_LENGTH); std::vector<GLchar> errorLog(LOG_LENGTH); glGetShaderInfoLog(fragmentShader, LOG_LENGTH, nullptr, &errorLog[0]); std::cerr << "Fragment shader compilation failed:" << std::endl << &errorLog[0] << std::endl; } assert(isFragmentShaderCompiled); GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glDeleteShader(vertexShader); glDeleteShader(fragmentShader); GLint isShaderProgramLinked; glGetProgramiv(shaderProgram, GL_LINK_STATUS, &isShaderProgramLinked); if (!isShaderProgramLinked) { GLint LOG_LENGTH; glGetProgramiv(shaderProgram, GL_INFO_LOG_LENGTH, &LOG_LENGTH); std::vector<GLchar> errorLog(LOG_LENGTH); glGetProgramInfoLog(shaderProgram, LOG_LENGTH, nullptr, &errorLog[0]); std::cerr << "Shader program linkage failed:" << std::endl << &errorLog[0] << std::endl; } assert(isShaderProgramLinked); glUseProgram(shaderProgram); glm::mat4 projection = glm::ortho(0.0f, (float) WIDTH, (float) HEIGHT, 0.0f); GLint projectionUniformLocation = glGetUniformLocation(shaderProgram, "projection"); assert(projectionUniformLocation != -1); glUniformMatrix4fv(projectionUniformLocation, 1, GL_FALSE, glm::value_ptr(projection)); GLint modelUniformLocation = glGetUniformLocation(shaderProgram, "model"); assert(modelUniformLocation != -1); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*) 0); glEnableVertexAttribArray(0); double lastTime = glfwGetTime(); double currentTime; double delta; while (!glfwWindowShouldClose(window)) { currentTime = glfwGetTime(); glfwPollEvents(); processInput(); glm::mat4 model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(topLeftPosition, 0.0f)); model = glm::scale(model, glm::vec3(SIZE, SIZE, 1.0f)); glUniformMatrix4fv(modelUniformLocation, 1, GL_FALSE, glm::value_ptr(model)); glClearColor(0.5f, greenOffset, blueOffset, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glfwSwapBuffers(window); delta = currentTime - lastTime; lastTime = currentTime; // std::cout << delta * 1000.f << " ms" << std::endl; } glfwTerminate(); return EXIT_SUCCESS; } void processInput() { float step = 8.f; if (keys[GLFW_KEY_UP] == GLFW_PRESS) { if (topLeftPosition.y > 0.f) { topLeftPosition.y -= step; } } if (keys[GLFW_KEY_DOWN] == GLFW_PRESS) { if (topLeftPosition.y < HEIGHT - SIZE) { topLeftPosition.y += step; } } if (keys[GLFW_KEY_LEFT] == GLFW_PRESS) { if (topLeftPosition.x > 0.f) { topLeftPosition.x -= step; } } if (keys[GLFW_KEY_RIGHT] == GLFW_PRESS) { if (topLeftPosition.x < WIDTH - SIZE) { topLeftPosition.x += step; } } } std::string readTextFile(const std::string& path) { std::ifstream in(path); assert(in.good()); std::ostringstream ss; ss << in.rdbuf(); return ss.str(); } <commit_msg>random background<commit_after>// GLAD will not include windows.h for APIENTRY if it was previously defined #ifdef _WIN32 #define APIENTRY __stdcall #endif #include <glad/glad.h> #include <GLFW/glfw3.h> // confirm that neither GLAD nor GLFW didn't include windows.h #ifdef _WINDOWS_ #error windows.h was included! #endif #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <cstdlib> #include <string> #include <cassert> #include <fstream> #include <sstream> #include <iostream> #include <vector> const int WIDTH = 1280; const int HEIGHT = 720; float redOffset = 0.5f; float greenOffset = 0.6f; float blueOffset = 0.92f; bool keys[512]; bool processedKeys[512]; const float SIZE = 50.f; glm::vec2 topLeftPosition = glm::vec2(WIDTH / 2 - SIZE, HEIGHT / 2 - SIZE); std::string readTextFile(const std::string& path); void processInput(); int main(int argc, char* argv[]) { if (!glfwInit()) { std::cout << "Failed to initialize GLFW" << std::endl; return EXIT_FAILURE; } // glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "Fuzzy", nullptr, nullptr); if (!window) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return EXIT_FAILURE; } GLFWmonitor* monitor = glfwGetPrimaryMonitor(); const GLFWvidmode* vidmode = glfwGetVideoMode(monitor); glfwSetWindowPos(window, (vidmode->width - WIDTH) / 2, (vidmode->height - HEIGHT) / 2); glfwSetKeyCallback(window, [](GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, GLFW_TRUE); } if (action == GLFW_PRESS) { keys[key] = true; } else if (action == GLFW_RELEASE) { keys[key] = false; processedKeys[key] = false; } }); glfwSetFramebufferSizeCallback(window, [](GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); }); glfwMakeContextCurrent(window); glfwSwapInterval(1); if (!gladLoadGLLoader((GLADloadproc) glfwGetProcAddress)) { std::cout << "Failed to initialize OpenGL context" << std::endl; return EXIT_FAILURE; } std::cout << glGetString(GL_VERSION) << std::endl; glViewport(0, 0, WIDTH, HEIGHT); float vertices[] = { 0.f, 0.f, 0.f, 1.0f, 1.0f, 0.f, 1.0f, 1.0f }; GLuint VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // vertex shader GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); std::string vertexShaderSource = readTextFile("shaders/basic.vert"); const GLchar* vertexShaderSourcePtr = vertexShaderSource.c_str(); glShaderSource(vertexShader, 1, &vertexShaderSourcePtr, nullptr); glCompileShader(vertexShader); GLint isVertexShaderCompiled; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &isVertexShaderCompiled); if (!isVertexShaderCompiled) { GLint LOG_LENGTH; glGetShaderiv(vertexShader, GL_INFO_LOG_LENGTH, &LOG_LENGTH); std::vector<GLchar> errorLog(LOG_LENGTH); glGetShaderInfoLog(vertexShader, LOG_LENGTH, nullptr, &errorLog[0]); std::cerr << "Vertex shader compilation failed:" << std::endl << &errorLog[0] << std::endl; } assert(isVertexShaderCompiled); // fragment shader GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); std::string fragmentShaderSource = readTextFile("shaders/basic.frag"); const GLchar* fragmentShaderSourcePtr = fragmentShaderSource.c_str(); glShaderSource(fragmentShader, 1, &fragmentShaderSourcePtr, nullptr); glCompileShader(fragmentShader); GLint isFragmentShaderCompiled; glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &isFragmentShaderCompiled); if (!isFragmentShaderCompiled) { GLint LOG_LENGTH; glGetShaderiv(fragmentShader, GL_INFO_LOG_LENGTH, &LOG_LENGTH); std::vector<GLchar> errorLog(LOG_LENGTH); glGetShaderInfoLog(fragmentShader, LOG_LENGTH, nullptr, &errorLog[0]); std::cerr << "Fragment shader compilation failed:" << std::endl << &errorLog[0] << std::endl; } assert(isFragmentShaderCompiled); GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glDeleteShader(vertexShader); glDeleteShader(fragmentShader); GLint isShaderProgramLinked; glGetProgramiv(shaderProgram, GL_LINK_STATUS, &isShaderProgramLinked); if (!isShaderProgramLinked) { GLint LOG_LENGTH; glGetProgramiv(shaderProgram, GL_INFO_LOG_LENGTH, &LOG_LENGTH); std::vector<GLchar> errorLog(LOG_LENGTH); glGetProgramInfoLog(shaderProgram, LOG_LENGTH, nullptr, &errorLog[0]); std::cerr << "Shader program linkage failed:" << std::endl << &errorLog[0] << std::endl; } assert(isShaderProgramLinked); glUseProgram(shaderProgram); glm::mat4 projection = glm::ortho(0.0f, (float) WIDTH, (float) HEIGHT, 0.0f); GLint projectionUniformLocation = glGetUniformLocation(shaderProgram, "projection"); assert(projectionUniformLocation != -1); glUniformMatrix4fv(projectionUniformLocation, 1, GL_FALSE, glm::value_ptr(projection)); GLint modelUniformLocation = glGetUniformLocation(shaderProgram, "model"); assert(modelUniformLocation != -1); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*) 0); glEnableVertexAttribArray(0); double lastTime = glfwGetTime(); double currentTime; double delta; while (!glfwWindowShouldClose(window)) { currentTime = glfwGetTime(); glfwPollEvents(); processInput(); glm::mat4 model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(topLeftPosition, 0.0f)); model = glm::scale(model, glm::vec3(SIZE, SIZE, 1.0f)); glUniformMatrix4fv(modelUniformLocation, 1, GL_FALSE, glm::value_ptr(model)); glClearColor(redOffset, greenOffset, blueOffset, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glfwSwapBuffers(window); delta = currentTime - lastTime; lastTime = currentTime; // std::cout << delta * 1000.f << " ms" << std::endl; } glfwTerminate(); return EXIT_SUCCESS; } void processInput() { float step = 8.f; if (keys[GLFW_KEY_UP] == GLFW_PRESS) { if (topLeftPosition.y > 0.f) { topLeftPosition.y -= step; } } if (keys[GLFW_KEY_DOWN] == GLFW_PRESS) { if (topLeftPosition.y < HEIGHT - SIZE) { topLeftPosition.y += step; } } if (keys[GLFW_KEY_LEFT] == GLFW_PRESS) { if (topLeftPosition.x > 0.f) { topLeftPosition.x -= step; } } if (keys[GLFW_KEY_RIGHT] == GLFW_PRESS) { if (topLeftPosition.x < WIDTH - SIZE) { topLeftPosition.x += step; } } if (keys[GLFW_KEY_SPACE] == GLFW_PRESS && !processedKeys[GLFW_KEY_SPACE]) { processedKeys[GLFW_KEY_SPACE] = true; redOffset = (float) (rand()) / (float) RAND_MAX; greenOffset = (float) (rand()) / (float) RAND_MAX; blueOffset = (float) (rand()) / (float) RAND_MAX; } } std::string readTextFile(const std::string& path) { std::ifstream in(path); assert(in.good()); std::ostringstream ss; ss << in.rdbuf(); return ss.str(); } <|endoftext|>
<commit_before>#pragma once #include "physics/geopotential.hpp" #include <cmath> #include "numerics/legendre.hpp" #include "numerics/polynomial_evaluators.hpp" #include "quantities/elementary_functions.hpp" #include "quantities/quantities.hpp" #include "quantities/si.hpp" namespace principia { namespace physics { namespace internal_geopotential { using numerics::HornerEvaluator; using numerics::LegendrePolynomial; using geometry::InnerProduct; using quantities::Cos; using quantities::Inverse; using quantities::Length; using quantities::Pow; using quantities::Sqrt; using quantities::Square; using quantities::Sin; using quantities::SIUnit; template<typename Frame> Geopotential<Frame>::Geopotential(not_null<OblateBody<Frame> const*> body) : body_(body) {} template<typename Frame> Vector<Quotient<Acceleration, GravitationalParameter>, Frame> Geopotential<Frame>::SphericalHarmonicsAcceleration( Instant const& t, Displacement<Frame> const& r, Square<Length> const& r², Exponentiation<Length, -3> const& one_over_r³) const { Exponentiation<Length, -2> const one_over_r² = 1 / r²; UnitVector const& axis = body_->polar_axis(); Vector<Quotient<Acceleration, GravitationalParameter>, Frame> acceleration = Degree2ZonalAcceleration(axis, r, one_over_r², one_over_r³); if (body_->has_c22() || body_->has_s22()) { auto const from_surface_frame = body_->template FromSurfaceFrame<SurfaceFrame>(t); UnitVector const reference = from_surface_frame(x_); UnitVector const bireference = from_surface_frame(y_); acceleration += Degree2SectoralAcceleration( reference, bireference, r, one_over_r², one_over_r³); } if (body_->has_j3()) { acceleration += Degree3ZonalAcceleration(axis, r, r², one_over_r², one_over_r³); } return acceleration; } template<typename Frame> template<int degree, int order> struct Geopotential<Frame>::DegreeNOrderM { static Vector<Exponentiation<Length, -2>, Frame> Acceleration(UnitVector const& x, UnitVector const& y, UnitVector const& z, Displacement<Frame> const& r, Square<Length> const rx²_plus_ry², Length const& rx, Length const& ry, Length const& rz, Length const& r_norm, Exponentiation<Length, -3> const& one_over_r³, Inverse<Length> const& radial_factor, Vector<Exponentiation<Length, -2>, Frame> const& radial_factor_derivative, double const sin_β, double const cos_β, double const one_over_cos²_β, Angle const& λ) { constexpr int n = degree; constexpr int m = order; double const latitudinal_factor = AssociatedLegendrePolynomial<n, m>(sin_β); Vector<Inverse<Length>, Frame> const latitudinal_factor_derivative = one_over_cos²_β * (cos_β * AssociatedLegendrePolynomial<n, m + 1>(sin_β) + m * sin_β * latitudinal_factor) * (r * rz * one_over_r³- z / r_norm); //TODO(phl): Fix. double const Cnm = 1.0; double const Snm = 1.0; Angle const mλ = m * λ; double const sin_mλ = Sin(mλ); double const cos_mλ = Cos(mλ); double const longitudinal_factor = Cnm * cos_mλ + Snm * sin_mλ ; Vector<Inverse<Length>, Frame> const longitudinal_factor_derivative = m * (Snm * cos_mλ - Cnm * sin_mλ) * (rx * y - ry * x) / rx²_plus_ry²; return radial_factor_derivative * latitudinal_factor * longitudinal_factor + radial_factor * latitudinal_factor_derivative * longitudinal_factor + radial_factor * latitudinal_factor * longitudinal_factor_derivative; } }; template<typename Frame> template<int degree, int... orders> struct Geopotential<Frame>:: DegreeNAllOrders<degree, std::integer_sequence<int, orders...>> { static Vector<Exponentiation<Length, -2>, Frame> Acceleration(UnitVector const& x, UnitVector const& y, UnitVector const& z, Length const& reference_radius, Displacement<Frame> const& r, Square<Length> const& r², Square<Length> const rx²_plus_ry², Length const& rx, Length const& ry, Length const& rz, Length const& r_norm, Exponentiation<Length, -3> const& one_over_r³, double const sin_β, double const cos_β, double const one_over_cos²_β, Angle const& λ) { constexpr int n = degree; Inverse<Length> const radial_factor = Pow<n>(reference_radius / r_norm) / r_norm; Vector<Exponentiation<Length, -2>, Frame> const radial_factor_derivative = -(n + 1) * r * radial_factor / r²; return (DegreeNOrderM<degree, orders>::Acceleration( x, y, z, r, rx²_plus_ry², rx, ry, rz, r_norm, one_over_r³, radial_factor, radial_factor_derivative, sin_β, cos_β, one_over_cos²_β, λ) + ...); } }; template<typename Frame> template<int... degrees> struct Geopotential<Frame>::AllDegrees<std::integer_sequence<int, degrees...>> { static Vector<Exponentiation<Length, -2>, Frame> Acceleration(UnitVector const& x, UnitVector const& y, UnitVector const& z, Length const& reference_radius, Displacement<Frame> const& r, Square<Length> const& r², Square<Length> const rx²_plus_ry², Length const& rx, Length const& ry, Length const& rz, Length const& r_norm, Exponentiation<Length, -3> const& one_over_r³, double const sin_β, double const cos_β, double const one_over_cos²_β, Angle const& λ) { return (DegreeNAllOrders<degrees, std::make_integer_sequence<int, degrees + 1>>:: Acceleration(x, y, z, reference_radius, r, r², rx²_plus_ry², rx, ry, rz, r_norm, one_over_r³, sin_β, cos_β, one_over_cos²_β, λ) + ...); } }; template<typename Frame> Vector<Exponentiation<Length, -2>, Frame> Geopotential<Frame>::FullSphericalHarmonicsAcceleration( Instant const& t, Displacement<Frame> const& r, Square<Length> const& r², Exponentiation<Length, -3> const& one_over_r³) const { Vector<Quotient<Acceleration, GravitationalParameter>, Frame> acceleration; auto const from_surface_frame = body_->FromSurfaceFrame<SurfaceFrame>(t); UnitVector const x = from_surface_frame(x_); UnitVector const y = from_surface_frame(y_); UnitVector const& z = body_->polar_axis(); Length const rx = InnerProduct(r, x); Length const ry = InnerProduct(r, y); Length const rz = InnerProduct(r, z); Length const r_norm = r.Norm(); Square<Length> const rx²_plus_ry² = r² - rz * rz; double const sin_β = rz / r_norm; double const cos_β = Sqrt(rx²_plus_ry²) / r_norm; double const one_over_cos²_β = r² / rx²_plus_ry²; Angle const λ = SIUnit<Angle>() * std::atan2(ry / SIUnit<Length>(), rx / SIUnit<Length>()); //TODO(phl): fix Length const reference_radius; return AllDegrees<std::make_integer_sequence<int, 20>>::Acceleration( x, y, z, reference_radius, r, r², rx²_plus_ry², rx, ry, rz, r_norm, one_over_r³, sin_β, cos_β, one_over_cos²_β, λ); } template<typename Frame> template<int degree, int order> double Geopotential<Frame>::AssociatedLegendrePolynomial( double const argument) { static auto const Pn = LegendrePolynomial<degree, HornerEvaluator>(); static auto const DmPn = Pn.Derivative<order>(); double const one_minus_argument² = 1 - argument * argument; double const multiplier = Pow<order / 2>(one_minus_argument²); if constexpr (order % 2 == 0) { return DmPn.Evaluate(argument); } else { return -Sqrt(one_minus_argument²) * DmPn.Evaluate(argument); } } template<typename Frame> Vector<Quotient<Acceleration, GravitationalParameter>, Frame> Geopotential<Frame>::Degree2ZonalAcceleration( UnitVector const& axis, Displacement<Frame> const& r, Exponentiation<Length, -2> const& one_over_r², Exponentiation<Length, -3> const& one_over_r³) const { Length const r_axis_projection = InnerProduct(axis, r); auto const j2_over_r⁵ = body_->j2_over_μ() * one_over_r³ * one_over_r²; Vector<Quotient<Acceleration, GravitationalParameter>, Frame> const axis_effect = -3 * j2_over_r⁵ * r_axis_projection * axis; Vector<Quotient<Acceleration, GravitationalParameter>, Frame> const radial_effect = j2_over_r⁵ * (-1.5 + 7.5 * r_axis_projection * r_axis_projection * one_over_r²) * r; return axis_effect + radial_effect; } template<typename Frame> Vector<Quotient<Acceleration, GravitationalParameter>, Frame> Geopotential<Frame>::Degree2SectoralAcceleration( UnitVector const& reference, UnitVector const& bireference, Displacement<Frame> const& r, Exponentiation<Length, -2> const& one_over_r², Exponentiation<Length, -3> const& one_over_r³) const { Length const r_reference_projection = InnerProduct(reference, r); Length const r_bireference_projection = InnerProduct(bireference, r); auto const c22_over_r⁵ = body_->c22_over_μ() * one_over_r³ * one_over_r²; auto const s22_over_r⁵ = body_->s22_over_μ() * one_over_r³ * one_over_r²; Vector<Quotient<Acceleration, GravitationalParameter>, Frame> const c22_effect = 6 * c22_over_r⁵ * (-r_bireference_projection * bireference + r_reference_projection * reference + 2.5 * (r_bireference_projection * r_bireference_projection - r_reference_projection * r_reference_projection) * one_over_r² * r); Vector<Quotient<Acceleration, GravitationalParameter>, Frame> const s22_effect = 6 * s22_over_r⁵ * (r_reference_projection * bireference + r_bireference_projection * reference - 5 * r_reference_projection * r_bireference_projection * one_over_r² * r); return c22_effect + s22_effect; } template<typename Frame> Vector<Quotient<Acceleration, GravitationalParameter>, Frame> Geopotential<Frame>::Degree3ZonalAcceleration( UnitVector const& axis, Displacement<Frame> const& r, Square<Length> const& r², Exponentiation<Length, -2> const& one_over_r², Exponentiation<Length, -3> const& one_over_r³) const { // TODO(phl): Factor the projections across accelerations? Length const r_axis_projection = InnerProduct(axis, r); Square<Length> const r_axis_projection² = r_axis_projection * r_axis_projection; auto const j3_over_r⁷ = body_->j3_over_μ() * one_over_r³ * one_over_r²* one_over_r²; Vector<Quotient<Acceleration, GravitationalParameter>, Frame> const axis_effect = 1.5 * j3_over_r⁷ * (r² - 5 * r_axis_projection²) * axis; Vector<Quotient<Acceleration, GravitationalParameter>, Frame> const radial_effect = j3_over_r⁷ * r_axis_projection * (-7.5 + 17.5 * r_axis_projection² * one_over_r²) * r; return axis_effect + radial_effect; } template<typename Frame> const Vector<double, typename Geopotential<Frame>::SurfaceFrame> Geopotential<Frame>::x_({1, 0, 0}); template<typename Frame> const Vector<double, typename Geopotential<Frame>::SurfaceFrame> Geopotential<Frame>::y_({0, 1, 0}); } // namespace internal_geopotential } // namespace physics } // namespace principia <commit_msg>Now it compiles.<commit_after>#pragma once #include "physics/geopotential.hpp" #include <cmath> #include "numerics/legendre.hpp" #include "numerics/polynomial_evaluators.hpp" #include "quantities/elementary_functions.hpp" #include "quantities/quantities.hpp" #include "quantities/si.hpp" namespace principia { namespace physics { namespace internal_geopotential { using numerics::HornerEvaluator; using numerics::LegendrePolynomial; using geometry::InnerProduct; using quantities::Cos; using quantities::Inverse; using quantities::Length; using quantities::Pow; using quantities::Sqrt; using quantities::Square; using quantities::Sin; using quantities::SIUnit; template<typename Frame> Geopotential<Frame>::Geopotential(not_null<OblateBody<Frame> const*> body) : body_(body) {} template<typename Frame> Vector<Quotient<Acceleration, GravitationalParameter>, Frame> Geopotential<Frame>::SphericalHarmonicsAcceleration( Instant const& t, Displacement<Frame> const& r, Square<Length> const& r², Exponentiation<Length, -3> const& one_over_r³) const { Exponentiation<Length, -2> const one_over_r² = 1 / r²; UnitVector const& axis = body_->polar_axis(); Vector<Quotient<Acceleration, GravitationalParameter>, Frame> acceleration = Degree2ZonalAcceleration(axis, r, one_over_r², one_over_r³); if (body_->has_c22() || body_->has_s22()) { auto const from_surface_frame = body_->template FromSurfaceFrame<SurfaceFrame>(t); UnitVector const reference = from_surface_frame(x_); UnitVector const bireference = from_surface_frame(y_); acceleration += Degree2SectoralAcceleration( reference, bireference, r, one_over_r², one_over_r³); } if (body_->has_j3()) { acceleration += Degree3ZonalAcceleration(axis, r, r², one_over_r², one_over_r³); } return acceleration; } template<typename Frame> template<int degree, int order> struct Geopotential<Frame>::DegreeNOrderM { static Vector<Exponentiation<Length, -2>, Frame> Acceleration(UnitVector const& x, UnitVector const& y, UnitVector const& z, Displacement<Frame> const& r, Square<Length> const rx²_plus_ry², Length const& rx, Length const& ry, Length const& rz, Length const& r_norm, Exponentiation<Length, -3> const& one_over_r³, Inverse<Length> const& radial_factor, Vector<Exponentiation<Length, -2>, Frame> const& radial_factor_derivative, double const sin_β, double const cos_β, double const one_over_cos²_β, Angle const& λ) { constexpr int n = degree; constexpr int m = order; static_assert(0 <= m && m <= n); double const latitudinal_factor = AssociatedLegendrePolynomial<n, m>(sin_β); double latitudinal_polynomials = m * sin_β * latitudinal_factor; if constexpr (m < n) { latitudinal_polynomials += AssociatedLegendrePolynomial<n, m + 1>(sin_β); } Vector<Inverse<Length>, Frame> const latitudinal_factor_derivative = one_over_cos²_β * latitudinal_polynomials * (r * rz * one_over_r³- z / r_norm); //TODO(phl): Fix. double const Cnm = 1.0; double const Snm = 1.0; Angle const mλ = m * λ; double const sin_mλ = Sin(mλ); double const cos_mλ = Cos(mλ); double const longitudinal_factor = Cnm * cos_mλ + Snm * sin_mλ ; Vector<Inverse<Length>, Frame> const longitudinal_factor_derivative = m * (Snm * cos_mλ - Cnm * sin_mλ) * (rx * y - ry * x) / rx²_plus_ry²; return radial_factor_derivative * latitudinal_factor * longitudinal_factor + radial_factor * latitudinal_factor_derivative * longitudinal_factor + radial_factor * latitudinal_factor * longitudinal_factor_derivative; } }; template<typename Frame> template<int degree, int... orders> struct Geopotential<Frame>:: DegreeNAllOrders<degree, std::integer_sequence<int, orders...>> { static Vector<Exponentiation<Length, -2>, Frame> Acceleration(UnitVector const& x, UnitVector const& y, UnitVector const& z, Length const& reference_radius, Displacement<Frame> const& r, Square<Length> const& r², Square<Length> const rx²_plus_ry², Length const& rx, Length const& ry, Length const& rz, Length const& r_norm, Exponentiation<Length, -3> const& one_over_r³, double const sin_β, double const cos_β, double const one_over_cos²_β, Angle const& λ) { constexpr int n = degree; Inverse<Length> const radial_factor = Pow<n>(reference_radius / r_norm) / r_norm; Vector<Exponentiation<Length, -2>, Frame> const radial_factor_derivative = -(n + 1) * r * radial_factor / r²; return (DegreeNOrderM<degree, orders>::Acceleration( x, y, z, r, rx²_plus_ry², rx, ry, rz, r_norm, one_over_r³, radial_factor, radial_factor_derivative, sin_β, cos_β, one_over_cos²_β, λ) + ...); } }; template<typename Frame> template<int... degrees> struct Geopotential<Frame>::AllDegrees<std::integer_sequence<int, degrees...>> { static Vector<Exponentiation<Length, -2>, Frame> Acceleration(UnitVector const& x, UnitVector const& y, UnitVector const& z, Length const& reference_radius, Displacement<Frame> const& r, Square<Length> const& r², Square<Length> const rx²_plus_ry², Length const& rx, Length const& ry, Length const& rz, Length const& r_norm, Exponentiation<Length, -3> const& one_over_r³, double const sin_β, double const cos_β, double const one_over_cos²_β, Angle const& λ) { return (DegreeNAllOrders<degrees, std::make_integer_sequence<int, degrees + 1>>:: Acceleration(x, y, z, reference_radius, r, r², rx²_plus_ry², rx, ry, rz, r_norm, one_over_r³, sin_β, cos_β, one_over_cos²_β, λ) + ...); } }; template<typename Frame> Vector<Exponentiation<Length, -2>, Frame> Geopotential<Frame>::FullSphericalHarmonicsAcceleration( Instant const& t, Displacement<Frame> const& r, Square<Length> const& r², Exponentiation<Length, -3> const& one_over_r³) const { Vector<Quotient<Acceleration, GravitationalParameter>, Frame> acceleration; auto const from_surface_frame = body_->FromSurfaceFrame<SurfaceFrame>(t); UnitVector const x = from_surface_frame(x_); UnitVector const y = from_surface_frame(y_); UnitVector const& z = body_->polar_axis(); Length const rx = InnerProduct(r, x); Length const ry = InnerProduct(r, y); Length const rz = InnerProduct(r, z); Length const r_norm = r.Norm(); Square<Length> const rx²_plus_ry² = r² - rz * rz; double const sin_β = rz / r_norm; double const cos_β = Sqrt(rx²_plus_ry²) / r_norm; double const one_over_cos²_β = r² / rx²_plus_ry²; Angle const λ = SIUnit<Angle>() * std::atan2(ry / SIUnit<Length>(), rx / SIUnit<Length>()); //TODO(phl): fix Length const reference_radius; return AllDegrees<std::make_integer_sequence<int, 4>>::Acceleration( x, y, z, reference_radius, r, r², rx²_plus_ry², rx, ry, rz, r_norm, one_over_r³, sin_β, cos_β, one_over_cos²_β, λ); } template<typename Frame> template<int degree, int order> double Geopotential<Frame>::AssociatedLegendrePolynomial( double const argument) { static auto const Pn = LegendrePolynomial<degree, HornerEvaluator>(); static auto const DmPn = Pn.Derivative<order>(); double const one_minus_argument² = 1 - argument * argument; double const multiplier = Pow<order / 2>(one_minus_argument²); if constexpr (order % 2 == 0) { return DmPn.Evaluate(argument); } else { return -Sqrt(one_minus_argument²) * DmPn.Evaluate(argument); } } template<typename Frame> Vector<Quotient<Acceleration, GravitationalParameter>, Frame> Geopotential<Frame>::Degree2ZonalAcceleration( UnitVector const& axis, Displacement<Frame> const& r, Exponentiation<Length, -2> const& one_over_r², Exponentiation<Length, -3> const& one_over_r³) const { Length const r_axis_projection = InnerProduct(axis, r); auto const j2_over_r⁵ = body_->j2_over_μ() * one_over_r³ * one_over_r²; Vector<Quotient<Acceleration, GravitationalParameter>, Frame> const axis_effect = -3 * j2_over_r⁵ * r_axis_projection * axis; Vector<Quotient<Acceleration, GravitationalParameter>, Frame> const radial_effect = j2_over_r⁵ * (-1.5 + 7.5 * r_axis_projection * r_axis_projection * one_over_r²) * r; return axis_effect + radial_effect; } template<typename Frame> Vector<Quotient<Acceleration, GravitationalParameter>, Frame> Geopotential<Frame>::Degree2SectoralAcceleration( UnitVector const& reference, UnitVector const& bireference, Displacement<Frame> const& r, Exponentiation<Length, -2> const& one_over_r², Exponentiation<Length, -3> const& one_over_r³) const { Length const r_reference_projection = InnerProduct(reference, r); Length const r_bireference_projection = InnerProduct(bireference, r); auto const c22_over_r⁵ = body_->c22_over_μ() * one_over_r³ * one_over_r²; auto const s22_over_r⁵ = body_->s22_over_μ() * one_over_r³ * one_over_r²; Vector<Quotient<Acceleration, GravitationalParameter>, Frame> const c22_effect = 6 * c22_over_r⁵ * (-r_bireference_projection * bireference + r_reference_projection * reference + 2.5 * (r_bireference_projection * r_bireference_projection - r_reference_projection * r_reference_projection) * one_over_r² * r); Vector<Quotient<Acceleration, GravitationalParameter>, Frame> const s22_effect = 6 * s22_over_r⁵ * (r_reference_projection * bireference + r_bireference_projection * reference - 5 * r_reference_projection * r_bireference_projection * one_over_r² * r); return c22_effect + s22_effect; } template<typename Frame> Vector<Quotient<Acceleration, GravitationalParameter>, Frame> Geopotential<Frame>::Degree3ZonalAcceleration( UnitVector const& axis, Displacement<Frame> const& r, Square<Length> const& r², Exponentiation<Length, -2> const& one_over_r², Exponentiation<Length, -3> const& one_over_r³) const { // TODO(phl): Factor the projections across accelerations? Length const r_axis_projection = InnerProduct(axis, r); Square<Length> const r_axis_projection² = r_axis_projection * r_axis_projection; auto const j3_over_r⁷ = body_->j3_over_μ() * one_over_r³ * one_over_r²* one_over_r²; Vector<Quotient<Acceleration, GravitationalParameter>, Frame> const axis_effect = 1.5 * j3_over_r⁷ * (r² - 5 * r_axis_projection²) * axis; Vector<Quotient<Acceleration, GravitationalParameter>, Frame> const radial_effect = j3_over_r⁷ * r_axis_projection * (-7.5 + 17.5 * r_axis_projection² * one_over_r²) * r; return axis_effect + radial_effect; } template<typename Frame> const Vector<double, typename Geopotential<Frame>::SurfaceFrame> Geopotential<Frame>::x_({1, 0, 0}); template<typename Frame> const Vector<double, typename Geopotential<Frame>::SurfaceFrame> Geopotential<Frame>::y_({0, 1, 0}); } // namespace internal_geopotential } // namespace physics } // namespace principia <|endoftext|>
<commit_before>// The MIT License (MIT) // // Copyright (c) 2015 Sergey Makeev, Vadim Slyusarev // // 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 "Tests.h" #include <UnitTest++.h> #include <MTScheduler.h> SUITE(StackSizeTests) { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct StandartStackSizeTask { MT_DECLARE_TASK(StandartStackSizeTask, MT::StackRequirements::STANDARD, MT::Color::Blue); void Do(MT::FiberContext&) { byte stackData[32000]; memset(stackData, 0x0D, MT_ARRAY_SIZE(stackData)); } }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct ExtendedStackSizeTask { MT_DECLARE_TASK(ExtendedStackSizeTask, MT::StackRequirements::EXTENDED, MT::Color::Red); void Do(MT::FiberContext&) { byte stackData[262144]; memset(stackData, 0x0D, MT_ARRAY_SIZE(stackData)); } }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST(RunStandartTasks) { MT::TaskScheduler scheduler(8); StandartStackSizeTask tasks[100]; scheduler.RunAsync(MT::TaskGroup::Default(), &tasks[0], MT_ARRAY_SIZE(tasks)); CHECK(scheduler.WaitAll(1000)); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST(RunExtendedTasks) { MT::TaskScheduler scheduler(8); ExtendedStackSizeTask tasks[100]; scheduler.RunAsync(MT::TaskGroup::Default(), &tasks[0], MT_ARRAY_SIZE(tasks)); CHECK(scheduler.WaitAll(1000)); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST(RunMixedTasks) { MT::TaskScheduler scheduler(8); MT::TaskPool<ExtendedStackSizeTask, 64> extendedTaskPool; MT::TaskPool<StandartStackSizeTask, 64> standardTaskPool; MT::TaskHandle taskHandles[100]; for (size_t i = 0; i < MT_ARRAY_SIZE(taskHandles); ++i) { MT::TaskHandle handle; if (i & 1) { handle = extendedTaskPool.Alloc(ExtendedStackSizeTask()); } else { handle = standardTaskPool.Alloc(StandartStackSizeTask()); } taskHandles[i] = handle; } scheduler.RunAsync(MT::TaskGroup::Default(), &taskHandles[0], MT_ARRAY_SIZE(taskHandles)); CHECK(scheduler.WaitAll(1000)); } } <commit_msg>Fixed test<commit_after>// The MIT License (MIT) // // Copyright (c) 2015 Sergey Makeev, Vadim Slyusarev // // 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 "Tests.h" #include <UnitTest++.h> #include <MTScheduler.h> SUITE(StackSizeTests) { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct StandartStackSizeTask { MT_DECLARE_TASK(StandartStackSizeTask, MT::StackRequirements::STANDARD, MT::Color::Blue); void Do(MT::FiberContext&) { byte stackData[28000]; memset(stackData, 0x0D, MT_ARRAY_SIZE(stackData)); } }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct ExtendedStackSizeTask { MT_DECLARE_TASK(ExtendedStackSizeTask, MT::StackRequirements::EXTENDED, MT::Color::Red); void Do(MT::FiberContext&) { byte stackData[262144]; memset(stackData, 0x0D, MT_ARRAY_SIZE(stackData)); } }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST(RunStandartTasks) { MT::TaskScheduler scheduler(8); StandartStackSizeTask tasks[100]; scheduler.RunAsync(MT::TaskGroup::Default(), &tasks[0], MT_ARRAY_SIZE(tasks)); CHECK(scheduler.WaitAll(1000)); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST(RunExtendedTasks) { MT::TaskScheduler scheduler(8); ExtendedStackSizeTask tasks[100]; scheduler.RunAsync(MT::TaskGroup::Default(), &tasks[0], MT_ARRAY_SIZE(tasks)); CHECK(scheduler.WaitAll(1000)); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST(RunMixedTasks) { MT::TaskScheduler scheduler(8); MT::TaskPool<ExtendedStackSizeTask, 64> extendedTaskPool; MT::TaskPool<StandartStackSizeTask, 64> standardTaskPool; MT::TaskHandle taskHandles[100]; for (size_t i = 0; i < MT_ARRAY_SIZE(taskHandles); ++i) { MT::TaskHandle handle; if (i & 1) { handle = extendedTaskPool.Alloc(ExtendedStackSizeTask()); } else { handle = standardTaskPool.Alloc(StandartStackSizeTask()); } taskHandles[i] = handle; } scheduler.RunAsync(MT::TaskGroup::Default(), &taskHandles[0], MT_ARRAY_SIZE(taskHandles)); CHECK(scheduler.WaitAll(1000)); } } <|endoftext|>
<commit_before>#include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkQuadric.h" #include "vtkSampleFunction.h" #include "vtkContourFilter.h" #include "vtkOutlineFilter.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "SaveImage.h" void main( int argc, char *argv[] ) { vtkRenderer *ren1 = vtkRenderer::New(); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->AddRenderer(ren1); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); renWin->SetSize( 300, 300 ); // Quadric definition vtkQuadric *quadric = vtkQuadric::New(); quadric->SetCoefficients(.5,1,.2,0,.1,0,0,.2,0,0); vtkSampleFunction *sample = vtkSampleFunction::New(); sample->SetSampleDimensions(30,30,30); sample->SetImplicitFunction(quadric); // Create five surfaces F(x,y,z) = constant between range specified vtkContourFilter *contours = vtkContourFilter::New(); contours->SetInput(sample->GetOutput()); contours->GenerateValues(5, 0.0, 1.2); contours->Update(); vtkPolyDataMapper *contMapper = vtkPolyDataMapper::New(); contMapper->SetInput(contours->GetOutput()); contMapper->SetScalarRange(0.0, 1.2); vtkActor *contActor = vtkActor::New(); contActor->SetMapper(contMapper); // Create outline vtkOutlineFilter *outline = vtkOutlineFilter::New(); outline->SetInput(sample->GetOutput()); vtkPolyDataMapper *outlineMapper = vtkPolyDataMapper::New(); outlineMapper->SetInput(outline->GetOutput()); vtkActor *outlineActor = vtkActor::New(); outlineActor->SetMapper(outlineMapper); outlineActor->GetProperty()->SetColor(0,0,0); ren1->SetBackground(1,1,1); ren1->AddActor(contActor); ren1->AddActor(outlineActor); renWin->Render(); SAVEIMAGE( renWin ); // interact with data iren->Initialize(); iren->Start(); // Clean up ren1->Delete(); renWin->Delete(); iren->Delete(); quadric->Delete(); sample->Delete(); contours->Delete(); contMapper->Delete(); contActor->Delete(); outline->Delete(); outlineMapper->Delete(); outlineActor->Delete(); } <commit_msg>FIX: main return type and exit() calls<commit_after>#include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkQuadric.h" #include "vtkSampleFunction.h" #include "vtkContourFilter.h" #include "vtkOutlineFilter.h" #include "vtkPolyDataMapper.h" #include "vtkActor.h" #include "SaveImage.h" int main( int argc, char *argv[] ) { vtkRenderer *ren1 = vtkRenderer::New(); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->AddRenderer(ren1); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); renWin->SetSize( 300, 300 ); // Quadric definition vtkQuadric *quadric = vtkQuadric::New(); quadric->SetCoefficients(.5,1,.2,0,.1,0,0,.2,0,0); vtkSampleFunction *sample = vtkSampleFunction::New(); sample->SetSampleDimensions(30,30,30); sample->SetImplicitFunction(quadric); // Create five surfaces F(x,y,z) = constant between range specified vtkContourFilter *contours = vtkContourFilter::New(); contours->SetInput(sample->GetOutput()); contours->GenerateValues(5, 0.0, 1.2); contours->Update(); vtkPolyDataMapper *contMapper = vtkPolyDataMapper::New(); contMapper->SetInput(contours->GetOutput()); contMapper->SetScalarRange(0.0, 1.2); vtkActor *contActor = vtkActor::New(); contActor->SetMapper(contMapper); // Create outline vtkOutlineFilter *outline = vtkOutlineFilter::New(); outline->SetInput(sample->GetOutput()); vtkPolyDataMapper *outlineMapper = vtkPolyDataMapper::New(); outlineMapper->SetInput(outline->GetOutput()); vtkActor *outlineActor = vtkActor::New(); outlineActor->SetMapper(outlineMapper); outlineActor->GetProperty()->SetColor(0,0,0); ren1->SetBackground(1,1,1); ren1->AddActor(contActor); ren1->AddActor(outlineActor); renWin->Render(); SAVEIMAGE( renWin ); // interact with data iren->Initialize(); iren->Start(); // Clean up ren1->Delete(); renWin->Delete(); iren->Delete(); quadric->Delete(); sample->Delete(); contours->Delete(); contMapper->Delete(); contActor->Delete(); outline->Delete(); outlineMapper->Delete(); outlineActor->Delete(); exit( 1 ); } <|endoftext|>
<commit_before>// Author: Sergey Linev, GSI 10/04/2017 /************************************************************************* * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TWebPainting.h" /////////////////////////////////////////////////////////////////////////////////////// /// Constructor TWebPainting::TWebPainting() { fLastFill.SetFillStyle(9999); fLastLine.SetLineWidth(-123); fLastMarker.SetMarkerStyle(9999); } /////////////////////////////////////////////////////////////////////////////////////// /// Add next custom operator to painting /// Operations are separated by semicolons void TWebPainting::AddOper(const std::string &oper) { if (!fOper.empty()) fOper.append(";"); fOper.append(oper); } /////////////////////////////////////////////////////////////////////////////////////// /// Create text operation /// If text include special symbols - use TBase64 coding std::string TWebPainting::MakeTextOper(const char *str) { std::string oper("t"); if (str) oper.append(str); return oper; } /////////////////////////////////////////////////////////////////////////////////////// /// Reserve place in the float buffer /// Returns pointer on first element in reserved area Float_t *TWebPainting::Reserve(Int_t sz) { if (sz <= 0) return nullptr; if (fSize + sz > fBuf.GetSize()) { Int_t nextsz = fBuf.GetSize() + TMath::Max(1024, (sz/128 + 1) * 128); fBuf.Set(nextsz); } Float_t *res = fBuf.GetArray() + fSize; fSize += sz; return res; // return size where drawing can start } /////////////////////////////////////////////////////////////////////////////////////// /// Store line attributes /// If attributes were not changed - ignore operation void TWebPainting::AddLineAttr(const TAttLine &attr) { if ((attr.GetLineColor() == fLastLine.GetLineColor()) && (attr.GetLineStyle() == fLastLine.GetLineStyle()) && (attr.GetLineWidth() == fLastLine.GetLineWidth())) return; fLastLine = attr; AddOper(std::string("z") + std::to_string((int) attr.GetLineColor()) + ":" + std::to_string((int) attr.GetLineStyle()) + ":" + std::to_string((int) attr.GetLineWidth())); } /////////////////////////////////////////////////////////////////////////////////////// /// Store fill attributes /// If attributes were not changed - ignore operation void TWebPainting::AddFillAttr(const TAttFill &attr) { if ((fLastFill.GetFillColor() == attr.GetFillColor()) && (fLastFill.GetFillStyle() == attr.GetFillStyle())) return; fLastFill = attr; AddOper(std::string("y") + std::to_string((int) attr.GetFillColor()) + ":" + std::to_string((int) attr.GetFillStyle())); } /////////////////////////////////////////////////////////////////////////////////////// /// Store text attributes /// If attributes were not changed - ignore operation void TWebPainting::AddTextAttr(const TAttText &attr) { AddOper(std::string("o") + std::to_string((int) attr.GetTextColor()) + ":" + std::to_string((int) attr.GetTextFont()) + ":" + std::to_string((int) (attr.GetTextSize()>=1 ? attr.GetTextSize() : -1000*attr.GetTextSize())) + ":" + std::to_string((int) attr.GetTextAlign()) + ":" + std::to_string((int) attr.GetTextAngle())); } /////////////////////////////////////////////////////////////////////////////////////// /// Store marker attributes /// If attributes were not changed - ignore operation void TWebPainting::AddMarkerAttr(const TAttMarker &attr) { if ((attr.GetMarkerColor() == fLastMarker.GetMarkerColor()) && (attr.GetMarkerStyle() == fLastMarker.GetMarkerStyle()) && (attr.GetMarkerSize() == fLastMarker.GetMarkerSize())) return; fLastMarker = attr; AddOper(std::string("x") + std::to_string((int) attr.GetMarkerColor()) + ":" + std::to_string((int) attr.GetMarkerStyle()) + ":" + std::to_string((int) attr.GetMarkerSize())); } /////////////////////////////////////////////////////////////////////////////////////// /// Add custom color to operations void TWebPainting::AddColor(Int_t indx, TColor *col) { if (!col) return; TString code; if (col->GetAlpha() == 1) code.Form("rgb(%d,%d,%d)", (int) (255*col->GetRed()), (int) (255*col->GetGreen()), (int) (255*col->GetBlue())); else code.Form("rgba(%d,%d,%d,%5.3f)", (int) (255*col->GetRed()), (int) (255*col->GetGreen()), (int) (255*col->GetBlue()), col->GetAlpha()); if (indx>=0) code.Prepend(TString::Format("%d:", indx)); AddOper(code.Data()); } <commit_msg>webgui6: use more compact representations for colors<commit_after>// Author: Sergey Linev, GSI 10/04/2017 /************************************************************************* * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "TWebPainting.h" /////////////////////////////////////////////////////////////////////////////////////// /// Constructor TWebPainting::TWebPainting() { fLastFill.SetFillStyle(9999); fLastLine.SetLineWidth(-123); fLastMarker.SetMarkerStyle(9999); } /////////////////////////////////////////////////////////////////////////////////////// /// Add next custom operator to painting /// Operations are separated by semicolons void TWebPainting::AddOper(const std::string &oper) { if (!fOper.empty()) fOper.append(";"); fOper.append(oper); } /////////////////////////////////////////////////////////////////////////////////////// /// Create text operation /// If text include special symbols - use TBase64 coding std::string TWebPainting::MakeTextOper(const char *str) { std::string oper("t"); if (str) oper.append(str); return oper; } /////////////////////////////////////////////////////////////////////////////////////// /// Reserve place in the float buffer /// Returns pointer on first element in reserved area Float_t *TWebPainting::Reserve(Int_t sz) { if (sz <= 0) return nullptr; if (fSize + sz > fBuf.GetSize()) { Int_t nextsz = fBuf.GetSize() + TMath::Max(1024, (sz/128 + 1) * 128); fBuf.Set(nextsz); } Float_t *res = fBuf.GetArray() + fSize; fSize += sz; return res; // return size where drawing can start } /////////////////////////////////////////////////////////////////////////////////////// /// Store line attributes /// If attributes were not changed - ignore operation void TWebPainting::AddLineAttr(const TAttLine &attr) { if ((attr.GetLineColor() == fLastLine.GetLineColor()) && (attr.GetLineStyle() == fLastLine.GetLineStyle()) && (attr.GetLineWidth() == fLastLine.GetLineWidth())) return; fLastLine = attr; AddOper(std::string("z") + std::to_string((int) attr.GetLineColor()) + ":" + std::to_string((int) attr.GetLineStyle()) + ":" + std::to_string((int) attr.GetLineWidth())); } /////////////////////////////////////////////////////////////////////////////////////// /// Store fill attributes /// If attributes were not changed - ignore operation void TWebPainting::AddFillAttr(const TAttFill &attr) { if ((fLastFill.GetFillColor() == attr.GetFillColor()) && (fLastFill.GetFillStyle() == attr.GetFillStyle())) return; fLastFill = attr; AddOper(std::string("y") + std::to_string((int) attr.GetFillColor()) + ":" + std::to_string((int) attr.GetFillStyle())); } /////////////////////////////////////////////////////////////////////////////////////// /// Store text attributes /// If attributes were not changed - ignore operation void TWebPainting::AddTextAttr(const TAttText &attr) { AddOper(std::string("o") + std::to_string((int) attr.GetTextColor()) + ":" + std::to_string((int) attr.GetTextFont()) + ":" + std::to_string((int) (attr.GetTextSize()>=1 ? attr.GetTextSize() : -1000*attr.GetTextSize())) + ":" + std::to_string((int) attr.GetTextAlign()) + ":" + std::to_string((int) attr.GetTextAngle())); } /////////////////////////////////////////////////////////////////////////////////////// /// Store marker attributes /// If attributes were not changed - ignore operation void TWebPainting::AddMarkerAttr(const TAttMarker &attr) { if ((attr.GetMarkerColor() == fLastMarker.GetMarkerColor()) && (attr.GetMarkerStyle() == fLastMarker.GetMarkerStyle()) && (attr.GetMarkerSize() == fLastMarker.GetMarkerSize())) return; fLastMarker = attr; AddOper(std::string("x") + std::to_string((int) attr.GetMarkerColor()) + ":" + std::to_string((int) attr.GetMarkerStyle()) + ":" + std::to_string((int) attr.GetMarkerSize())); } /////////////////////////////////////////////////////////////////////////////////////// /// Add custom color to operations void TWebPainting::AddColor(Int_t indx, TColor *col) { if (!col) return; TString code; if (col->GetAlpha() == 1) code.Form("%d:%d,%d,%d", indx, (int) (255*col->GetRed()), (int) (255*col->GetGreen()), (int) (255*col->GetBlue())); else code.Form("%d=%d,%d,%d,%5.3f", indx, (int) (255*col->GetRed()), (int) (255*col->GetGreen()), (int) (255*col->GetBlue()), col->GetAlpha()); AddOper(code.Data()); } <|endoftext|>
<commit_before>/* * bin_hierarchical_clustering_index_test.cpp * * Created on: Sep 18, 2013 * Author: andresf */ #include <ctime> #include <limits.h> #include <gtest/gtest.h> #include <opencv2/core/core.hpp> #include <FileUtils.hpp> #include <VocabTree.h> TEST(VocabTree, Instantiation) { cv::Ptr<cvflann::VocabTreeBase> tree; EXPECT_TRUE(tree == NULL); tree = new cvflann::VocabTree<float, cv::L2<float> >(); EXPECT_TRUE(tree != NULL); } TEST(VocabTree, LoadSaveReal) { ///////////////////////////////////////////////////////////////////// std::vector<std::string> keysFilenames; keysFilenames.push_back("sift_0.yaml.gz"); keysFilenames.push_back("sift_1.yaml.gz"); DynamicMat data(keysFilenames); ///////////////////////////////////////////////////////////////////// cv::Ptr<cvflann::VocabTree<float, cv::L2<float> > > tree = new cvflann::VocabTree<float, cv::L2<float> >(data); cvflann::seed_random(unsigned(std::time(0))); tree->build(); tree->save("test_tree.yaml.gz"); cv::Ptr<cvflann::VocabTree<float, cv::L2<float> > > treeLoad = new cvflann::VocabTree<float, cv::L2<float> >(); treeLoad->load("test_tree.yaml.gz"); ASSERT_TRUE(tree->size() == treeLoad->size()); ASSERT_TRUE(*tree.obj == *treeLoad.obj); } TEST(VocabTree, LoadSaveBinary) { ///////////////////////////////////////////////////////////////////// std::vector<std::string> keysFilenames; keysFilenames.push_back("brief_0.yaml.gz"); keysFilenames.push_back("brief_1.yaml.gz"); DynamicMat data(keysFilenames); ///////////////////////////////////////////////////////////////////// cv::Ptr<cvflann::VocabTree<uchar, cv::Hamming> > tree; tree = new cvflann::VocabTree<uchar, cv::Hamming>(data); tree->build(); tree->save("test_tree.yaml.gz"); cv::Ptr<cvflann::VocabTree<uchar, cv::Hamming> > treeLoad = new cvflann::VocabTree<uchar, cv::Hamming>(); treeLoad->load("test_tree.yaml.gz"); ASSERT_TRUE(tree->size() == treeLoad->size()); ASSERT_TRUE(*tree.obj == *treeLoad.obj); } TEST(VocabTree, TestDatabase) { ///////////////////////////////////////////////////////////////////// cv::Mat imgDescriptors; std::vector<std::string> keysFilenames; keysFilenames.push_back("sift_0.yaml.gz"); keysFilenames.push_back("sift_1.yaml.gz"); DynamicMat data(keysFilenames); ///////////////////////////////////////////////////////////////////// cv::Ptr<cvflann::VocabTreeBase> tree = new cvflann::VocabTree<float, cv::L2<float> >(data); tree->build(); tree->clearDatabase(); bool gotException = false; uint i = 0; for (std::string keyFileName : keysFilenames) { try { imgDescriptors = cv::Mat(); FileUtils::loadDescriptors(keyFileName, imgDescriptors); tree->addImageToDatabase(i, imgDescriptors); } catch (const std::runtime_error& error) { fprintf(stdout, "%s\n", error.what()); gotException = true; } i++; } ASSERT_FALSE(gotException); tree->computeWordsWeights(cvflann::TF_IDF); tree->createDatabase(); // TODO assert inverted files are not empty anymore tree->normalizeDatabase(cv::NORM_L1); // TODO assert DB BoW vector's values are in the [0,1] range // Querying the tree using the same documents used for building it // The top result must be the document itself and hence the score must be 1 i = 0; for (std::string keyFileName : keysFilenames) { cv::Mat scores; imgDescriptors = cv::Mat(); FileUtils::loadDescriptors(keyFileName, imgDescriptors); tree->scoreQuery(imgDescriptors, scores, cv::NORM_L1); // Check that scores has the right type EXPECT_TRUE(cv::DataType<float>::type == scores.type()); // Check that scores is a row vector EXPECT_TRUE(1 == scores.rows); // Check all DB images have been scored EXPECT_TRUE((int )keysFilenames.size() == scores.cols); cv::Mat perm; cv::sortIdx(scores, perm, cv::SORT_EVERY_ROW + cv::SORT_DESCENDING); EXPECT_TRUE(scores.rows == perm.rows); EXPECT_TRUE(scores.cols == perm.cols); EXPECT_TRUE((int )i == perm.at<int>(0, 0)); EXPECT_TRUE(round(scores.at<float>(0, perm.at<int>(0, 0))) == 1.0); i++; } } <commit_msg>VocabLib/tests/VocabTree_test.cpp * Refactored tests to test weight saving/loading.<commit_after>/* * bin_hierarchical_clustering_index_test.cpp * * Created on: Sep 18, 2013 * Author: andresf */ #include <ctime> #include <limits.h> #include <gtest/gtest.h> #include <opencv2/core/core.hpp> #include <FileUtils.hpp> #include <VocabTree.h> TEST(VocabTree, Instantiation) { cv::Ptr<cvflann::VocabTreeBase> tree; EXPECT_TRUE(tree == NULL); tree = new cvflann::VocabTree<float, cv::L2<float> >(); EXPECT_TRUE(tree != NULL); } TEST(VocabTree, LoadSaveReal) { ///////////////////////////////////////////////////////////////////// std::vector<std::string> keysFilenames; keysFilenames.push_back("sift_0.yaml.gz"); keysFilenames.push_back("sift_1.yaml.gz"); DynamicMat data(keysFilenames); ///////////////////////////////////////////////////////////////////// cv::Ptr<cvflann::VocabTree<float, cv::L2<float> > > tree = new cvflann::VocabTree<float, cv::L2<float> >(data); cvflann::seed_random(unsigned(std::time(0))); tree->build(); tree->save("test_tree.yaml.gz"); tree->saveInvertedIndex("test_idf.yaml.gz"); cv::Ptr<cvflann::VocabTree<float, cv::L2<float> > > treeLoad = new cvflann::VocabTree<float, cv::L2<float> >(); treeLoad->load("test_tree.yaml.gz"); treeLoad->loadInvertedIndex("test_idf.yaml.gz"); ASSERT_TRUE(tree->size() == treeLoad->size()); ASSERT_TRUE(*tree.obj == *treeLoad.obj); } TEST(VocabTree, LoadSaveBinary) { ///////////////////////////////////////////////////////////////////// std::vector<std::string> keysFilenames; keysFilenames.push_back("brief_0.yaml.gz"); keysFilenames.push_back("brief_1.yaml.gz"); DynamicMat data(keysFilenames); ///////////////////////////////////////////////////////////////////// cv::Ptr<cvflann::VocabTree<uchar, cv::Hamming> > tree; tree = new cvflann::VocabTree<uchar, cv::Hamming>(data); tree->build(); tree->save("test_tree.yaml.gz"); tree->saveInvertedIndex("test_idf.yaml.gz"); cv::Ptr<cvflann::VocabTree<uchar, cv::Hamming> > treeLoad = new cvflann::VocabTree<uchar, cv::Hamming>(); treeLoad->load("test_tree.yaml.gz"); treeLoad->loadInvertedIndex("test_idf.yaml.gz"); ASSERT_TRUE(tree->size() == treeLoad->size()); ASSERT_TRUE(*tree.obj == *treeLoad.obj); } TEST(VocabTree, TestDatabase) { ///////////////////////////////////////////////////////////////////// cv::Mat imgDescriptors; std::vector<std::string> keysFilenames; keysFilenames.push_back("sift_0.yaml.gz"); keysFilenames.push_back("sift_1.yaml.gz"); DynamicMat data(keysFilenames); ///////////////////////////////////////////////////////////////////// cv::Ptr<cvflann::VocabTreeBase> tree = new cvflann::VocabTree<float, cv::L2<float> >(data); tree->build(); tree->clearDatabase(); bool gotException = false; uint i = 0; for (std::string keyFileName : keysFilenames) { try { imgDescriptors = cv::Mat(); FileUtils::loadDescriptors(keyFileName, imgDescriptors); tree->addImageToDatabase(i, imgDescriptors); } catch (const std::runtime_error& error) { fprintf(stdout, "%s\n", error.what()); gotException = true; } i++; } ASSERT_FALSE(gotException); tree->computeWordsWeights(cvflann::TF_IDF); tree->createDatabase(); // TODO assert inverted files are not empty anymore tree->normalizeDatabase(cv::NORM_L1); // TODO assert DB BoW vector's values are in the [0,1] range // Querying the tree using the same documents used for building it // The top result must be the document itself and hence the score must be 1 i = 0; for (std::string keyFileName : keysFilenames) { cv::Mat scores; imgDescriptors = cv::Mat(); FileUtils::loadDescriptors(keyFileName, imgDescriptors); tree->scoreQuery(imgDescriptors, scores, cv::NORM_L1); // Check that scores has the right type EXPECT_TRUE(cv::DataType<float>::type == scores.type()); // Check that scores is a row vector EXPECT_TRUE(1 == scores.rows); // Check all DB images have been scored EXPECT_TRUE((int )keysFilenames.size() == scores.cols); cv::Mat perm; cv::sortIdx(scores, perm, cv::SORT_EVERY_ROW + cv::SORT_DESCENDING); EXPECT_TRUE(scores.rows == perm.rows); EXPECT_TRUE(scores.cols == perm.cols); EXPECT_TRUE((int )i == perm.at<int>(0, 0)); EXPECT_TRUE(round(scores.at<float>(0, perm.at<int>(0, 0))) == 1.0); i++; } } <|endoftext|>
<commit_before>/* main.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klar�vdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <config-kleopatra.h> #include "aboutdata.h" #include "kleopatraapplication.h" #include "mainwindow.h" #include <commands/reloadkeyscommand.h> #include <commands/selftestcommand.h> #include <utils/gnupg-helper.h> #ifdef HAVE_USABLE_ASSUAN # include <uiserver/uiserver.h> # include <uiserver/assuancommand.h> # include <uiserver/echocommand.h> # include <uiserver/decryptcommand.h> # include <uiserver/verifycommand.h> # include <uiserver/decryptverifyfilescommand.h> # include <uiserver/decryptfilescommand.h> # include <uiserver/verifyfilescommand.h> # include <uiserver/prepencryptcommand.h> # include <uiserver/encryptcommand.h> # include <uiserver/signcommand.h> # include <uiserver/signencryptfilescommand.h> # include <uiserver/selectcertificatecommand.h> #else namespace Kleo { class UiServer; } #endif #include <kcmdlineargs.h> #include <klocale.h> #include <kiconloader.h> #include <ksplashscreen.h> #include <KDebug> #include <QTextDocument> // for Qt::escape #include <QStringList> #include <QMessageBox> #include <QTimer> #include <QEventLoop> #include <QThreadPool> #include <boost/shared_ptr.hpp> #include <cassert> using namespace boost; namespace { template <typename T> boost::shared_ptr<T> make_shared_ptr( T * t ) { return t ? boost::shared_ptr<T>( t ) : boost::shared_ptr<T>() ; } } static bool selfCheck( KSplashScreen & splash ) { splash.showMessage( i18n("Performing Self-Check...") ); Kleo::Commands::SelfTestCommand cmd( 0 ); cmd.setAutoDelete( false ); cmd.setAutomaticMode( true ); cmd.setSplashScreen( &splash ); QEventLoop loop; QObject::connect( &cmd, SIGNAL(finished()), &loop, SLOT(quit()) ); QObject::connect( &cmd, SIGNAL(info(QString)), &splash, SLOT(showMessage(QString)) ); QTimer::singleShot( 0, &cmd, SLOT(start()) ); // start() may emit finished()... loop.exec(); if ( cmd.isCanceled() ) { splash.showMessage( i18nc("didn't pass", "Self-Check Failed") ); return false; } else { splash.showMessage( i18n("Self-Check Passed") ); return true; } } static void fillKeyCache( KSplashScreen * splash, Kleo::UiServer * server ) { QEventLoop loop; Kleo::ReloadKeysCommand * cmd = new Kleo::ReloadKeysCommand( 0 ); QObject::connect( cmd, SIGNAL(finished()), &loop, SLOT(quit()) ); #ifdef HAVE_USABLE_ASSUAN QObject::connect( cmd, SIGNAL(finished()), server, SLOT(enableCryptoCommands()) ); #else Q_UNUSED( server ); #endif splash->showMessage( i18n("Loading certificate cache...") ); cmd->start(); loop.exec(); splash->showMessage( i18n("Certificate cache loaded.") ); } int main( int argc, char** argv ) { { const unsigned int threads = QThreadPool::globalInstance()->maxThreadCount(); QThreadPool::globalInstance()->setMaxThreadCount( qMax( 2U, threads ) ); } AboutData aboutData; KCmdLineArgs::init(argc, argv, &aboutData); KCmdLineArgs::addCmdLineOptions( KleopatraApplication::commandLineOptions() ); KleopatraApplication app; KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); KSplashScreen splash( UserIcon( "kleopatra_splashscreen" ), Qt::WindowStaysOnTopHint ); int rc; #ifdef HAVE_USABLE_ASSUAN try { Kleo::UiServer server( args->getOption("uiserver-socket") ); QObject::connect( &server, SIGNAL(startKeyManagerRequested()), &app, SLOT(openOrRaiseMainWindow()) ); QObject::connect( &server, SIGNAL(startConfigDialogRequested()), &app, SLOT(openOrRaiseConfigDialog()) ); #define REGISTER( Command ) server.registerCommandFactory( boost::shared_ptr<Kleo::AssuanCommandFactory>( new Kleo::GenericAssuanCommandFactory<Kleo::Command> ) ) REGISTER( DecryptCommand ); REGISTER( DecryptFilesCommand ); REGISTER( DecryptVerifyFilesCommand ); REGISTER( EchoCommand ); REGISTER( EncryptCommand ); REGISTER( EncryptFilesCommand ); REGISTER( EncryptSignFilesCommand ); REGISTER( PrepEncryptCommand ); REGISTER( SelectCertificateCommand ); REGISTER( SignCommand ); REGISTER( SignEncryptFilesCommand ); REGISTER( SignFilesCommand ); REGISTER( VerifyCommand ); REGISTER( VerifyFilesCommand ); #undef REGISTER server.start(); #endif const bool daemon = args->isSet("daemon"); if ( !daemon ) splash.show(); if ( !selfCheck( splash ) ) return 1; #ifdef HAVE_USABLE_ASSUAN fillKeyCache( &splash, &server ); #else fillKeyCache( &splash, 0 ); #endif app.setIgnoreNewInstance( false ); if ( !daemon ) { app.newInstance(); splash.finish( app.mainWindow() ); } rc = app.exec(); #ifdef HAVE_USABLE_ASSUAN app.setIgnoreNewInstance( true ); QObject::disconnect( &server, SIGNAL(startKeyManagerRequested()), &app, SLOT(openOrRaiseMainWindow()) ); QObject::disconnect( &server, SIGNAL(startConfigDialogRequested()), &app, SLOT(openOrRaiseConfigDialog()) ); server.stop(); server.waitForStopped(); } catch ( const std::exception & e ) { QMessageBox::information( 0, i18n("GPG UI Server Error"), i18n("<qt>The Kleopatra GPG UI Server Module couldn't be initialized.<br/>" "The error given was: <b>%1</b><br/>" "You can use Kleopatra as a certificate manager, but cryptographic plugins that " "rely on a GPG UI Server being present might not work correctly, or at all.</qt>", Qt::escape( QString::fromUtf8( e.what() ) ) )); app.setIgnoreNewInstance( false ); rc = app.exec(); app.setIgnoreNewInstance( true ); } #endif return rc; } <commit_msg>Hide the splashscreen after 5s, just in case there's a pinentry waiting in the background. BUG:173435<commit_after>/* main.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2001,2002,2004 Klar�vdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include <config-kleopatra.h> #include "aboutdata.h" #include "kleopatraapplication.h" #include "mainwindow.h" #include <commands/reloadkeyscommand.h> #include <commands/selftestcommand.h> #include <utils/gnupg-helper.h> #ifdef HAVE_USABLE_ASSUAN # include <uiserver/uiserver.h> # include <uiserver/assuancommand.h> # include <uiserver/echocommand.h> # include <uiserver/decryptcommand.h> # include <uiserver/verifycommand.h> # include <uiserver/decryptverifyfilescommand.h> # include <uiserver/decryptfilescommand.h> # include <uiserver/verifyfilescommand.h> # include <uiserver/prepencryptcommand.h> # include <uiserver/encryptcommand.h> # include <uiserver/signcommand.h> # include <uiserver/signencryptfilescommand.h> # include <uiserver/selectcertificatecommand.h> #else namespace Kleo { class UiServer; } #endif #include <kcmdlineargs.h> #include <klocale.h> #include <kiconloader.h> #include <ksplashscreen.h> #include <KDebug> #include <QTextDocument> // for Qt::escape #include <QStringList> #include <QMessageBox> #include <QTimer> #include <QEventLoop> #include <QThreadPool> #include <boost/shared_ptr.hpp> #include <cassert> using namespace boost; static const int SPLASHSCREEN_TIMEOUT = 5000; // 5s namespace { template <typename T> boost::shared_ptr<T> make_shared_ptr( T * t ) { return t ? boost::shared_ptr<T>( t ) : boost::shared_ptr<T>() ; } } class SplashScreen : public KSplashScreen { QBasicTimer m_timer; public: SplashScreen() : KSplashScreen( UserIcon( "kleopatra_splashscreen" ), Qt::WindowStaysOnTopHint ), m_timer() { m_timer.start( SPLASHSCREEN_TIMEOUT, this ); } protected: void timerEvent( QTimerEvent * ev ) { if ( ev->timerId() == m_timer.timerId() ) { m_timer.stop(); hide(); } else { KSplashScreen::timerEvent( ev ); } } }; static bool selfCheck( KSplashScreen & splash ) { splash.showMessage( i18n("Performing Self-Check...") ); Kleo::Commands::SelfTestCommand cmd( 0 ); cmd.setAutoDelete( false ); cmd.setAutomaticMode( true ); cmd.setSplashScreen( &splash ); QEventLoop loop; QObject::connect( &cmd, SIGNAL(finished()), &loop, SLOT(quit()) ); QObject::connect( &cmd, SIGNAL(info(QString)), &splash, SLOT(showMessage(QString)) ); QTimer::singleShot( 0, &cmd, SLOT(start()) ); // start() may emit finished()... loop.exec(); if ( cmd.isCanceled() ) { splash.showMessage( i18nc("didn't pass", "Self-Check Failed") ); return false; } else { splash.showMessage( i18n("Self-Check Passed") ); return true; } } static void fillKeyCache( KSplashScreen * splash, Kleo::UiServer * server ) { QEventLoop loop; Kleo::ReloadKeysCommand * cmd = new Kleo::ReloadKeysCommand( 0 ); QObject::connect( cmd, SIGNAL(finished()), &loop, SLOT(quit()) ); #ifdef HAVE_USABLE_ASSUAN QObject::connect( cmd, SIGNAL(finished()), server, SLOT(enableCryptoCommands()) ); #else Q_UNUSED( server ); #endif splash->showMessage( i18n("Loading certificate cache...") ); cmd->start(); loop.exec(); splash->showMessage( i18n("Certificate cache loaded.") ); } int main( int argc, char** argv ) { { const unsigned int threads = QThreadPool::globalInstance()->maxThreadCount(); QThreadPool::globalInstance()->setMaxThreadCount( qMax( 2U, threads ) ); } AboutData aboutData; KCmdLineArgs::init(argc, argv, &aboutData); KCmdLineArgs::addCmdLineOptions( KleopatraApplication::commandLineOptions() ); KleopatraApplication app; KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); SplashScreen splash; int rc; #ifdef HAVE_USABLE_ASSUAN try { Kleo::UiServer server( args->getOption("uiserver-socket") ); QObject::connect( &server, SIGNAL(startKeyManagerRequested()), &app, SLOT(openOrRaiseMainWindow()) ); QObject::connect( &server, SIGNAL(startConfigDialogRequested()), &app, SLOT(openOrRaiseConfigDialog()) ); #define REGISTER( Command ) server.registerCommandFactory( boost::shared_ptr<Kleo::AssuanCommandFactory>( new Kleo::GenericAssuanCommandFactory<Kleo::Command> ) ) REGISTER( DecryptCommand ); REGISTER( DecryptFilesCommand ); REGISTER( DecryptVerifyFilesCommand ); REGISTER( EchoCommand ); REGISTER( EncryptCommand ); REGISTER( EncryptFilesCommand ); REGISTER( EncryptSignFilesCommand ); REGISTER( PrepEncryptCommand ); REGISTER( SelectCertificateCommand ); REGISTER( SignCommand ); REGISTER( SignEncryptFilesCommand ); REGISTER( SignFilesCommand ); REGISTER( VerifyCommand ); REGISTER( VerifyFilesCommand ); #undef REGISTER server.start(); #endif const bool daemon = args->isSet("daemon"); if ( !daemon ) splash.show(); if ( !selfCheck( splash ) ) return 1; #ifdef HAVE_USABLE_ASSUAN fillKeyCache( &splash, &server ); #else fillKeyCache( &splash, 0 ); #endif app.setIgnoreNewInstance( false ); if ( !daemon ) { app.newInstance(); splash.finish( app.mainWindow() ); } rc = app.exec(); #ifdef HAVE_USABLE_ASSUAN app.setIgnoreNewInstance( true ); QObject::disconnect( &server, SIGNAL(startKeyManagerRequested()), &app, SLOT(openOrRaiseMainWindow()) ); QObject::disconnect( &server, SIGNAL(startConfigDialogRequested()), &app, SLOT(openOrRaiseConfigDialog()) ); server.stop(); server.waitForStopped(); } catch ( const std::exception & e ) { QMessageBox::information( 0, i18n("GPG UI Server Error"), i18n("<qt>The Kleopatra GPG UI Server Module couldn't be initialized.<br/>" "The error given was: <b>%1</b><br/>" "You can use Kleopatra as a certificate manager, but cryptographic plugins that " "rely on a GPG UI Server being present might not work correctly, or at all.</qt>", Qt::escape( QString::fromUtf8( e.what() ) ) )); app.setIgnoreNewInstance( false ); rc = app.exec(); app.setIgnoreNewInstance( true ); } #endif return rc; } <|endoftext|>
<commit_before>/* -*- c++ -*- callback.cpp This file is used by KMail's plugin interface. Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk> KMail is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. KMail is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "config.h" #include "callback.h" #include "kmkernel.h" #include "kmmessage.h" #include <kpimutils/email.h> #include <libkpimidentities/identity.h> #include <libkpimidentities/identitymanager.h> #include "kmmainwin.h" #include "composer.h" #include "kmreaderwin.h" #include "secondarywindow.h" #include <mimelib/enum.h> #include <kinputdialog.h> #include <klocale.h> #include <kdebug.h> #include <kconfiggroup.h> using namespace KMail; Callback::Callback( KMMessage* msg, KMReaderWin* readerWin ) : mMsg( msg ), mReaderWin( readerWin ), mReceiverSet( false ) { } bool Callback::mailICal( const QString& to, const QString iCal, const QString& subject ) const { kDebug(5006) << "Mailing message:\n" << iCal << endl; KMMessage *msg = new KMMessage; msg->initHeader(); msg->setHeaderField( "Content-Type", "text/calendar; method=reply; charset=\"utf-8\"" ); msg->setSubject( subject ); msg->setTo( to ); msg->setBody( iCal.toUtf8() ); msg->setFrom( receiver() ); /* We want the triggering mail to be moved to the trash once this one * has been sent successfully. Set a link header which accomplishes that. */ msg->link( mMsg, MessageStatus::statusDeleted() ); // Outlook will only understand the reply if the From: header is the // same as the To: header of the invitation message. KConfigGroup options( KMKernel::config(), "Groupware" ); if( !options.readEntry( "LegacyMangleFromToHeaders", true ) ) { // Try and match the receiver with an identity const KPIM::Identity& identity = kmkernel->identityManager()->identityForAddress( receiver() ); if( identity != KPIM::Identity::null() ) // Identity found. Use this msg->setFrom( identity.fullEmailAddr() ); msg->setHeaderField("X-KMail-Identity", QString::number( identity.uoid() )); // Remove BCC from identity on ical invitations (https://intevation.de/roundup/kolab/issue474) msg->setBcc( "" ); } KMail::Composer * cWin = KMail::makeComposer(); cWin->setMsg( msg, false /* mayAutoSign */ ); // cWin->setCharset( "", true ); cWin->slotWordWrapToggled( false ); cWin->setSigningAndEncryptionDisabled( true ); if ( options.readEntry( "AutomaticSending", true ) ) { cWin->setAttribute( Qt::WA_DeleteOnClose ); cWin->slotSendNow(); } else { cWin->show(); } return true; } QString Callback::receiver() const { if ( mReceiverSet ) // Already figured this out return mReceiver; mReceiverSet = true; QStringList addrs = KPIMUtils::splitAddressList( mMsg->to() ); int found = 0; for( QStringList::Iterator it = addrs.begin(); it != addrs.end(); ++it ) { if( kmkernel->identityManager()->identityForAddress( *it ) != KPIM::Identity::null() ) { // Ok, this could be us ++found; mReceiver = *it; } } QStringList ccaddrs = KPIMUtils::splitAddressList( mMsg->cc() ); for( QStringList::Iterator it = ccaddrs.begin(); it != ccaddrs.end(); ++it ) { if( kmkernel->identityManager()->identityForAddress( *it ) != KPIM::Identity::null() ) { // Ok, this could be us ++found; mReceiver = *it; } } if( found != 1 ) { bool ok; QString selectMessage; if (found == 0) { selectMessage = i18n("<qt>None of your identities match the " "receiver of this message,<br>please " "choose which of the following addresses " "is yours, if any:"); } else { selectMessage = i18n("<qt>Several of your identities match the " "receiver of this message,<br>please " "choose which of the following addresses " "is yours:"); } mReceiver = KInputDialog::getItem( i18n( "Select Address" ), selectMessage, addrs, 0, false, &ok, kmkernel->mainWin() ); if( !ok ) mReceiver.clear(); } return mReceiver; } void Callback::closeIfSecondaryWindow() const { KMail::SecondaryWindow *window = dynamic_cast<KMail::SecondaryWindow*>( mReaderWin->mainWindow() ); if ( window ) window->close(); } <commit_msg>forward port SVN commit 659861 by winterz:<commit_after>/* -*- c++ -*- callback.cpp This file is used by KMail's plugin interface. Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk> KMail is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. KMail is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "config.h" #include "callback.h" #include "kmkernel.h" #include "kmmessage.h" #include <kpimutils/email.h> #include <libkpimidentities/identity.h> #include <libkpimidentities/identitymanager.h> #include "kmmainwin.h" #include "composer.h" #include "kmreaderwin.h" #include "secondarywindow.h" #include <mimelib/enum.h> #include <kinputdialog.h> #include <klocale.h> #include <kdebug.h> #include <kconfiggroup.h> using namespace KMail; Callback::Callback( KMMessage* msg, KMReaderWin* readerWin ) : mMsg( msg ), mReaderWin( readerWin ), mReceiverSet( false ) { } bool Callback::mailICal( const QString& to, const QString iCal, const QString& subject ) const { kDebug(5006) << "Mailing message:\n" << iCal << endl; KMMessage *msg = new KMMessage; msg->initHeader(); msg->setHeaderField( "Content-Type", "text/calendar; method=reply; charset=\"utf-8\"" ); msg->setSubject( subject ); msg->setTo( to ); msg->setBody( iCal.toUtf8() ); msg->setFrom( receiver() ); /* We want the triggering mail to be moved to the trash once this one * has been sent successfully. Set a link header which accomplishes that. */ msg->link( mMsg, MessageStatus::statusDeleted() ); // Outlook will only understand the reply if the From: header is the // same as the To: header of the invitation message. KConfigGroup options( KMKernel::config(), "Groupware" ); if( !options.readEntry( "LegacyMangleFromToHeaders", true ) ) { // Try and match the receiver with an identity const KPIM::Identity& identity = kmkernel->identityManager()->identityForAddress( receiver() ); if( identity != KPIM::Identity::null() ) // Identity found. Use this msg->setFrom( identity.fullEmailAddr() ); msg->setHeaderField("X-KMail-Identity", QString::number( identity.uoid() )); // Remove BCC from identity on ical invitations (https://intevation.de/roundup/kolab/issue474) msg->setBcc( "" ); } KMail::Composer * cWin = KMail::makeComposer(); cWin->setMsg( msg, false /* mayAutoSign */ ); // cWin->setCharset( "", true ); cWin->slotWordWrapToggled( false ); cWin->setSigningAndEncryptionDisabled( true ); if ( options.readEntry( "AutomaticSending", true ) ) { cWin->setAttribute( Qt::WA_DeleteOnClose ); cWin->slotSendNow(); } else { cWin->show(); } return true; } QString Callback::receiver() const { if ( mReceiverSet ) { // Already figured this out return mReceiver; } mReceiverSet = true; QStringList addrs = KPIMUtils::splitAddressList( mMsg->to() ); int found = 0; for ( QStringList::Iterator it = addrs.begin(); it != addrs.end(); ++it ) { if ( kmkernel->identityManager()->identityForAddress( *it ) != KPIM::Identity::null() ) { // Ok, this could be us ++found; mReceiver = *it; } } QStringList ccaddrs = KPIMUtils::splitAddressList( mMsg->cc() ); for ( QStringList::Iterator it = ccaddrs.begin(); it != ccaddrs.end(); ++it ) { if( kmkernel->identityManager()->identityForAddress( *it ) != KPIM::Identity::null() ) { // Ok, this could be us ++found; mReceiver = *it; } } if ( found != 1 ) { bool ok; QString selectMessage; if ( found == 0 ) { selectMessage = i18n("<qt>None of your identities match the " "receiver of this message,<br>please " "choose which of the following addresses " "is yours, if any:"); } else { selectMessage = i18n("<qt>Several of your identities match the " "receiver of this message,<br>please " "choose which of the following addresses " "is yours:"); } mReceiver = KInputDialog::getItem( i18n( "Select Address" ), selectMessage, addrs+ccaddrs, 0, false, &ok, kmkernel->mainWin() ); if ( !ok ) { mReceiver.clear(); } } return mReceiver; } void Callback::closeIfSecondaryWindow() const { KMail::SecondaryWindow *window = dynamic_cast<KMail::SecondaryWindow*>( mReaderWin->mainWindow() ); if ( window ) { window->close(); } } <|endoftext|>
<commit_before>#pragma once #include <iostream> #include <cmath> #include <vector> #include <array> #include <algorithm> #include "acmacs-base/string.hh" #include "acmacs-base/location.hh" #include "acmacs-base/line.hh" // ---------------------------------------------------------------------- namespace acmacs { namespace detail { using TransformationBase = std::array<double, 16>; constexpr size_t transformation_size = 4; constexpr std::array<size_t, transformation_size> transformation_row_base{0, transformation_size, transformation_size * 2, transformation_size * 3}; } // handles transformation and translation in 2D and 3D class Transformation : public detail::TransformationBase { public: //# double a = 1.0, b = 0.0, c = 0.0, d = 1.0; Transformation() : detail::TransformationBase{1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0} {} Transformation(const Transformation&) = default; Transformation(double a11, double a12, double a21, double a22) : detail::TransformationBase{a11, a12, 0.0, 0.0, a21, a22, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0}, number_of_dimensions{2} {} Transformation& operator=(const Transformation&) = default; Transformation& operator=(Transformation&&) = default; bool operator==(const Transformation& rhs) const { return std::equal(begin(), end(), rhs.begin()); } // float_equal(a, o.a) && float_equal(b, o.b) && float_equal(c, o.c) && float_equal(d, o.d); } bool operator!=(const Transformation& rhs) const { return ! operator==(rhs); } void reset() { operator=(Transformation()); } constexpr double _x(size_t offset) const { return operator[](offset); } constexpr double& _x(size_t offset) { return operator[](offset); } constexpr double _x(size_t row, size_t column) const { return operator[](detail::transformation_row_base[row] + column); } constexpr double& _x(size_t row, size_t column) { return operator[](detail::transformation_row_base[row] + column); } std::vector<double> as_vector() const { switch (number_of_dimensions) { case 2: return {_x(0, 0), _x(0, 1), _x(1, 0), _x(1, 1)}; case 3: return {_x(0, 0), _x(0, 1), _x(0, 2), _x(1, 0), _x(1, 1), _x(1, 2), _x(2, 0), _x(2, 1), _x(2, 2)}; } return {}; } // 2D -------------------------------------------------- constexpr double a() const { return _x(0, 0); } constexpr double& a() { return _x(0, 0); } constexpr double b() const { return _x(0, 1); } constexpr double& b() { return _x(0, 1); } constexpr double c() const { return _x(1, 0); } constexpr double& c() { return _x(1, 0); } constexpr double d() const { return _x(1, 1); } constexpr double& d() { return _x(1, 1); } Transformation& set(double a11, double a12, double a21, double a22) { a() = a11; b() = a12; c() = a21; d() = a22; return *this; } void rotate(double aAngle) { const double cos = std::cos(aAngle); const double sin = std::sin(aAngle); const double r0 = cos * a() + -sin * c(); const double r1 = cos * b() + -sin * d(); c() = sin * a() + cos * c(); d() = sin * b() + cos * d(); a() = r0; b() = r1; } void flip_transformed(double x, double y) { const double x2y2 = x * x - y * y, xy = 2 * x * y; const double r0 = x2y2 * a() + xy * c(); const double r1 = x2y2 * b() + xy * d(); c() = xy * a() + -x2y2 * c(); d() = xy * b() + -x2y2 * d(); a() = r0; b() = r1; } // reflect about a line specified with vector [aX, aY] void flip(double aX, double aY) { // vector [aX, aY] must be first transformed using inversion of this const auto inv = inverse(); const double x = aX * inv.a() + aY * inv.c(); const double y = aX * inv.b() + aY * inv.d(); flip_transformed(x, y); } void multiply_by(const Transformation& t) { const auto r0 = a() * t.a() + b() * t.c(); const auto r1 = a() * t.b() + b() * t.d(); const auto r2 = c() * t.a() + d() * t.c(); const auto r3 = c() * t.b() + d() * t.d(); a() = r0; b() = r1; c() = r2; d() = r3; } Location2D transform(Location2D loc) const { return {loc.x() * a() + loc.y() * c(), loc.x() * b() + loc.y() * d()}; } LineDefinedByEquation transform(LineDefinedByEquation source) const { const auto p1 = transform(Location2D{0, source.intercept()}); const auto p2 = transform(Location2D{1, source.slope() + source.intercept()}); const auto slope = (p2.y() - p1.y()) / (p2.x() - p1.x()); return {slope, p1.y() - slope * p1.x()}; } double determinant() const { return a() * d() - b() * c(); } class singular : public std::exception {}; Transformation inverse() const { const auto deter = determinant(); if (float_zero(deter)) throw singular{}; return {d() / deter, - b() / deter, -c() / deter, a() / deter}; } size_t number_of_dimensions = 2; }; // class Transformation inline std::string to_string(const Transformation& t) { switch (t.number_of_dimensions) { case 2: return ::string::concat("[[", t.a(), ", ", t.b(), "], [", t.c(), ", ", t.d(), "]]"); case 3: return ::string::concat("[[", t._x(0, 0), t._x(0, 1), t._x(0, 2), "], [", t._x(1, 0), t._x(1, 1), t._x(1, 2), "], [", t._x(2, 0), t._x(2, 1), t._x(2, 2), "]]"); } return "[[*invalid number_of_dimensions*]]"; } inline std::ostream& operator << (std::ostream& out, const Transformation& t) { return out << to_string(t); } // ---------------------------------------------------------------------- // (N+1)xN matrix handling transformation in N-dimensional space. The last row is for translation class TransformationTranslation : public std::vector<double> { public: TransformationTranslation(size_t number_of_dimensions) : std::vector<double>((number_of_dimensions + 1) * number_of_dimensions, 0.0), number_of_dimensions_{number_of_dimensions} { for (size_t dim = 0; dim < number_of_dimensions; ++dim) operator()(dim, dim) = 1.0; } TransformationTranslation(const TransformationTranslation&) = default; size_t number_of_dimensions() const { return number_of_dimensions_; } template <typename S> double& operator()(S row, S column) { return operator[](static_cast<size_t>(row) * number_of_dimensions_ + static_cast<size_t>(column)); } template <typename S> double operator()(S row, S column) const { return operator[](static_cast<size_t>(row) * number_of_dimensions_ + static_cast<size_t>(column)); } template <typename S> double& translation(S dimension) { return operator[](number_of_dimensions_ * number_of_dimensions_ + static_cast<size_t>(dimension)); } template <typename S> double translation(S dimension) const { return operator[](number_of_dimensions_ * number_of_dimensions_ + static_cast<size_t>(dimension)); } Transformation transformation() const { return {operator[](0), operator[](1), operator[](2), operator[](3)}; } private: size_t number_of_dimensions_; }; // class TransformationTranslation inline std::string to_string(const TransformationTranslation& t) { std::string result{'['}; auto p = t.cbegin(); for (size_t row = 0; row < (t.number_of_dimensions() + 1); ++row) { result += '['; for (size_t col = 0; col < t.number_of_dimensions(); ++col) { result += to_string(*p); if (col < t.number_of_dimensions()) result += ','; ++p; } result += "],"; } result.back() = ']'; return result; } inline std::ostream& operator << (std::ostream& out, const TransformationTranslation& t) { return out << to_string(t); } } // namespace acmacs // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>acmacs::Transformation refactored<commit_after>#pragma once #include <iostream> #include <cmath> #include <vector> #include <array> #include <algorithm> #include "acmacs-base/string.hh" #include "acmacs-base/location.hh" #include "acmacs-base/line.hh" // ---------------------------------------------------------------------- namespace acmacs { namespace detail { using TransformationBase = std::array<double, 16>; constexpr size_t transformation_size = 4; constexpr std::array<size_t, transformation_size> transformation_row_base{0, transformation_size, transformation_size * 2, transformation_size * 3}; } // handles transformation and translation in 2D and 3D class Transformation : public detail::TransformationBase { public: Transformation(size_t num_dim = 2) : detail::TransformationBase{1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0}, number_of_dimensions{num_dim} {} Transformation(const Transformation&) = default; Transformation(double a11, double a12, double a21, double a22) : detail::TransformationBase{a11, a12, 0.0, 0.0, a21, a22, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0}, number_of_dimensions{2} {} Transformation& operator=(const Transformation&) = default; Transformation& operator=(Transformation&&) = default; bool operator==(const Transformation& rhs) const { return std::equal(begin(), end(), rhs.begin()); } bool operator!=(const Transformation& rhs) const { return ! operator==(rhs); } void reset() { operator=(Transformation()); } constexpr double _x(size_t offset) const { return operator[](offset); } constexpr double& _x(size_t offset) { return operator[](offset); } constexpr double _x(size_t row, size_t column) const { return operator[](detail::transformation_row_base[row] + column); } constexpr double& _x(size_t row, size_t column) { return operator[](detail::transformation_row_base[row] + column); } std::vector<double> as_vector() const { switch (number_of_dimensions) { case 2: return {_x(0, 0), _x(0, 1), _x(1, 0), _x(1, 1)}; case 3: return {_x(0, 0), _x(0, 1), _x(0, 2), _x(1, 0), _x(1, 1), _x(1, 2), _x(2, 0), _x(2, 1), _x(2, 2)}; } return {}; } // 2D -------------------------------------------------- constexpr double a() const { return _x(0, 0); } constexpr double& a() { return _x(0, 0); } constexpr double b() const { return _x(0, 1); } constexpr double& b() { return _x(0, 1); } constexpr double c() const { return _x(1, 0); } constexpr double& c() { return _x(1, 0); } constexpr double d() const { return _x(1, 1); } constexpr double& d() { return _x(1, 1); } Transformation& set(double a11, double a12, double a21, double a22) { a() = a11; b() = a12; c() = a21; d() = a22; return *this; } void rotate(double aAngle) { const double cos = std::cos(aAngle); const double sin = std::sin(aAngle); const double r0 = cos * a() + -sin * c(); const double r1 = cos * b() + -sin * d(); c() = sin * a() + cos * c(); d() = sin * b() + cos * d(); a() = r0; b() = r1; } void flip_transformed(double x, double y) { const double x2y2 = x * x - y * y, xy = 2 * x * y; const double r0 = x2y2 * a() + xy * c(); const double r1 = x2y2 * b() + xy * d(); c() = xy * a() + -x2y2 * c(); d() = xy * b() + -x2y2 * d(); a() = r0; b() = r1; } // reflect about a line specified with vector [aX, aY] void flip(double aX, double aY) { // vector [aX, aY] must be first transformed using inversion of this const auto inv = inverse(); const double x = aX * inv.a() + aY * inv.c(); const double y = aX * inv.b() + aY * inv.d(); flip_transformed(x, y); } void multiply_by(const Transformation& t) { const auto r0 = a() * t.a() + b() * t.c(); const auto r1 = a() * t.b() + b() * t.d(); const auto r2 = c() * t.a() + d() * t.c(); const auto r3 = c() * t.b() + d() * t.d(); a() = r0; b() = r1; c() = r2; d() = r3; } Location2D transform(Location2D loc) const { return {loc.x() * a() + loc.y() * c(), loc.x() * b() + loc.y() * d()}; } LineDefinedByEquation transform(LineDefinedByEquation source) const { const auto p1 = transform(Location2D{0, source.intercept()}); const auto p2 = transform(Location2D{1, source.slope() + source.intercept()}); const auto slope = (p2.y() - p1.y()) / (p2.x() - p1.x()); return {slope, p1.y() - slope * p1.x()}; } double determinant() const { return a() * d() - b() * c(); } class singular : public std::exception {}; Transformation inverse() const { const auto deter = determinant(); if (float_zero(deter)) throw singular{}; return {d() / deter, - b() / deter, -c() / deter, a() / deter}; } size_t number_of_dimensions = 2; }; // class Transformation inline std::string to_string(const Transformation& t) { switch (t.number_of_dimensions) { case 2: return ::string::concat("[[", t.a(), ", ", t.b(), "], [", t.c(), ", ", t.d(), "]]"); case 3: return ::string::concat("[[", t._x(0, 0), t._x(0, 1), t._x(0, 2), "], [", t._x(1, 0), t._x(1, 1), t._x(1, 2), "], [", t._x(2, 0), t._x(2, 1), t._x(2, 2), "]]"); } return "[[*invalid number_of_dimensions*]]"; } inline std::ostream& operator << (std::ostream& out, const Transformation& t) { return out << to_string(t); } // ---------------------------------------------------------------------- // (N+1)xN matrix handling transformation in N-dimensional space. The last row is for translation class TransformationTranslation : public std::vector<double> { public: TransformationTranslation(size_t number_of_dimensions) : std::vector<double>((number_of_dimensions + 1) * number_of_dimensions, 0.0), number_of_dimensions_{number_of_dimensions} { for (size_t dim = 0; dim < number_of_dimensions; ++dim) operator()(dim, dim) = 1.0; } TransformationTranslation(const TransformationTranslation&) = default; size_t number_of_dimensions() const { return number_of_dimensions_; } template <typename S> double& operator()(S row, S column) { return operator[](static_cast<size_t>(row) * number_of_dimensions_ + static_cast<size_t>(column)); } template <typename S> double operator()(S row, S column) const { return operator[](static_cast<size_t>(row) * number_of_dimensions_ + static_cast<size_t>(column)); } template <typename S> double& translation(S dimension) { return operator[](number_of_dimensions_ * number_of_dimensions_ + static_cast<size_t>(dimension)); } template <typename S> double translation(S dimension) const { return operator[](number_of_dimensions_ * number_of_dimensions_ + static_cast<size_t>(dimension)); } Transformation transformation() const { return {operator[](0), operator[](1), operator[](2), operator[](3)}; } private: size_t number_of_dimensions_; }; // class TransformationTranslation inline std::string to_string(const TransformationTranslation& t) { std::string result{'['}; auto p = t.cbegin(); for (size_t row = 0; row < (t.number_of_dimensions() + 1); ++row) { result += '['; for (size_t col = 0; col < t.number_of_dimensions(); ++col) { result += to_string(*p); if (col < t.number_of_dimensions()) result += ','; ++p; } result += "],"; } result.back() = ']'; return result; } inline std::ostream& operator << (std::ostream& out, const TransformationTranslation& t) { return out << to_string(t); } } // namespace acmacs // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>// KMail startup and initialize code // Author: Stefan Taferner <taferner@alpin.or.at> #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <sys/types.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <kuniqueapplication.h> #include <klocale.h> #include <kglobal.h> #include <ksimpleconfig.h> #include <kstandarddirs.h> #include <knotifyclient.h> #include <dcopclient.h> #include <kcrash.h> #include "kmkernel.h" //control center #undef Status // stupid X headers #include "kmailIface_stub.h" // to call control center of master kmail #include <kaboutdata.h> #include "kmversion.h" // OLD about text. This is horrbly outdated. /*const char* aboutText = "KMail [" KMAIL_VERSION "] by\n\n" "Stefan Taferner <taferner@kde.org>,\n" "Markus Wbben <markus.wuebben@kde.org>\n\n" "based on the work of:\n" "Lynx <lynx@topaz.hknet.com>,\n" "Stephan Meyer <Stephan.Meyer@pobox.com>,\n" "and the above authors.\n\n" "This program is covered by the GPL.\n\n" "Please send bugreports to taferner@kde.org"; */ static KCmdLineOptions kmoptions[] = { { "s", 0 , 0 }, { "subject <subject>", I18N_NOOP("Set subject of msg."), 0 }, { "c", 0 , 0 }, { "cc <address>", I18N_NOOP("Send CC: to 'address'."), 0 }, { "b", 0 , 0 }, { "bcc <address>", I18N_NOOP("Send BCC: to 'addres'."), 0 }, { "h", 0 , 0 }, { "header <header>", I18N_NOOP("Add 'header' to msg."), 0 }, { "msg <file>", I18N_NOOP("Read msg-body from 'file'."), 0 }, { "body <text>", I18N_NOOP("Set body of msg."), 0 }, { "attach <url>", I18N_NOOP("Add an attachment to the mail, this can be repeated"), 0 }, { "check", I18N_NOOP("Check for new mail only."), 0 }, { "composer", I18N_NOOP("Open only composer window."), 0 }, { "+[address]", I18N_NOOP("Send msg to 'address'."), 0 }, // { "+[file]", I18N_NOOP("Show message from file 'file'."), 0 }, { 0, 0, 0} }; //----------------------------------------------------------------------------- extern "C" { static void setSignalHandler(void (*handler)(int)); // Crash recovery signal handler static void signalHandler(int sigId) { setSignalHandler(SIG_DFL); fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId); // try to cleanup all windows kernel->dumpDeadLetters(); ::exit(-1); // } // Crash recovery signal handler static void crashHandler(int sigId) { setSignalHandler(SIG_DFL); fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId); // try to cleanup all windows kernel->dumpDeadLetters(); // Return to DrKonqi. } //----------------------------------------------------------------------------- static void setSignalHandler(void (*handler)(int)) { signal(SIGKILL, handler); signal(SIGTERM, handler); signal(SIGHUP, handler); KCrash::setEmergencySaveFunction(crashHandler); } } //----------------------------------------------------------------------------- class KMailApplication : public KUniqueApplication { public: KMailApplication() : KUniqueApplication() { }; virtual int newInstance(); void commitData(QSessionManager& sm) { kernel->notClosedByUser(); KApplication::commitData( sm ); } }; int KMailApplication::newInstance() { QString to, cc, bcc, subj, body; KURL messageFile = QString::null; KURL::List attachURLs; bool mailto = false; bool checkMail = false; //bool viewOnly = false; // process args: KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if (args->getOption("subject")) { mailto = true; subj = QString::fromLocal8Bit(args->getOption("subject")); } if (args->getOption("cc")) { mailto = true; cc = QString::fromLocal8Bit(args->getOption("cc")); } if (args->getOption("bcc")) { mailto = true; bcc = QString::fromLocal8Bit(args->getOption("bcc")); } if (args->getOption("msg")) { mailto = true; messageFile = QString::fromLocal8Bit(args->getOption("msg")); } if (args->getOption("body")) { mailto = true; body = QString::fromLocal8Bit(args->getOption("body")); } QCStringList attachList = args->getOptionList("attach"); if (!attachList.isEmpty()) { mailto = true; for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it ) if ( !(*it).isEmpty() ) attachURLs += KURL( QString::fromLocal8Bit( *it ) ); } if (args->isSet("composer")) mailto = true; if (args->isSet("check")) checkMail = true; for(int i= 0; i < args->count(); i++) { if (!to.isEmpty()) to += ", "; if (strncasecmp(args->arg(i),"mailto:",7)==0) to += args->arg(i); else to += args->arg(i); mailto = true; } args->clear(); if (!kernel->firstInstance() || !kapp->isRestored()) kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs); kernel->setFirstInstance(FALSE); return 0; } int main(int argc, char *argv[]) { // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging // a bit harder: You should pass --nofork as commandline argument when using // a debugger. In gdb you can do this by typing "set args --nofork" before // typing "run". KAboutData about("kmail", I18N_NOOP("KMail"), KMAIL_VERSION, I18N_NOOP("The KDE Email client."), KAboutData::License_GPL, I18N_NOOP("(c) 1997-2002, The KMail developers"), 0, "http://kmail.kde.org"); about.addAuthor( "Michael H\303\244ckel", I18N_NOOP("Current maintainer"), "haeckel@kde.org" ); about.addAuthor( "Don Sanders", I18N_NOOP("Core developer and former maintainer"), "sanders@kde.org" ); about.addAuthor( "Stefan Taferner ", I18N_NOOP("Original author"), "taferner@kde.org" ); about.addAuthor( "Ingo Kl\303\266cker", I18N_NOOP("Encryption"), "ingo.kloecker@epost.de" ); about.addAuthor( "Marc Mutz", I18N_NOOP("Core developer"), "mutz@kde.org" ); about.addAuthor( "Daniel Naber", I18N_NOOP("Documentation"), "daniel.naber@t-online.de" ); about.addAuthor( "Andreas Gungl", I18N_NOOP("Encryption"), "a.gungl@gmx.de" ); about.addAuthor( "Toyohiro Asukai", 0, "toyohiro@ksmplus.com" ); about.addAuthor( "Waldo Bastian", 0, "bastian@kde.org" ); about.addAuthor( "Carsten Burghardt", 0, "carsten.burghardt@web.de" ); about.addAuthor( "Steven Brown", 0, "swbrown@ucsd.edu" ); about.addAuthor( "Cristi Dumitrescu", 0, "cristid@chip.ro" ); about.addAuthor( "Philippe Fremy", 0, "pfremy@chez.com" ); about.addAuthor( "Kurt Granroth", 0, "granroth@kde.org" ); about.addAuthor( "Heiko Hund", 0, "heiko@ist.eigentlich.net" ); about.addAuthor( "Igor Janssen", 0, "rm@linux.ru.net" ); about.addAuthor( "Matt Johnston", 0, "matt@caifex.org" ); about.addAuthor( "Christer Kaivo-oja", 0, "whizkid@telia.com" ); about.addAuthor( "Lars Knoll", 0, "knoll@kde.org" ); about.addAuthor( "J. Nick Koston", 0, "bdraco@darkorb.net" ); about.addAuthor( "Stephan Kulow", 0, "coolo@kde.org" ); about.addAuthor( "Guillaume Laurent", 0, "glaurent@telegraph-road.org" ); about.addAuthor( "Sam Magnuson", 0, "sam@trolltech.com" ); about.addAuthor( "Laurent Montel", 0, "lmontel@mandrakesoft.com" ); about.addAuthor( "Matt Newell", 0, "newellm@proaxis.com" ); about.addAuthor( "Denis Perchine", 0, "dyp@perchine.com" ); about.addAuthor( "Samuel Penn", 0, "sam@bifrost.demon.co.uk" ); about.addAuthor( "Carsten Pfeiffer", 0, "pfeiffer@kde.org" ); about.addAuthor( "Sven Radej", 0, "radej@kde.org" ); about.addAuthor( "Mark Roberts", 0, "mark@taurine.demon.co.uk" ); about.addAuthor( "Wolfgang Rohdewald", 0, "wrohdewald@dplanet.ch" ); about.addAuthor( "Espen Sand", 0, "espen@kde.org" ); about.addAuthor( "Jan Simonson", 0, "jan@simonson.pp.se" ); about.addAuthor( "George Staikos", 0, "staikos@kde.org" ); about.addAuthor( "Jason Stephenson", 0, "panda@mis.net" ); about.addAuthor( "Jacek Stolarczyk", 0, "jacek@mer.chemia.polsl.gliwice.pl" ); about.addAuthor( "Roberto S. Teixeira", 0, "maragato@kde.org" ); about.addAuthor( "Ronen Tzur", 0, "rtzur@shani.net" ); about.addAuthor( "Mario Weilguni", 0, "mweilguni@sime.com" ); about.addAuthor( "Wynn Wilkes", 0, "wynnw@calderasystems.com" ); about.addAuthor( "Robert D. Williams", 0, "rwilliams@kde.org" ); about.addAuthor( "Markus Wuebben", 0, "markus.wuebben@kde.org" ); about.addAuthor( "Thorsten Zachmann", 0, "t.zachmann@zagge.de" ); about.addAuthor( "Karl-Heinz Zimmer", 0, "khz@kde.org" ); KCmdLineArgs::init(argc, argv, &about); KCmdLineArgs::addCmdLineOptions( kmoptions ); // Add kmail options if (!KMailApplication::start()) return 0; KMailApplication app; KGlobal::locale()->insertCatalogue("libkdenetwork"); KSimpleConfig config(locateLocal("appdata", "lock")); int oldPid = config.readNumEntry("pid", -1); if (oldPid != -1 && kill(oldPid, 0) != -1) { QString msg = i18n("Only one instance of KMail can be run at " "any one time. It is already running on a different display " "with PID %1.").arg(oldPid); KNotifyClient::userEvent( msg, KNotifyClient::Messagebox, KNotifyClient::Error ); fprintf(stderr, "*** KMail is already running with PID %d\n", oldPid); return 1; } config.writeEntry("pid", getpid()); config.sync(); kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet //local, do the init KMKernel kmailKernel; kmailKernel.init(); kapp->dcopClient()->setDefaultObject( kmailKernel.objId() ); // and session management kmailKernel.doSessionManagement(); // any dead letters? kmailKernel.recoverDeadLetters(); setSignalHandler(signalHandler); kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests. // Go! int ret = kapp->exec(); // clean up kmailKernel.cleanup(); config.writeEntry("pid", -1); config.sync(); return ret; } <commit_msg>Enhanced lock file handling, *with* comments<commit_after>// KMail startup and initialize code // Author: Stefan Taferner <taferner@alpin.or.at> #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <errno.h> #include <sys/types.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <kuniqueapplication.h> #include <klocale.h> #include <kglobal.h> #include <ksimpleconfig.h> #include <kstandarddirs.h> #include <knotifyclient.h> #include <dcopclient.h> #include <kcrash.h> #include "kmkernel.h" //control center #undef Status // stupid X headers #include "kmailIface_stub.h" // to call control center of master kmail #include <kaboutdata.h> #include "kmversion.h" // OLD about text. This is horrbly outdated. /*const char* aboutText = "KMail [" KMAIL_VERSION "] by\n\n" "Stefan Taferner <taferner@kde.org>,\n" "Markus Wbben <markus.wuebben@kde.org>\n\n" "based on the work of:\n" "Lynx <lynx@topaz.hknet.com>,\n" "Stephan Meyer <Stephan.Meyer@pobox.com>,\n" "and the above authors.\n\n" "This program is covered by the GPL.\n\n" "Please send bugreports to taferner@kde.org"; */ static KCmdLineOptions kmoptions[] = { { "s", 0 , 0 }, { "subject <subject>", I18N_NOOP("Set subject of msg."), 0 }, { "c", 0 , 0 }, { "cc <address>", I18N_NOOP("Send CC: to 'address'."), 0 }, { "b", 0 , 0 }, { "bcc <address>", I18N_NOOP("Send BCC: to 'addres'."), 0 }, { "h", 0 , 0 }, { "header <header>", I18N_NOOP("Add 'header' to msg."), 0 }, { "msg <file>", I18N_NOOP("Read msg-body from 'file'."), 0 }, { "body <text>", I18N_NOOP("Set body of msg."), 0 }, { "attach <url>", I18N_NOOP("Add an attachment to the mail, this can be repeated"), 0 }, { "check", I18N_NOOP("Check for new mail only."), 0 }, { "composer", I18N_NOOP("Open only composer window."), 0 }, { "+[address]", I18N_NOOP("Send msg to 'address'."), 0 }, // { "+[file]", I18N_NOOP("Show message from file 'file'."), 0 }, { 0, 0, 0} }; //----------------------------------------------------------------------------- extern "C" { static void setSignalHandler(void (*handler)(int)); // Crash recovery signal handler static void signalHandler(int sigId) { setSignalHandler(SIG_DFL); fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId); // try to cleanup all windows kernel->dumpDeadLetters(); ::exit(-1); // } // Crash recovery signal handler static void crashHandler(int sigId) { setSignalHandler(SIG_DFL); fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId); // try to cleanup all windows kernel->dumpDeadLetters(); // Return to DrKonqi. } //----------------------------------------------------------------------------- static void setSignalHandler(void (*handler)(int)) { signal(SIGKILL, handler); signal(SIGTERM, handler); signal(SIGHUP, handler); KCrash::setEmergencySaveFunction(crashHandler); } } //----------------------------------------------------------------------------- class KMailApplication : public KUniqueApplication { public: KMailApplication() : KUniqueApplication() { }; virtual int newInstance(); void commitData(QSessionManager& sm) { kernel->notClosedByUser(); KApplication::commitData( sm ); } }; int KMailApplication::newInstance() { QString to, cc, bcc, subj, body; KURL messageFile = QString::null; KURL::List attachURLs; bool mailto = false; bool checkMail = false; //bool viewOnly = false; // process args: KCmdLineArgs *args = KCmdLineArgs::parsedArgs(); if (args->getOption("subject")) { mailto = true; subj = QString::fromLocal8Bit(args->getOption("subject")); } if (args->getOption("cc")) { mailto = true; cc = QString::fromLocal8Bit(args->getOption("cc")); } if (args->getOption("bcc")) { mailto = true; bcc = QString::fromLocal8Bit(args->getOption("bcc")); } if (args->getOption("msg")) { mailto = true; messageFile = QString::fromLocal8Bit(args->getOption("msg")); } if (args->getOption("body")) { mailto = true; body = QString::fromLocal8Bit(args->getOption("body")); } QCStringList attachList = args->getOptionList("attach"); if (!attachList.isEmpty()) { mailto = true; for ( QCStringList::Iterator it = attachList.begin() ; it != attachList.end() ; ++it ) if ( !(*it).isEmpty() ) attachURLs += KURL( QString::fromLocal8Bit( *it ) ); } if (args->isSet("composer")) mailto = true; if (args->isSet("check")) checkMail = true; for(int i= 0; i < args->count(); i++) { if (!to.isEmpty()) to += ", "; if (strncasecmp(args->arg(i),"mailto:",7)==0) to += args->arg(i); else to += args->arg(i); mailto = true; } args->clear(); if (!kernel->firstInstance() || !kapp->isRestored()) kernel->action (mailto, checkMail, to, cc, bcc, subj, body, messageFile, attachURLs); kernel->setFirstInstance(FALSE); return 0; } namespace { QString getMyHostName(void) { char hostNameC[256]; // null terminate this C string hostNameC[255] = 0; // set the string to 0 length if gethostname fails if(gethostname(hostNameC, 255)) hostNameC[0] = 0; return QString::fromLocal8Bit(hostNameC); } } int main(int argc, char *argv[]) { // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging // a bit harder: You should pass --nofork as commandline argument when using // a debugger. In gdb you can do this by typing "set args --nofork" before // typing "run". KAboutData about("kmail", I18N_NOOP("KMail"), KMAIL_VERSION, I18N_NOOP("The KDE Email client."), KAboutData::License_GPL, I18N_NOOP("(c) 1997-2002, The KMail developers"), 0, "http://kmail.kde.org"); about.addAuthor( "Michael H\303\244ckel", I18N_NOOP("Current maintainer"), "haeckel@kde.org" ); about.addAuthor( "Don Sanders", I18N_NOOP("Core developer and former maintainer"), "sanders@kde.org" ); about.addAuthor( "Stefan Taferner ", I18N_NOOP("Original author"), "taferner@kde.org" ); about.addAuthor( "Ingo Kl\303\266cker", I18N_NOOP("Encryption"), "ingo.kloecker@epost.de" ); about.addAuthor( "Marc Mutz", I18N_NOOP("Core developer"), "mutz@kde.org" ); about.addAuthor( "Daniel Naber", I18N_NOOP("Documentation"), "daniel.naber@t-online.de" ); about.addAuthor( "Andreas Gungl", I18N_NOOP("Encryption"), "a.gungl@gmx.de" ); about.addAuthor( "Toyohiro Asukai", 0, "toyohiro@ksmplus.com" ); about.addAuthor( "Waldo Bastian", 0, "bastian@kde.org" ); about.addAuthor( "Carsten Burghardt", 0, "carsten.burghardt@web.de" ); about.addAuthor( "Steven Brown", 0, "swbrown@ucsd.edu" ); about.addAuthor( "Cristi Dumitrescu", 0, "cristid@chip.ro" ); about.addAuthor( "Philippe Fremy", 0, "pfremy@chez.com" ); about.addAuthor( "Kurt Granroth", 0, "granroth@kde.org" ); about.addAuthor( "Heiko Hund", 0, "heiko@ist.eigentlich.net" ); about.addAuthor( "Igor Janssen", 0, "rm@linux.ru.net" ); about.addAuthor( "Matt Johnston", 0, "matt@caifex.org" ); about.addAuthor( "Christer Kaivo-oja", 0, "whizkid@telia.com" ); about.addAuthor( "Lars Knoll", 0, "knoll@kde.org" ); about.addAuthor( "J. Nick Koston", 0, "bdraco@darkorb.net" ); about.addAuthor( "Stephan Kulow", 0, "coolo@kde.org" ); about.addAuthor( "Guillaume Laurent", 0, "glaurent@telegraph-road.org" ); about.addAuthor( "Sam Magnuson", 0, "sam@trolltech.com" ); about.addAuthor( "Laurent Montel", 0, "lmontel@mandrakesoft.com" ); about.addAuthor( "Matt Newell", 0, "newellm@proaxis.com" ); about.addAuthor( "Denis Perchine", 0, "dyp@perchine.com" ); about.addAuthor( "Samuel Penn", 0, "sam@bifrost.demon.co.uk" ); about.addAuthor( "Carsten Pfeiffer", 0, "pfeiffer@kde.org" ); about.addAuthor( "Sven Radej", 0, "radej@kde.org" ); about.addAuthor( "Mark Roberts", 0, "mark@taurine.demon.co.uk" ); about.addAuthor( "Wolfgang Rohdewald", 0, "wrohdewald@dplanet.ch" ); about.addAuthor( "Espen Sand", 0, "espen@kde.org" ); about.addAuthor( "Jan Simonson", 0, "jan@simonson.pp.se" ); about.addAuthor( "George Staikos", 0, "staikos@kde.org" ); about.addAuthor( "Jason Stephenson", 0, "panda@mis.net" ); about.addAuthor( "Jacek Stolarczyk", 0, "jacek@mer.chemia.polsl.gliwice.pl" ); about.addAuthor( "Roberto S. Teixeira", 0, "maragato@kde.org" ); about.addAuthor( "Ronen Tzur", 0, "rtzur@shani.net" ); about.addAuthor( "Mario Weilguni", 0, "mweilguni@sime.com" ); about.addAuthor( "Wynn Wilkes", 0, "wynnw@calderasystems.com" ); about.addAuthor( "Robert D. Williams", 0, "rwilliams@kde.org" ); about.addAuthor( "Markus Wuebben", 0, "markus.wuebben@kde.org" ); about.addAuthor( "Thorsten Zachmann", 0, "t.zachmann@zagge.de" ); about.addAuthor( "Karl-Heinz Zimmer", 0, "khz@kde.org" ); KCmdLineArgs::init(argc, argv, &about); KCmdLineArgs::addCmdLineOptions( kmoptions ); // Add kmail options if (!KMailApplication::start()) return 0; KMailApplication app; KGlobal::locale()->insertCatalogue("libkdenetwork"); // Check and create a lock file to prevent concurrent access to kmail files const QString lockLocation = locateLocal("appdata", "lock"); KSimpleConfig config(lockLocation); int oldPid = config.readNumEntry("pid", -1); const QString oldHostName = config.readEntry("hostname"); const QString hostName = getMyHostName(); // proceed if there is no lock at present if (oldPid != -1 && // proceed if the lock is our pid, or if the lock is from the same host oldPid != getpid() && hostName != oldHostName && // proceed if the pid doesn't exist (kill(oldPid, 0) != -1 || errno != ESRCH)) { QString msg = i18n("Only one instance of KMail can be run at " "any one time. It is already running on a different display " "with PID %1 on host %2 according to the lock file located " "at %3").arg(oldPid).arg(oldHostName).arg(lockLocation); KNotifyClient::userEvent( msg, KNotifyClient::Messagebox, KNotifyClient::Error ); fprintf(stderr, "*** KMail is already running with PID %d on host %s\n", oldPid, oldHostName.local8Bit().data()); return 1; } config.writeEntry("pid", getpid()); config.writeEntry("hostname", hostName); config.sync(); kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet //local, do the init KMKernel kmailKernel; kmailKernel.init(); kapp->dcopClient()->setDefaultObject( kmailKernel.objId() ); // and session management kmailKernel.doSessionManagement(); // any dead letters? kmailKernel.recoverDeadLetters(); setSignalHandler(signalHandler); kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests. // Go! int ret = kapp->exec(); // clean up kmailKernel.cleanup(); config.writeEntry("pid", -1); config.sync(); return ret; } <|endoftext|>
<commit_before>/* * Copyright (c) 2008 The Hewlett-Packard Development Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __BASE_FLAGS_HH__ #define __BASE_FLAGS_HH__ #include <type_traits> template <typename T> class Flags { private: static_assert(std::is_unsigned<T>::value, "Flag type must be unsigned"); T _flags; public: typedef T Type; /** * @ingroup api_flags * @{ */ Flags() : _flags(0) {} Flags(Type flags) : _flags(flags) {} /** @} */ // end of api_flags /** * @ingroup api_flags */ operator const Type() const { return _flags; } /** * @ingroup api_flags */ template <typename U> const Flags<T> & operator=(const Flags<U> &flags) { _flags = flags._flags; return *this; } /** * @ingroup api_flags */ const Flags<T> & operator=(T flags) { _flags = flags; return *this; } /** * @ingroup api_flags * @{ */ bool isSet() const { return _flags; } bool isSet(Type flags) const { return (_flags & flags); } bool allSet() const { return !(~_flags); } bool allSet(Type flags) const { return (_flags & flags) == flags; } bool noneSet() const { return _flags == 0; } bool noneSet(Type flags) const { return (_flags & flags) == 0; } void clear() { _flags = 0; } void clear(Type flags) { _flags &= ~flags; } void set(Type flags) { _flags |= flags; } void set(Type f, bool val) { _flags = (_flags & ~f) | (val ? f : 0); } void update(Type flags, Type mask) { _flags = (_flags & ~mask) | (flags & mask); } /** @} */ // end of api_flags }; #endif // __BASE_FLAGS_HH__ <commit_msg>base: Remove Flags<U> assignment<commit_after>/* * Copyright (c) 2008 The Hewlett-Packard Development Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __BASE_FLAGS_HH__ #define __BASE_FLAGS_HH__ #include <type_traits> template <typename T> class Flags { private: static_assert(std::is_unsigned<T>::value, "Flag type must be unsigned"); T _flags; public: typedef T Type; /** * @ingroup api_flags * @{ */ Flags() : _flags(0) {} Flags(Type flags) : _flags(flags) {} /** @} */ // end of api_flags /** * @ingroup api_flags */ operator const Type() const { return _flags; } /** * @ingroup api_flags */ const Flags<T> & operator=(T flags) { _flags = flags; return *this; } /** * @ingroup api_flags * @{ */ bool isSet() const { return _flags; } bool isSet(Type flags) const { return (_flags & flags); } bool allSet() const { return !(~_flags); } bool allSet(Type flags) const { return (_flags & flags) == flags; } bool noneSet() const { return _flags == 0; } bool noneSet(Type flags) const { return (_flags & flags) == 0; } void clear() { _flags = 0; } void clear(Type flags) { _flags &= ~flags; } void set(Type flags) { _flags |= flags; } void set(Type f, bool val) { _flags = (_flags & ~f) | (val ? f : 0); } void update(Type flags, Type mask) { _flags = (_flags & ~mask) | (flags & mask); } /** @} */ // end of api_flags }; #endif // __BASE_FLAGS_HH__ <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Kaveh Vahedipour //////////////////////////////////////////////////////////////////////////////// #include "State.h" #include <chrono> #include <thread> using namespace arangodb::consensus; State::State() {} State::~State() { save(); } std::vector<size_t> State::log (query_t const& query, term_t term, id_t lid, size_t size) { MUTEX_LOCKER(mutexLocker, _logLock); index_t idx = _log.end().index+1; _log.push_back(idx, term, lid, query.toString(), std::vector<bool>(size)); } void State::log (query_t const& query, index_t idx, term_t term, id_t lid, size_t size) { MUTEX_LOCKER(mutexLocker, _logLock); _log.push_back(idx, term, lid, query.toString(), std::vector<bool>(size)); } void State::confirm (id_t id, index_t index) { MUTEX_LOCKER(mutexLocker, _logLock); _log[index][id] = true; } bool findit (index_t index, term_t term) { auto i = std::begin(_log); while (i != std::end(_log)) { // Find entry matching index and term if ((*i).index == index) { if ((*i).term == term) { return true; } else if ((*i).term < term) { // If an existing entry conflicts with a new one (same index // but different terms), delete the existing entry and all that // follow it (§5.3) _log.erase(i, _log.end()); return true; } } } return false; } bool save (std::string const& ep) {}; bool load (std::string const& ep) {}; <commit_msg>agency on<commit_after>//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Kaveh Vahedipour //////////////////////////////////////////////////////////////////////////////// #include "State.h" #include <chrono> #include <thread> using namespace arangodb::consensus; State::State() {} State::~State() { save(); } //Leader std::vector<index_t> State::log (query_t const& query, term_t term, id_t lid, size_t size) { MUTEX_LOCKER(mutexLocker, _logLock); std::vector<index_t> idx; Builder builder; for (size_t i = 0; i < query->slice().length()) { idx.push_back(_log.end().index+1); _log.push_back(idx[i], term, lid, query.toString(), std::vector<bool>(size)); builder.add("query", qyery->Slice()); builder.add("idx", Value(term)); builder.add("term", Value(term)); builder.add("leaderID", Value(lid)); builder.close(); } save (builder.slice()); return idx; } //Leader void State::log (query_t const& query, std::vector<index_t> cont& idx, term_t term, id_t lid, size_t size) { MUTEX_LOCKER(mutexLocker, _logLock); Builder builder; for (size_t i = 0; i < query->slice().length()) { _log.push_back(idx[i], term, lid, query.toString(), std::vector<bool>(size)); builder.add("query", qyery->Slice()); builder.add("idx", Value(term)); builder.add("term", Value(term)); builder.add("leaderID", Value(lid)); builder.close(); } save (builder.slice()); } void State::log (query_t const& query, index_t idx, term_t term, id_t lid, size_t size) { MUTEX_LOCKER(mutexLocker, _logLock); _log.push_back(idx, term, lid, query.toString(), std::vector<bool>(size)); } void State::confirm (id_t id, index_t index) { MUTEX_LOCKER(mutexLocker, _logLock); _log[index][id] = true; } bool findit (index_t index, term_t term) { auto i = std::begin(_log); while (i != std::end(_log)) { // Find entry matching index and term if ((*i).index == index) { if ((*i).term == term) { return true; } else if ((*i).term < term) { // If an existing entry conflicts with a new one (same index // but different terms), delete the existing entry and all that // follow it (§5.3) _log.erase(i, _log.end()); return true; } } } return false; } bool save (std::string const& ep) { // Persist to arango db }; load_ret_t load (std::string const& ep) { // Read all from arango db return load_ret_t (currentTerm, votedFor) }; <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of the Mula project * Copyright (c) Opera Wang <wangvisual AT sohu DOT com> * Copyright (c) 2011 Laszlo Papp <lpapp@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* http://www.merriampark.com/ld.htm What is Levenshtein Distance? Levenshtein distance (LD) is a measure of the similarity between two strings, which we will refer to as the source string (s) and the target string (t). The distance is the number of deletions, insertions, or substitutions required to transform s into t. For example, * If s is "test" and t is "test", then LD(s,t) = 0, because no transformations are needed. The strings are already identical. * If s is "test" and t is "tent", then LD(s,t) = 1, because one substitution (change "s" to "n") is sufficient to transform s into t. The greater the Levenshtein distance, the more different the strings are. Levenshtein distance is named after the Russian scientist Vladimir Levenshtein, who devised the algorithm in 1965. If you can't spell or pronounce Levenshtein, the metric is also sometimes called edit distance. The Levenshtein distance algorithm has been used in: * Spell checking * Speech recognition * DNA analysis * Plagiarism detection */ #include "distance.h" #include <stdlib.h> #include <QtCore/QString> #define OPTIMIZE_ED /* Cover transposition, in addition to deletion, insertion and substitution. This step is taken from: Berghel, Hal ; Roach, David : "An Extension of Ukkonen's Enhanced Dynamic Programming ASM Algorithm" (http://www.acm.org/~hlb/publications/asm/asm.html) */ #define COVER_TRANSPOSITION /****************************************/ /*Implementation of Levenshtein distance*/ /****************************************/ EditDistance::EditDistance() { currentelements = 2500; // It's enough for most conditions :-) d = (int*)malloc(sizeof(int) * currentelements); } EditDistance::~EditDistance() { // printf("size:%d\n",currentelements); if (d) free(d); } #ifdef OPTIMIZE_ED int EditDistance::calEditDistance(QString s, QString t, const int limit) /*Compute levenshtein distance between s and t, this is using QUICK algorithm*/ { int n = 0; int m = 0; int iLenDif; int k; int i = 0; int j; int cost; // Remove leftmost matching portion of strings while ( !s.at(i).isNull() && (s.at(i) == t.at(i)) ) ++i; s = s.mid(i); t = t.mid(i); while (!s.at(n).isNull()) { ++n; } while (!t.at(m).isNull()) { ++m; } // Remove rightmost matching portion of strings by decrement n and m. while ( n && m && (s.at(n - 1) == t.at(m - 1)) ) { --n; --m; } if ( m == 0 || n == 0 || d == (int*)0 ) return (m + n); if ( m < n ) { const QString temp = s; int itemp = n; s = t; t = temp; n = m; m = itemp; } iLenDif = m - n; if ( iLenDif >= limit ) return iLenDif; // step 1 ++n; ++m; // d=(int*)malloc(sizeof(int)*m*n); if ( m*n > currentelements ) { currentelements = m * n * 2; // double the request d = (int*)realloc(d, sizeof(int) * currentelements); if ( (int*)0 == d ) return (m + n); } // step 2, init matrix for (k = 0;k < n;k++) d[k] = k; for (k = 1;k < m;k++) d[k*n] = k; // step 3 for (i = 1;i < n;i++) { // first calculate column, d(i,j) for ( j = 1;j < iLenDif + i;j++ ) { cost = s[i - 1] == t[j - 1] ? 0 : 1; d[j*n + i] = minimum(d[(j - 1) * n + i] + 1, d[j * n + i - 1] + 1, d[(j - 1) * n + i - 1] + cost); #ifdef COVER_TRANSPOSITION if ( i >= 2 && j >= 2 && (d[j*n + i] - d[(j - 2)*n + i - 2] == 2) && (s[i - 2] == t[j - 1]) && (s[i - 1] == t[j - 2]) ) d[j*n + i]--; #endif } // second calculate row, d(k,j) // now j==iLenDif+i; for ( k = 1;k <= i;k++ ) { cost = s[k - 1] == t[j - 1] ? 0 : 1; d[j*n + k] = minimum(d[(j - 1) * n + k] + 1, d[j * n + k - 1] + 1, d[(j - 1) * n + k - 1] + cost); #ifdef COVER_TRANSPOSITION if ( k >= 2 && j >= 2 && (d[j*n + k] - d[(j - 2)*n + k - 2] == 2) && (s[k - 2] == t[j - 1]) && (s[k - 1] == t[j - 2]) ) d[j*n + k]--; #endif } // test if d(i,j) limit gets equal or exceed if ( d[j*n + i] >= limit ) { return d[j*n + i]; } } // d(n-1,m-1) return d[n*m - 1]; } #else int EditDistance::CalEditDistance(const char *s, const char *t, const int limit) { //Step 1 int k, i, j, n, m, cost; n = strlen(s); m = strlen(t); if ( n != 0 && m != 0 && d != (int*)0 ) { m++; n++; if ( m*n > currentelements ) { currentelements = m * n * 2; d = (int*)realloc(d, sizeof(int) * currentelements); if ( (int*)0 == d ) return (m + n); } //Step 2 for (k = 0;k < n;k++) d[k] = k; for (k = 0;k < m;k++) d[k*n] = k; //Step 3 and 4 for (i = 1;i < n;i++) for (j = 1;j < m;j++) { //Step 5 if (s[i - 1] == t[j - 1]) cost = 0; else cost = 1; //Step 6 d[j*n + i] = minimum(d[(j - 1) * n + i] + 1, d[j * n + i - 1] + 1, d[(j - 1) * n + i - 1] + cost); #ifdef COVER_TRANSPOSITION if ( i >= 2 && j >= 2 && (d[j*n + i] - d[(j - 2)*n + i - 2] == 2) && (s[i - 2] == t[j - 1]) && (s[i - 1] == t[j - 2]) ) d[j*n + i]--; #endif } return d[n*m - 1]; } else return (n + m); } #endif <commit_msg>Fix Check for postfix usage of ++ and -- [postfixop]...<commit_after>/****************************************************************************** * This file is part of the Mula project * Copyright (c) Opera Wang <wangvisual AT sohu DOT com> * Copyright (c) 2011 Laszlo Papp <lpapp@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* http://www.merriampark.com/ld.htm What is Levenshtein Distance? Levenshtein distance (LD) is a measure of the similarity between two strings, which we will refer to as the source string (s) and the target string (t). The distance is the number of deletions, insertions, or substitutions required to transform s into t. For example, * If s is "test" and t is "test", then LD(s,t) = 0, because no transformations are needed. The strings are already identical. * If s is "test" and t is "tent", then LD(s,t) = 1, because one substitution (change "s" to "n") is sufficient to transform s into t. The greater the Levenshtein distance, the more different the strings are. Levenshtein distance is named after the Russian scientist Vladimir Levenshtein, who devised the algorithm in 1965. If you can't spell or pronounce Levenshtein, the metric is also sometimes called edit distance. The Levenshtein distance algorithm has been used in: * Spell checking * Speech recognition * DNA analysis * Plagiarism detection */ #include "distance.h" #include <stdlib.h> #include <QtCore/QString> #define OPTIMIZE_ED /* Cover transposition, in addition to deletion, insertion and substitution. This step is taken from: Berghel, Hal ; Roach, David : "An Extension of Ukkonen's Enhanced Dynamic Programming ASM Algorithm" (http://www.acm.org/~hlb/publications/asm/asm.html) */ #define COVER_TRANSPOSITION /****************************************/ /*Implementation of Levenshtein distance*/ /****************************************/ EditDistance::EditDistance() { currentelements = 2500; // It's enough for most conditions :-) d = (int*)malloc(sizeof(int) * currentelements); } EditDistance::~EditDistance() { // printf("size:%d\n",currentelements); if (d) free(d); } #ifdef OPTIMIZE_ED int EditDistance::calEditDistance(QString s, QString t, const int limit) /*Compute levenshtein distance between s and t, this is using QUICK algorithm*/ { int n = 0; int m = 0; int iLenDif; int k; int i = 0; int j; int cost; // Remove leftmost matching portion of strings while ( !s.at(i).isNull() && (s.at(i) == t.at(i)) ) ++i; s = s.mid(i); t = t.mid(i); while (!s.at(n).isNull()) { ++n; } while (!t.at(m).isNull()) { ++m; } // Remove rightmost matching portion of strings by decrement n and m. while ( n && m && (s.at(n - 1) == t.at(m - 1)) ) { --n; --m; } if ( m == 0 || n == 0 || d == (int*)0 ) return (m + n); if ( m < n ) { const QString temp = s; int itemp = n; s = t; t = temp; n = m; m = itemp; } iLenDif = m - n; if ( iLenDif >= limit ) return iLenDif; // step 1 ++n; ++m; // d=(int*)malloc(sizeof(int)*m*n); if ( m*n > currentelements ) { currentelements = m * n * 2; // double the request d = (int*)realloc(d, sizeof(int) * currentelements); if ( (int*)0 == d ) return (m + n); } // step 2, init matrix for (k = 0; k < n; ++k) d[k] = k; for (k = 1; k < m; ++k) d[k*n] = k; // step 3 for (i = 1; i < n; ++i) { // first calculate column, d(i,j) for ( j = 1; j < iLenDif + i; ++j ) { cost = s[i - 1] == t[j - 1] ? 0 : 1; d[j*n + i] = minimum(d[(j - 1) * n + i] + 1, d[j * n + i - 1] + 1, d[(j - 1) * n + i - 1] + cost); #ifdef COVER_TRANSPOSITION if ( i >= 2 && j >= 2 && (d[j*n + i] - d[(j - 2)*n + i - 2] == 2) && (s[i - 2] == t[j - 1]) && (s[i - 1] == t[j - 2]) ) d[j*n + i]--; #endif } // second calculate row, d(k,j) // now j==iLenDif+i; for ( k = 1; k <= i; ++k ) { cost = s[k - 1] == t[j - 1] ? 0 : 1; d[j*n + k] = minimum(d[(j - 1) * n + k] + 1, d[j * n + k - 1] + 1, d[(j - 1) * n + k - 1] + cost); #ifdef COVER_TRANSPOSITION if ( k >= 2 && j >= 2 && (d[j*n + k] - d[(j - 2)*n + k - 2] == 2) && (s[k - 2] == t[j - 1]) && (s[k - 1] == t[j - 2]) ) d[j*n + k]--; #endif } // test if d(i,j) limit gets equal or exceed if ( d[j*n + i] >= limit ) { return d[j*n + i]; } } // d(n-1,m-1) return d[n*m - 1]; } #else int EditDistance::CalEditDistance(const char *s, const char *t, const int limit) { //Step 1 int k, i, j, n, m, cost; n = strlen(s); m = strlen(t); if ( n != 0 && m != 0 && d != (int*)0 ) { m++; n++; if ( m*n > currentelements ) { currentelements = m * n * 2; d = (int*)realloc(d, sizeof(int) * currentelements); if ( (int*)0 == d ) return (m + n); } //Step 2 for (k = 0;k < n;k++) d[k] = k; for (k = 0;k < m;k++) d[k*n] = k; //Step 3 and 4 for (i = 1; i < n; ++i) for (j = 1; j < m; ++j) { //Step 5 if (s[i - 1] == t[j - 1]) cost = 0; else cost = 1; //Step 6 d[j*n + i] = minimum(d[(j - 1) * n + i] + 1, d[j * n + i - 1] + 1, d[(j - 1) * n + i - 1] + cost); #ifdef COVER_TRANSPOSITION if ( i >= 2 && j >= 2 && (d[j*n + i] - d[(j - 2)*n + i - 2] == 2) && (s[i - 2] == t[j - 1]) && (s[i - 1] == t[j - 2]) ) d[j*n + i]--; #endif } return d[n*m - 1]; } else return (n + m); } #endif <|endoftext|>
<commit_before>#include "context.hpp" #include <SFML/Graphics.hpp> #include <iostream> #include <cstdlib> #include "../debug.hpp" static sf::Font font; static sf::Text debugText; static sf::RenderWindow window; static sf::Texture displayTexture; static sf::Sprite displaySprite; // SFML needs a sprite to render a texture static uint8_t* displayBuffer = nullptr; static float speedInput = 1.0f; // Placeholder uint8_t pixels[160 * 144 * 4]; // Placeholder bool prevShouldHalt = false; bool prevShouldStep = false; bool Context::SetupContext (int scale = 1) { font.loadFromFile("./resources/fonts/OpenSans-Bold.ttf"); debugText.setFont(font); debugText.setFillColor(sf::Color::Magenta); debugText.setCharacterSize(20); debugText.setString("Debug :D"); window.create(sf::VideoMode(160 * scale, 144 * scale), "Hello :)"); displayTexture.create(160, 144); displayTexture.setSmooth(false); displaySprite.setTexture(displayTexture); sf::Vector2u textureSize = displayTexture.getSize(); sf::Vector2u windowSize = window.getSize(); float scaleX = (float) windowSize.x / textureSize.x; float scaleY = (float) windowSize.y / textureSize.y; displaySprite.setScale(scaleX, scaleY); return true; } void Context::DestroyContext () { if (window.isOpen()) window.close(); } void Context::HandleEvents () { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); else if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::Escape) { window.close(); } else if (event.key.code == sf::Keyboard::Num0) { speedInput = 1.0f; } else if (event.key.code == sf::Keyboard::Num9) { speedInput = 0.5f; } else if (event.key.code == sf::Keyboard::Num8) { speedInput = 0.25f; } else if (event.key.code == sf::Keyboard::Num7) { speedInput = 0.1f; } else if (event.key.code == sf::Keyboard::Num6) { speedInput = 0.05f; } else if (event.key.code == sf::Keyboard::Num5) { speedInput = 0.01f; } } } } void Context::RenderDebugText () { window.draw(debugText); } void Context::RenderDisplay () { window.clear(); CopyDisplayBuffer(displayBuffer); displayTexture.update(pixels); window.draw(displaySprite); RenderDebugText(); window.display(); } // TODO: Use opengl texture binding and GL_R8UI color format to use the VRAM di- //rectly as a pixel buffer. // http://fr.sfml-dev.org/forums/index.php?topic=17847.0 // http://www.sfml-dev.org/documentation/2.4.1/classsf_1_1Texture.php void Context::SetDisplayBuffer (uint8_t* buffer) { assert(buffer != nullptr); displayBuffer = buffer; } // HACK: Temporary solution // Currently, Instead of accessing the VRAM memory directly, we convert it's contents to a //color format that SFML can understand. void Context::CopyDisplayBuffer (uint8_t* buffer) { for (size_t i = 0; i < 160 * 144 * 4; i += 4) { int luminosity = (buffer[i / 4] + 1) * 64 - 1; pixels[i] = luminosity; pixels[i + 1] = luminosity; pixels[i + 2] = luminosity; pixels[i + 3] = 255; } } void Context::SetTitle (std::string title) { window.setTitle(title); } bool Context::IsOpen () { return window.isOpen(); } bool Context::ShouldHalt () { bool curr = sf::Keyboard::isKeyPressed(sf::Keyboard::P); bool prev = prevShouldHalt; prevShouldHalt = curr; return curr ^ prev && curr; } bool Context::ShouldStep () { bool curr = sf::Keyboard::isKeyPressed(sf::Keyboard::O); bool prev = prevShouldStep; prevShouldStep = curr; return curr ^ prev && curr; } void Context::SetDebugText (std::string text) { debugText.setString(text); } float Context::GetSpeedInput () { return speedInput; } <commit_msg>Changed SFML's setFillColor to setColor due restriction to SFML 2.3<commit_after>#include "context.hpp" #include <SFML/Graphics.hpp> #include <iostream> #include <cstdlib> #include "../debug.hpp" static sf::Font font; static sf::Text debugText; static sf::RenderWindow window; static sf::Texture displayTexture; static sf::Sprite displaySprite; // SFML needs a sprite to render a texture static uint8_t* displayBuffer = nullptr; static float speedInput = 1.0f; // Placeholder uint8_t pixels[160 * 144 * 4]; // Placeholder bool prevShouldHalt = false; bool prevShouldStep = false; bool Context::SetupContext (int scale = 1) { font.loadFromFile("./resources/fonts/OpenSans-Bold.ttf"); debugText.setFont(font); debugText.setColor(sf::Color::Magenta); debugText.setCharacterSize(20); debugText.setString("Debug :D"); window.create(sf::VideoMode(160 * scale, 144 * scale), "Hello :)"); displayTexture.create(160, 144); displayTexture.setSmooth(false); displaySprite.setTexture(displayTexture); sf::Vector2u textureSize = displayTexture.getSize(); sf::Vector2u windowSize = window.getSize(); float scaleX = (float) windowSize.x / textureSize.x; float scaleY = (float) windowSize.y / textureSize.y; displaySprite.setScale(scaleX, scaleY); return true; } void Context::DestroyContext () { if (window.isOpen()) window.close(); } void Context::HandleEvents () { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); else if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::Escape) { window.close(); } else if (event.key.code == sf::Keyboard::Num0) { speedInput = 1.0f; } else if (event.key.code == sf::Keyboard::Num9) { speedInput = 0.5f; } else if (event.key.code == sf::Keyboard::Num8) { speedInput = 0.25f; } else if (event.key.code == sf::Keyboard::Num7) { speedInput = 0.1f; } else if (event.key.code == sf::Keyboard::Num6) { speedInput = 0.05f; } else if (event.key.code == sf::Keyboard::Num5) { speedInput = 0.01f; } } } } void Context::RenderDebugText () { window.draw(debugText); } void Context::RenderDisplay () { window.clear(); CopyDisplayBuffer(displayBuffer); displayTexture.update(pixels); window.draw(displaySprite); RenderDebugText(); window.display(); } // TODO: Use opengl texture binding and GL_R8UI color format to use the VRAM di- //rectly as a pixel buffer. // http://fr.sfml-dev.org/forums/index.php?topic=17847.0 // http://www.sfml-dev.org/documentation/2.4.1/classsf_1_1Texture.php void Context::SetDisplayBuffer (uint8_t* buffer) { assert(buffer != nullptr); displayBuffer = buffer; } // HACK: Temporary solution // Currently, Instead of accessing the VRAM memory directly, we convert it's contents to a //color format that SFML can understand. void Context::CopyDisplayBuffer (uint8_t* buffer) { for (size_t i = 0; i < 160 * 144 * 4; i += 4) { int luminosity = (buffer[i / 4] + 1) * 64 - 1; pixels[i] = luminosity; pixels[i + 1] = luminosity; pixels[i + 2] = luminosity; pixels[i + 3] = 255; } } void Context::SetTitle (std::string title) { window.setTitle(title); } bool Context::IsOpen () { return window.isOpen(); } bool Context::ShouldHalt () { bool curr = sf::Keyboard::isKeyPressed(sf::Keyboard::P); bool prev = prevShouldHalt; prevShouldHalt = curr; return curr ^ prev && curr; } bool Context::ShouldStep () { bool curr = sf::Keyboard::isKeyPressed(sf::Keyboard::O); bool prev = prevShouldStep; prevShouldStep = curr; return curr ^ prev && curr; } void Context::SetDebugText (std::string text) { debugText.setString(text); } float Context::GetSpeedInput () { return speedInput; } <|endoftext|>
<commit_before>/* ============================================================================ * Copyright (c) 2012 Michael A. Jackson (BlueQuartz Software) * Copyright (c) 2012 Singanallur Venkatakrishnan (Purdue University) * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 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 Singanallur Venkatakrishnan, Michael A. Jackson, the Pudue * Univeristy, BlueQuartz Software nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This code was written under United States Air Force Contract number * FA8650-07-D-5800 * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include "MRCInfoWidget.h" #include <QtCore/QFileInfo> #include "TomoEngine/IO/MRCHeader.h" #include "TomoEngine/IO/MRCReader.h" // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- MRCInfoWidget::MRCInfoWidget(QWidget *parent) : QWidget(parent) { setupUi(this); this->setWindowFlags(Qt::Tool); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- MRCInfoWidget::~MRCInfoWidget() {} #define SET_MRC_INFO(var)\ var->setText(QString::number(header.var)); // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void MRCInfoWidget::setInfo(QString mrcFilePath) { QFileInfo fi(mrcFilePath); this->setWindowTitle(fi.fileName()); MRCHeader header; ::memset(&header, 0, sizeof(header)); MRCReader::Pointer reader = MRCReader::New(true); // Read the header from the file int err = reader->readHeader(mrcFilePath.toStdString(), &header); if(err < 0) { return; } int tiltIndex = 0; // Transfer the meta data from the MRC Header to the GUI SET_MRC_INFO(nx) SET_MRC_INFO(ny) SET_MRC_INFO(nz) SET_MRC_INFO(mode) SET_MRC_INFO(nxstart) SET_MRC_INFO(nystart) SET_MRC_INFO(nzstart) SET_MRC_INFO(mx) SET_MRC_INFO(my) SET_MRC_INFO(mz) SET_MRC_INFO(xlen) SET_MRC_INFO(ylen) SET_MRC_INFO(zlen) SET_MRC_INFO(alpha) SET_MRC_INFO(beta) SET_MRC_INFO(gamma) SET_MRC_INFO(mapc) SET_MRC_INFO(mapr) SET_MRC_INFO(maps) SET_MRC_INFO(amin) SET_MRC_INFO(amax) SET_MRC_INFO(amean) SET_MRC_INFO(idtype) SET_MRC_INFO(lens) SET_MRC_INFO(nd1) SET_MRC_INFO(nd2) SET_MRC_INFO(vd1) SET_MRC_INFO(vd2) SET_MRC_INFO(xorg) SET_MRC_INFO(yorg) SET_MRC_INFO(zorg) // If we have the FEI headers get that information if(header.feiHeaders != NULL) { FEIHeader fei = header.feiHeaders[tiltIndex]; // a_tilt->setText(QString::number(fei.a_tilt)); // b_tilt->setText(QString::number(fei.b_tilt)); // x_stage->setText(QString::number(fei.x_stage)); // y_stage->setText(QString::number(fei.y_stage)); // z_stage->setText(QString::number(fei.z_stage)); // x_shift->setText(QString::number(fei.x_shift)); // y_shift->setText(QString::number(fei.y_shift)); // defocus->setText(QString::number(fei.defocus)); // exp_time->setText(QString::number(fei.exp_time)); // mean_int->setText(QString::number(fei.mean_int)); // tiltaxis->setText(QString::number(fei.tiltaxis)); // pixelsize->setText(QString::number(fei.pixelsize)); // magnification->setText(QString::number(fei.magnification)); // voltage->setText(QString::number(fei.voltage)); } else { return; } } <commit_msg>Adding Debug output<commit_after>/* ============================================================================ * Copyright (c) 2012 Michael A. Jackson (BlueQuartz Software) * Copyright (c) 2012 Singanallur Venkatakrishnan (Purdue University) * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 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 Singanallur Venkatakrishnan, Michael A. Jackson, the Pudue * Univeristy, BlueQuartz Software nor the names of its contributors may be used * to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This code was written under United States Air Force Contract number * FA8650-07-D-5800 * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include "MRCInfoWidget.h" #include <QtCore/QFileInfo> #include "TomoEngine/IO/MRCHeader.h" #include "TomoEngine/IO/MRCReader.h" // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- MRCInfoWidget::MRCInfoWidget(QWidget *parent) : QWidget(parent) { setupUi(this); this->setWindowFlags(Qt::Tool); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- MRCInfoWidget::~MRCInfoWidget() {} #define SET_MRC_INFO(var)\ var->setText(QString::number(header.var)); // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void MRCInfoWidget::setInfo(QString mrcFilePath) { QFileInfo fi(mrcFilePath); this->setWindowTitle(fi.fileName()); MRCHeader header; ::memset(&header, 0, sizeof(header)); MRCReader::Pointer reader = MRCReader::New(true); // Read the header from the file int err = reader->readHeader(mrcFilePath.toStdString(), &header); if(err < 0) { std::cout << "Failed to open MRC File: " << mrcFilePath.toStdString() << std::endl; return; } int tiltIndex = 0; // Transfer the meta data from the MRC Header to the GUI SET_MRC_INFO(nx) SET_MRC_INFO(ny) SET_MRC_INFO(nz) SET_MRC_INFO(mode) SET_MRC_INFO(nxstart) SET_MRC_INFO(nystart) SET_MRC_INFO(nzstart) SET_MRC_INFO(mx) SET_MRC_INFO(my) SET_MRC_INFO(mz) SET_MRC_INFO(xlen) SET_MRC_INFO(ylen) SET_MRC_INFO(zlen) SET_MRC_INFO(alpha) SET_MRC_INFO(beta) SET_MRC_INFO(gamma) SET_MRC_INFO(mapc) SET_MRC_INFO(mapr) SET_MRC_INFO(maps) SET_MRC_INFO(amin) SET_MRC_INFO(amax) SET_MRC_INFO(amean) SET_MRC_INFO(idtype) SET_MRC_INFO(lens) SET_MRC_INFO(nd1) SET_MRC_INFO(nd2) SET_MRC_INFO(vd1) SET_MRC_INFO(vd2) SET_MRC_INFO(xorg) SET_MRC_INFO(yorg) SET_MRC_INFO(zorg) // If we have the FEI headers get that information if(header.feiHeaders != NULL) { FEIHeader fei = header.feiHeaders[tiltIndex]; // a_tilt->setText(QString::number(fei.a_tilt)); // b_tilt->setText(QString::number(fei.b_tilt)); // x_stage->setText(QString::number(fei.x_stage)); // y_stage->setText(QString::number(fei.y_stage)); // z_stage->setText(QString::number(fei.z_stage)); // x_shift->setText(QString::number(fei.x_shift)); // y_shift->setText(QString::number(fei.y_shift)); // defocus->setText(QString::number(fei.defocus)); // exp_time->setText(QString::number(fei.exp_time)); // mean_int->setText(QString::number(fei.mean_int)); // tiltaxis->setText(QString::number(fei.tiltaxis)); // pixelsize->setText(QString::number(fei.pixelsize)); // magnification->setText(QString::number(fei.magnification)); // voltage->setText(QString::number(fei.voltage)); } else { return; } } <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ #include <quic/state/AckHandlers.h> #include <quic/logging/QuicLogger.h> #include <quic/loss/QuicLossFunctions.h> #include <quic/state/QuicStateFunctions.h> #include <iterator> namespace quic { /** * Process ack frame and acked outstanding packets. * * This function process incoming ack blocks which is sorted in the descending * order of packet number. For each ack block, we try to find a continuous range * of outstanding packets in the connection's outstanding packets list that is * acked by the current ack block. The search is in the reverse order of the * outstandings.packets given that the list is sorted in the ascending order of * packet number. For each outstanding packet that is acked by current ack * frame, ack and loss visitors are invoked on the sent frames. The outstanding * packets may contain packets from all three packet number spaces. But ack is * always restrained to a single space. So we also need to skip packets that are * not in the current packet number space. * */ void processAckFrame( QuicConnectionStateBase& conn, PacketNumberSpace pnSpace, const ReadAckFrame& frame, const AckVisitor& ackVisitor, const LossVisitor& lossVisitor, const TimePoint& ackReceiveTime) { // TODO: send error if we get an ack for a packet we've not sent t18721184 CongestionController::AckEvent ack; ack.ackTime = ackReceiveTime; ack.implicit = frame.implicit; ack.adjustedAckTime = ackReceiveTime - frame.ackDelay; // Using kDefaultRxPacketsBeforeAckAfterInit to reseve for ackedPackets // container is a hueristic. Other quic implementations may have very // different acking policy. It's also possibly that all acked packets are pure // acks which leads to different number of packets being acked usually. ack.ackedPackets.reserve(kDefaultRxPacketsBeforeAckAfterInit); auto currentPacketIt = getLastOutstandingPacketIncludingLost(conn, pnSpace); uint64_t initialPacketAcked = 0; uint64_t handshakePacketAcked = 0; uint64_t clonedPacketsAcked = 0; folly::Optional<decltype(conn.lossState.lastAckedPacketSentTime)> lastAckedPacketSentTime; auto ackBlockIt = frame.ackBlocks.cbegin(); while (ackBlockIt != frame.ackBlocks.cend() && currentPacketIt != conn.outstandings.packets.rend()) { // In reverse order, find the first outstanding packet that has a packet // number LE the endPacket of the current ack range. auto rPacketIt = std::lower_bound( currentPacketIt, conn.outstandings.packets.rend(), ackBlockIt->endPacket, [&](const auto& packetWithTime, const auto& val) { return packetWithTime.packet.header.getPacketSequenceNum() > val; }); if (rPacketIt == conn.outstandings.packets.rend()) { // This means that all the packets are greater than the end packet. // Since we iterate the ACK blocks in reverse order of end packets, our // work here is done. VLOG(10) << __func__ << " less than all outstanding packets outstanding=" << conn.outstandings.numOutstanding() << " range=[" << ackBlockIt->startPacket << ", " << ackBlockIt->endPacket << "]" << " " << conn; ackBlockIt++; break; } // TODO: only process ACKs from packets which are sent from a greater than // or equal to crypto protection level. auto eraseEnd = rPacketIt; while (rPacketIt != conn.outstandings.packets.rend()) { auto currentPacketNum = rPacketIt->packet.header.getPacketSequenceNum(); auto currentPacketNumberSpace = rPacketIt->packet.header.getPacketNumberSpace(); if (pnSpace != currentPacketNumberSpace) { // When the next packet is not in the same packet number space, we need // to skip it in current ack processing. If the iterator has moved, that // means we have found packets in the current space that are acked by // this ack block. So the code erases the current iterator range and // move the iterator to be the next search point. if (rPacketIt != eraseEnd) { auto nextElem = conn.outstandings.packets.erase( rPacketIt.base(), eraseEnd.base()); rPacketIt = std::reverse_iterator<decltype(nextElem)>(nextElem) + 1; eraseEnd = rPacketIt; } else { rPacketIt++; eraseEnd = rPacketIt; } continue; } if (currentPacketNum < ackBlockIt->startPacket) { break; } VLOG(10) << __func__ << " acked packetNum=" << currentPacketNum << " space=" << currentPacketNumberSpace << " handshake=" << (int)((rPacketIt->metadata.isHandshake) ? 1 : 0) << " " << conn; // If we hit a packet which has been lost we need to count the spurious // loss and ignore all other processing. // TODO also remove any stream data from the loss buffer. if (rPacketIt->declaredLost) { CHECK_GT(conn.outstandings.declaredLostCount, 0); conn.lossState.spuriousLossCount++; QUIC_STATS(conn.statsCallback, onPacketSpuriousLoss); // Decrement the counter, trust that we will erase this as part of // the bulk erase. conn.outstandings.declaredLostCount--; rPacketIt++; continue; } bool needsProcess = !rPacketIt->associatedEvent || conn.outstandings.packetEvents.count(*rPacketIt->associatedEvent); if (rPacketIt->metadata.isHandshake && needsProcess) { if (currentPacketNumberSpace == PacketNumberSpace::Initial) { ++initialPacketAcked; } else { CHECK_EQ(PacketNumberSpace::Handshake, currentPacketNumberSpace); ++handshakePacketAcked; } } ack.ackedBytes += rPacketIt->metadata.encodedSize; if (rPacketIt->associatedEvent) { ++clonedPacketsAcked; } // Update RTT if current packet is the largestAcked in the frame: auto ackReceiveTimeOrNow = ackReceiveTime > rPacketIt->metadata.time ? ackReceiveTime : Clock::now(); auto rttSample = std::chrono::duration_cast<std::chrono::microseconds>( ackReceiveTimeOrNow - rPacketIt->metadata.time); if (!ack.implicit && currentPacketNum == frame.largestAcked) { InstrumentationObserver::PacketRTT packetRTT( ackReceiveTimeOrNow, rttSample, frame.ackDelay, *rPacketIt); for (const auto& observer : conn.instrumentationObservers_) { conn.pendingCallbacks.emplace_back( [observer, packetRTT](QuicSocket* qSocket) { observer->rttSampleGenerated(qSocket, packetRTT); }); } updateRtt(conn, rttSample, frame.ackDelay); } // D6D probe acked. Only if it's for the last probe do we // trigger state change if (rPacketIt->metadata.isD6DProbe) { CHECK(conn.d6d.lastProbe); if (!rPacketIt->declaredLost) { ++conn.d6d.meta.totalAckedProbes; if (currentPacketNum == conn.d6d.lastProbe->packetNum) { onD6DLastProbeAcked(conn); } } } // Only invoke AckVisitor if the packet doesn't have an associated // PacketEvent; or the PacketEvent is in conn.outstandings.packetEvents if (needsProcess /*!rPacketIt->associatedEvent || conn.outstandings.packetEvents.count(*rPacketIt->associatedEvent)*/) { for (auto& packetFrame : rPacketIt->packet.frames) { ackVisitor(*rPacketIt, packetFrame, frame); } // Remove this PacketEvent from the outstandings.packetEvents set if (rPacketIt->associatedEvent) { conn.outstandings.packetEvents.erase(*rPacketIt->associatedEvent); } } if (!ack.largestAckedPacket || *ack.largestAckedPacket < currentPacketNum) { ack.largestAckedPacket = currentPacketNum; ack.largestAckedPacketSentTime = rPacketIt->metadata.time; ack.largestAckedPacketAppLimited = rPacketIt->isAppLimited; } if (!ack.implicit && ackReceiveTime > rPacketIt->metadata.time) { ack.mrttSample = std::min(ack.mrttSample.value_or(rttSample), rttSample); } if (!ack.implicit) { conn.lossState.totalBytesAcked += rPacketIt->metadata.encodedSize; conn.lossState.totalBytesSentAtLastAck = conn.lossState.totalBytesSent; conn.lossState.totalBytesAckedAtLastAck = conn.lossState.totalBytesAcked; if (!lastAckedPacketSentTime) { lastAckedPacketSentTime = rPacketIt->metadata.time; } conn.lossState.lastAckedTime = ackReceiveTime; conn.lossState.adjustedLastAckedTime = ackReceiveTime - frame.ackDelay; } ack.ackedPackets.push_back( CongestionController::AckEvent::AckPacket::Builder() .setSentTime(rPacketIt->metadata.time) .setEncodedSize(rPacketIt->metadata.encodedSize) .setLastAckedPacketInfo(std::move(rPacketIt->lastAckedPacketInfo)) .setTotalBytesSentThen(rPacketIt->metadata.totalBytesSent) .setAppLimited(rPacketIt->isAppLimited) .build()); rPacketIt++; } // Done searching for acked outstanding packets in current ack block. Erase // the current iterator range which is the last batch of continuous // outstanding packets that are in this ack block. Move the iterator to be // the next search point. if (rPacketIt != eraseEnd) { auto nextElem = conn.outstandings.packets.erase(rPacketIt.base(), eraseEnd.base()); currentPacketIt = std::reverse_iterator<decltype(nextElem)>(nextElem); } else { currentPacketIt = rPacketIt; } ackBlockIt++; } if (lastAckedPacketSentTime) { conn.lossState.lastAckedPacketSentTime = *lastAckedPacketSentTime; } CHECK_GE(conn.outstandings.initialPacketsCount, initialPacketAcked); conn.outstandings.initialPacketsCount -= initialPacketAcked; CHECK_GE(conn.outstandings.handshakePacketsCount, handshakePacketAcked); conn.outstandings.handshakePacketsCount -= handshakePacketAcked; CHECK_GE(conn.outstandings.clonedPacketsCount, clonedPacketsAcked); conn.outstandings.clonedPacketsCount -= clonedPacketsAcked; CHECK_GE( conn.outstandings.packets.size(), conn.outstandings.declaredLostCount); auto updatedOustandingPacketsCount = conn.outstandings.numOutstanding(); CHECK_GE( updatedOustandingPacketsCount, conn.outstandings.handshakePacketsCount + conn.outstandings.initialPacketsCount); CHECK_GE(updatedOustandingPacketsCount, conn.outstandings.clonedPacketsCount); auto lossEvent = handleAckForLoss(conn, lossVisitor, ack, pnSpace); if (conn.congestionController && (ack.largestAckedPacket.has_value() || lossEvent)) { if (lossEvent) { CHECK(lossEvent->largestLostSentTime && lossEvent->smallestLostSentTime); // TODO it's not clear that we should be using the smallest and largest // lost times here. It may perhaps be better to only consider the latest // contiguous lost block and determine if that block is larger than the // congestion period. Alternatively we could consider every lost block // and check if any of them constitute persistent congestion. lossEvent->persistentCongestion = isPersistentCongestion( conn, *lossEvent->smallestLostSentTime, *lossEvent->largestLostSentTime); if (lossEvent->persistentCongestion) { QUIC_STATS(conn.statsCallback, onPersistentCongestion); } } conn.congestionController->onPacketAckOrLoss( std::move(ack), std::move(lossEvent)); } clearOldOutstandingPackets(conn, ackReceiveTime, pnSpace); } void clearOldOutstandingPackets( QuicConnectionStateBase& conn, TimePoint time, PacketNumberSpace pnSpace) { if (conn.outstandings.declaredLostCount) { // Reap any old packets declared lost that are unlikely to be ACK'd. auto threshold = calculatePTO(conn); auto opItr = conn.outstandings.packets.begin(); auto eraseBegin = opItr; while (opItr != conn.outstandings.packets.end()) { // This case can happen when we have buffered an undecryptable ACK and // are able to decrypt it later. if (time < opItr->metadata.time) { break; } if (opItr->packet.header.getPacketNumberSpace() != pnSpace) { if (eraseBegin != opItr) { // We want to keep [eraseBegin, opItr) within a single PN space. opItr = conn.outstandings.packets.erase(eraseBegin, opItr); } opItr++; eraseBegin = opItr; continue; } auto timeSinceSent = time - opItr->metadata.time; if (opItr->declaredLost && timeSinceSent > threshold) { opItr++; conn.outstandings.declaredLostCount--; } else { break; } } if (eraseBegin != opItr) { conn.outstandings.packets.erase(eraseBegin, opItr); } } } void commonAckVisitorForAckFrame( AckState& ackState, const WriteAckFrame& frame) { // Remove ack interval from ackState if an outstandingPacket with a AckFrame // is acked. // We may remove the current largest acked packet here, but keep its receive // time behind. But then right after this updateLargestReceivedPacketNum will // update that time stamp. Please note that this assume the peer isn't buggy // in the sense that packet numbers it issues are only increasing. auto iter = frame.ackBlocks.crbegin(); while (iter != frame.ackBlocks.crend()) { ackState.acks.withdraw(*iter); iter++; } if (!frame.ackBlocks.empty()) { auto largestAcked = frame.ackBlocks.front().end; if (largestAcked > kAckPurgingThresh) { ackState.acks.withdraw({0, largestAcked - kAckPurgingThresh}); } } } } // namespace quic <commit_msg>Sanity check Quic AckFrame ack delay value<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ #include <quic/state/AckHandlers.h> #include <quic/logging/QuicLogger.h> #include <quic/loss/QuicLossFunctions.h> #include <quic/state/QuicStateFunctions.h> #include <iterator> namespace quic { /** * Process ack frame and acked outstanding packets. * * This function process incoming ack blocks which is sorted in the descending * order of packet number. For each ack block, we try to find a continuous range * of outstanding packets in the connection's outstanding packets list that is * acked by the current ack block. The search is in the reverse order of the * outstandings.packets given that the list is sorted in the ascending order of * packet number. For each outstanding packet that is acked by current ack * frame, ack and loss visitors are invoked on the sent frames. The outstanding * packets may contain packets from all three packet number spaces. But ack is * always restrained to a single space. So we also need to skip packets that are * not in the current packet number space. * */ void processAckFrame( QuicConnectionStateBase& conn, PacketNumberSpace pnSpace, const ReadAckFrame& frame, const AckVisitor& ackVisitor, const LossVisitor& lossVisitor, const TimePoint& ackReceiveTime) { // TODO: send error if we get an ack for a packet we've not sent t18721184 CongestionController::AckEvent ack; ack.ackTime = ackReceiveTime; ack.implicit = frame.implicit; if (UNLIKELY(frame.ackDelay < 0us)) { LOG(ERROR) << "Quic received negative ack delay=" << frame.ackDelay.count(); ack.adjustedAckTime = ackReceiveTime; } else if (UNLIKELY(frame.ackDelay > 1000s)) { LOG(ERROR) << "Quic very long ack delay=" << frame.ackDelay.count(); ack.adjustedAckTime = ackReceiveTime; } else { ack.adjustedAckTime = ackReceiveTime - frame.ackDelay; } // Using kDefaultRxPacketsBeforeAckAfterInit to reseve for ackedPackets // container is a hueristic. Other quic implementations may have very // different acking policy. It's also possibly that all acked packets are pure // acks which leads to different number of packets being acked usually. ack.ackedPackets.reserve(kDefaultRxPacketsBeforeAckAfterInit); auto currentPacketIt = getLastOutstandingPacketIncludingLost(conn, pnSpace); uint64_t initialPacketAcked = 0; uint64_t handshakePacketAcked = 0; uint64_t clonedPacketsAcked = 0; folly::Optional<decltype(conn.lossState.lastAckedPacketSentTime)> lastAckedPacketSentTime; auto ackBlockIt = frame.ackBlocks.cbegin(); while (ackBlockIt != frame.ackBlocks.cend() && currentPacketIt != conn.outstandings.packets.rend()) { // In reverse order, find the first outstanding packet that has a packet // number LE the endPacket of the current ack range. auto rPacketIt = std::lower_bound( currentPacketIt, conn.outstandings.packets.rend(), ackBlockIt->endPacket, [&](const auto& packetWithTime, const auto& val) { return packetWithTime.packet.header.getPacketSequenceNum() > val; }); if (rPacketIt == conn.outstandings.packets.rend()) { // This means that all the packets are greater than the end packet. // Since we iterate the ACK blocks in reverse order of end packets, our // work here is done. VLOG(10) << __func__ << " less than all outstanding packets outstanding=" << conn.outstandings.numOutstanding() << " range=[" << ackBlockIt->startPacket << ", " << ackBlockIt->endPacket << "]" << " " << conn; ackBlockIt++; break; } // TODO: only process ACKs from packets which are sent from a greater than // or equal to crypto protection level. auto eraseEnd = rPacketIt; while (rPacketIt != conn.outstandings.packets.rend()) { auto currentPacketNum = rPacketIt->packet.header.getPacketSequenceNum(); auto currentPacketNumberSpace = rPacketIt->packet.header.getPacketNumberSpace(); if (pnSpace != currentPacketNumberSpace) { // When the next packet is not in the same packet number space, we need // to skip it in current ack processing. If the iterator has moved, that // means we have found packets in the current space that are acked by // this ack block. So the code erases the current iterator range and // move the iterator to be the next search point. if (rPacketIt != eraseEnd) { auto nextElem = conn.outstandings.packets.erase( rPacketIt.base(), eraseEnd.base()); rPacketIt = std::reverse_iterator<decltype(nextElem)>(nextElem) + 1; eraseEnd = rPacketIt; } else { rPacketIt++; eraseEnd = rPacketIt; } continue; } if (currentPacketNum < ackBlockIt->startPacket) { break; } VLOG(10) << __func__ << " acked packetNum=" << currentPacketNum << " space=" << currentPacketNumberSpace << " handshake=" << (int)((rPacketIt->metadata.isHandshake) ? 1 : 0) << " " << conn; // If we hit a packet which has been lost we need to count the spurious // loss and ignore all other processing. // TODO also remove any stream data from the loss buffer. if (rPacketIt->declaredLost) { CHECK_GT(conn.outstandings.declaredLostCount, 0); conn.lossState.spuriousLossCount++; QUIC_STATS(conn.statsCallback, onPacketSpuriousLoss); // Decrement the counter, trust that we will erase this as part of // the bulk erase. conn.outstandings.declaredLostCount--; rPacketIt++; continue; } bool needsProcess = !rPacketIt->associatedEvent || conn.outstandings.packetEvents.count(*rPacketIt->associatedEvent); if (rPacketIt->metadata.isHandshake && needsProcess) { if (currentPacketNumberSpace == PacketNumberSpace::Initial) { ++initialPacketAcked; } else { CHECK_EQ(PacketNumberSpace::Handshake, currentPacketNumberSpace); ++handshakePacketAcked; } } ack.ackedBytes += rPacketIt->metadata.encodedSize; if (rPacketIt->associatedEvent) { ++clonedPacketsAcked; } // Update RTT if current packet is the largestAcked in the frame: auto ackReceiveTimeOrNow = ackReceiveTime > rPacketIt->metadata.time ? ackReceiveTime : Clock::now(); auto rttSample = std::chrono::duration_cast<std::chrono::microseconds>( ackReceiveTimeOrNow - rPacketIt->metadata.time); if (!ack.implicit && currentPacketNum == frame.largestAcked) { InstrumentationObserver::PacketRTT packetRTT( ackReceiveTimeOrNow, rttSample, frame.ackDelay, *rPacketIt); for (const auto& observer : conn.instrumentationObservers_) { conn.pendingCallbacks.emplace_back( [observer, packetRTT](QuicSocket* qSocket) { observer->rttSampleGenerated(qSocket, packetRTT); }); } updateRtt(conn, rttSample, frame.ackDelay); } // D6D probe acked. Only if it's for the last probe do we // trigger state change if (rPacketIt->metadata.isD6DProbe) { CHECK(conn.d6d.lastProbe); if (!rPacketIt->declaredLost) { ++conn.d6d.meta.totalAckedProbes; if (currentPacketNum == conn.d6d.lastProbe->packetNum) { onD6DLastProbeAcked(conn); } } } // Only invoke AckVisitor if the packet doesn't have an associated // PacketEvent; or the PacketEvent is in conn.outstandings.packetEvents if (needsProcess /*!rPacketIt->associatedEvent || conn.outstandings.packetEvents.count(*rPacketIt->associatedEvent)*/) { for (auto& packetFrame : rPacketIt->packet.frames) { ackVisitor(*rPacketIt, packetFrame, frame); } // Remove this PacketEvent from the outstandings.packetEvents set if (rPacketIt->associatedEvent) { conn.outstandings.packetEvents.erase(*rPacketIt->associatedEvent); } } if (!ack.largestAckedPacket || *ack.largestAckedPacket < currentPacketNum) { ack.largestAckedPacket = currentPacketNum; ack.largestAckedPacketSentTime = rPacketIt->metadata.time; ack.largestAckedPacketAppLimited = rPacketIt->isAppLimited; } if (!ack.implicit && ackReceiveTime > rPacketIt->metadata.time) { ack.mrttSample = std::min(ack.mrttSample.value_or(rttSample), rttSample); } if (!ack.implicit) { conn.lossState.totalBytesAcked += rPacketIt->metadata.encodedSize; conn.lossState.totalBytesSentAtLastAck = conn.lossState.totalBytesSent; conn.lossState.totalBytesAckedAtLastAck = conn.lossState.totalBytesAcked; if (!lastAckedPacketSentTime) { lastAckedPacketSentTime = rPacketIt->metadata.time; } conn.lossState.lastAckedTime = ackReceiveTime; conn.lossState.adjustedLastAckedTime = ackReceiveTime - frame.ackDelay; } ack.ackedPackets.push_back( CongestionController::AckEvent::AckPacket::Builder() .setSentTime(rPacketIt->metadata.time) .setEncodedSize(rPacketIt->metadata.encodedSize) .setLastAckedPacketInfo(std::move(rPacketIt->lastAckedPacketInfo)) .setTotalBytesSentThen(rPacketIt->metadata.totalBytesSent) .setAppLimited(rPacketIt->isAppLimited) .build()); rPacketIt++; } // Done searching for acked outstanding packets in current ack block. Erase // the current iterator range which is the last batch of continuous // outstanding packets that are in this ack block. Move the iterator to be // the next search point. if (rPacketIt != eraseEnd) { auto nextElem = conn.outstandings.packets.erase(rPacketIt.base(), eraseEnd.base()); currentPacketIt = std::reverse_iterator<decltype(nextElem)>(nextElem); } else { currentPacketIt = rPacketIt; } ackBlockIt++; } if (lastAckedPacketSentTime) { conn.lossState.lastAckedPacketSentTime = *lastAckedPacketSentTime; } CHECK_GE(conn.outstandings.initialPacketsCount, initialPacketAcked); conn.outstandings.initialPacketsCount -= initialPacketAcked; CHECK_GE(conn.outstandings.handshakePacketsCount, handshakePacketAcked); conn.outstandings.handshakePacketsCount -= handshakePacketAcked; CHECK_GE(conn.outstandings.clonedPacketsCount, clonedPacketsAcked); conn.outstandings.clonedPacketsCount -= clonedPacketsAcked; CHECK_GE( conn.outstandings.packets.size(), conn.outstandings.declaredLostCount); auto updatedOustandingPacketsCount = conn.outstandings.numOutstanding(); CHECK_GE( updatedOustandingPacketsCount, conn.outstandings.handshakePacketsCount + conn.outstandings.initialPacketsCount); CHECK_GE(updatedOustandingPacketsCount, conn.outstandings.clonedPacketsCount); auto lossEvent = handleAckForLoss(conn, lossVisitor, ack, pnSpace); if (conn.congestionController && (ack.largestAckedPacket.has_value() || lossEvent)) { if (lossEvent) { CHECK(lossEvent->largestLostSentTime && lossEvent->smallestLostSentTime); // TODO it's not clear that we should be using the smallest and largest // lost times here. It may perhaps be better to only consider the latest // contiguous lost block and determine if that block is larger than the // congestion period. Alternatively we could consider every lost block // and check if any of them constitute persistent congestion. lossEvent->persistentCongestion = isPersistentCongestion( conn, *lossEvent->smallestLostSentTime, *lossEvent->largestLostSentTime); if (lossEvent->persistentCongestion) { QUIC_STATS(conn.statsCallback, onPersistentCongestion); } } conn.congestionController->onPacketAckOrLoss( std::move(ack), std::move(lossEvent)); } clearOldOutstandingPackets(conn, ackReceiveTime, pnSpace); } void clearOldOutstandingPackets( QuicConnectionStateBase& conn, TimePoint time, PacketNumberSpace pnSpace) { if (conn.outstandings.declaredLostCount) { // Reap any old packets declared lost that are unlikely to be ACK'd. auto threshold = calculatePTO(conn); auto opItr = conn.outstandings.packets.begin(); auto eraseBegin = opItr; while (opItr != conn.outstandings.packets.end()) { // This case can happen when we have buffered an undecryptable ACK and // are able to decrypt it later. if (time < opItr->metadata.time) { break; } if (opItr->packet.header.getPacketNumberSpace() != pnSpace) { if (eraseBegin != opItr) { // We want to keep [eraseBegin, opItr) within a single PN space. opItr = conn.outstandings.packets.erase(eraseBegin, opItr); } opItr++; eraseBegin = opItr; continue; } auto timeSinceSent = time - opItr->metadata.time; if (opItr->declaredLost && timeSinceSent > threshold) { opItr++; conn.outstandings.declaredLostCount--; } else { break; } } if (eraseBegin != opItr) { conn.outstandings.packets.erase(eraseBegin, opItr); } } } void commonAckVisitorForAckFrame( AckState& ackState, const WriteAckFrame& frame) { // Remove ack interval from ackState if an outstandingPacket with a AckFrame // is acked. // We may remove the current largest acked packet here, but keep its receive // time behind. But then right after this updateLargestReceivedPacketNum will // update that time stamp. Please note that this assume the peer isn't buggy // in the sense that packet numbers it issues are only increasing. auto iter = frame.ackBlocks.crbegin(); while (iter != frame.ackBlocks.crend()) { ackState.acks.withdraw(*iter); iter++; } if (!frame.ackBlocks.empty()) { auto largestAcked = frame.ackBlocks.front().end; if (largestAcked > kAckPurgingThresh) { ackState.acks.withdraw({0, largestAcked - kAckPurgingThresh}); } } } } // namespace quic <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/core/util/clock.h> #include <inviwo/core/util/logcentral.h> namespace inviwo { Clock::Clock() { } void Clock::start() { startTime_ = std::chrono::high_resolution_clock::now(); tickTime_ = startTime_; } void Clock::tick() { tickTime_ = std::chrono::high_resolution_clock::now(); } float Clock::getElapsedMiliseconds() const { return 1000.f * getElapsedSeconds(); } float Clock::getElapsedSeconds() const { using std::chrono::duration_cast; using std::chrono::duration; return (duration_cast<duration<float>>(tickTime_ - startTime_)).count(); } void ScopedClockCPU::print() { clock_.tick(); if (clock_.getElapsedMiliseconds() > logIfAtLeastMilliSec_) { std::stringstream message; message << logMessage_ << ": " << clock_.getElapsedMiliseconds() << " ms"; LogCentral::getPtr()->log(logSource_, LogLevel::Info, LogAudience::Developer, __FILE__, __FUNCTION__, __LINE__, message.str()); } } void ScopedClockCPU::reset() { clock_.start(); } void ScopedClockCPU::printAndReset() { print(); reset(); } ScopedClockCPU::~ScopedClockCPU() { print(); } } // namespace<commit_msg>Core: ScopedClock: Using msToString to print readable time output<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/core/util/clock.h> #include <inviwo/core/util/logcentral.h> namespace inviwo { Clock::Clock() { } void Clock::start() { startTime_ = std::chrono::high_resolution_clock::now(); tickTime_ = startTime_; } void Clock::tick() { tickTime_ = std::chrono::high_resolution_clock::now(); } float Clock::getElapsedMiliseconds() const { return 1000.f * getElapsedSeconds(); } float Clock::getElapsedSeconds() const { using std::chrono::duration_cast; using std::chrono::duration; return (duration_cast<duration<float>>(tickTime_ - startTime_)).count(); } void ScopedClockCPU::print() { clock_.tick(); if (clock_.getElapsedMiliseconds() > logIfAtLeastMilliSec_) { std::stringstream message; message << logMessage_ << ": " << msToString(clock_.getElapsedMiliseconds()); LogCentral::getPtr()->log(logSource_, LogLevel::Info, LogAudience::Developer, __FILE__, __FUNCTION__, __LINE__, message.str()); } } void ScopedClockCPU::reset() { clock_.start(); } void ScopedClockCPU::printAndReset() { print(); reset(); } ScopedClockCPU::~ScopedClockCPU() { print(); } } // namespace<|endoftext|>
<commit_before>/* * Copyright 2017 deepstreamHub GmbH * * 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 DEEPSTREAM_WEBSOCKETS_HPP #define DEEPSTREAM_WEBSOCKETS_HPP #include <memory> #include <string> #include <utility> #include "time.hpp" #include <deepstream/core/buffer.hpp> namespace deepstream { namespace websockets { /** * This structure stores a WebSockets frame. * * To have the WebSocket data match the values in these enums, the * first eight bits of a frame must be interpreted in MSB order (most * significant bit first, also known as network order). This agrees * with the behavior of the POCO C++ WebSockets libraries. * * Enum classes are inappropriate here because a valid WebSocket frame * always contains combinations of flags. */ struct Frame { typedef int Flags; struct Bit { enum { FIN = 1u << 7, RSV1 = 1u << 6, RSV2 = 1u << 5, RSV3 = 1u << 4 }; }; struct Opcode { enum { CONTINUATION_FRAME = 0, TEXT_FRAME = 1, BINARY_FRAME = 2, CONNECTION_CLOSE_FRAME = 8, // pings are implemented in deepstream as `C|PI+` messages PING_FRAME = 9, // pongs are implemented in deepstream as `C|PO+` messages PONG_FRAME = 10 }; }; explicit Frame(Flags, const char*, std::size_t); Flags flags() const { return flags_; } const Buffer& payload() const { return payload_; } Flags flags_; Buffer payload_; }; enum class State { ERROR, OPEN, CLOSED }; struct Client { virtual ~Client() = default; /** * This method returns a new object of the concrete class * implementing this interface with the new object being connected * to the given URI. */ std::unique_ptr<Client> construct(const std::string& uri) const; std::string uri() const; time::Duration get_receive_timeout(); void set_receive_timeout(time::Duration); /** * This function tries to receive a single websocket frame. * * The meaning of the various combinations of return values is * listed below: * - received a frame: (Status::OPEN, frame) * - no data (socket timeout): (Status::OPEN, nullptr) * - received close frame: (Status::CLOSED, frame) * - received EOF: (Status::CLOSED, nullptr) * - received close frame with payload too long/too short: * (Status::ERROR, frame) */ std::pair<State, std::unique_ptr<Frame> > receive_frame(); /** * This function sends a non-fragmented text frame with the contents * of the buffer as payload. * * @return 0 on connection close or the number of bytes sent * otherwise */ State send_frame(const Buffer&); /** * This function sends a frame with the given flags and with the * contents of the buffer as payload. * * @return 0 on connection close or the number of bytes sent * otherwise */ State send_frame(const Buffer&, Frame::Flags); void close(); protected: virtual std::unique_ptr<websockets::Client> construct_impl(const std::string&) const = 0; virtual std::string uri_impl() const = 0; virtual time::Duration get_receive_timeout_impl() = 0; virtual void set_receive_timeout_impl(time::Duration) = 0; virtual std::pair<State, std::unique_ptr<Frame> > receive_frame_impl() = 0; virtual State send_frame_impl(const Buffer& buffer, Frame::Flags) = 0; virtual void close_impl() = 0; }; } } #endif <commit_msg>src/core/websockets.hpp: remove more dead code<commit_after>/* * Copyright 2017 deepstreamHub GmbH * * 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 DEEPSTREAM_WEBSOCKETS_HPP #define DEEPSTREAM_WEBSOCKETS_HPP #include <memory> #include <string> #include <utility> #include "time.hpp" #include <deepstream/core/buffer.hpp> namespace deepstream { namespace websockets { /** * This structure stores a WebSockets frame. * * To have the WebSocket data match the values in these enums, the * first eight bits of a frame must be interpreted in MSB order (most * significant bit first, also known as network order). This agrees * with the behavior of the POCO C++ WebSockets libraries. * * Enum classes are inappropriate here because a valid WebSocket frame * always contains combinations of flags. */ struct Frame { typedef int Flags; struct Bit { enum { FIN = 1u << 7, RSV1 = 1u << 6, RSV2 = 1u << 5, RSV3 = 1u << 4 }; }; struct Opcode { enum { CONTINUATION_FRAME = 0, TEXT_FRAME = 1, BINARY_FRAME = 2, CONNECTION_CLOSE_FRAME = 8, // pings are implemented in deepstream as `C|PI+` messages PING_FRAME = 9, // pongs are implemented in deepstream as `C|PO+` messages PONG_FRAME = 10 }; }; explicit Frame(Flags, const char*, std::size_t); Flags flags() const { return flags_; } const Buffer& payload() const { return payload_; } Flags flags_; Buffer payload_; }; enum class State { ERROR, OPEN, CLOSED }; struct Client { virtual ~Client() = default; /** * This method returns a new object of the concrete class * implementing this interface with the new object being connected * to the given URI. */ std::unique_ptr<Client> construct(const std::string& uri) const; std::string uri() const; time::Duration get_receive_timeout(); void set_receive_timeout(time::Duration); /** * This function tries to receive a single websocket frame. * * The meaning of the various combinations of return values is * listed below: * - received a frame: (Status::OPEN, frame) * - no data (socket timeout): (Status::OPEN, nullptr) * - received close frame: (Status::CLOSED, frame) * - received EOF: (Status::CLOSED, nullptr) * - received close frame with payload too long/too short: * (Status::ERROR, frame) */ std::pair<State, std::unique_ptr<Frame> > receive_frame(); /** * This function sends a frame with the given flags and with the * contents of the buffer as payload. * * @return 0 on connection close or the number of bytes sent * otherwise */ State send_frame(const Buffer&, Frame::Flags); void close(); protected: virtual std::unique_ptr<websockets::Client> construct_impl(const std::string&) const = 0; virtual std::string uri_impl() const = 0; virtual time::Duration get_receive_timeout_impl() = 0; virtual void set_receive_timeout_impl(time::Duration) = 0; virtual std::pair<State, std::unique_ptr<Frame> > receive_frame_impl() = 0; virtual State send_frame_impl(const Buffer& buffer, Frame::Flags) = 0; virtual void close_impl() = 0; }; } } #endif <|endoftext|>
<commit_before>#include "Base.h" #include "Gamepad.h" #include "Game.h" namespace gameplay { Gamepad::Gamepad(unsigned int handle, const char* formPath) : _id(""), _gamepadForm(NULL), _uiJoysticks(NULL), _uiButtons(NULL), _handle(handle), _buttonCount(0), _joystickCount(0), _triggerCount(0) { GP_ASSERT(formPath); _gamepadForm = Form::create(formPath); GP_ASSERT(_gamepadForm); _id = _gamepadForm->getId(); bindGamepadControls(_gamepadForm); } Gamepad::Gamepad(const char* id, unsigned int handle, unsigned int buttonCount, unsigned int joystickCount, unsigned int triggerCount) : _id(id), _gamepadForm(NULL), _uiJoysticks(NULL), _uiButtons(NULL), _handle(handle), _buttonCount(buttonCount), _joystickCount(joystickCount), _triggerCount(triggerCount) { } void Gamepad::bindGamepadControls(Container* container) { std::vector<Control*> controls = container->getControls(); std::vector<Control*>::iterator itr = controls.begin(); for (; itr != controls.end(); itr++) { Control* control = *itr; GP_ASSERT(control); if (control->isContainer()) { bindGamepadControls((Container*) control); } else if (std::strcmp("joystick", control->getType()) == 0) { control->addRef(); if (!_uiJoysticks) _uiJoysticks = new std::vector<Joystick*>; _uiJoysticks->push_back((Joystick*) control); _joystickCount++; } else if (std::strcmp("button", control->getType()) == 0) { control->addRef(); if (!_uiButtons) _uiButtons = new std::vector<Button*>; _uiButtons->push_back((Button*) control); _buttonCount++; } } } Gamepad::~Gamepad() { if (_gamepadForm) { if (_uiJoysticks) { for (std::vector<Joystick*>::iterator itr = _uiJoysticks->begin(); itr != _uiJoysticks->end(); itr++) { SAFE_RELEASE((*itr)); } _uiJoysticks->clear(); SAFE_DELETE(_uiJoysticks); } if (_uiButtons) { for (std::vector<Button*>::iterator itr = _uiButtons->begin(); itr!= _uiButtons->end(); itr++) { SAFE_RELEASE((*itr)); } _uiButtons->clear(); SAFE_DELETE(_uiButtons); } SAFE_RELEASE(_gamepadForm); } } const char* Gamepad::getId() const { return _id.c_str(); } void Gamepad::update(float elapsedTime) { if (_gamepadForm && _gamepadForm->isEnabled()) { _gamepadForm->update(elapsedTime); } else { isAttached(); } } void Gamepad::draw() { if (_gamepadForm && _gamepadForm->isEnabled()) { _gamepadForm->draw(); } } unsigned int Gamepad::getButtonCount() const { return _buttonCount; } Gamepad::ButtonState Gamepad::getButtonState(unsigned int buttonId) const { GP_ASSERT(buttonId < _buttonCount); if (_gamepadForm) { if (_uiButtons) return _uiButtons->at(buttonId)->getState() == Control::ACTIVE ? BUTTON_PRESSED : BUTTON_RELEASED; else return BUTTON_RELEASED; } else return Platform::getGamepadButtonState(_handle, buttonId) ? BUTTON_PRESSED : BUTTON_RELEASED; } unsigned int Gamepad::getJoystickCount() const { return _joystickCount; } bool Gamepad::isJoystickActive(unsigned int joystickId) const { GP_ASSERT(joystickId < _joystickCount); if (_gamepadForm) { if (_uiJoysticks) return !_uiJoysticks->at(joystickId)->getValue().isZero(); else return false; } else { return Platform::isGamepadJoystickActive(_handle, joystickId); } } void Gamepad::getJoystickValue(unsigned int joystickId, Vector2* outValue) const { GP_ASSERT(joystickId < _joystickCount); if (_gamepadForm) { if (_uiJoysticks) { const Vector2& value = _uiJoysticks->at(joystickId)->getValue(); outValue->set(value.x, value.y); } else { outValue->set(0.0f, 0.0f); } } else { Platform::getGamepadJoystickValue(_handle, joystickId, outValue); } } float Gamepad::getJoystickXAxis(unsigned int joystickId) const { return Platform::getGamepadJoystickXAxis(_handle, joystickId); } float Gamepad::getJoystickYAxis(unsigned int joystickId) const { return Platform::getGamepadJoystickYAxis(_handle, joystickId); } bool Gamepad::isVirtual() const { return _gamepadForm; } Form* Gamepad::getForm() const { return _gamepadForm; } bool Gamepad::isAttached() const { if (_gamepadForm) { return true; } else { return Platform::isGamepadAttached(_handle); } } }<commit_msg>Removes warnings.<commit_after>#include "Base.h" #include "Gamepad.h" #include "Game.h" namespace gameplay { Gamepad::Gamepad(unsigned int handle, const char* formPath) : _id(""), _handle(handle), _buttonCount(0), _joystickCount(0), _triggerCount(0), _gamepadForm(NULL), _uiJoysticks(NULL), _uiButtons(NULL) { GP_ASSERT(formPath); _gamepadForm = Form::create(formPath); GP_ASSERT(_gamepadForm); _id = _gamepadForm->getId(); bindGamepadControls(_gamepadForm); } Gamepad::Gamepad(const char* id, unsigned int handle, unsigned int buttonCount, unsigned int joystickCount, unsigned int triggerCount) : _id(id), _handle(handle), _buttonCount(buttonCount), _joystickCount(joystickCount), _triggerCount(triggerCount), _gamepadForm(NULL), _uiJoysticks(NULL), _uiButtons(NULL) { } void Gamepad::bindGamepadControls(Container* container) { std::vector<Control*> controls = container->getControls(); std::vector<Control*>::iterator itr = controls.begin(); for (; itr != controls.end(); itr++) { Control* control = *itr; GP_ASSERT(control); if (control->isContainer()) { bindGamepadControls((Container*) control); } else if (std::strcmp("joystick", control->getType()) == 0) { control->addRef(); if (!_uiJoysticks) _uiJoysticks = new std::vector<Joystick*>; _uiJoysticks->push_back((Joystick*) control); _joystickCount++; } else if (std::strcmp("button", control->getType()) == 0) { control->addRef(); if (!_uiButtons) _uiButtons = new std::vector<Button*>; _uiButtons->push_back((Button*) control); _buttonCount++; } } } Gamepad::~Gamepad() { if (_gamepadForm) { if (_uiJoysticks) { for (std::vector<Joystick*>::iterator itr = _uiJoysticks->begin(); itr != _uiJoysticks->end(); itr++) { SAFE_RELEASE((*itr)); } _uiJoysticks->clear(); SAFE_DELETE(_uiJoysticks); } if (_uiButtons) { for (std::vector<Button*>::iterator itr = _uiButtons->begin(); itr!= _uiButtons->end(); itr++) { SAFE_RELEASE((*itr)); } _uiButtons->clear(); SAFE_DELETE(_uiButtons); } SAFE_RELEASE(_gamepadForm); } } const char* Gamepad::getId() const { return _id.c_str(); } void Gamepad::update(float elapsedTime) { if (_gamepadForm && _gamepadForm->isEnabled()) { _gamepadForm->update(elapsedTime); } else { isAttached(); } } void Gamepad::draw() { if (_gamepadForm && _gamepadForm->isEnabled()) { _gamepadForm->draw(); } } unsigned int Gamepad::getButtonCount() const { return _buttonCount; } Gamepad::ButtonState Gamepad::getButtonState(unsigned int buttonId) const { GP_ASSERT(buttonId < _buttonCount); if (_gamepadForm) { if (_uiButtons) return _uiButtons->at(buttonId)->getState() == Control::ACTIVE ? BUTTON_PRESSED : BUTTON_RELEASED; else return BUTTON_RELEASED; } else return Platform::getGamepadButtonState(_handle, buttonId) ? BUTTON_PRESSED : BUTTON_RELEASED; } unsigned int Gamepad::getJoystickCount() const { return _joystickCount; } bool Gamepad::isJoystickActive(unsigned int joystickId) const { GP_ASSERT(joystickId < _joystickCount); if (_gamepadForm) { if (_uiJoysticks) return !_uiJoysticks->at(joystickId)->getValue().isZero(); else return false; } else { return Platform::isGamepadJoystickActive(_handle, joystickId); } } void Gamepad::getJoystickValue(unsigned int joystickId, Vector2* outValue) const { GP_ASSERT(joystickId < _joystickCount); if (_gamepadForm) { if (_uiJoysticks) { const Vector2& value = _uiJoysticks->at(joystickId)->getValue(); outValue->set(value.x, value.y); } else { outValue->set(0.0f, 0.0f); } } else { Platform::getGamepadJoystickValue(_handle, joystickId, outValue); } } float Gamepad::getJoystickXAxis(unsigned int joystickId) const { return Platform::getGamepadJoystickXAxis(_handle, joystickId); } float Gamepad::getJoystickYAxis(unsigned int joystickId) const { return Platform::getGamepadJoystickYAxis(_handle, joystickId); } bool Gamepad::isVirtual() const { return _gamepadForm; } Form* Gamepad::getForm() const { return _gamepadForm; } bool Gamepad::isAttached() const { if (_gamepadForm) { return true; } else { return Platform::isGamepadAttached(_handle); } } } <|endoftext|>
<commit_before>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <algorithm> #include <visionaray/math/detail/math.h> namespace MATH_NAMESPACE { namespace simd { //------------------------------------------------------------------------------------------------- // int4 members // MATH_FUNC VSNRAY_FORCE_INLINE int4::basic_int(int x, int y, int z, int w) : value{x, y, z, w} { } MATH_FUNC VSNRAY_FORCE_INLINE int4::basic_int(int const v[4]) : value{v[0], v[1], v[2], v[3]} { } MATH_FUNC VSNRAY_FORCE_INLINE int4::basic_int(int s) : value{s, s, s, s} { } MATH_FUNC VSNRAY_FORCE_INLINE int4::basic_int(unsigned s) : value{static_cast<int>(s), static_cast<int>(s), static_cast<int>(s), static_cast<int>(s)} { } //------------------------------------------------------------------------------------------------- // Bitwise cast // MATH_FUNC VSNRAY_FORCE_INLINE float4 reinterpret_as_float(int4 const& a) { return *reinterpret_cast<float4 const*>(&a); } //------------------------------------------------------------------------------------------------- // Static cast // MATH_FUNC VSNRAY_FORCE_INLINE float4 convert_to_float(int4 const& a) { return float4( static_cast<float>(a.value[0]), static_cast<float>(a.value[1]), static_cast<float>(a.value[2]), static_cast<float>(a.value[3]) ); } //------------------------------------------------------------------------------------------------- // select intrinsic // MATH_FUNC VSNRAY_FORCE_INLINE int4 select(mask4 const& m, int4 const& a, int4 const& b) { return int4( m.value[0] ? a.value[0] : b.value[0], m.value[1] ? a.value[1] : b.value[1], m.value[2] ? a.value[2] : b.value[2], m.value[3] ? a.value[3] : b.value[3] ); } //------------------------------------------------------------------------------------------------- // Load / store / get // MATH_FUNC VSNRAY_FORCE_INLINE void store(int dst[4], int4 const& v) { dst[0] = v.value[0]; dst[1] = v.value[1]; dst[2] = v.value[2]; dst[3] = v.value[3]; } MATH_FUNC VSNRAY_FORCE_INLINE void store(unsigned dst[4], int4 const& v) { dst[0] = static_cast<unsigned>(v.value[0]); dst[1] = static_cast<unsigned>(v.value[1]); dst[2] = static_cast<unsigned>(v.value[2]); dst[3] = static_cast<unsigned>(v.value[3]); } template <int A0, int A1, int A2, int A3> MATH_FUNC VSNRAY_FORCE_INLINE int4 shuffle(int4 const& a) { return int4(a.value[A0], a.value[A1], a.value[A2], a.value[A3]); } template <size_t I> MATH_FUNC VSNRAY_FORCE_INLINE int& get(int4& v) { static_assert(I >= 0 && I < 4, "Index out of range for SIMD vector access"); return v.value[I]; } template <size_t I> MATH_FUNC VSNRAY_FORCE_INLINE int const& get(int4 const& v) { static_assert(I >= 0 && I < 4, "Index out of range for SIMD vector access"); return v.value[I]; } //------------------------------------------------------------------------------------------------- // Basic arithmethic // MATH_FUNC VSNRAY_FORCE_INLINE int4 operator+(int4 const& v) { return int4( +v.value[0], +v.value[1], +v.value[2], +v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator-(int4 const& v) { return int4( -v.value[0], -v.value[1], -v.value[2], -v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator+(int4 const& u, int4 const& v) { return int4( u.value[0] + v.value[0], u.value[1] + v.value[1], u.value[2] + v.value[2], u.value[3] + v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator-(int4 const& u, int4 const& v) { return int4( u.value[0] + v.value[0], u.value[1] + v.value[1], u.value[2] + v.value[2], u.value[3] + v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator*(int4 const& u, int4 const& v) { return int4( u.value[0] * v.value[0], u.value[1] * v.value[1], u.value[2] * v.value[2], u.value[3] * v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator/(int4 const& u, int4 const& v) { return int4( u.value[0] / v.value[0], u.value[1] / v.value[1], u.value[2] / v.value[2], u.value[3] / v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator%(int4 const& u, int4 const& v) { return int4( u.value[0] % v.value[0], u.value[1] % v.value[1], u.value[2] % v.value[2], u.value[3] % v.value[3] ); } //------------------------------------------------------------------------------------------------- // Bitwise operations // MATH_FUNC VSNRAY_FORCE_INLINE int4 operator&(int4 const& u, int4 const& v) { return int4( u.value[0] & v.value[0], u.value[1] & v.value[1], u.value[2] & v.value[2], u.value[3] & v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator|(int4 const& u, int4 const& v) { return int4( u.value[0] | v.value[0], u.value[1] | v.value[1], u.value[2] | v.value[2], u.value[3] | v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator^(int4 const& u, int4 const& v) { return int4( u.value[0] ^ v.value[0], u.value[1] ^ v.value[1], u.value[2] ^ v.value[2], u.value[3] ^ v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator<<(int4 const& a, int count) { return int4( a.value[0] << count, a.value[1] << count, a.value[2] << count, a.value[3] << count ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator>>(int4 const& a, int count) { return int4( a.value[0] >> count, a.value[1] >> count, a.value[2] >> count, a.value[3] >> count ); } //------------------------------------------------------------------------------------------------- // Logical operations // MATH_FUNC VSNRAY_FORCE_INLINE mask4 operator&&(int4 const& u, int4 const& v) { return mask4( u.value[0] && v.value[0], u.value[1] && v.value[1], u.value[2] && v.value[2], u.value[3] && v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE mask4 operator||(int4 const& u, int4 const& v) { return mask4( u.value[0] || v.value[0], u.value[1] || v.value[1], u.value[2] || v.value[2], u.value[3] || v.value[3] ); } //------------------------------------------------------------------------------------------------- // Comparisons // MATH_FUNC VSNRAY_FORCE_INLINE mask4 operator<(int4 const& u, int4 const& v) { return mask4( u.value[0] < v.value[0], u.value[1] < v.value[1], u.value[2] < v.value[2], u.value[3] < v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE mask4 operator>(int4 const& u, int4 const& v) { return mask4( u.value[0] > v.value[0], u.value[1] > v.value[1], u.value[2] > v.value[2], u.value[3] > v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE mask4 operator==(int4 const& u, int4 const& v) { return mask4( u.value[0] == v.value[0], u.value[1] == v.value[1], u.value[2] == v.value[2], u.value[3] == v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE mask4 operator<=(int4 const& u, int4 const& v) { return mask4( u.value[0] <= v.value[0], u.value[1] <= v.value[1], u.value[2] <= v.value[2], u.value[3] <= v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE mask4 operator>=(int4 const& u, int4 const& v) { return mask4( u.value[0] >= v.value[0], u.value[1] >= v.value[1], u.value[2] >= v.value[2], u.value[3] >= v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE mask4 operator!=(int4 const& u, int4 const& v) { return mask4( u.value[0] != v.value[0], u.value[1] != v.value[1], u.value[2] != v.value[2], u.value[3] != v.value[3] ); } //------------------------------------------------------------------------------------------------- // Math functions // MATH_FUNC VSNRAY_FORCE_INLINE int4 min(int4 const& u, int4 const& v) { return int4( MATH_NAMESPACE::min(u.value[0], v.value[0]), MATH_NAMESPACE::min(u.value[1], v.value[1]), MATH_NAMESPACE::min(u.value[2], v.value[2]), MATH_NAMESPACE::min(u.value[3], v.value[3]) ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 max(int4 const& u, int4 const& v) { return int4( MATH_NAMESPACE::max(u.value[0], v.value[0]), MATH_NAMESPACE::max(u.value[1], v.value[1]), MATH_NAMESPACE::max(u.value[2], v.value[2]), MATH_NAMESPACE::max(u.value[3], v.value[3]) ); } } // simd } // MATH_NAMESPACE <commit_msg>Fix binary operator-(builtin::int4)<commit_after>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <algorithm> #include <visionaray/math/detail/math.h> namespace MATH_NAMESPACE { namespace simd { //------------------------------------------------------------------------------------------------- // int4 members // MATH_FUNC VSNRAY_FORCE_INLINE int4::basic_int(int x, int y, int z, int w) : value{x, y, z, w} { } MATH_FUNC VSNRAY_FORCE_INLINE int4::basic_int(int const v[4]) : value{v[0], v[1], v[2], v[3]} { } MATH_FUNC VSNRAY_FORCE_INLINE int4::basic_int(int s) : value{s, s, s, s} { } MATH_FUNC VSNRAY_FORCE_INLINE int4::basic_int(unsigned s) : value{static_cast<int>(s), static_cast<int>(s), static_cast<int>(s), static_cast<int>(s)} { } //------------------------------------------------------------------------------------------------- // Bitwise cast // MATH_FUNC VSNRAY_FORCE_INLINE float4 reinterpret_as_float(int4 const& a) { return *reinterpret_cast<float4 const*>(&a); } //------------------------------------------------------------------------------------------------- // Static cast // MATH_FUNC VSNRAY_FORCE_INLINE float4 convert_to_float(int4 const& a) { return float4( static_cast<float>(a.value[0]), static_cast<float>(a.value[1]), static_cast<float>(a.value[2]), static_cast<float>(a.value[3]) ); } //------------------------------------------------------------------------------------------------- // select intrinsic // MATH_FUNC VSNRAY_FORCE_INLINE int4 select(mask4 const& m, int4 const& a, int4 const& b) { return int4( m.value[0] ? a.value[0] : b.value[0], m.value[1] ? a.value[1] : b.value[1], m.value[2] ? a.value[2] : b.value[2], m.value[3] ? a.value[3] : b.value[3] ); } //------------------------------------------------------------------------------------------------- // Load / store / get // MATH_FUNC VSNRAY_FORCE_INLINE void store(int dst[4], int4 const& v) { dst[0] = v.value[0]; dst[1] = v.value[1]; dst[2] = v.value[2]; dst[3] = v.value[3]; } MATH_FUNC VSNRAY_FORCE_INLINE void store(unsigned dst[4], int4 const& v) { dst[0] = static_cast<unsigned>(v.value[0]); dst[1] = static_cast<unsigned>(v.value[1]); dst[2] = static_cast<unsigned>(v.value[2]); dst[3] = static_cast<unsigned>(v.value[3]); } template <int A0, int A1, int A2, int A3> MATH_FUNC VSNRAY_FORCE_INLINE int4 shuffle(int4 const& a) { return int4(a.value[A0], a.value[A1], a.value[A2], a.value[A3]); } template <size_t I> MATH_FUNC VSNRAY_FORCE_INLINE int& get(int4& v) { static_assert(I >= 0 && I < 4, "Index out of range for SIMD vector access"); return v.value[I]; } template <size_t I> MATH_FUNC VSNRAY_FORCE_INLINE int const& get(int4 const& v) { static_assert(I >= 0 && I < 4, "Index out of range for SIMD vector access"); return v.value[I]; } //------------------------------------------------------------------------------------------------- // Basic arithmethic // MATH_FUNC VSNRAY_FORCE_INLINE int4 operator+(int4 const& v) { return int4( +v.value[0], +v.value[1], +v.value[2], +v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator-(int4 const& v) { return int4( -v.value[0], -v.value[1], -v.value[2], -v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator+(int4 const& u, int4 const& v) { return int4( u.value[0] + v.value[0], u.value[1] + v.value[1], u.value[2] + v.value[2], u.value[3] + v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator-(int4 const& u, int4 const& v) { return int4( u.value[0] - v.value[0], u.value[1] - v.value[1], u.value[2] - v.value[2], u.value[3] - v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator*(int4 const& u, int4 const& v) { return int4( u.value[0] * v.value[0], u.value[1] * v.value[1], u.value[2] * v.value[2], u.value[3] * v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator/(int4 const& u, int4 const& v) { return int4( u.value[0] / v.value[0], u.value[1] / v.value[1], u.value[2] / v.value[2], u.value[3] / v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator%(int4 const& u, int4 const& v) { return int4( u.value[0] % v.value[0], u.value[1] % v.value[1], u.value[2] % v.value[2], u.value[3] % v.value[3] ); } //------------------------------------------------------------------------------------------------- // Bitwise operations // MATH_FUNC VSNRAY_FORCE_INLINE int4 operator&(int4 const& u, int4 const& v) { return int4( u.value[0] & v.value[0], u.value[1] & v.value[1], u.value[2] & v.value[2], u.value[3] & v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator|(int4 const& u, int4 const& v) { return int4( u.value[0] | v.value[0], u.value[1] | v.value[1], u.value[2] | v.value[2], u.value[3] | v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator^(int4 const& u, int4 const& v) { return int4( u.value[0] ^ v.value[0], u.value[1] ^ v.value[1], u.value[2] ^ v.value[2], u.value[3] ^ v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator<<(int4 const& a, int count) { return int4( a.value[0] << count, a.value[1] << count, a.value[2] << count, a.value[3] << count ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 operator>>(int4 const& a, int count) { return int4( a.value[0] >> count, a.value[1] >> count, a.value[2] >> count, a.value[3] >> count ); } //------------------------------------------------------------------------------------------------- // Logical operations // MATH_FUNC VSNRAY_FORCE_INLINE mask4 operator&&(int4 const& u, int4 const& v) { return mask4( u.value[0] && v.value[0], u.value[1] && v.value[1], u.value[2] && v.value[2], u.value[3] && v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE mask4 operator||(int4 const& u, int4 const& v) { return mask4( u.value[0] || v.value[0], u.value[1] || v.value[1], u.value[2] || v.value[2], u.value[3] || v.value[3] ); } //------------------------------------------------------------------------------------------------- // Comparisons // MATH_FUNC VSNRAY_FORCE_INLINE mask4 operator<(int4 const& u, int4 const& v) { return mask4( u.value[0] < v.value[0], u.value[1] < v.value[1], u.value[2] < v.value[2], u.value[3] < v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE mask4 operator>(int4 const& u, int4 const& v) { return mask4( u.value[0] > v.value[0], u.value[1] > v.value[1], u.value[2] > v.value[2], u.value[3] > v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE mask4 operator==(int4 const& u, int4 const& v) { return mask4( u.value[0] == v.value[0], u.value[1] == v.value[1], u.value[2] == v.value[2], u.value[3] == v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE mask4 operator<=(int4 const& u, int4 const& v) { return mask4( u.value[0] <= v.value[0], u.value[1] <= v.value[1], u.value[2] <= v.value[2], u.value[3] <= v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE mask4 operator>=(int4 const& u, int4 const& v) { return mask4( u.value[0] >= v.value[0], u.value[1] >= v.value[1], u.value[2] >= v.value[2], u.value[3] >= v.value[3] ); } MATH_FUNC VSNRAY_FORCE_INLINE mask4 operator!=(int4 const& u, int4 const& v) { return mask4( u.value[0] != v.value[0], u.value[1] != v.value[1], u.value[2] != v.value[2], u.value[3] != v.value[3] ); } //------------------------------------------------------------------------------------------------- // Math functions // MATH_FUNC VSNRAY_FORCE_INLINE int4 min(int4 const& u, int4 const& v) { return int4( MATH_NAMESPACE::min(u.value[0], v.value[0]), MATH_NAMESPACE::min(u.value[1], v.value[1]), MATH_NAMESPACE::min(u.value[2], v.value[2]), MATH_NAMESPACE::min(u.value[3], v.value[3]) ); } MATH_FUNC VSNRAY_FORCE_INLINE int4 max(int4 const& u, int4 const& v) { return int4( MATH_NAMESPACE::max(u.value[0], v.value[0]), MATH_NAMESPACE::max(u.value[1], v.value[1]), MATH_NAMESPACE::max(u.value[2], v.value[2]), MATH_NAMESPACE::max(u.value[3], v.value[3]) ); } } // simd } // MATH_NAMESPACE <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: otherjre.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2006-06-20 00:08:52 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "osl/thread.h" #include "otherjre.hxx" using namespace rtl; using namespace std; namespace jfw_plugin { Reference<VendorBase> OtherInfo::createInstance() { return new OtherInfo; } char const* const* OtherInfo::getJavaExePaths(int * size) { static char const * ar[] = { #ifdef WNT "bin/java.exe", "jre/bin/java.exe" #elif UNX "bin/java", "jre/bin/java" #endif }; *size = sizeof (ar) / sizeof (char*); return ar; } char const* const* OtherInfo::getRuntimePaths(int * size) { static char const* ar[]= { #ifdef WNT "/bin/client/jvm.dll", "/bin/hotspot/jvm.dll", "/bin/classic/jvm.dll", "/bin/jrockit/jvm.dll" #elif UNX #ifdef MACOSX "/../../../JavaVM" #else "/bin/classic/libjvm.so", // for IBM Java "/jre/bin/classic/libjvm.so", // for IBM Java "/lib/" JFW_PLUGIN_ARCH "/client/libjvm.so", // for Blackdown PPC "/lib/" JFW_PLUGIN_ARCH "/server/libjvm.so", // for Blackdown AMD64 "/lib/" JFW_PLUGIN_ARCH "/classic/libjvm.so", // for Blackdown PPC "/lib/" JFW_PLUGIN_ARCH "/jrockit/libjvm.so" // for Java of BEA Systems #endif #endif }; *size = sizeof(ar) / sizeof (char*); return ar; } char const* const* OtherInfo::getLibraryPaths(int* size) { #ifdef UNX static char const * ar[] = { #ifdef MACOSX "/../Libraries", "/lib" #else "/bin", "/jre/bin", "/bin/classic", "/jre/bin/classic", "/lib/" JFW_PLUGIN_ARCH "/client", "/lib/" JFW_PLUGIN_ARCH "/server", "/lib/" JFW_PLUGIN_ARCH "/classic", "/lib/" JFW_PLUGIN_ARCH "/jrockit", "/lib/" JFW_PLUGIN_ARCH "/native_threads", "/lib/" JFW_PLUGIN_ARCH #endif }; *size = sizeof(ar) / sizeof (char*); return ar; #else size = 0; return NULL; #endif } int OtherInfo::compareVersions(const rtl::OUString& /*sSecond*/) const { //Need to provide an own algorithm for comparing version. //Because this function returns always 0, which means the version of //this JRE and the provided version "sSecond" are equal, one cannot put //any excludeVersion entries in the javavendors.xml file. return 0; } } <commit_msg>INTEGRATION: CWS pchfix02 (1.12.16); FILE MERGED 2006/09/01 17:31:39 kaib 1.12.16.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: otherjre.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: obo $ $Date: 2006-09-16 17:45:42 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_jvmfwk.hxx" #include "osl/thread.h" #include "otherjre.hxx" using namespace rtl; using namespace std; namespace jfw_plugin { Reference<VendorBase> OtherInfo::createInstance() { return new OtherInfo; } char const* const* OtherInfo::getJavaExePaths(int * size) { static char const * ar[] = { #ifdef WNT "bin/java.exe", "jre/bin/java.exe" #elif UNX "bin/java", "jre/bin/java" #endif }; *size = sizeof (ar) / sizeof (char*); return ar; } char const* const* OtherInfo::getRuntimePaths(int * size) { static char const* ar[]= { #ifdef WNT "/bin/client/jvm.dll", "/bin/hotspot/jvm.dll", "/bin/classic/jvm.dll", "/bin/jrockit/jvm.dll" #elif UNX #ifdef MACOSX "/../../../JavaVM" #else "/bin/classic/libjvm.so", // for IBM Java "/jre/bin/classic/libjvm.so", // for IBM Java "/lib/" JFW_PLUGIN_ARCH "/client/libjvm.so", // for Blackdown PPC "/lib/" JFW_PLUGIN_ARCH "/server/libjvm.so", // for Blackdown AMD64 "/lib/" JFW_PLUGIN_ARCH "/classic/libjvm.so", // for Blackdown PPC "/lib/" JFW_PLUGIN_ARCH "/jrockit/libjvm.so" // for Java of BEA Systems #endif #endif }; *size = sizeof(ar) / sizeof (char*); return ar; } char const* const* OtherInfo::getLibraryPaths(int* size) { #ifdef UNX static char const * ar[] = { #ifdef MACOSX "/../Libraries", "/lib" #else "/bin", "/jre/bin", "/bin/classic", "/jre/bin/classic", "/lib/" JFW_PLUGIN_ARCH "/client", "/lib/" JFW_PLUGIN_ARCH "/server", "/lib/" JFW_PLUGIN_ARCH "/classic", "/lib/" JFW_PLUGIN_ARCH "/jrockit", "/lib/" JFW_PLUGIN_ARCH "/native_threads", "/lib/" JFW_PLUGIN_ARCH #endif }; *size = sizeof(ar) / sizeof (char*); return ar; #else size = 0; return NULL; #endif } int OtherInfo::compareVersions(const rtl::OUString& /*sSecond*/) const { //Need to provide an own algorithm for comparing version. //Because this function returns always 0, which means the version of //this JRE and the provided version "sSecond" are equal, one cannot put //any excludeVersion entries in the javavendors.xml file. return 0; } } <|endoftext|>
<commit_before>#ifndef BLENDMODE_HPP_INCLUDED #define BLENDMODE_HPP_INCLUDED namespace gst { enum class BlendMode { NONE, ADDITIVE, MULTIPLICATIVE, INTERPOLATIVE }; } #endif <commit_msg>add documentation to blend mode<commit_after>#ifndef BLENDMODE_HPP_INCLUDED #define BLENDMODE_HPP_INCLUDED namespace gst { // Supported blending techniques. enum class BlendMode { NONE, // Blending disabled. ADDITIVE, // Additive blending: out = src_frag + dst_frag. MULTIPLICATIVE, // Multiplicative blending: out = src_frag * dst_frag. INTERPOLATIVE // Interpolative blending: out = (src_alpha * src_frag) + ((1 - src_alpha) * dst_frag). }; } #endif <|endoftext|>
<commit_before><commit_msg>Delete unused code<commit_after><|endoftext|>
<commit_before>#include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkSphereSource.h" #include "vtkShrinkFilter.h" #include "vtkElevationFilter.h" #include "vtkDataSetMapper.h" #include "vtkActor.h" #include "SaveImage.h" void main( int argc, char *argv[] ) { vtkRenderer *renderer = vtkRenderer::New(); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->AddRenderer(renderer); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); vtkSphereSource *sphere = vtkSphereSource::New(); sphere->SetThetaResolution(12); sphere->SetPhiResolution(12); vtkShrinkFilter *shrink = vtkShrinkFilter::New(); shrink->SetInput(sphere->GetOutput()); shrink->SetShrinkFactor(0.9); vtkElevationFilter *colorIt = vtkElevationFilter::New(); colorIt->SetInput(shrink->GetOutput()); colorIt->SetLowPoint(0,0,-.5); colorIt->SetHighPoint(0,0,.5); vtkDataSetMapper *mapper = vtkDataSetMapper::New(); mapper->SetInput(colorIt->GetOutput()); vtkActor *actor = vtkActor::New(); actor->SetMapper(mapper); renderer->AddActor(actor); renderer->SetBackground(1,1,1); renWin->SetSize(300,300); renWin->Render(); // execute first time shrink->SetInput(colorIt->GetOutput()); // create loop renWin->Render(); // begin looping renWin->Render(); renWin->Render(); SAVEIMAGE( renWin ); // interact with data iren->Start(); // Clean up renderer->Delete(); renWin->Delete(); iren->Delete(); sphere->Delete(); shrink->Delete(); colorIt->Delete(); mapper->Delete(); actor->Delete(); } <commit_msg>Removed culler from renderer so that we don't get any extra updates (which causes the filter to execute more times that it used to and therefore messes up the regression test)<commit_after>#include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkSphereSource.h" #include "vtkShrinkFilter.h" #include "vtkElevationFilter.h" #include "vtkDataSetMapper.h" #include "vtkActor.h" #include "SaveImage.h" void main( int argc, char *argv[] ) { vtkRenderer *renderer = vtkRenderer::New(); renderer->GetCullers()->RemoveAllItems(); vtkRenderWindow *renWin = vtkRenderWindow::New(); renWin->AddRenderer(renderer); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); iren->SetRenderWindow(renWin); vtkSphereSource *sphere = vtkSphereSource::New(); sphere->SetThetaResolution(12); sphere->SetPhiResolution(12); vtkShrinkFilter *shrink = vtkShrinkFilter::New(); shrink->SetInput(sphere->GetOutput()); shrink->SetShrinkFactor(0.9); vtkElevationFilter *colorIt = vtkElevationFilter::New(); colorIt->SetInput(shrink->GetOutput()); colorIt->SetLowPoint(0,0,-.5); colorIt->SetHighPoint(0,0,.5); vtkDataSetMapper *mapper = vtkDataSetMapper::New(); mapper->SetInput(colorIt->GetOutput()); vtkActor *actor = vtkActor::New(); actor->SetMapper(mapper); renderer->AddActor(actor); renderer->SetBackground(1,1,1); renWin->SetSize(300,300); renWin->Render(); // execute first time shrink->SetInput(colorIt->GetOutput()); // create loop renWin->Render(); // begin looping renWin->Render(); renWin->Render(); SAVEIMAGE( renWin ); // interact with data iren->Start(); // Clean up renderer->Delete(); renWin->Delete(); iren->Delete(); sphere->Delete(); shrink->Delete(); colorIt->Delete(); mapper->Delete(); actor->Delete(); } <|endoftext|>
<commit_before>#include "mitkAutoCropImageFilter.h" #include "mitkImageCast.h" //#include "itkLinearInterpolateImageFunction.h" //#include <itkBinaryMedianImageFilter.h> #include <itkImageRegionConstIterator.h> #include <itkImageRegionIterator.h> #include <mitkImage.h> #include <vtkLinearTransform.h> #include "mitkTimeHelper.h" #include "mitkImageAccessByItk.h" #include "mitkGeometry3D.h" #include "mitkStatusBar.h" template < typename TPixel, unsigned int VImageDimension> void mitk::AutoCropImageFilter::Crop3DImage( itk::Image< TPixel, VImageDimension >* inputItkImage, mitk::AutoCropImageFilter* cropper, int timeStep) { typedef itk::Image< TPixel, VImageDimension > InternalImageType; typedef InternalImageType::Pointer InternalImagePointer; typedef itk::CropImageFilter<InternalImageType,InternalImageType> FilterType; InternalImagePointer outputItk = InternalImageType::New(); FilterType::Pointer cropFilter = FilterType::New(); cropFilter->SetLowerBoundaryCropSize( m_LowerBounds ); cropFilter->SetUpperBoundaryCropSize( m_UpperBounds ); cropFilter->SetInput( inputItkImage ); cropFilter->Update(); outputItk = cropFilter->GetOutput(); outputItk->DisconnectPipeline(); // ************************* typedef typename itk::ImageBase<VImageDimension>::RegionType ItkRegionType; typedef itk::ImageRegionIteratorWithIndex< InternalImageType > ItkInputImageIteratorType; if (inputItkImage == NULL) { mitk::StatusBar::DisplayErrorText ("An internal error occurred. Can't convert Image. Please report to bugs@mitk.org"); std::cout << " image is NULL...returning" << std::endl; return; } // PART 1: convert m_InputRequestedRegion (type mitk::SlicedData::RegionType) // into ITK-image-region (ItkImageType::RegionType) // unfortunately, we cannot use input->GetRequestedRegion(), because it // has been destroyed by the mitk::CastToItkImage call of PART 1 // (which sets the m_RequestedRegion to the LargestPossibleRegion). // Thus, use our own member m_InputRequestedRegion insead. // first convert the index typename ItkRegionType::IndexType index; index.Fill(0); typename ItkRegionType::SizeType size; size[0] = outputItk->GetLargestPossibleRegion().GetSize()[0]; size[1] = outputItk->GetLargestPossibleRegion().GetSize()[1]; size[2] = outputItk->GetLargestPossibleRegion().GetSize()[2]; //create the ITK-image-region out of index and size ItkRegionType inputRegionOfInterest(index, size); // PART 2: get access to the MITK output image via an ITK image typename mitk::ImageToItk<InternalImageType>::Pointer outputimagetoitk = mitk::ImageToItk<InternalImageType>::New(); mitk::Image::Pointer timeImage = m_OutputTimeSelector->GetOutput(); outputimagetoitk->SetInput(timeImage); outputimagetoitk->Update(); typename InternalImageType::Pointer outputItkImage = outputimagetoitk->GetOutput(); // outputItkImage->DisconnectPipeline(); // PART 3: iterate over input and output using ITK iterators // create the iterators ItkInputImageIteratorType inputIt( outputItk, outputItk->GetLargestPossibleRegion()); ItkInputImageIteratorType outputIt( outputItkImage, inputRegionOfInterest ); // Cut the boundingbox out of the image by iterating through // all pixels and checking if they are inside using IsInside() mitk::Point3D p; mitk::Geometry3D* inputGeometry = this->GetInput()->GetGeometry(); for ( inputIt.GoToBegin(), outputIt.GoToBegin(); !inputIt.IsAtEnd(); ++inputIt, ++outputIt) { outputIt.Set(inputIt.Get()); } std::cout << "GenerateData done." << std::endl; // ************************* //// this->GraftNthOutput(0,output); // this->SetNthOutput(0,output); } mitk::AutoCropImageFilter::AutoCropImageFilter() : m_BackgroundValue(0), m_MarginFactor(1.0) { m_InputTimeSelector = mitk::ImageTimeSelector::New(); m_OutputTimeSelector = mitk::ImageTimeSelector::New(); } mitk::AutoCropImageFilter::~AutoCropImageFilter() { } void mitk::AutoCropImageFilter::GenerateOutputInformation() { ComputeNewImageBounds(); // mitk::Image::ConstPointer input = this->GetInput(); mitk::Image::Pointer input = const_cast< mitk::Image * > ( this->GetInput() ); mitk::Image::Pointer output = this->GetOutput(); if ((output->IsInitialized()) && (output->GetPipelineMTime() <= m_TimeOfHeaderInitialization.GetMTime())) return; itkDebugMacro(<<"GenerateOutputInformation()"); mitk::Geometry3D* inputImageGeometry = input->GetSlicedGeometry(); // PART I: initialize input requested region. We do this already here (and not // later when GenerateInputRequestedRegion() is called), because we // also need the information to setup the output. // pre-initialize input-requested-region to largest-possible-region // and correct time-region; spatial part will be cropped by // bounding-box of bounding-object below m_InputRequestedRegion = input->GetLargestPossibleRegion(); // build region out of bounding-box of cropping region size mitk::SlicedData::IndexType index; index[0] = m_RegionSize[0]; index[1] = m_RegionSize[1]; index[2] = m_RegionSize[2]; index[3] = m_InputRequestedRegion.GetIndex()[3]; index[4] = m_InputRequestedRegion.GetIndex()[4]; mitk::SlicedData::SizeType size; size[0] = m_RegionSize[0]; size[1] = m_RegionSize[1]; size[2] = m_RegionSize[2]; size[3] = m_InputRequestedRegion.GetSize()[3]; size[4] = m_InputRequestedRegion.GetSize()[4]; mitk::SlicedData::RegionType boRegion(index, size); // crop input-requested-region with cropping region computed from the image data if(m_InputRequestedRegion.Crop(boRegion)==false) { // crop not possible => do nothing: set time size to 0. size.Fill(0); m_InputRequestedRegion.SetSize(size); boRegion.SetSize(size); return; } // set input-requested-region, because we access it later in // GenerateInputRequestedRegion (there we just set the time) input->SetRequestedRegion(&m_InputRequestedRegion); // PART II: initialize output image unsigned int dimension = input->GetDimension(); unsigned int *dimensions = new unsigned int [dimension]; itk2vtk(m_InputRequestedRegion.GetSize(), dimensions); if(dimension>3) memcpy(dimensions+3, input->GetDimensions()+3, (dimension-3)*sizeof(unsigned int)); output->Initialize(mitk::PixelType( GetOutputPixelType() ), dimension, dimensions); delete [] dimensions; // set the spacing mitk::Vector3D spacing = input->GetSlicedGeometry()->GetSpacing(); output->SetSpacing(spacing); // Position the output Image to match the corresponding region of the input image mitk::SlicedGeometry3D* slicedGeometry = output->GetSlicedGeometry(); const mitk::SlicedData::IndexType& start = m_InputRequestedRegion.GetIndex(); mitk::Point3D origin; vtk2itk(start, origin); inputImageGeometry->IndexToWorld(origin, origin); origin.Fill(0); slicedGeometry->SetOrigin(origin); mitk::TimeSlicedGeometry* timeSlicedGeometry = output->GetTimeSlicedGeometry(); timeSlicedGeometry->InitializeEvenlyTimed(slicedGeometry, output->GetDimension(3)); timeSlicedGeometry->CopyTimes(input->GetTimeSlicedGeometry()); m_TimeOfHeaderInitialization.Modified(); output->SetPropertyList(input->GetPropertyList()->Clone()); } void mitk::AutoCropImageFilter::GenerateData() { mitk::Image::ConstPointer input = this->GetInput(); mitk::Image::Pointer output = this->GetOutput(); if(input.IsNull()) return; if((output->IsInitialized()==false) ) return; m_InputTimeSelector->SetInput(input); m_OutputTimeSelector->SetInput(this->GetOutput()); mitk::SlicedData::RegionType outputRegion = input->GetRequestedRegion(); const mitk::TimeSlicedGeometry *outputTimeGeometry = output->GetTimeSlicedGeometry(); const mitk::TimeSlicedGeometry *inputTimeGeometry = input->GetTimeSlicedGeometry(); ScalarType timeInMS; int timestep=0; int tstart=outputRegion.GetIndex(3); int tmax=tstart+outputRegion.GetSize(3); int t; for(t=tstart;t<tmax;++t) { timeInMS = outputTimeGeometry->TimeStepToMS( t ); timestep = inputTimeGeometry->MSToTimeStep( timeInMS ); m_InputTimeSelector->SetTimeNr(t); m_InputTimeSelector->UpdateLargestPossibleRegion(); m_OutputTimeSelector->SetTimeNr(t); m_OutputTimeSelector->UpdateLargestPossibleRegion(); timestep = inputTimeGeometry->MSToTimeStep( timeInMS ); AccessFixedDimensionByItk_2( m_InputTimeSelector->GetOutput(), Crop3DImage, 3, this, timestep); } float origin[3]; origin[0] = m_RegionIndex[0]; origin[1] = m_RegionIndex[1]; origin[2] = m_RegionIndex[2]; Vector3D originVector; vtk2itk(origin, originVector); this->GetOutput()->GetGeometry()->Translate(originVector); m_TimeOfHeaderInitialization.Modified(); } void mitk::AutoCropImageFilter::ComputeNewImageBounds() { mitk::Image::ConstPointer img; if ( this->GetInput()->GetDimension()==4) { mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New(); timeSelector->SetInput( this->GetInput() ); timeSelector->SetTimeNr( 0 ); timeSelector->UpdateLargestPossibleRegion(); img = timeSelector->GetOutput(); } else if (this->GetInput()->GetDimension() == 3 ) { img = this->GetInput(); } ImagePointer inputItk = ImageType::New(); mitk::CastToItkImage( img , inputItk ); typedef itk::ImageRegionConstIterator< ImageType > ConstIteratorType; ConstIteratorType inIt( inputItk, inputItk->GetLargestPossibleRegion() ); ImageType::IndexType minima,maxima; maxima = inputItk->GetLargestPossibleRegion().GetIndex(); minima[0] = inputItk->GetLargestPossibleRegion().GetSize()[0]; minima[1] = inputItk->GetLargestPossibleRegion().GetSize()[1]; minima[2] = inputItk->GetLargestPossibleRegion().GetSize()[2]; for ( inIt.GoToBegin(); !inIt.IsAtEnd(); ++inIt) { float pix_val = inIt.Get(); if ( fabs(pix_val - m_BackgroundValue) > mitk::eps ) { for (int i=0; i < 3; i++) { minima[i] = vnl_math_min((int)minima[i],(int)(inIt.GetIndex()[i])); maxima[i] = vnl_math_max((int)maxima[i],(int)(inIt.GetIndex()[i])); } } } m_RegionSize[0] = (ImageType::RegionType::SizeType::SizeValueType)(m_MarginFactor * (maxima[0] - minima[0])); m_RegionSize[1] = (ImageType::RegionType::SizeType::SizeValueType)(m_MarginFactor * (maxima[1] - minima[1])); m_RegionSize[2] = (ImageType::RegionType::SizeType::SizeValueType)(m_MarginFactor * (maxima[2] - minima[2])); m_RegionIndex = minima; m_RegionIndex[0] -= (m_RegionSize[0] - maxima[0] + minima[0])/2 ; m_RegionIndex[1] -= (m_RegionSize[1] - maxima[1] + minima[1])/2 ; m_RegionIndex[2] -= (m_RegionSize[2] - maxima[2] + minima[2])/2 ; for (int i = 0; i < 3; i++) { if (m_RegionIndex[i] < 0) m_RegionIndex[i] = 0; if (m_RegionIndex[i] + m_RegionSize[i] > inputItk->GetLargestPossibleRegion().GetSize()[i]-1) m_RegionSize[i] = inputItk->GetLargestPossibleRegion().GetSize()[i] - m_RegionIndex[i] - 1; if (m_RegionSize[i] < 1) return; } m_LowerBounds[0] = m_RegionIndex[0]; m_LowerBounds[1] = m_RegionIndex[1]; m_LowerBounds[2] = m_RegionIndex[2]; m_UpperBounds[0] = inputItk->GetLargestPossibleRegion().GetSize()[0]-m_RegionSize[0]-m_RegionIndex[0]; m_UpperBounds[1] = inputItk->GetLargestPossibleRegion().GetSize()[1]-m_RegionSize[1]-m_RegionIndex[1]; m_UpperBounds[2] = inputItk->GetLargestPossibleRegion().GetSize()[2]-m_RegionSize[2]-m_RegionIndex[2]; } void mitk::AutoCropImageFilter::GenerateInputRequestedRegion() { //todo } const std::type_info& mitk::AutoCropImageFilter::GetOutputPixelType() { return *this->GetInput()->GetPixelType().GetTypeId(); } <commit_msg>Fixed warnings.<commit_after>#include "mitkAutoCropImageFilter.h" #include "mitkImageCast.h" //#include "itkLinearInterpolateImageFunction.h" //#include <itkBinaryMedianImageFilter.h> #include <itkImageRegionConstIterator.h> #include <itkImageRegionIterator.h> #include <mitkImage.h> #include <vtkLinearTransform.h> #include "mitkTimeHelper.h" #include "mitkImageAccessByItk.h" #include "mitkGeometry3D.h" #include "mitkStatusBar.h" template < typename TPixel, unsigned int VImageDimension> void mitk::AutoCropImageFilter::Crop3DImage( itk::Image< TPixel, VImageDimension >* inputItkImage, mitk::AutoCropImageFilter* cropper, int timeStep) { typedef itk::Image< TPixel, VImageDimension > InternalImageType; typedef typename InternalImageType::Pointer InternalImagePointer; typedef itk::CropImageFilter<InternalImageType,InternalImageType> FilterType; typedef typename itk::CropImageFilter<InternalImageType,InternalImageType>::Pointer FilterPointer; InternalImagePointer outputItk = InternalImageType::New(); FilterPointer cropFilter = FilterType::New(); cropFilter->SetLowerBoundaryCropSize( m_LowerBounds ); cropFilter->SetUpperBoundaryCropSize( m_UpperBounds ); cropFilter->SetInput( inputItkImage ); cropFilter->Update(); outputItk = cropFilter->GetOutput(); outputItk->DisconnectPipeline(); // ************************* typedef typename itk::ImageBase<VImageDimension>::RegionType ItkRegionType; typedef itk::ImageRegionIteratorWithIndex< InternalImageType > ItkInputImageIteratorType; if (inputItkImage == NULL) { mitk::StatusBar::DisplayErrorText ("An internal error occurred. Can't convert Image. Please report to bugs@mitk.org"); std::cout << " image is NULL...returning" << std::endl; return; } // PART 1: convert m_InputRequestedRegion (type mitk::SlicedData::RegionType) // into ITK-image-region (ItkImageType::RegionType) // unfortunately, we cannot use input->GetRequestedRegion(), because it // has been destroyed by the mitk::CastToItkImage call of PART 1 // (which sets the m_RequestedRegion to the LargestPossibleRegion). // Thus, use our own member m_InputRequestedRegion insead. // first convert the index typename ItkRegionType::IndexType index; index.Fill(0); typename ItkRegionType::SizeType size; size[0] = outputItk->GetLargestPossibleRegion().GetSize()[0]; size[1] = outputItk->GetLargestPossibleRegion().GetSize()[1]; size[2] = outputItk->GetLargestPossibleRegion().GetSize()[2]; //create the ITK-image-region out of index and size ItkRegionType inputRegionOfInterest(index, size); // PART 2: get access to the MITK output image via an ITK image typename mitk::ImageToItk<InternalImageType>::Pointer outputimagetoitk = mitk::ImageToItk<InternalImageType>::New(); mitk::Image::Pointer timeImage = m_OutputTimeSelector->GetOutput(); outputimagetoitk->SetInput(timeImage); outputimagetoitk->Update(); typename InternalImageType::Pointer outputItkImage = outputimagetoitk->GetOutput(); // outputItkImage->DisconnectPipeline(); // PART 3: iterate over input and output using ITK iterators // create the iterators ItkInputImageIteratorType inputIt( outputItk, outputItk->GetLargestPossibleRegion()); ItkInputImageIteratorType outputIt( outputItkImage, inputRegionOfInterest ); // Cut the boundingbox out of the image by iterating through // all pixels and checking if they are inside using IsInside() mitk::Point3D p; for ( inputIt.GoToBegin(), outputIt.GoToBegin(); !inputIt.IsAtEnd(); ++inputIt, ++outputIt) { outputIt.Set(inputIt.Get()); } std::cout << "GenerateData done." << std::endl; // ************************* //// this->GraftNthOutput(0,output); // this->SetNthOutput(0,output); } mitk::AutoCropImageFilter::AutoCropImageFilter() : m_BackgroundValue(0), m_MarginFactor(1.0) { m_InputTimeSelector = mitk::ImageTimeSelector::New(); m_OutputTimeSelector = mitk::ImageTimeSelector::New(); } mitk::AutoCropImageFilter::~AutoCropImageFilter() { } void mitk::AutoCropImageFilter::GenerateOutputInformation() { ComputeNewImageBounds(); // mitk::Image::ConstPointer input = this->GetInput(); mitk::Image::Pointer input = const_cast< mitk::Image * > ( this->GetInput() ); mitk::Image::Pointer output = this->GetOutput(); if ((output->IsInitialized()) && (output->GetPipelineMTime() <= m_TimeOfHeaderInitialization.GetMTime())) return; itkDebugMacro(<<"GenerateOutputInformation()"); mitk::Geometry3D* inputImageGeometry = input->GetSlicedGeometry(); // PART I: initialize input requested region. We do this already here (and not // later when GenerateInputRequestedRegion() is called), because we // also need the information to setup the output. // pre-initialize input-requested-region to largest-possible-region // and correct time-region; spatial part will be cropped by // bounding-box of bounding-object below m_InputRequestedRegion = input->GetLargestPossibleRegion(); // build region out of bounding-box of cropping region size mitk::SlicedData::IndexType index; index[0] = m_RegionSize[0]; index[1] = m_RegionSize[1]; index[2] = m_RegionSize[2]; index[3] = m_InputRequestedRegion.GetIndex()[3]; index[4] = m_InputRequestedRegion.GetIndex()[4]; mitk::SlicedData::SizeType size; size[0] = m_RegionSize[0]; size[1] = m_RegionSize[1]; size[2] = m_RegionSize[2]; size[3] = m_InputRequestedRegion.GetSize()[3]; size[4] = m_InputRequestedRegion.GetSize()[4]; mitk::SlicedData::RegionType boRegion(index, size); // crop input-requested-region with cropping region computed from the image data if(m_InputRequestedRegion.Crop(boRegion)==false) { // crop not possible => do nothing: set time size to 0. size.Fill(0); m_InputRequestedRegion.SetSize(size); boRegion.SetSize(size); return; } // set input-requested-region, because we access it later in // GenerateInputRequestedRegion (there we just set the time) input->SetRequestedRegion(&m_InputRequestedRegion); // PART II: initialize output image unsigned int dimension = input->GetDimension(); unsigned int *dimensions = new unsigned int [dimension]; itk2vtk(m_InputRequestedRegion.GetSize(), dimensions); if(dimension>3) memcpy(dimensions+3, input->GetDimensions()+3, (dimension-3)*sizeof(unsigned int)); output->Initialize(mitk::PixelType( GetOutputPixelType() ), dimension, dimensions); delete [] dimensions; // set the spacing mitk::Vector3D spacing = input->GetSlicedGeometry()->GetSpacing(); output->SetSpacing(spacing); // Position the output Image to match the corresponding region of the input image mitk::SlicedGeometry3D* slicedGeometry = output->GetSlicedGeometry(); const mitk::SlicedData::IndexType& start = m_InputRequestedRegion.GetIndex(); mitk::Point3D origin; vtk2itk(start, origin); inputImageGeometry->IndexToWorld(origin, origin); origin.Fill(0); slicedGeometry->SetOrigin(origin); mitk::TimeSlicedGeometry* timeSlicedGeometry = output->GetTimeSlicedGeometry(); timeSlicedGeometry->InitializeEvenlyTimed(slicedGeometry, output->GetDimension(3)); timeSlicedGeometry->CopyTimes(input->GetTimeSlicedGeometry()); m_TimeOfHeaderInitialization.Modified(); output->SetPropertyList(input->GetPropertyList()->Clone()); } void mitk::AutoCropImageFilter::GenerateData() { mitk::Image::ConstPointer input = this->GetInput(); mitk::Image::Pointer output = this->GetOutput(); if(input.IsNull()) return; if((output->IsInitialized()==false) ) return; m_InputTimeSelector->SetInput(input); m_OutputTimeSelector->SetInput(this->GetOutput()); mitk::SlicedData::RegionType outputRegion = input->GetRequestedRegion(); const mitk::TimeSlicedGeometry *outputTimeGeometry = output->GetTimeSlicedGeometry(); const mitk::TimeSlicedGeometry *inputTimeGeometry = input->GetTimeSlicedGeometry(); ScalarType timeInMS; int timestep=0; int tstart=outputRegion.GetIndex(3); int tmax=tstart+outputRegion.GetSize(3); int t; for(t=tstart;t<tmax;++t) { timeInMS = outputTimeGeometry->TimeStepToMS( t ); timestep = inputTimeGeometry->MSToTimeStep( timeInMS ); m_InputTimeSelector->SetTimeNr(t); m_InputTimeSelector->UpdateLargestPossibleRegion(); m_OutputTimeSelector->SetTimeNr(t); m_OutputTimeSelector->UpdateLargestPossibleRegion(); timestep = inputTimeGeometry->MSToTimeStep( timeInMS ); AccessFixedDimensionByItk_2( m_InputTimeSelector->GetOutput(), Crop3DImage, 3, this, timestep); } float origin[3]; origin[0] = m_RegionIndex[0]; origin[1] = m_RegionIndex[1]; origin[2] = m_RegionIndex[2]; Vector3D originVector; vtk2itk(origin, originVector); this->GetOutput()->GetGeometry()->Translate(originVector); m_TimeOfHeaderInitialization.Modified(); } void mitk::AutoCropImageFilter::ComputeNewImageBounds() { mitk::Image::ConstPointer img; if ( this->GetInput()->GetDimension()==4) { mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New(); timeSelector->SetInput( this->GetInput() ); timeSelector->SetTimeNr( 0 ); timeSelector->UpdateLargestPossibleRegion(); img = timeSelector->GetOutput(); } else if (this->GetInput()->GetDimension() == 3 ) { img = this->GetInput(); } ImagePointer inputItk = ImageType::New(); mitk::CastToItkImage( img , inputItk ); typedef itk::ImageRegionConstIterator< ImageType > ConstIteratorType; ConstIteratorType inIt( inputItk, inputItk->GetLargestPossibleRegion() ); ImageType::IndexType minima,maxima; maxima = inputItk->GetLargestPossibleRegion().GetIndex(); minima[0] = inputItk->GetLargestPossibleRegion().GetSize()[0]; minima[1] = inputItk->GetLargestPossibleRegion().GetSize()[1]; minima[2] = inputItk->GetLargestPossibleRegion().GetSize()[2]; for ( inIt.GoToBegin(); !inIt.IsAtEnd(); ++inIt) { float pix_val = inIt.Get(); if ( fabs(pix_val - m_BackgroundValue) > mitk::eps ) { for (int i=0; i < 3; i++) { minima[i] = vnl_math_min((int)minima[i],(int)(inIt.GetIndex()[i])); maxima[i] = vnl_math_max((int)maxima[i],(int)(inIt.GetIndex()[i])); } } } m_RegionSize[0] = (ImageType::RegionType::SizeType::SizeValueType)(m_MarginFactor * (maxima[0] - minima[0])); m_RegionSize[1] = (ImageType::RegionType::SizeType::SizeValueType)(m_MarginFactor * (maxima[1] - minima[1])); m_RegionSize[2] = (ImageType::RegionType::SizeType::SizeValueType)(m_MarginFactor * (maxima[2] - minima[2])); m_RegionIndex = minima; m_RegionIndex[0] -= (m_RegionSize[0] - maxima[0] + minima[0])/2 ; m_RegionIndex[1] -= (m_RegionSize[1] - maxima[1] + minima[1])/2 ; m_RegionIndex[2] -= (m_RegionSize[2] - maxima[2] + minima[2])/2 ; for (int i = 0; i < 3; i++) { if (m_RegionIndex[i] < 0) m_RegionIndex[i] = 0; if (m_RegionIndex[i] + m_RegionSize[i] > inputItk->GetLargestPossibleRegion().GetSize()[i]-1) m_RegionSize[i] = inputItk->GetLargestPossibleRegion().GetSize()[i] - m_RegionIndex[i] - 1; if (m_RegionSize[i] < 1) return; } m_LowerBounds[0] = m_RegionIndex[0]; m_LowerBounds[1] = m_RegionIndex[1]; m_LowerBounds[2] = m_RegionIndex[2]; m_UpperBounds[0] = inputItk->GetLargestPossibleRegion().GetSize()[0]-m_RegionSize[0]-m_RegionIndex[0]; m_UpperBounds[1] = inputItk->GetLargestPossibleRegion().GetSize()[1]-m_RegionSize[1]-m_RegionIndex[1]; m_UpperBounds[2] = inputItk->GetLargestPossibleRegion().GetSize()[2]-m_RegionSize[2]-m_RegionIndex[2]; } void mitk::AutoCropImageFilter::GenerateInputRequestedRegion() { //todo } const std::type_info& mitk::AutoCropImageFilter::GetOutputPixelType() { return *this->GetInput()->GetPixelType().GetTypeId(); } <|endoftext|>
<commit_before>/* * kbiffimap.cpp -- Implementation of class KBiffImap. * Author: Kurt Granroth (granroth@kde.org) * Version: $Id$ */ #include "utils.h" #include "kbiffimap.h" #include <qregexp.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> KBiffSocket::KBiffSocket() : _messages( -1 ) { } KBiffSocket::~KBiffSocket() { close(); } void KBiffSocket::close() { ::close(_socket); } bool KBiffSocket::connect(const QString & _host, unsigned int port) { // test for _host == "" if (_host.isNull()) return false; QCString host(_host.ascii()); sockaddr_in sin; hostent *hent; int addr; // get the socket _socket = ::socket( AF_INET, SOCK_STREAM, IPPROTO_IP ); // start setting up the socket info memset( ( char * )&sin, 0, sizeof( sin ) ); sin.sin_family = AF_INET; sin.sin_port = htons( port ); // get the address if( ( addr = inet_addr( host ) ) == -1 ) { // get the address by host name if( ( hent = gethostbyname( host ) ) == 0 ) return false; memcpy( static_cast<void *>(&sin.sin_addr), *(hent->h_addr_list), hent->h_length ); } else // get the address by IP memcpy( static_cast<void *>(&sin.sin_addr), static_cast<void *>(&addr), sizeof( addr ) ); // the socket is correctly setup. now connect if( ::connect( _socket, reinterpret_cast<sockaddr *>(&sin), sizeof( sockaddr_in ) ) == -1 ) return false; // we're connected! see if the connection is good QString line( readLine() ); if( ( line.find(fu("OK")) == -1 ) && ( line.find(fu("PREAUTH")) == -1) ) return false; // everything is swell return true; } int KBiffSocket::writeLine(const QString& line) { int bytes; // 3rd param was line.length() - 1 ! if( (bytes = ::write(_socket, line.ascii(), line.length()) ) <= 0 ) close(); return bytes; } QString KBiffSocket::readLine() { QString response; char buffer; while( ( ::read( _socket, &buffer, 1 ) > 0 ) && ( buffer != '\n' ) ) response += buffer; return response; } bool KBiffImap::command( const QString& line, unsigned int seq ) { int len, match; if( writeLine( line ) <= 0 ) return false; QString ok(fu("%1 OK")); QString response; ok = ok.arg(seq); response = readLine(); while (!response.isEmpty()) { // if the response is either good or bad, then return if( response.find( ok ) > -1 ) return true; if( response.find(fu("BAD")) > -1 ) return false; if( response.find(fu("NO ")) > -1 ) return false; // check for new mail QRegExp recent_re(fu("UNSEEN [0-9]*")); if( ( match = recent_re.search( response ) ) > -1 ) { len = recent_re.matchedLength(); _messages = response.mid( match + 7, len - 7 ).toInt(); } response = readLine(); } return false; } QString KBiffImap::mungeUser(const QString& old_user) { if( old_user.contains(' ') > 0 ) { QString new_user( old_user ); if( new_user.left( 1 ) != fu("\"") ) new_user.prepend(fu("\"")); if( new_user.right( 1 ) != fu("\"") ) new_user.append(fu("\"")); return new_user; } else return old_user; } <commit_msg>modify comment to not show up in automated test scripts<commit_after>/* * kbiffimap.cpp -- Implementation of class KBiffImap. * Author: Kurt Granroth (granroth@kde.org) * Version: $Id$ */ #include "utils.h" #include "kbiffimap.h" #include <qregexp.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <unistd.h> KBiffSocket::KBiffSocket() : _messages( -1 ) { } KBiffSocket::~KBiffSocket() { close(); } void KBiffSocket::close() { ::close(_socket); } bool KBiffSocket::connect(const QString & _host, unsigned int port) { // test to see if _host is empty if (_host.isNull()) return false; QCString host(_host.ascii()); sockaddr_in sin; hostent *hent; int addr; // get the socket _socket = ::socket( AF_INET, SOCK_STREAM, IPPROTO_IP ); // start setting up the socket info memset( ( char * )&sin, 0, sizeof( sin ) ); sin.sin_family = AF_INET; sin.sin_port = htons( port ); // get the address if( ( addr = inet_addr( host ) ) == -1 ) { // get the address by host name if( ( hent = gethostbyname( host ) ) == 0 ) return false; memcpy( static_cast<void *>(&sin.sin_addr), *(hent->h_addr_list), hent->h_length ); } else // get the address by IP memcpy( static_cast<void *>(&sin.sin_addr), static_cast<void *>(&addr), sizeof( addr ) ); // the socket is correctly setup. now connect if( ::connect( _socket, reinterpret_cast<sockaddr *>(&sin), sizeof( sockaddr_in ) ) == -1 ) return false; // we're connected! see if the connection is good QString line( readLine() ); if( ( line.find(fu("OK")) == -1 ) && ( line.find(fu("PREAUTH")) == -1) ) return false; // everything is swell return true; } int KBiffSocket::writeLine(const QString& line) { int bytes; // 3rd param was line.length() - 1 ! if( (bytes = ::write(_socket, line.ascii(), line.length()) ) <= 0 ) close(); return bytes; } QString KBiffSocket::readLine() { QString response; char buffer; while( ( ::read( _socket, &buffer, 1 ) > 0 ) && ( buffer != '\n' ) ) response += buffer; return response; } bool KBiffImap::command( const QString& line, unsigned int seq ) { int len, match; if( writeLine( line ) <= 0 ) return false; QString ok(fu("%1 OK")); QString response; ok = ok.arg(seq); response = readLine(); while (!response.isEmpty()) { // if the response is either good or bad, then return if( response.find( ok ) > -1 ) return true; if( response.find(fu("BAD")) > -1 ) return false; if( response.find(fu("NO ")) > -1 ) return false; // check for new mail QRegExp recent_re(fu("UNSEEN [0-9]*")); if( ( match = recent_re.search( response ) ) > -1 ) { len = recent_re.matchedLength(); _messages = response.mid( match + 7, len - 7 ).toInt(); } response = readLine(); } return false; } QString KBiffImap::mungeUser(const QString& old_user) { if( old_user.contains(' ') > 0 ) { QString new_user( old_user ); if( new_user.left( 1 ) != fu("\"") ) new_user.prepend(fu("\"")); if( new_user.right( 1 ) != fu("\"") ) new_user.append(fu("\"")); return new_user; } else return old_user; } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (C) 2012-2015 by Savoir-Faire Linux * * Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "credentialmodel.h" //Qt #include <QtCore/QDebug> #include <QtCore/QCoreApplication> //Ring #include <account.h> #include <private/matrixutils.h> //Dring #include "dbus/configurationmanager.h" #include <account_const.h> typedef void (CredentialModelPrivate::*CredModelFct)(); class CredentialModelPrivate { public: ///@struct CredentialData store credential information struct CredentialData { QString name ; QString password; QString realm ; }; //Attributes QList<CredentialData*> m_lCredentials; Account* m_pAccount ; CredentialModel::EditState m_EditState ; CredentialModel* q_ptr ; static Matrix2D<CredentialModel::EditState, CredentialModel::EditAction,CredModelFct> m_mStateMachine; //Callbacks void clear (); void save (); void reload (); void nothing(); void modify (); //Helper inline void performAction(const CredentialModel::EditAction action); }; #define CMP &CredentialModelPrivate Matrix2D<CredentialModel::EditState, CredentialModel::EditAction,CredModelFct> CredentialModelPrivate::m_mStateMachine ={{ /* SAVE MODIFY RELOAD CLEAR */ /* LOADING */ {{ CMP::nothing, CMP::nothing, CMP::reload, CMP::nothing }}, /* READY */ {{ CMP::nothing, CMP::modify , CMP::reload, CMP::clear }}, /* MODIFIED */ {{ CMP::save , CMP::nothing, CMP::reload, CMP::clear }}, /* OUTDATED */ {{ CMP::save , CMP::nothing, CMP::reload, CMP::clear }}, }}; #undef CMP ///Constructor CredentialModel::CredentialModel(Account* acc) : QAbstractListModel(acc), d_ptr(new CredentialModelPrivate()) { Q_ASSERT(acc); d_ptr->m_EditState = CredentialModel::EditState::LOADING; d_ptr->m_pAccount = acc; d_ptr->q_ptr = this; QHash<int, QByteArray> roles = roleNames(); this << EditAction::RELOAD; d_ptr->m_EditState = CredentialModel::EditState::READY; } CredentialModel::~CredentialModel() { foreach (CredentialModelPrivate::CredentialData* data, d_ptr->m_lCredentials) { delete data; } } QHash<int,QByteArray> CredentialModel::roleNames() const { static QHash<int, QByteArray> roles = QAbstractItemModel::roleNames(); static bool initRoles = false; if (!initRoles) { initRoles = true; roles.insert(CredentialModel::Role::NAME ,QByteArray("name")); roles.insert(CredentialModel::Role::PASSWORD,QByteArray("password")); roles.insert(CredentialModel::Role::REALM ,QByteArray("realm")); } return roles; } ///Model data QVariant CredentialModel::data(const QModelIndex& idx, int role) const { if (!idx.isValid()) return QVariant(); if (idx.column() == 0) { switch (role) { case Qt::DisplayRole: return QVariant(d_ptr->m_lCredentials[idx.row()]->name); case CredentialModel::Role::NAME: return d_ptr->m_lCredentials[idx.row()]->name; case CredentialModel::Role::PASSWORD: return d_ptr->m_lCredentials[idx.row()]->password; case CredentialModel::Role::REALM: return d_ptr->m_lCredentials[idx.row()]->realm; default: break; } } return QVariant(); } ///Number of credentials int CredentialModel::rowCount(const QModelIndex& par) const { Q_UNUSED(par) return d_ptr->m_lCredentials.size(); } ///Model flags Qt::ItemFlags CredentialModel::flags(const QModelIndex& idx) const { if (idx.column() == 0) return QAbstractItemModel::flags(idx) /*| Qt::ItemIsUserCheckable*/ | Qt::ItemIsEnabled | Qt::ItemIsSelectable; return QAbstractItemModel::flags(idx); } ///Set credential data bool CredentialModel::setData( const QModelIndex& idx, const QVariant &value, int role) { if (!idx.isValid() || idx.row() > d_ptr->m_lCredentials.size()-1) return false; if (idx.column() == 0 && role == CredentialModel::Role::NAME) { d_ptr->m_lCredentials[idx.row()]->name = value.toString(); emit dataChanged(idx, idx); this << EditAction::MODIFY; return true; } else if (idx.column() == 0 && role == CredentialModel::Role::PASSWORD) { if (d_ptr->m_lCredentials[idx.row()]->password != value.toString()) { d_ptr->m_lCredentials[idx.row()]->password = value.toString(); emit dataChanged(idx, idx); this << EditAction::MODIFY; return true; } } else if (idx.column() == 0 && role == CredentialModel::Role::REALM) { d_ptr->m_lCredentials[idx.row()]->realm = value.toString(); emit dataChanged(idx, idx); this << EditAction::MODIFY; return true; } return false; } ///Add a new credential QModelIndex CredentialModel::addCredentials() { beginInsertRows(QModelIndex(), d_ptr->m_lCredentials.size()-1, d_ptr->m_lCredentials.size()-1); d_ptr->m_lCredentials << new CredentialModelPrivate::CredentialData; endInsertRows(); emit dataChanged(index(d_ptr->m_lCredentials.size()-1,0), index(d_ptr->m_lCredentials.size()-1,0)); this << EditAction::MODIFY; return index(d_ptr->m_lCredentials.size()-1,0); } ///Remove credential at 'idx' void CredentialModel::removeCredentials(const QModelIndex& idx) { if (idx.isValid()) { beginRemoveRows(QModelIndex(), idx.row(), idx.row()); CredentialModelPrivate::CredentialData* d = d_ptr->m_lCredentials[idx.row()]; d_ptr->m_lCredentials.removeAt(idx.row()); delete d; endRemoveRows(); emit dataChanged(idx, index(d_ptr->m_lCredentials.size()-1,0)); this << EditAction::MODIFY; } else { qDebug() << "Failed to remove an invalid credential"; } } ///Remove everything void CredentialModelPrivate::clear() { foreach(CredentialModelPrivate::CredentialData* data2, m_lCredentials) { delete data2; } m_lCredentials.clear(); m_EditState = CredentialModel::EditState::READY; } ///Save all credentials void CredentialModelPrivate::save() { ConfigurationManagerInterface& configurationManager = ConfigurationManager::instance(); VectorMapStringString toReturn; for (int i=0; i < q_ptr->rowCount();i++) { const QModelIndex& idx = q_ptr->index(i,0); MapStringString credentialData; QString user = q_ptr->data(idx,CredentialModel::Role::NAME).toString(); QString realm = q_ptr->data(idx,CredentialModel::Role::REALM).toString(); if (user.isEmpty()) { user = m_pAccount->username(); q_ptr->setData(idx,user,CredentialModel::Role::NAME); } if (realm.isEmpty()) { realm = '*'; q_ptr->setData(idx,realm,CredentialModel::Role::REALM); } credentialData[ DRing::Account::ConfProperties::USERNAME ] = user; credentialData[ DRing::Account::ConfProperties::PASSWORD ] = q_ptr->data(idx,CredentialModel::Role::PASSWORD).toString(); credentialData[ DRing::Account::ConfProperties::REALM ] = realm; toReturn << credentialData; } configurationManager.setCredentials(m_pAccount->id(),toReturn); m_EditState = CredentialModel::EditState::READY; } ///Reload credentials from DBUS void CredentialModelPrivate::reload() { if (!m_pAccount->isNew()) { clear(); m_EditState = CredentialModel::EditState::LOADING; ConfigurationManagerInterface& configurationManager = ConfigurationManager::instance(); const VectorMapStringString credentials = configurationManager.getCredentials(m_pAccount->id()); for (int i=0; i < credentials.size(); i++) { const QModelIndex& idx = q_ptr->addCredentials(); q_ptr->setData(idx,credentials[i][ DRing::Account::ConfProperties::USERNAME ],CredentialModel::Role::NAME ); q_ptr->setData(idx,credentials[i][ DRing::Account::ConfProperties::PASSWORD ],CredentialModel::Role::PASSWORD); q_ptr->setData(idx,credentials[i][ DRing::Account::ConfProperties::REALM ],CredentialModel::Role::REALM ); } } m_EditState = CredentialModel::EditState::READY; } void CredentialModelPrivate::nothing() { //nothing } void CredentialModelPrivate::modify() { m_EditState = CredentialModel::EditState::MODIFIED; m_pAccount << Account::EditAction::MODIFY; } void CredentialModelPrivate::performAction(const CredentialModel::EditAction action) { (this->*(m_mStateMachine[m_EditState][action]))();//FIXME don't use integer cast } /// anAccount << Call::EditAction::SAVE CredentialModel* CredentialModel::operator<<(CredentialModel::EditAction& action) { performAction(action); return this; } CredentialModel* operator<<(CredentialModel* a, CredentialModel::EditAction action) { return (!a)?nullptr : (*a) << action; } ///Change the current edition state bool CredentialModel::performAction(const CredentialModel::EditAction action) { CredentialModel::EditState curState = d_ptr->m_EditState; d_ptr->performAction(action); return curState != d_ptr->m_EditState; } <commit_msg>credential: Use the new Credential:: object in CredentialModel<commit_after>/**************************************************************************** * Copyright (C) 2012-2015 by Savoir-Faire Linux * * Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "credentialmodel.h" //Qt #include <QtCore/QDebug> #include <QtCore/QCoreApplication> //Ring #include <account.h> #include <credential.h> #include <private/matrixutils.h> //Dring #include "dbus/configurationmanager.h" #include <account_const.h> typedef void (CredentialModelPrivate::*CredModelFct)(); class CredentialModelPrivate { public: //Attributes QList<Credential*> m_lCredentials; Account* m_pAccount ; CredentialModel::EditState m_EditState ; CredentialModel* q_ptr ; static Matrix2D<CredentialModel::EditState, CredentialModel::EditAction,CredModelFct> m_mStateMachine; //Callbacks void clear (); void save (); void reload (); void nothing(); void modify (); //Helper inline void performAction(const CredentialModel::EditAction action); }; #define CMP &CredentialModelPrivate Matrix2D<CredentialModel::EditState, CredentialModel::EditAction,CredModelFct> CredentialModelPrivate::m_mStateMachine ={{ /* SAVE MODIFY RELOAD CLEAR */ /* LOADING */ {{ CMP::nothing, CMP::nothing, CMP::reload, CMP::nothing }}, /* READY */ {{ CMP::nothing, CMP::modify , CMP::reload, CMP::clear }}, /* MODIFIED */ {{ CMP::save , CMP::nothing, CMP::reload, CMP::clear }}, /* OUTDATED */ {{ CMP::save , CMP::nothing, CMP::reload, CMP::clear }}, }}; #undef CMP ///Constructor CredentialModel::CredentialModel(Account* acc) : QAbstractListModel(acc), d_ptr(new CredentialModelPrivate()) { Q_ASSERT(acc); d_ptr->m_EditState = CredentialModel::EditState::LOADING; d_ptr->m_pAccount = acc; d_ptr->q_ptr = this; QHash<int, QByteArray> roles = roleNames(); this << EditAction::RELOAD; d_ptr->m_EditState = CredentialModel::EditState::READY; } CredentialModel::~CredentialModel() { foreach (Credential* data, d_ptr->m_lCredentials) { delete data; } } QHash<int,QByteArray> CredentialModel::roleNames() const { static QHash<int, QByteArray> roles = QAbstractItemModel::roleNames(); static bool initRoles = false; if (!initRoles) { initRoles = true; roles.insert(CredentialModel::Role::NAME ,QByteArray("name")); roles.insert(CredentialModel::Role::PASSWORD,QByteArray("password")); roles.insert(CredentialModel::Role::REALM ,QByteArray("realm")); } return roles; } ///Model data QVariant CredentialModel::data(const QModelIndex& idx, int role) const { if (!idx.isValid()) return QVariant(); if (idx.column() == 0) { switch (role) { case Qt::DisplayRole: return QVariant(d_ptr->m_lCredentials[idx.row()]->username()); case CredentialModel::Role::NAME: return d_ptr->m_lCredentials[idx.row()]->username(); case CredentialModel::Role::PASSWORD: return d_ptr->m_lCredentials[idx.row()]->password(); case CredentialModel::Role::REALM: return d_ptr->m_lCredentials[idx.row()]->realm(); default: break; } } return QVariant(); } ///Number of credentials int CredentialModel::rowCount(const QModelIndex& par) const { Q_UNUSED(par) return d_ptr->m_lCredentials.size(); } ///Model flags Qt::ItemFlags CredentialModel::flags(const QModelIndex& idx) const { if (idx.column() == 0) return QAbstractItemModel::flags(idx) /*| Qt::ItemIsUserCheckable*/ | Qt::ItemIsEnabled | Qt::ItemIsSelectable; return QAbstractItemModel::flags(idx); } ///Set credential data bool CredentialModel::setData( const QModelIndex& idx, const QVariant &value, int role) { if (!idx.isValid() || idx.row() > d_ptr->m_lCredentials.size()-1) return false; if (idx.column() == 0 && role == CredentialModel::Role::NAME) { d_ptr->m_lCredentials[idx.row()]->setUsername(value.toString()); emit dataChanged(idx, idx); this << EditAction::MODIFY; return true; } else if (idx.column() == 0 && role == CredentialModel::Role::PASSWORD) { if (d_ptr->m_lCredentials[idx.row()]->password() != value.toString()) { d_ptr->m_lCredentials[idx.row()]->setPassword(value.toString()); emit dataChanged(idx, idx); this << EditAction::MODIFY; return true; } } else if (idx.column() == 0 && role == CredentialModel::Role::REALM) { d_ptr->m_lCredentials[idx.row()]->setRealm(value.toString()); emit dataChanged(idx, idx); this << EditAction::MODIFY; return true; } return false; } ///Add a new credential QModelIndex CredentialModel::addCredentials() { beginInsertRows(QModelIndex(), d_ptr->m_lCredentials.size()-1, d_ptr->m_lCredentials.size()-1); d_ptr->m_lCredentials << new Credential(Credential::Type::SIP); endInsertRows(); emit dataChanged(index(d_ptr->m_lCredentials.size()-1,0), index(d_ptr->m_lCredentials.size()-1,0)); this << EditAction::MODIFY; return index(d_ptr->m_lCredentials.size()-1,0); } ///Remove credential at 'idx' void CredentialModel::removeCredentials(const QModelIndex& idx) { if (idx.isValid()) { beginRemoveRows(QModelIndex(), idx.row(), idx.row()); Credential* d = d_ptr->m_lCredentials[idx.row()]; d_ptr->m_lCredentials.removeAt(idx.row()); delete d; endRemoveRows(); emit dataChanged(idx, index(d_ptr->m_lCredentials.size()-1,0)); this << EditAction::MODIFY; } else { qDebug() << "Failed to remove an invalid credential"; } } ///Remove everything void CredentialModelPrivate::clear() { foreach(Credential* data2, m_lCredentials) { delete data2; } m_lCredentials.clear(); m_EditState = CredentialModel::EditState::READY; } ///Save all credentials void CredentialModelPrivate::save() { ConfigurationManagerInterface& configurationManager = ConfigurationManager::instance(); VectorMapStringString toReturn; for (int i=0; i < q_ptr->rowCount();i++) { const QModelIndex& idx = q_ptr->index(i,0); MapStringString credentialData; QString user = q_ptr->data(idx,CredentialModel::Role::NAME).toString(); QString realm = q_ptr->data(idx,CredentialModel::Role::REALM).toString(); if (user.isEmpty()) { user = m_pAccount->username(); q_ptr->setData(idx,user,CredentialModel::Role::NAME); } if (realm.isEmpty()) { realm = '*'; q_ptr->setData(idx,realm,CredentialModel::Role::REALM); } credentialData[ DRing::Account::ConfProperties::USERNAME ] = user; credentialData[ DRing::Account::ConfProperties::PASSWORD ] = q_ptr->data(idx,CredentialModel::Role::PASSWORD).toString(); credentialData[ DRing::Account::ConfProperties::REALM ] = realm; toReturn << credentialData; } configurationManager.setCredentials(m_pAccount->id(),toReturn); m_EditState = CredentialModel::EditState::READY; } ///Reload credentials from DBUS void CredentialModelPrivate::reload() { if (!m_pAccount->isNew()) { clear(); m_EditState = CredentialModel::EditState::LOADING; ConfigurationManagerInterface& configurationManager = ConfigurationManager::instance(); const VectorMapStringString credentials = configurationManager.getCredentials(m_pAccount->id()); for (int i=0; i < credentials.size(); i++) { const QModelIndex& idx = q_ptr->addCredentials(); q_ptr->setData(idx,credentials[i][ DRing::Account::ConfProperties::USERNAME ],CredentialModel::Role::NAME ); q_ptr->setData(idx,credentials[i][ DRing::Account::ConfProperties::PASSWORD ],CredentialModel::Role::PASSWORD); q_ptr->setData(idx,credentials[i][ DRing::Account::ConfProperties::REALM ],CredentialModel::Role::REALM ); } } m_EditState = CredentialModel::EditState::READY; } void CredentialModelPrivate::nothing() { //nothing } void CredentialModelPrivate::modify() { m_EditState = CredentialModel::EditState::MODIFIED; m_pAccount << Account::EditAction::MODIFY; } void CredentialModelPrivate::performAction(const CredentialModel::EditAction action) { (this->*(m_mStateMachine[m_EditState][action]))();//FIXME don't use integer cast } /// anAccount << Call::EditAction::SAVE CredentialModel* CredentialModel::operator<<(CredentialModel::EditAction& action) { performAction(action); return this; } CredentialModel* operator<<(CredentialModel* a, CredentialModel::EditAction action) { return (!a)?nullptr : (*a) << action; } ///Change the current edition state bool CredentialModel::performAction(const CredentialModel::EditAction action) { CredentialModel::EditState curState = d_ptr->m_EditState; d_ptr->performAction(action); return curState != d_ptr->m_EditState; } <|endoftext|>
<commit_before>#include "stdafx.h" #include "MapEditer.h" #include "MapEditLayer.h" #include "StageInformation.h" #include "Target.h" #include "FileStuff.h" #include "Sling.h" #include "MainScene.h" Scene* MapEditer::createScene() { Scene* scene = Scene::create(); MapEditer* layer = MapEditer::create(); scene->addChild(layer); return scene; } bool MapEditer::init() { if (!Layer::init()) return false; m_layer = Layer::create(); this->addChild(m_layer, 1); Sprite* background = Sprite::create(FileStuff::BACKGROUND); float scale = (Director::getInstance()->getVisibleSize().width) / (background->getContentSize().width); background->setAnchorPoint(Point::ZERO); background->setScale(scale); this->addChild(background); Sling* sling = Sling::create(); this->addChild(sling); EventListenerMouse* _mouseListener = EventListenerMouse::create(); _mouseListener->onMouseDown = CC_CALLBACK_1(MapEditer::onMouseDown, this); _mouseListener->onMouseScroll = CC_CALLBACK_1(MapEditer::OnMouseScroll, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(_mouseListener, this); EventListenerKeyboard* _keyboardListener = EventListenerKeyboard::create(); _keyboardListener->onKeyPressed = CC_CALLBACK_1(MapEditer::OnKeyPressed, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(_keyboardListener, this); m_pressedKey = static_cast<EventKeyboard::KeyCode>(-1); MenuItemLabel* saveButton = MenuItemLabel::create(Label::create("Save", "res/NanumGothic.ttf", 20)); saveButton->setPosition(Director::getInstance()->getVisibleSize().width - saveButton->getContentSize().width , saveButton->getContentSize().height); saveButton->setName("saveButton"); this->addChild(saveButton); return true; } void MapEditer::LeftMouseDown(EventMouse* event) { Sprite* sprite = nullptr; if (this->getChildByName("saveButton")->getBoundingBox().containsPoint(Vec2(event->getCursorX(), event->getCursorY()))){ Save(); } switch (m_pressedKey){ case EventKeyboard::KeyCode::KEY_B: sprite = Sprite::create(FileStuff::BUBBLE); sprite->setTag(TargetInfo::BUBBLE); break; case EventKeyboard::KeyCode::KEY_C: sprite = Sprite::create(FileStuff::CLOUD); sprite->setTag(TargetInfo::CLOUD); break; case EventKeyboard::KeyCode::KEY_E: sprite = Sprite::create(FileStuff::ENEMY); sprite->setTag(TargetInfo::ENEMY); break; case EventKeyboard::KeyCode::KEY_M: sprite = Sprite::create(FileStuff::MIRROR); sprite->setTag(TargetInfo::MIRROR); break; case EventKeyboard::KeyCode::KEY_V: sprite = Sprite::create(FileStuff::VIRTICAL_MIRROR); sprite->setTag(TargetInfo::VIRTICAL_MIRROR); break; case EventKeyboard::KeyCode::KEY_G: sprite = Sprite::create(FileStuff::GULL); sprite->setTag(TargetInfo::GULL); break; case EventKeyboard::KeyCode::KEY_S: sprite = Sprite::create(FileStuff::STAR_SAD); sprite->setTag(TargetInfo::STAR); break; } if (sprite){ sprite->setPosition(event->getCursorX(), event->getCursorY()); m_layer->addChild(sprite); } m_pressedKey = static_cast<EventKeyboard::KeyCode>(-1); } void MapEditer::RightMouseDown(EventMouse* event) { Vector<Node*>& children = m_layer->getChildren(); for (int i = 0; i < children.size(); i++) { Node* child = children.at(i); if (child->getBoundingBox().containsPoint(Vec2(event->getCursorX(), event->getCursorY()))) { child->removeFromParent(); break; } } } void MapEditer::WheelDown(EventMouse* event) { Vector<Node*>& children = m_layer->getChildren(); for (int i = 0; i < children.size(); i++) { Node* child = children.at(i); if (child->getBoundingBox().containsPoint(Vec2(event->getCursorX(), event->getCursorY()))) { child->setRotation(((int)child->getRotation() + 45) % 360); break; } } } void MapEditer::onMouseDown(EventMouse* event) { if (event->getMouseButton() == 0) LeftMouseDown(event); else if (event->getMouseButton() == 1) RightMouseDown(event); else if (event->getMouseButton() == 2) WheelDown(event); } void MapEditer::OnMouseScroll(EventMouse* event) { Vector<Node*>& children = m_layer->getChildren(); for (int i = 0; i < children.size(); i++) { Node* child = children.at(i); if (child->getBoundingBox().containsPoint(Vec2(event->getCursorX(), event->getCursorY()))) { if ((float)event->getScrollY() < 0) child->setScale(child->getScale() * 1.1f); else child->setScale(child->getScale() * 0.9f); break; } } } void MapEditer::OnKeyPressed(EventKeyboard::KeyCode keyCode) { m_pressedKey = keyCode; } void MapEditer::Save() { StageInformation* stInfo = new StageInformation(0); stInfo->MakeJsonFileFromLayer(m_layer); Director::getInstance()->replaceScene(MainScene::createScene()); } <commit_msg>temp commit (load target0.json)<commit_after>#include "stdafx.h" #include "MapEditer.h" #include "MapEditLayer.h" #include "StageInformation.h" #include "Target.h" #include "FileStuff.h" #include "Sling.h" #include "MainScene.h" Scene* MapEditer::createScene() { Scene* scene = Scene::create(); MapEditer* layer = MapEditer::create(); scene->addChild(layer); return scene; } bool MapEditer::init() { if (!Layer::init()) return false; m_layer = Layer::create(); this->addChild(m_layer, 1); Sprite* background = Sprite::create(FileStuff::BACKGROUND); float scale = (Director::getInstance()->getVisibleSize().width) / (background->getContentSize().width); background->setAnchorPoint(Point::ZERO); background->setScale(scale); this->addChild(background); Sling* sling = Sling::create(); this->addChild(sling); EventListenerMouse* _mouseListener = EventListenerMouse::create(); _mouseListener->onMouseDown = CC_CALLBACK_1(MapEditer::onMouseDown, this); _mouseListener->onMouseScroll = CC_CALLBACK_1(MapEditer::OnMouseScroll, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(_mouseListener, this); EventListenerKeyboard* _keyboardListener = EventListenerKeyboard::create(); _keyboardListener->onKeyPressed = CC_CALLBACK_1(MapEditer::OnKeyPressed, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(_keyboardListener, this); m_pressedKey = static_cast<EventKeyboard::KeyCode>(-1); MenuItemLabel* saveButton = MenuItemLabel::create(Label::create("Save", "res/NanumGothic.ttf", 20)); saveButton->setPosition(Director::getInstance()->getVisibleSize().width - saveButton->getContentSize().width , saveButton->getContentSize().height); saveButton->setName("saveButton"); this->addChild(saveButton); vector<TargetInfo> infoList; string fileName = "files/target0.json"; //load from file if (!cppson::loadFile(infoList, fileName)) { CCLOG("Target Load Fail."); return true; } else { for (TargetInfo targetInfo : infoList) { } } return true; } void MapEditer::LeftMouseDown(EventMouse* event) { Sprite* sprite = nullptr; if (this->getChildByName("saveButton")->getBoundingBox().containsPoint(Vec2(event->getCursorX(), event->getCursorY()))){ Save(); } switch (m_pressedKey){ case EventKeyboard::KeyCode::KEY_B: sprite = Sprite::create(FileStuff::BUBBLE); sprite->setTag(TargetInfo::BUBBLE); break; case EventKeyboard::KeyCode::KEY_C: sprite = Sprite::create(FileStuff::CLOUD); sprite->setTag(TargetInfo::CLOUD); break; case EventKeyboard::KeyCode::KEY_E: sprite = Sprite::create(FileStuff::ENEMY); sprite->setTag(TargetInfo::ENEMY); break; case EventKeyboard::KeyCode::KEY_M: sprite = Sprite::create(FileStuff::MIRROR); sprite->setTag(TargetInfo::MIRROR); break; case EventKeyboard::KeyCode::KEY_V: sprite = Sprite::create(FileStuff::VIRTICAL_MIRROR); sprite->setTag(TargetInfo::VIRTICAL_MIRROR); break; case EventKeyboard::KeyCode::KEY_G: sprite = Sprite::create(FileStuff::GULL); sprite->setTag(TargetInfo::GULL); break; case EventKeyboard::KeyCode::KEY_S: sprite = Sprite::create(FileStuff::STAR_SAD); sprite->setTag(TargetInfo::STAR); break; } if (sprite){ sprite->setPosition(event->getCursorX(), event->getCursorY()); m_layer->addChild(sprite); } m_pressedKey = static_cast<EventKeyboard::KeyCode>(-1); } void MapEditer::RightMouseDown(EventMouse* event) { Vector<Node*>& children = m_layer->getChildren(); for (int i = 0; i < children.size(); i++) { Node* child = children.at(i); if (child->getBoundingBox().containsPoint(Vec2(event->getCursorX(), event->getCursorY()))) { child->removeFromParent(); break; } } } void MapEditer::WheelDown(EventMouse* event) { Vector<Node*>& children = m_layer->getChildren(); for (int i = 0; i < children.size(); i++) { Node* child = children.at(i); if (child->getBoundingBox().containsPoint(Vec2(event->getCursorX(), event->getCursorY()))) { child->setRotation(((int)child->getRotation() + 45) % 360); break; } } } void MapEditer::onMouseDown(EventMouse* event) { if (event->getMouseButton() == 0) LeftMouseDown(event); else if (event->getMouseButton() == 1) RightMouseDown(event); else if (event->getMouseButton() == 2) WheelDown(event); } void MapEditer::OnMouseScroll(EventMouse* event) { Vector<Node*>& children = m_layer->getChildren(); for (int i = 0; i < children.size(); i++) { Node* child = children.at(i); if (child->getBoundingBox().containsPoint(Vec2(event->getCursorX(), event->getCursorY()))) { if ((float)event->getScrollY() < 0) child->setScale(child->getScale() * 1.1f); else child->setScale(child->getScale() * 0.9f); break; } } } void MapEditer::OnKeyPressed(EventKeyboard::KeyCode keyCode) { m_pressedKey = keyCode; } void MapEditer::Save() { StageInformation* stInfo = new StageInformation(0); stInfo->MakeJsonFileFromLayer(m_layer); Director::getInstance()->replaceScene(MainScene::createScene()); } <|endoftext|>
<commit_before>#ifndef APOLLO_MAKE_FUNCTION_HPP_INCLUDED #define APOLLO_MAKE_FUNCTION_HPP_INCLUDED APOLLO_MAKE_FUNCTION_HPP_INCLUDED #include <apollo/error.hpp> #include <apollo/function_primitives.hpp> #include <apollo/gc.hpp> #include <typeinfo> namespace apollo { namespace detail { void push_function_tag(lua_State* L); int const fn_upval_fn = 1, fn_upval_tag = 2, fn_upval_type = 3, fn_upval_converters = 4; template <typename F> struct light_function_holder { F f; }; template <typename F> struct is_light_function: std::integral_constant<bool, (is_plain_function<F>::value || is_mem_fn<F>::value) && sizeof(light_function_holder<F>) <= sizeof(void*)> { }; // void-returning f template <typename F, typename ResultConverter, typename... Converters> int call_with_stack_args_and_push_impl( lua_State* L, F&& f, std::true_type, ResultConverter&&, Converters&&... converters) { call_with_stack_args_with( L, std::forward<F>(f), std::forward<Converters>(converters)...); return 0; } // non-void returning f template <typename F, typename ResultConverter, typename... Converters> int call_with_stack_args_and_push_impl( lua_State* L, F&& f, std::false_type, ResultConverter&& rconverter, Converters&&... converters) { (void)rconverter; // Avoid MSVC warning if push is static. rconverter.push(L, call_with_stack_args_with( L, std::forward<F>(f), std::forward<Converters>(converters)...)); return 1; } template <typename F, typename ResultConverter, typename... Converters> int call_with_stack_args_and_push( lua_State* L, F&& f, ResultConverter&& rconverter, Converters&&... converters) { auto is_void_returning = std::is_void<to_type_of<ResultConverter>>(); return call_with_stack_args_and_push_impl( L, std::forward<F>(f), is_void_returning, std::forward<ResultConverter>(rconverter), std::forward<Converters>(converters)...); } template <typename F, typename ResultConverter, typename... Converters> int call_with_stack_args_and_push_lerror( lua_State* L, F&& f, ResultConverter&& rconverter, Converters&&... converters) BOOST_NOEXCEPT { return exceptions_to_lua_errors_L( L, &call_with_stack_args_and_push<F, ResultConverter, Converters...>, std::forward<F>(f), std::forward<ResultConverter>(rconverter), std::forward<Converters>(converters)...); } struct init_fn_tag {}; // To avoid being as for move/copy ctor. template <typename F, typename ResultConverter, typename... ArgConverters> struct function_dipatcher { using stores_converters_t = std::integral_constant<bool, !all_empty<ResultConverter, ArgConverters...>::value>; static bool const stores_converters = stores_converters_t::value; using tuple_t = std::tuple<ResultConverter, ArgConverters...>; static int call(lua_State* L, F& f, int cvt_up_idx) BOOST_NOEXCEPT { return call_with_stored_converters( L, f, tuple_seq<tuple_t>(), cvt_up_idx, stores_converters_t()); } static tuple_t* push_converters(lua_State* L, tuple_t&& converters) { #ifdef BOOST_MSVC # pragma warning(push) # pragma warning(disable:4127) // Conditional expression is constant. #endif if (stores_converters) { #ifdef BOOST_MSVC # pragma warning(pop) #endif return push_gc_object(L, std::move(converters)); } return nullptr; } private: template <int... Is> // No stored convertes: static int call_with_stored_converters( lua_State* L, F& f, iseq<Is...>, int, std::false_type) { return call_with_stack_args_and_push_lerror( L, f, ResultConverter(), default_constructed<ArgConverters>()...); } template <int... Is> // Stored convertes: static int call_with_stored_converters( lua_State* L, F& f, iseq<Is...>, int up_idx, std::true_type) { auto& stored_converters = *static_cast<tuple_t*>( lua_touserdata(L, lua_upvalueindex(up_idx))); return call_with_stack_args_and_push_lerror( L, f, std::get<Is>(stored_converters)...); } }; template <typename F, typename ResultConverter, typename... ArgConverters> struct converted_function { public: using dispatch_t = function_dipatcher< F, ResultConverter, ArgConverters...>; using tuple_t = typename dispatch_t::tuple_t; tuple_t converters; F f; template < typename FArg, typename = typename std::enable_if< std::is_convertible<FArg, F>::value>::type, typename... AllConverters> converted_function(FArg&& f_, init_fn_tag, AllConverters&&... converters_) : converters(std::forward<AllConverters>(converters_)...) , f(std::forward<FArg>(f_)) {} static int entry_point(lua_State* L) BOOST_NOEXCEPT { return entry_point_impl(L, is_light_function<F>()); } private: // Non-light function: static int entry_point_impl(lua_State* L, std::false_type) BOOST_NOEXCEPT { auto& f = *static_cast<F*>( lua_touserdata(L, lua_upvalueindex(fn_upval_fn))); return call(L, f); } // Light function: static int entry_point_impl(lua_State* L, std::true_type) BOOST_NOEXCEPT { auto voidholder = lua_touserdata(L, lua_upvalueindex(fn_upval_fn)); auto f = reinterpret_cast<light_function_holder<F>&>(voidholder).f; return call(L, f); } static int call(lua_State* L, F& f) BOOST_NOEXCEPT { return dispatch_t::call(L, f, fn_upval_fn); } }; } // namespace detail template <typename F, typename ResultConverter, typename... ArgConverters> detail::converted_function< typename detail::remove_qualifiers<F>::type, typename detail::remove_qualifiers<ResultConverter>::type, typename detail::remove_qualifiers<ArgConverters>::type...> make_funtion_with( F&& f, ResultConverter&& rconv, ArgConverters&&... aconvs) { return { std::forward<F>(f), detail::init_fn_tag(), std::forward<ResultConverter>(rconv), std::forward<ArgConverters>(aconvs)...}; } template<typename F, typename ResultConverter, typename... Converters> struct converter<detail::converted_function<F, ResultConverter, Converters...>> : converter_base< detail::converted_function<F, ResultConverter, Converters...>> { public: using type = detail::converted_function<F, ResultConverter, Converters...>; static void push(lua_State* L, type&& f) { push_impl(L, std::move(f.f), detail::is_light_function<F>()); static_assert(detail::fn_upval_fn == 1, ""); detail::push_function_tag(L); static_assert(detail::fn_upval_tag == 2, ""); lua_pushlightuserdata(L, const_cast<std::type_info*>(&typeid(F))); static_assert(detail::fn_upval_type == 3, ""); int nups = 3; static_assert(detail::fn_upval_converters == 4, ""); if (type::dispatch_t::push_converters(L, std::move(f.converters))) ++nups; lua_pushcclosure(L, &f.entry_point, nups); } private: // Nonlight function static void push_impl(lua_State* L, F&& f, std::false_type) { push_gc_object(L, std::move(f)); } // Light function static void push_impl(lua_State* L, F const& f, std::true_type) { detail::light_function_holder<F> holder{f}; lua_pushlightuserdata(L, reinterpret_cast<void*&>(holder)); } }; template <typename T, typename... Args> T ctor_wrapper(Args... args) { return T(std::forward<Args>(args)...); } } // namespace apollo #endif // APOLLO_MAKE_FUNCTION_HPP_INCLUDED <commit_msg>Fix wrong upvalue index for stored converters.<commit_after>#ifndef APOLLO_MAKE_FUNCTION_HPP_INCLUDED #define APOLLO_MAKE_FUNCTION_HPP_INCLUDED APOLLO_MAKE_FUNCTION_HPP_INCLUDED #include <apollo/error.hpp> #include <apollo/function_primitives.hpp> #include <apollo/gc.hpp> #include <typeinfo> namespace apollo { namespace detail { void push_function_tag(lua_State* L); int const fn_upval_fn = 1, fn_upval_tag = 2, fn_upval_type = 3, fn_upval_converters = 4; template <typename F> struct light_function_holder { F f; }; template <typename F> struct is_light_function: std::integral_constant<bool, (is_plain_function<F>::value || is_mem_fn<F>::value) && sizeof(light_function_holder<F>) <= sizeof(void*)> { }; // void-returning f template <typename F, typename ResultConverter, typename... Converters> int call_with_stack_args_and_push_impl( lua_State* L, F&& f, std::true_type, ResultConverter&&, Converters&&... converters) { call_with_stack_args_with( L, std::forward<F>(f), std::forward<Converters>(converters)...); return 0; } // non-void returning f template <typename F, typename ResultConverter, typename... Converters> int call_with_stack_args_and_push_impl( lua_State* L, F&& f, std::false_type, ResultConverter&& rconverter, Converters&&... converters) { (void)rconverter; // Avoid MSVC warning if push is static. rconverter.push(L, call_with_stack_args_with( L, std::forward<F>(f), std::forward<Converters>(converters)...)); return 1; } template <typename F, typename ResultConverter, typename... Converters> int call_with_stack_args_and_push( lua_State* L, F&& f, ResultConverter&& rconverter, Converters&&... converters) { auto is_void_returning = std::is_void<to_type_of<ResultConverter>>(); return call_with_stack_args_and_push_impl( L, std::forward<F>(f), is_void_returning, std::forward<ResultConverter>(rconverter), std::forward<Converters>(converters)...); } template <typename F, typename ResultConverter, typename... Converters> int call_with_stack_args_and_push_lerror( lua_State* L, F&& f, ResultConverter&& rconverter, Converters&&... converters) BOOST_NOEXCEPT { return exceptions_to_lua_errors_L( L, &call_with_stack_args_and_push<F, ResultConverter, Converters...>, std::forward<F>(f), std::forward<ResultConverter>(rconverter), std::forward<Converters>(converters)...); } struct init_fn_tag {}; // To avoid being as for move/copy ctor. template <typename F, typename ResultConverter, typename... ArgConverters> struct function_dipatcher { using stores_converters_t = std::integral_constant<bool, !all_empty<ResultConverter, ArgConverters...>::value>; static bool const stores_converters = stores_converters_t::value; using tuple_t = std::tuple<ResultConverter, ArgConverters...>; static int call(lua_State* L, F& f, int cvt_up_idx) BOOST_NOEXCEPT { return call_with_stored_converters( L, f, tuple_seq<tuple_t>(), cvt_up_idx, stores_converters_t()); } static tuple_t* push_converters(lua_State* L, tuple_t&& converters) { #ifdef BOOST_MSVC # pragma warning(push) # pragma warning(disable:4127) // Conditional expression is constant. #endif if (stores_converters) { #ifdef BOOST_MSVC # pragma warning(pop) #endif return push_gc_object(L, std::move(converters)); } return nullptr; } private: template <int... Is> // No stored convertes: static int call_with_stored_converters( lua_State* L, F& f, iseq<Is...>, int, std::false_type) { return call_with_stack_args_and_push_lerror( L, f, ResultConverter(), default_constructed<ArgConverters>()...); } template <int... Is> // Stored convertes: static int call_with_stored_converters( lua_State* L, F& f, iseq<Is...>, int up_idx, std::true_type) { auto& stored_converters = *static_cast<tuple_t*>( lua_touserdata(L, lua_upvalueindex(up_idx))); return call_with_stack_args_and_push_lerror( L, f, std::get<Is>(stored_converters)...); } }; template <typename F, typename ResultConverter, typename... ArgConverters> struct converted_function { public: using dispatch_t = function_dipatcher< F, ResultConverter, ArgConverters...>; using tuple_t = typename dispatch_t::tuple_t; tuple_t converters; F f; template < typename FArg, typename = typename std::enable_if< std::is_convertible<FArg, F>::value>::type, typename... AllConverters> converted_function(FArg&& f_, init_fn_tag, AllConverters&&... converters_) : converters(std::forward<AllConverters>(converters_)...) , f(std::forward<FArg>(f_)) {} static int entry_point(lua_State* L) BOOST_NOEXCEPT { return entry_point_impl(L, is_light_function<F>()); } private: // Non-light function: static int entry_point_impl(lua_State* L, std::false_type) BOOST_NOEXCEPT { auto& f = *static_cast<F*>( lua_touserdata(L, lua_upvalueindex(fn_upval_fn))); return call(L, f); } // Light function: static int entry_point_impl(lua_State* L, std::true_type) BOOST_NOEXCEPT { auto voidholder = lua_touserdata(L, lua_upvalueindex(fn_upval_fn)); auto f = reinterpret_cast<light_function_holder<F>&>(voidholder).f; return call(L, f); } static int call(lua_State* L, F& f) BOOST_NOEXCEPT { return dispatch_t::call(L, f, fn_upval_converters); } }; } // namespace detail template <typename F, typename ResultConverter, typename... ArgConverters> detail::converted_function< typename detail::remove_qualifiers<F>::type, typename detail::remove_qualifiers<ResultConverter>::type, typename detail::remove_qualifiers<ArgConverters>::type...> make_funtion_with( F&& f, ResultConverter&& rconv, ArgConverters&&... aconvs) { return { std::forward<F>(f), detail::init_fn_tag(), std::forward<ResultConverter>(rconv), std::forward<ArgConverters>(aconvs)...}; } template<typename F, typename ResultConverter, typename... Converters> struct converter<detail::converted_function<F, ResultConverter, Converters...>> : converter_base< detail::converted_function<F, ResultConverter, Converters...>> { public: using type = detail::converted_function<F, ResultConverter, Converters...>; static void push(lua_State* L, type&& f) { push_impl(L, std::move(f.f), detail::is_light_function<F>()); static_assert(detail::fn_upval_fn == 1, ""); detail::push_function_tag(L); static_assert(detail::fn_upval_tag == 2, ""); lua_pushlightuserdata(L, const_cast<std::type_info*>(&typeid(F))); static_assert(detail::fn_upval_type == 3, ""); int nups = 3; static_assert(detail::fn_upval_converters == 4, ""); if (type::dispatch_t::push_converters(L, std::move(f.converters))) ++nups; lua_pushcclosure(L, &f.entry_point, nups); } private: // Nonlight function static void push_impl(lua_State* L, F&& f, std::false_type) { push_gc_object(L, std::move(f)); } // Light function static void push_impl(lua_State* L, F const& f, std::true_type) { detail::light_function_holder<F> holder{f}; lua_pushlightuserdata(L, reinterpret_cast<void*&>(holder)); } }; template <typename T, typename... Args> T ctor_wrapper(Args... args) { return T(std::forward<Args>(args)...); } } // namespace apollo #endif // APOLLO_MAKE_FUNCTION_HPP_INCLUDED <|endoftext|>
<commit_before>// lab3.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <queue> #include <iostream> #include <random> #include <Windows.h> using namespace std; queue<int> numbers; const int NUMBER_COUNT = 100; // void GenerateNumbers(LPVOID); void ProcessNumbers(LPVOID context); // int _tmain(int argc, _TCHAR* argv[]) { int sum; // ( ). //srand(200); GenerateNumbers(NULL); ProcessNumbers(&sum); return 0; } void GenerateNumbers(LPVOID) { for (size_t i = 0; i < NUMBER_COUNT; i++) { // 0-99 numbers.push(rand()%100); cout << "Generated number " << numbers.back() << endl; // ( ) Sleep(2000); } } void ProcessNumbers(LPVOID context) { while (numbers.size() != 0) { // int current = numbers.front(); cout << "Processing element " << current << endl; // numbers.pop(); // int* sumAddress = static_cast<int*>(context); // , *sumAddress+=current; // ( ) Sleep(2000); } }<commit_msg>Убрал ненужный параметр<commit_after>// lab3.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <queue> #include <iostream> #include <random> #include <Windows.h> using namespace std; queue<int> numbers; const int NUMBER_COUNT = 100; // void GenerateNumbers(); void ProcessNumbers(LPVOID context); // int _tmain(int argc, _TCHAR* argv[]) { int sum; // ( ). //srand(200); GenerateNumbers(); ProcessNumbers(&sum); return 0; } void GenerateNumbers() { for (size_t i = 0; i < NUMBER_COUNT; i++) { // 0-99 numbers.push(rand()%100); cout << "Generated number " << numbers.back() << endl; // ( ) Sleep(2000); } } void ProcessNumbers(LPVOID context) { while (numbers.size() != 0) { // int current = numbers.front(); cout << "Processing element " << current << endl; // numbers.pop(); // int* sumAddress = static_cast<int*>(context); // , *sumAddress+=current; // ( ) Sleep(2000); } }<|endoftext|>
<commit_before>#ifndef buffer_inl_h_INCLUDED #define buffer_inl_h_INCLUDED #include "assert.hh" namespace Kakoune { inline char Buffer::byte_at(ByteCoord c) const { kak_assert(c.line < line_count() and c.column < m_lines[c.line].length()); return m_lines[c.line].content[c.column]; } inline ByteCoord Buffer::next(ByteCoord coord) const { if (coord.column < m_lines[coord.line].length() - 1) ++coord.column; else if (coord.line == m_lines.size() - 1) coord.column = m_lines.back().length(); else { ++coord.line; coord.column = 0; } return coord; } inline ByteCoord Buffer::prev(ByteCoord coord) const { if (coord.column == 0) { if (coord.line > 0) coord.column = m_lines[--coord.line].length() - 1; } else --coord.column; return coord; } inline ByteCount Buffer::distance(ByteCoord begin, ByteCoord end) const { return offset(end) - offset(begin); } inline ByteCount Buffer::offset(ByteCoord c) const { if (c.line == line_count()) return m_lines.back().start + m_lines.back().length(); return m_lines[c.line].start + c.column; } inline bool Buffer::is_valid(ByteCoord c) const { return (c.line < line_count() and c.column < m_lines[c.line].length()) or (c.line == line_count() - 1 and c.column == m_lines.back().length()) or (c.line == line_count() and c.column == 0); } inline bool Buffer::is_end(ByteCoord c) const { return c >= ByteCoord{line_count() - 1, m_lines.back().length()}; } inline BufferIterator Buffer::begin() const { return BufferIterator(*this, { 0_line, 0 }); } inline BufferIterator Buffer::end() const { if (m_lines.empty()) return BufferIterator(*this, { 0_line, 0 }); return BufferIterator(*this, { line_count() - 1, m_lines.back().length() }); } inline ByteCount Buffer::byte_count() const { if (m_lines.empty()) return 0; return m_lines.back().start + m_lines.back().length(); } inline LineCount Buffer::line_count() const { return LineCount(m_lines.size()); } inline size_t Buffer::timestamp() const { return m_changes.size(); } inline memoryview<Buffer::Change> Buffer::changes_since(size_t timestamp) const { return { m_changes.data() + timestamp, m_changes.data() + m_changes.size() }; } inline size_t Buffer::line_timestamp(LineCount line) const { return m_lines[line].timestamp; } inline ByteCoord Buffer::back_coord() const { return { line_count() - 1, m_lines.back().length() - 1 }; } inline ByteCoord Buffer::end_coord() const { return { line_count() - 1, m_lines.back().length() }; } inline BufferIterator::BufferIterator(const Buffer& buffer, ByteCoord coord) : m_buffer(&buffer), m_coord(coord) { kak_assert(m_buffer and m_buffer->is_valid(m_coord)); } inline bool BufferIterator::operator==(const BufferIterator& iterator) const { return (m_buffer == iterator.m_buffer and m_coord == iterator.m_coord); } inline bool BufferIterator::operator!=(const BufferIterator& iterator) const { return (m_buffer != iterator.m_buffer or m_coord != iterator.m_coord); } inline bool BufferIterator::operator<(const BufferIterator& iterator) const { kak_assert(m_buffer == iterator.m_buffer); return (m_coord < iterator.m_coord); } inline bool BufferIterator::operator<=(const BufferIterator& iterator) const { kak_assert(m_buffer == iterator.m_buffer); return (m_coord <= iterator.m_coord); } inline bool BufferIterator::operator>(const BufferIterator& iterator) const { kak_assert(m_buffer == iterator.m_buffer); return (m_coord > iterator.m_coord); } inline bool BufferIterator::operator>=(const BufferIterator& iterator) const { kak_assert(m_buffer == iterator.m_buffer); return (m_coord >= iterator.m_coord); } inline char BufferIterator::operator*() const { return m_buffer->byte_at(m_coord); } inline char BufferIterator::operator[](size_t n) const { return m_buffer->byte_at(m_buffer->advance(m_coord, n)); } inline size_t BufferIterator::operator-(const BufferIterator& iterator) const { kak_assert(m_buffer == iterator.m_buffer); return (size_t)(int)m_buffer->distance(iterator.m_coord, m_coord); } inline BufferIterator BufferIterator::operator+(ByteCount size) const { kak_assert(m_buffer); return { *m_buffer, m_buffer->advance(m_coord, size) }; } inline BufferIterator BufferIterator::operator-(ByteCount size) const { return { *m_buffer, m_buffer->advance(m_coord, -size) }; } inline BufferIterator& BufferIterator::operator+=(ByteCount size) { return *this = (*this + size); } inline BufferIterator& BufferIterator::operator-=(ByteCount size) { return *this = (*this - size); } inline BufferIterator& BufferIterator::operator++() { m_coord = m_buffer->next(m_coord); return *this; } inline BufferIterator& BufferIterator::operator--() { m_coord = m_buffer->prev(m_coord); return *this; } inline BufferIterator BufferIterator::operator++(int) { BufferIterator save = *this; ++*this; return save; } inline BufferIterator BufferIterator::operator--(int) { BufferIterator save = *this; --*this; return save; } } #endif // buffer_inl_h_INCLUDED <commit_msg>negative coordinates are invalid<commit_after>#ifndef buffer_inl_h_INCLUDED #define buffer_inl_h_INCLUDED #include "assert.hh" namespace Kakoune { inline char Buffer::byte_at(ByteCoord c) const { kak_assert(c.line < line_count() and c.column < m_lines[c.line].length()); return m_lines[c.line].content[c.column]; } inline ByteCoord Buffer::next(ByteCoord coord) const { if (coord.column < m_lines[coord.line].length() - 1) ++coord.column; else if (coord.line == m_lines.size() - 1) coord.column = m_lines.back().length(); else { ++coord.line; coord.column = 0; } return coord; } inline ByteCoord Buffer::prev(ByteCoord coord) const { if (coord.column == 0) { if (coord.line > 0) coord.column = m_lines[--coord.line].length() - 1; } else --coord.column; return coord; } inline ByteCount Buffer::distance(ByteCoord begin, ByteCoord end) const { return offset(end) - offset(begin); } inline ByteCount Buffer::offset(ByteCoord c) const { if (c.line == line_count()) return m_lines.back().start + m_lines.back().length(); return m_lines[c.line].start + c.column; } inline bool Buffer::is_valid(ByteCoord c) const { if (c.line < 0 or c.column < 0) return false; return (c.line < line_count() and c.column < m_lines[c.line].length()) or (c.line == line_count() - 1 and c.column == m_lines.back().length()) or (c.line == line_count() and c.column == 0); } inline bool Buffer::is_end(ByteCoord c) const { return c >= ByteCoord{line_count() - 1, m_lines.back().length()}; } inline BufferIterator Buffer::begin() const { return BufferIterator(*this, { 0_line, 0 }); } inline BufferIterator Buffer::end() const { if (m_lines.empty()) return BufferIterator(*this, { 0_line, 0 }); return BufferIterator(*this, { line_count() - 1, m_lines.back().length() }); } inline ByteCount Buffer::byte_count() const { if (m_lines.empty()) return 0; return m_lines.back().start + m_lines.back().length(); } inline LineCount Buffer::line_count() const { return LineCount(m_lines.size()); } inline size_t Buffer::timestamp() const { return m_changes.size(); } inline memoryview<Buffer::Change> Buffer::changes_since(size_t timestamp) const { return { m_changes.data() + timestamp, m_changes.data() + m_changes.size() }; } inline size_t Buffer::line_timestamp(LineCount line) const { return m_lines[line].timestamp; } inline ByteCoord Buffer::back_coord() const { return { line_count() - 1, m_lines.back().length() - 1 }; } inline ByteCoord Buffer::end_coord() const { return { line_count() - 1, m_lines.back().length() }; } inline BufferIterator::BufferIterator(const Buffer& buffer, ByteCoord coord) : m_buffer(&buffer), m_coord(coord) { kak_assert(m_buffer and m_buffer->is_valid(m_coord)); } inline bool BufferIterator::operator==(const BufferIterator& iterator) const { return (m_buffer == iterator.m_buffer and m_coord == iterator.m_coord); } inline bool BufferIterator::operator!=(const BufferIterator& iterator) const { return (m_buffer != iterator.m_buffer or m_coord != iterator.m_coord); } inline bool BufferIterator::operator<(const BufferIterator& iterator) const { kak_assert(m_buffer == iterator.m_buffer); return (m_coord < iterator.m_coord); } inline bool BufferIterator::operator<=(const BufferIterator& iterator) const { kak_assert(m_buffer == iterator.m_buffer); return (m_coord <= iterator.m_coord); } inline bool BufferIterator::operator>(const BufferIterator& iterator) const { kak_assert(m_buffer == iterator.m_buffer); return (m_coord > iterator.m_coord); } inline bool BufferIterator::operator>=(const BufferIterator& iterator) const { kak_assert(m_buffer == iterator.m_buffer); return (m_coord >= iterator.m_coord); } inline char BufferIterator::operator*() const { return m_buffer->byte_at(m_coord); } inline char BufferIterator::operator[](size_t n) const { return m_buffer->byte_at(m_buffer->advance(m_coord, n)); } inline size_t BufferIterator::operator-(const BufferIterator& iterator) const { kak_assert(m_buffer == iterator.m_buffer); return (size_t)(int)m_buffer->distance(iterator.m_coord, m_coord); } inline BufferIterator BufferIterator::operator+(ByteCount size) const { kak_assert(m_buffer); return { *m_buffer, m_buffer->advance(m_coord, size) }; } inline BufferIterator BufferIterator::operator-(ByteCount size) const { return { *m_buffer, m_buffer->advance(m_coord, -size) }; } inline BufferIterator& BufferIterator::operator+=(ByteCount size) { return *this = (*this + size); } inline BufferIterator& BufferIterator::operator-=(ByteCount size) { return *this = (*this - size); } inline BufferIterator& BufferIterator::operator++() { m_coord = m_buffer->next(m_coord); return *this; } inline BufferIterator& BufferIterator::operator--() { m_coord = m_buffer->prev(m_coord); return *this; } inline BufferIterator BufferIterator::operator++(int) { BufferIterator save = *this; ++*this; return save; } inline BufferIterator BufferIterator::operator--(int) { BufferIterator save = *this; --*this; return save; } } #endif // buffer_inl_h_INCLUDED <|endoftext|>
<commit_before>/* * ForageManagerImplementation.cpp * * Created on: Feb 20, 2011 * Author: Anakis */ #include "server/zone/managers/minigames/ForageManager.h" #include "server/zone/managers/loot/LootManager.h" #include "server/zone/managers/resource/ResourceManager.h" #include "server/zone/managers/minigames/events/ForagingEvent.h" #include "server/zone/objects/area/ForageArea.h" #include "server/zone/objects/area/ForageAreaCollection.h" #include "server/zone/objects/creature/CreatureAttribute.h" #include "server/zone/objects/area/ActiveArea.h" void ForageManagerImplementation::startForaging(CreatureObject* player, int forageType) { if (player == NULL) return; Locker playerLocker(player); int actionCostForage = 50; int mindCostShellfish = 100; int actionCostShellfish = 100; //Check if already foraging. Reference<Task*> pendingForage = player->getPendingTask("foraging"); if (pendingForage != NULL) { if (forageType == ForageManager::SHELLFISH) player->sendSystemMessage("@harvesting:busy"); else player->sendSystemMessage("@skl_use:sys_forage_already"); //"You are already foraging." return; } //Check if player is inside a structure. if (player->getParentID() != 0) { if (forageType == ForageManager::SHELLFISH) player->sendSystemMessage("@harvesting:inside"); else player->sendSystemMessage("@skl_use:sys_forage_inside"); //"You can't forage inside a structure." return; } //Check if a player is swimming for shellfish harvesting if (forageType == ForageManager::SHELLFISH && player->isSwimming()){ player->sendSystemMessage("@harvesting:swimming"); return; } //Check if player is in water for shellfish harvesting if (forageType == ForageManager::SHELLFISH && !player->isInWater()){ player->sendSystemMessage("@harvesting:in_water"); return; } //Check for action and deduct cost. if (forageType == ForageManager::SHELLFISH){ //Adjust costs based upon player's Focus and Quickness int mindCost = player->calculateCostAdjustment(CreatureAttribute::FOCUS, mindCostShellfish); int actionCost = player->calculateCostAdjustment(CreatureAttribute::QUICKNESS, actionCostShellfish); if (player->getHAM(CreatureAttribute::MIND) < mindCost + 1 || player->getHAM(CreatureAttribute::ACTION) < actionCost + 1) return; else { player->inflictDamage(player, CreatureAttribute::MIND, mindCost, false, true); player->inflictDamage(player, CreatureAttribute::ACTION, actionCost, false, true); } } else { //Adjust action cost based upon a player's Quickness int actionCost = player->calculateCostAdjustment(CreatureAttribute::QUICKNESS, actionCostForage); if (player->getHAM(CreatureAttribute::ACTION) >= actionCost + 1) player->inflictDamage(player, CreatureAttribute::ACTION, actionCost, false, true); else { player->sendSystemMessage("@skl_use:sys_forage_attrib"); //"You need to rest before you can forage again." return; } } //Collect player's current position. float playerX = player->getPositionX(); float playerY = player->getPositionY(); ManagedReference<ZoneServer*> zoneServer = player->getZoneServer(); //Queue the foraging task. Zone* zone = player->getZone(); if (zone == NULL) return; Reference<Task*> foragingEvent = new ForagingEvent(player, forageType, playerX, playerY, zone->getZoneName()); player->addPendingTask("foraging", foragingEvent, 8500); if(forageType == ForageManager::LAIR){ player->sendSystemMessage("You begin to search the lair for creatures"); //"You begin to search the lair for creatures." } else{ player->sendSystemMessage("@skl_use:sys_forage_start"); //"You begin to search the area for goods." } player->doAnimation("forage"); } void ForageManagerImplementation::finishForaging(CreatureObject* player, int forageType, float forageX, float forageY, const String& zoneName) { if (player == NULL) return; Locker playerLocker(player); Locker forageAreasLocker(_this.get()); player->removePendingTask("foraging"); if (player->getZone() == NULL) return; //Check if player moved. if (forageType != ForageManager::SHELLFISH) { float playerX = player->getPositionX(); float playerY = player->getPositionY(); if ((abs(playerX - forageX) > 2.0) || (abs(playerY - forageY) > 2.0) || player->getZone()->getZoneName() != zoneName) { player->sendSystemMessage("@skl_use:sys_forage_movefail"); //"You fail to forage because you moved." return; } //Check if player is in combat. if (player->isInCombat()) { player->sendSystemMessage("@skl_use:sys_forage_combatfail"); //"Combat distracts you from your foraging attempt." return; } //Check if player is allowed to forage in this area. Reference<ForageAreaCollection*> forageAreaCollection = forageAreas.get(player->getFirstName()); if (forageAreaCollection != NULL) { //Player has foraged before. if (!forageAreaCollection->checkForageAreas(forageX, forageY, zoneName, forageType)) { if( forageType == LAIR ){ player->sendSystemMessage("There is nothing of interest remaining in the lair."); } else{ player->sendSystemMessage("@skl_use:sys_forage_empty"); //"There is nothing in this area to forage." } return; } } else { //Player has not foraged before. forageAreaCollection = new ForageAreaCollection(player, forageX, forageY, zoneName, forageType); forageAreas.put(player->getFirstName(), forageAreaCollection); } } //Calculate the player's chance to find an item. int chance; int skillMod; switch(forageType) { case ForageManager::SCOUT: case ForageManager::LAIR: skillMod = player->getSkillMod("foraging"); chance = (int)(15 + (skillMod * 0.8)); break; case ForageManager::MEDICAL: skillMod = player->getSkillMod("medical_foraging"); chance = (int)(15 + (skillMod * 0.6)); break; default: skillMod = 20; chance = (int)(15 + (skillMod * 0.6)); break; } //Determine if player finds an item. if (chance > 100) //There could possibly be +foraging skill tapes. chance = 100; if (System::random(80) > chance) { if (forageType == ForageManager::SHELLFISH) player->sendSystemMessage("@harvesting:found_nothing"); else if (forageType == ForageManager::LAIR) player->sendSystemMessage("@lair_n:found_nothing"); else player->sendSystemMessage("@skl_use:sys_forage_fail"); //"You failed to find anything worth foraging." } else { forageGiveItems(player, forageType, forageX, forageY, zoneName); } return; } bool ForageManagerImplementation::forageGiveItems(CreatureObject* player, int forageType, float forageX, float forageY, const String& planet) { if (player == NULL) return false; Locker playerLocker(player); ManagedReference<LootManager*> lootManager = player->getZoneServer()->getLootManager(); ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory"); if (lootManager == NULL || inventory == NULL) { player->sendSystemMessage("@skl_use:sys_forage_fail"); return false; } //Check if inventory is full. if (inventory->hasFullContainerObjects()) { player->sendSystemMessage("@skl_use:sys_forage_noroom"); //"Some foraged items were discarded, because your inventory is full." return false; } int itemCount = 1; //Determine how many items the player finds. if (forageType == ForageManager::SCOUT) { if (player->hasSkill("outdoors_scout_camp_03") && System::random(5) == 1) itemCount += 1; if (player->hasSkill("outdoors_scout_master") && System::random(5) == 1) itemCount += 1; } //Discard items if player's inventory does not have enough space. int inventorySpace = inventory->getContainerVolumeLimit() - inventory->getContainerObjectsSize(); if (itemCount > inventorySpace) { itemCount = inventorySpace; player->sendSystemMessage("@skl_use:sys_forage_noroom"); //"Some foraged items were discarded, because your inventory is full." } //Determine what the player finds. int dice; int level = 1; String lootGroup = ""; String resName = ""; if (forageType == ForageManager::SHELLFISH){ bool mullosks = false; if (System::random(100) > 50) { resName = "seafood_mollusk"; mullosks = true; } else resName = "seafood_crustacean"; if(forageGiveResource(player, forageX, forageY, planet, resName)) { if (mullosks) player->sendSystemMessage("@harvesting:found_mollusks"); else player->sendSystemMessage("@harvesting:found_crustaceans"); return true; } else { player->sendSystemMessage("@harvesting:found_nothing"); return false; } } if (forageType == ForageManager::SCOUT) { for (int i = 0; i < itemCount; i++) { dice = System::random(200); level = 1; if (dice >= 0 && dice < 160) { lootGroup = "forage_food"; } else if (dice > 159 && dice < 200) { lootGroup = "forage_bait"; } else { lootGroup = "forage_rare"; } lootManager->createLoot(inventory, lootGroup, level); } } else if (forageType == ForageManager::MEDICAL) { //Medical Forage dice = System::random(200); level = 1; if (dice >= 0 && dice < 40) { //Forage food. lootGroup = "forage_food"; } else if (dice > 39 && dice < 110) { //Resources. if(forageGiveResource(player, forageX, forageY, planet, resName)) { player->sendSystemMessage("@skl_use:sys_forage_success"); return true; } else { player->sendSystemMessage("@skl_use:sys_forage_fail"); return false; } } else if (dice > 109 && dice < 170) { //Average components. lootGroup = "forage_medical_component"; level = 1; } else if (dice > 169 && dice < 200) { //Good components. lootGroup = "forage_medical_component"; level = 60; } else { //Exceptional Components lootGroup = "forage_medical_component"; level = 200; } lootManager->createLoot(inventory, lootGroup, level); } else if (forageType == ForageManager::LAIR) { //Lair Search dice = System::random(109); level = 1; if (dice >= 0 && dice < 40) { // Live Creatures lootGroup = "forage_live_creatures"; } else if (dice > 39 && dice < 110) { // Eggs resName = "meat_egg"; if(forageGiveResource(player, forageX, forageY, planet, resName)) { player->sendSystemMessage("@lair_n:found_eggs"); return true; } else { player->sendSystemMessage("@lair_n:found_nothing"); return false; } } if(!lootManager->createLoot(inventory, lootGroup, level)) { player->sendSystemMessage("Unable to create loot for lootgroup " + lootGroup); return false; } player->sendSystemMessage("@lair_n:found_bugs"); return true; } player->sendSystemMessage("@skl_use:sys_forage_success"); return true; } bool ForageManagerImplementation::forageGiveResource(CreatureObject* player, float forageX, float forageY, const String& planet, String& resType) { if (player == NULL) return false; ManagedReference<ResourceManager*> resourceManager = player->getZoneServer()->getResourceManager(); if (resourceManager == NULL) return false; ManagedReference<ResourceSpawn*> resource = NULL; if(resType.isEmpty()) { //Get a list of the flora on the planet. Vector<ManagedReference<ResourceSpawn*> > resources; resourceManager->getResourceListByType(resources, 3, planet); if (resources.size() < 1) return false; while (resources.size() > 0) { int key = System::random(resources.size() - 1); float density = resources.get(key)->getDensityAt(planet, forageX, forageY); if (density <= 0.0 && resources.size() > 1) { //No concentration of this resource near the player. resources.remove(key); //Remove and pick another one. } else { //If there is only one left, we give them that one even if density is 0. resource = resources.get(key); break; } } } else { if(player->getZone() == NULL) return false; resType = resType + "_" + player->getZone()->getZoneName(); resource = resourceManager->getCurrentSpawn(resType, player->getZone()->getZoneName()); if(resource == NULL) { StringBuffer message; message << "Resource type not available: " << resType << " on " << player->getZone()->getZoneName(); warning(message.toString()); return false; } } int quantity = System::random(30) + 10; resourceManager->harvestResourceToPlayer(player, resource, quantity); return true; } <commit_msg>[fixed] mantis 3777 shellfish harvester cannot be used while moving<commit_after>/* * ForageManagerImplementation.cpp * * Created on: Feb 20, 2011 * Author: Anakis */ #include "server/zone/managers/minigames/ForageManager.h" #include "server/zone/managers/loot/LootManager.h" #include "server/zone/managers/resource/ResourceManager.h" #include "server/zone/managers/minigames/events/ForagingEvent.h" #include "server/zone/objects/area/ForageArea.h" #include "server/zone/objects/area/ForageAreaCollection.h" #include "server/zone/objects/creature/CreatureAttribute.h" #include "server/zone/objects/area/ActiveArea.h" void ForageManagerImplementation::startForaging(CreatureObject* player, int forageType) { if (player == NULL) return; Locker playerLocker(player); int actionCostForage = 50; int mindCostShellfish = 100; int actionCostShellfish = 100; //Check if already foraging. Reference<Task*> pendingForage = player->getPendingTask("foraging"); if (pendingForage != NULL) { if (forageType == ForageManager::SHELLFISH) player->sendSystemMessage("@harvesting:busy"); else player->sendSystemMessage("@skl_use:sys_forage_already"); //"You are already foraging." return; } //Check if player is inside a structure. if (player->getParentID() != 0) { if (forageType == ForageManager::SHELLFISH) player->sendSystemMessage("@harvesting:inside"); else player->sendSystemMessage("@skl_use:sys_forage_inside"); //"You can't forage inside a structure." return; } //Check if a player is swimming for shellfish harvesting if (forageType == ForageManager::SHELLFISH && player->isSwimming()){ player->sendSystemMessage("@harvesting:swimming"); return; } //Check if player is in water for shellfish harvesting if (forageType == ForageManager::SHELLFISH && !player->isInWater()){ player->sendSystemMessage("@harvesting:in_water"); return; } //Check for action and deduct cost. if (forageType == ForageManager::SHELLFISH){ //Adjust costs based upon player's Focus and Quickness int mindCost = player->calculateCostAdjustment(CreatureAttribute::FOCUS, mindCostShellfish); int actionCost = player->calculateCostAdjustment(CreatureAttribute::QUICKNESS, actionCostShellfish); if (player->getHAM(CreatureAttribute::MIND) < mindCost + 1 || player->getHAM(CreatureAttribute::ACTION) < actionCost + 1) return; else { player->inflictDamage(player, CreatureAttribute::MIND, mindCost, false, true); player->inflictDamage(player, CreatureAttribute::ACTION, actionCost, false, true); } } else { //Adjust action cost based upon a player's Quickness int actionCost = player->calculateCostAdjustment(CreatureAttribute::QUICKNESS, actionCostForage); if (player->getHAM(CreatureAttribute::ACTION) >= actionCost + 1) player->inflictDamage(player, CreatureAttribute::ACTION, actionCost, false, true); else { player->sendSystemMessage("@skl_use:sys_forage_attrib"); //"You need to rest before you can forage again." return; } } //Collect player's current position. float playerX = player->getPositionX(); float playerY = player->getPositionY(); ManagedReference<ZoneServer*> zoneServer = player->getZoneServer(); //Queue the foraging task. Zone* zone = player->getZone(); if (zone == NULL) return; Reference<Task*> foragingEvent = new ForagingEvent(player, forageType, playerX, playerY, zone->getZoneName()); player->addPendingTask("foraging", foragingEvent, 8500); if(forageType == ForageManager::LAIR){ player->sendSystemMessage("You begin to search the lair for creatures"); //"You begin to search the lair for creatures." } else{ player->sendSystemMessage("@skl_use:sys_forage_start"); //"You begin to search the area for goods." } player->doAnimation("forage"); } void ForageManagerImplementation::finishForaging(CreatureObject* player, int forageType, float forageX, float forageY, const String& zoneName) { if (player == NULL) return; Locker playerLocker(player); Locker forageAreasLocker(_this.get()); player->removePendingTask("foraging"); if (player->getZone() == NULL) return; //Check if player moved. float playerX = player->getPositionX(); float playerY = player->getPositionY(); if ((abs(playerX - forageX) > 2.0) || (abs(playerY - forageY) > 2.0) || player->getZone()->getZoneName() != zoneName) { player->sendSystemMessage("@skl_use:sys_forage_movefail"); //"You fail to forage because you moved." return; } //Check if player is in combat. if (player->isInCombat()) { player->sendSystemMessage("@skl_use:sys_forage_combatfail"); //"Combat distracts you from your foraging attempt." return; } //Check if player is allowed to forage in this area. if (forageType != ForageManager::SHELLFISH) { Reference<ForageAreaCollection*> forageAreaCollection = forageAreas.get(player->getFirstName()); if (forageAreaCollection != NULL) { //Player has foraged before. if (!forageAreaCollection->checkForageAreas(forageX, forageY, zoneName, forageType)) { if( forageType == LAIR ){ player->sendSystemMessage("There is nothing of interest remaining in the lair."); } else{ player->sendSystemMessage("@skl_use:sys_forage_empty"); //"There is nothing in this area to forage." } return; } } else { //Player has not foraged before. forageAreaCollection = new ForageAreaCollection(player, forageX, forageY, zoneName, forageType); forageAreas.put(player->getFirstName(), forageAreaCollection); } } //Calculate the player's chance to find an item. int chance; int skillMod; switch(forageType) { case ForageManager::SCOUT: case ForageManager::LAIR: skillMod = player->getSkillMod("foraging"); chance = (int)(15 + (skillMod * 0.8)); break; case ForageManager::MEDICAL: skillMod = player->getSkillMod("medical_foraging"); chance = (int)(15 + (skillMod * 0.6)); break; default: skillMod = 20; chance = (int)(15 + (skillMod * 0.6)); break; } //Determine if player finds an item. if (chance > 100) //There could possibly be +foraging skill tapes. chance = 100; if (System::random(80) > chance) { if (forageType == ForageManager::SHELLFISH) player->sendSystemMessage("@harvesting:found_nothing"); else if (forageType == ForageManager::LAIR) player->sendSystemMessage("@lair_n:found_nothing"); else player->sendSystemMessage("@skl_use:sys_forage_fail"); //"You failed to find anything worth foraging." } else { forageGiveItems(player, forageType, forageX, forageY, zoneName); } return; } bool ForageManagerImplementation::forageGiveItems(CreatureObject* player, int forageType, float forageX, float forageY, const String& planet) { if (player == NULL) return false; Locker playerLocker(player); ManagedReference<LootManager*> lootManager = player->getZoneServer()->getLootManager(); ManagedReference<SceneObject*> inventory = player->getSlottedObject("inventory"); if (lootManager == NULL || inventory == NULL) { player->sendSystemMessage("@skl_use:sys_forage_fail"); return false; } //Check if inventory is full. if (inventory->hasFullContainerObjects()) { player->sendSystemMessage("@skl_use:sys_forage_noroom"); //"Some foraged items were discarded, because your inventory is full." return false; } int itemCount = 1; //Determine how many items the player finds. if (forageType == ForageManager::SCOUT) { if (player->hasSkill("outdoors_scout_camp_03") && System::random(5) == 1) itemCount += 1; if (player->hasSkill("outdoors_scout_master") && System::random(5) == 1) itemCount += 1; } //Discard items if player's inventory does not have enough space. int inventorySpace = inventory->getContainerVolumeLimit() - inventory->getContainerObjectsSize(); if (itemCount > inventorySpace) { itemCount = inventorySpace; player->sendSystemMessage("@skl_use:sys_forage_noroom"); //"Some foraged items were discarded, because your inventory is full." } //Determine what the player finds. int dice; int level = 1; String lootGroup = ""; String resName = ""; if (forageType == ForageManager::SHELLFISH){ bool mullosks = false; if (System::random(100) > 50) { resName = "seafood_mollusk"; mullosks = true; } else resName = "seafood_crustacean"; if(forageGiveResource(player, forageX, forageY, planet, resName)) { if (mullosks) player->sendSystemMessage("@harvesting:found_mollusks"); else player->sendSystemMessage("@harvesting:found_crustaceans"); return true; } else { player->sendSystemMessage("@harvesting:found_nothing"); return false; } } if (forageType == ForageManager::SCOUT) { for (int i = 0; i < itemCount; i++) { dice = System::random(200); level = 1; if (dice >= 0 && dice < 160) { lootGroup = "forage_food"; } else if (dice > 159 && dice < 200) { lootGroup = "forage_bait"; } else { lootGroup = "forage_rare"; } lootManager->createLoot(inventory, lootGroup, level); } } else if (forageType == ForageManager::MEDICAL) { //Medical Forage dice = System::random(200); level = 1; if (dice >= 0 && dice < 40) { //Forage food. lootGroup = "forage_food"; } else if (dice > 39 && dice < 110) { //Resources. if(forageGiveResource(player, forageX, forageY, planet, resName)) { player->sendSystemMessage("@skl_use:sys_forage_success"); return true; } else { player->sendSystemMessage("@skl_use:sys_forage_fail"); return false; } } else if (dice > 109 && dice < 170) { //Average components. lootGroup = "forage_medical_component"; level = 1; } else if (dice > 169 && dice < 200) { //Good components. lootGroup = "forage_medical_component"; level = 60; } else { //Exceptional Components lootGroup = "forage_medical_component"; level = 200; } lootManager->createLoot(inventory, lootGroup, level); } else if (forageType == ForageManager::LAIR) { //Lair Search dice = System::random(109); level = 1; if (dice >= 0 && dice < 40) { // Live Creatures lootGroup = "forage_live_creatures"; } else if (dice > 39 && dice < 110) { // Eggs resName = "meat_egg"; if(forageGiveResource(player, forageX, forageY, planet, resName)) { player->sendSystemMessage("@lair_n:found_eggs"); return true; } else { player->sendSystemMessage("@lair_n:found_nothing"); return false; } } if(!lootManager->createLoot(inventory, lootGroup, level)) { player->sendSystemMessage("Unable to create loot for lootgroup " + lootGroup); return false; } player->sendSystemMessage("@lair_n:found_bugs"); return true; } player->sendSystemMessage("@skl_use:sys_forage_success"); return true; } bool ForageManagerImplementation::forageGiveResource(CreatureObject* player, float forageX, float forageY, const String& planet, String& resType) { if (player == NULL) return false; ManagedReference<ResourceManager*> resourceManager = player->getZoneServer()->getResourceManager(); if (resourceManager == NULL) return false; ManagedReference<ResourceSpawn*> resource = NULL; if(resType.isEmpty()) { //Get a list of the flora on the planet. Vector<ManagedReference<ResourceSpawn*> > resources; resourceManager->getResourceListByType(resources, 3, planet); if (resources.size() < 1) return false; while (resources.size() > 0) { int key = System::random(resources.size() - 1); float density = resources.get(key)->getDensityAt(planet, forageX, forageY); if (density <= 0.0 && resources.size() > 1) { //No concentration of this resource near the player. resources.remove(key); //Remove and pick another one. } else { //If there is only one left, we give them that one even if density is 0. resource = resources.get(key); break; } } } else { if(player->getZone() == NULL) return false; resType = resType + "_" + player->getZone()->getZoneName(); resource = resourceManager->getCurrentSpawn(resType, player->getZone()->getZoneName()); if(resource == NULL) { StringBuffer message; message << "Resource type not available: " << resType << " on " << player->getZone()->getZoneName(); warning(message.toString()); return false; } } int quantity = System::random(30) + 10; resourceManager->harvestResourceToPlayer(player, resource, quantity); return true; } <|endoftext|>
<commit_before>/* * Copyright (C) 2017-present ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "schema.hh" #include "schema_registry.hh" #include "keys.hh" #include "mutation_fragment.hh" #include "mutation.hh" #include "schema_builder.hh" #include "sstable_utils.hh" #include "reader_permit.hh" // Helper for working with the following table: // // CREATE TABLE ks.cf (pk text, ck text, v text, s1 text static, PRIMARY KEY (pk, ck)); // class simple_schema { friend class global_simple_schema; schema_ptr _s; api::timestamp_type _timestamp = api::min_timestamp; const column_definition* _v_def = nullptr; table_schema_version _v_def_version; simple_schema(schema_ptr s, api::timestamp_type timestamp) : _s(s) , _timestamp(timestamp) {} private: const column_definition& get_v_def(const schema& s) { if (_v_def_version == s.version() && _v_def) { return *_v_def; } _v_def = s.get_column_definition(to_bytes("v")); _v_def_version = s.version(); return *_v_def; } public: api::timestamp_type current_timestamp() { return _timestamp; } api::timestamp_type new_timestamp() { return _timestamp++; } tombstone new_tombstone() { return {new_timestamp(), gc_clock::now()}; } public: using with_static = bool_class<class static_tag>; simple_schema(with_static ws = with_static::yes) : _s(schema_builder("ks", "cf") .with_column("pk", utf8_type, column_kind::partition_key) .with_column("ck", utf8_type, column_kind::clustering_key) .with_column("s1", utf8_type, ws ? column_kind::static_column : column_kind::regular_column) .with_column("v", utf8_type) .build()) { } sstring cql() const { return "CREATE TABLE ks.cf (pk text, ck text, v text, s1 text static, PRIMARY KEY (pk, ck))"; } clustering_key make_ckey(sstring ck) { return clustering_key::from_single_value(*_s, serialized(ck)); } query::clustering_range make_ckey_range(uint32_t start_inclusive, uint32_t end_inclusive) { return query::clustering_range::make({make_ckey(start_inclusive)}, {make_ckey(end_inclusive)}); } // Make a clustering_key which is n-th in some arbitrary sequence of keys clustering_key make_ckey(uint32_t n) { return make_ckey(format("ck{:010d}", n)); } // Make a partition key which is n-th in some arbitrary sequence of keys. // There is no particular order for the keys, they're not in ring order. dht::decorated_key make_pkey(uint32_t n) { return make_pkey(format("pk{:010d}", n)); } dht::decorated_key make_pkey(sstring pk) { auto key = partition_key::from_single_value(*_s, serialized(pk)); return dht::decorate_key(*_s, key); } api::timestamp_type add_row(mutation& m, const clustering_key& key, const sstring& v, api::timestamp_type t = api::missing_timestamp) { if (t == api::missing_timestamp) { t = new_timestamp(); } const column_definition& v_def = get_v_def(*_s); m.set_clustered_cell(key, v_def, atomic_cell::make_live(*v_def.type, t, serialized(v))); return t; } std::pair<sstring, api::timestamp_type> get_value(const schema& s, const clustering_row& row) { const column_definition& v_def = get_v_def(s); auto cell = row.cells().find_cell(v_def.id); if (!cell) { throw std::runtime_error("cell not found"); } atomic_cell_view ac = cell->as_atomic_cell(v_def); if (!ac.is_live()) { throw std::runtime_error("cell is dead"); } return std::make_pair(value_cast<sstring>(utf8_type->deserialize(ac.value().linearize())), ac.timestamp()); } mutation_fragment make_row(const clustering_key& key, sstring v) { auto row = clustering_row(key); const column_definition& v_def = get_v_def(*_s); row.cells().apply(v_def, atomic_cell::make_live(*v_def.type, new_timestamp(), serialized(v))); return mutation_fragment(*_s, tests::make_permit(), std::move(row)); } mutation_fragment make_row_from_serialized_value(const clustering_key& key, bytes_view v) { auto row = clustering_row(key); const column_definition& v_def = get_v_def(*_s); row.cells().apply(v_def, atomic_cell::make_live(*v_def.type, new_timestamp(), v)); return mutation_fragment(*_s, tests::make_permit(), std::move(row)); } mutation_fragment make_static_row(sstring v) { static_row row; const column_definition& s_def = *_s->get_column_definition(to_bytes("s1")); row.cells().apply(s_def, atomic_cell::make_live(*s_def.type, new_timestamp(), serialized(v))); return mutation_fragment(*_s, tests::make_permit(), std::move(row)); } void set_schema(schema_ptr s) { _s = s; } api::timestamp_type add_static_row(mutation& m, sstring s1, api::timestamp_type t = api::missing_timestamp) { if (t == api::missing_timestamp) { t = new_timestamp(); } m.set_static_cell(to_bytes("s1"), data_value(s1), t); return t; } range_tombstone delete_range(mutation& m, const query::clustering_range& range, tombstone t = {}) { auto rt = make_range_tombstone(range, t); m.partition().apply_delete(*_s, rt); return rt; } range_tombstone make_range_tombstone(const query::clustering_range& range, tombstone t = {}) { auto bv_range = bound_view::from_range(range); if (!t) { t = tombstone(new_timestamp(), gc_clock::now()); } range_tombstone rt(bv_range.first, bv_range.second, t); return rt; } range_tombstone make_range_tombstone(const query::clustering_range& range, gc_clock::time_point deletion_time) { return make_range_tombstone(range, tombstone(new_timestamp(), deletion_time)); } mutation new_mutation(sstring pk) { return mutation(_s, make_pkey(pk)); } schema_ptr schema() { return _s; } const schema_ptr schema() const { return _s; } // Creates a sequence of keys in ring order std::vector<dht::decorated_key> make_pkeys(int n) { auto local_keys = make_local_keys(n, _s); return boost::copy_range<std::vector<dht::decorated_key>>(local_keys | boost::adaptors::transformed([this] (sstring& key) { return make_pkey(std::move(key)); })); } dht::decorated_key make_pkey() { return make_pkey(make_local_key(_s)); } static std::vector<dht::ring_position> to_ring_positions(const std::vector<dht::decorated_key>& keys) { return boost::copy_range<std::vector<dht::ring_position>>(keys | boost::adaptors::transformed([] (const dht::decorated_key& key) { return dht::ring_position(key); })); } // Returns n clustering keys in their natural order std::vector<clustering_key> make_ckeys(int n) { std::vector<clustering_key> keys; for (int i = 0; i < n; ++i) { keys.push_back(make_ckey(i)); } return keys; } }; // Allows a simple_schema to be transferred to another shard. // Must be used in `cql_test_env`. class global_simple_schema { global_schema_ptr _gs; api::timestamp_type _timestamp; public: global_simple_schema(simple_schema& s) : _gs(s.schema()) , _timestamp(s.current_timestamp()) { } simple_schema get() const { return simple_schema(_gs.get(), _timestamp); } }; <commit_msg>test: lib: simple_schema: Reuse new_tombstone()<commit_after>/* * Copyright (C) 2017-present ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "schema.hh" #include "schema_registry.hh" #include "keys.hh" #include "mutation_fragment.hh" #include "mutation.hh" #include "schema_builder.hh" #include "sstable_utils.hh" #include "reader_permit.hh" // Helper for working with the following table: // // CREATE TABLE ks.cf (pk text, ck text, v text, s1 text static, PRIMARY KEY (pk, ck)); // class simple_schema { friend class global_simple_schema; schema_ptr _s; api::timestamp_type _timestamp = api::min_timestamp; const column_definition* _v_def = nullptr; table_schema_version _v_def_version; simple_schema(schema_ptr s, api::timestamp_type timestamp) : _s(s) , _timestamp(timestamp) {} private: const column_definition& get_v_def(const schema& s) { if (_v_def_version == s.version() && _v_def) { return *_v_def; } _v_def = s.get_column_definition(to_bytes("v")); _v_def_version = s.version(); return *_v_def; } public: api::timestamp_type current_timestamp() { return _timestamp; } api::timestamp_type new_timestamp() { return _timestamp++; } tombstone new_tombstone() { return {new_timestamp(), gc_clock::now()}; } public: using with_static = bool_class<class static_tag>; simple_schema(with_static ws = with_static::yes) : _s(schema_builder("ks", "cf") .with_column("pk", utf8_type, column_kind::partition_key) .with_column("ck", utf8_type, column_kind::clustering_key) .with_column("s1", utf8_type, ws ? column_kind::static_column : column_kind::regular_column) .with_column("v", utf8_type) .build()) { } sstring cql() const { return "CREATE TABLE ks.cf (pk text, ck text, v text, s1 text static, PRIMARY KEY (pk, ck))"; } clustering_key make_ckey(sstring ck) { return clustering_key::from_single_value(*_s, serialized(ck)); } query::clustering_range make_ckey_range(uint32_t start_inclusive, uint32_t end_inclusive) { return query::clustering_range::make({make_ckey(start_inclusive)}, {make_ckey(end_inclusive)}); } // Make a clustering_key which is n-th in some arbitrary sequence of keys clustering_key make_ckey(uint32_t n) { return make_ckey(format("ck{:010d}", n)); } // Make a partition key which is n-th in some arbitrary sequence of keys. // There is no particular order for the keys, they're not in ring order. dht::decorated_key make_pkey(uint32_t n) { return make_pkey(format("pk{:010d}", n)); } dht::decorated_key make_pkey(sstring pk) { auto key = partition_key::from_single_value(*_s, serialized(pk)); return dht::decorate_key(*_s, key); } api::timestamp_type add_row(mutation& m, const clustering_key& key, const sstring& v, api::timestamp_type t = api::missing_timestamp) { if (t == api::missing_timestamp) { t = new_timestamp(); } const column_definition& v_def = get_v_def(*_s); m.set_clustered_cell(key, v_def, atomic_cell::make_live(*v_def.type, t, serialized(v))); return t; } std::pair<sstring, api::timestamp_type> get_value(const schema& s, const clustering_row& row) { const column_definition& v_def = get_v_def(s); auto cell = row.cells().find_cell(v_def.id); if (!cell) { throw std::runtime_error("cell not found"); } atomic_cell_view ac = cell->as_atomic_cell(v_def); if (!ac.is_live()) { throw std::runtime_error("cell is dead"); } return std::make_pair(value_cast<sstring>(utf8_type->deserialize(ac.value().linearize())), ac.timestamp()); } mutation_fragment make_row(const clustering_key& key, sstring v) { auto row = clustering_row(key); const column_definition& v_def = get_v_def(*_s); row.cells().apply(v_def, atomic_cell::make_live(*v_def.type, new_timestamp(), serialized(v))); return mutation_fragment(*_s, tests::make_permit(), std::move(row)); } mutation_fragment make_row_from_serialized_value(const clustering_key& key, bytes_view v) { auto row = clustering_row(key); const column_definition& v_def = get_v_def(*_s); row.cells().apply(v_def, atomic_cell::make_live(*v_def.type, new_timestamp(), v)); return mutation_fragment(*_s, tests::make_permit(), std::move(row)); } mutation_fragment make_static_row(sstring v) { static_row row; const column_definition& s_def = *_s->get_column_definition(to_bytes("s1")); row.cells().apply(s_def, atomic_cell::make_live(*s_def.type, new_timestamp(), serialized(v))); return mutation_fragment(*_s, tests::make_permit(), std::move(row)); } void set_schema(schema_ptr s) { _s = s; } api::timestamp_type add_static_row(mutation& m, sstring s1, api::timestamp_type t = api::missing_timestamp) { if (t == api::missing_timestamp) { t = new_timestamp(); } m.set_static_cell(to_bytes("s1"), data_value(s1), t); return t; } range_tombstone delete_range(mutation& m, const query::clustering_range& range, tombstone t = {}) { auto rt = make_range_tombstone(range, t); m.partition().apply_delete(*_s, rt); return rt; } range_tombstone make_range_tombstone(const query::clustering_range& range, tombstone t = {}) { auto bv_range = bound_view::from_range(range); if (!t) { t = new_tombstone(); } range_tombstone rt(bv_range.first, bv_range.second, t); return rt; } range_tombstone make_range_tombstone(const query::clustering_range& range, gc_clock::time_point deletion_time) { return make_range_tombstone(range, tombstone(new_timestamp(), deletion_time)); } mutation new_mutation(sstring pk) { return mutation(_s, make_pkey(pk)); } schema_ptr schema() { return _s; } const schema_ptr schema() const { return _s; } // Creates a sequence of keys in ring order std::vector<dht::decorated_key> make_pkeys(int n) { auto local_keys = make_local_keys(n, _s); return boost::copy_range<std::vector<dht::decorated_key>>(local_keys | boost::adaptors::transformed([this] (sstring& key) { return make_pkey(std::move(key)); })); } dht::decorated_key make_pkey() { return make_pkey(make_local_key(_s)); } static std::vector<dht::ring_position> to_ring_positions(const std::vector<dht::decorated_key>& keys) { return boost::copy_range<std::vector<dht::ring_position>>(keys | boost::adaptors::transformed([] (const dht::decorated_key& key) { return dht::ring_position(key); })); } // Returns n clustering keys in their natural order std::vector<clustering_key> make_ckeys(int n) { std::vector<clustering_key> keys; for (int i = 0; i < n; ++i) { keys.push_back(make_ckey(i)); } return keys; } }; // Allows a simple_schema to be transferred to another shard. // Must be used in `cql_test_env`. class global_simple_schema { global_schema_ptr _gs; api::timestamp_type _timestamp; public: global_simple_schema(simple_schema& s) : _gs(s.schema()) , _timestamp(s.current_timestamp()) { } simple_schema get() const { return simple_schema(_gs.get(), _timestamp); } }; <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2018. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= inline size_t str_cat(char* destination, const char* source){ size_t n = 0; while(*source){ *destination++ = *source++; ++n; } return n; } std::string vsprintf(const std::string& format, va_list va){ std::string s(format.size()); char ch; int fi = 0; while ((ch = format[fi++])) { if(ch != '%'){ s += ch; } else { ch = format[fi++]; size_t min_width = 0; while(ch >= '0' && ch <= '9'){ min_width = 10 * min_width + (ch - '0'); ch = format[fi++]; } size_t min_digits = 0; if(ch == '.'){ ch = format[fi++]; while(ch >= '0' && ch <= '9'){ min_digits = 10 * min_digits + (ch - '0'); ch = format[fi++]; } } auto prev = s.size(); //Signed decimal if(ch == 'd'){ int64_t arg = va_arg(va, int64_t); if(min_digits > 0){ size_t d = std::digits(arg); if(min_digits > d){ min_digits -= d; if(arg < 0){ arg *= -1; s += '-'; } while(min_digits > 0){ s += '0'; --min_digits; } } } s += std::to_string(arg); } //Unsigned Decimal else if(ch == 'u'){ uint64_t arg = va_arg(va, uint64_t); if(min_digits > 0){ size_t d = std::digits(arg); if(min_digits > d){ min_digits -= d; while(min_digits > 0){ s += '0'; --min_digits; } } } s += std::to_string(arg); } //Hexadecimal else if(ch == 'h' || ch == 'x' || ch == 'p'){ if(ch == 'h' || ch == 'p'){ s += "0x"; } uint8_t buffer[20]; uint64_t arg = va_arg(va, uint64_t); size_t i = 0; while(arg / 16 != 0){ buffer[i++] = arg % 16; arg /= 16; } buffer[i] = arg; if(min_digits > 0 && min_digits > i){ min_digits -= i + 1; while(min_digits > 0){ arg += '0'; --min_digits; } } while(true){ uint8_t digit = buffer[i]; if(digit < 10){ s += static_cast<char>('0' + digit); } else { switch(digit){ case 10: s += 'A'; break; case 11: s += 'B'; break; case 12: s += 'C'; break; case 13: s += 'D'; break; case 14: s += 'E'; break; case 15: s += 'F'; break; } } if(i == 0){ break; } --i; } } //Memory else if(ch == 'm'){ uint64_t memory= va_arg(va, uint64_t); if(memory >= 1024 * 1024 * 1024){ s += std::to_string(memory / (1024 * 1024 * 1024)); s += "GiB"; } else if(memory >= 1024 * 1024){ s += std::to_string(memory / (1024 * 1024)); s += "MiB"; } else if(memory >= 1024){ s += std::to_string(memory / 1024); s += "KiB"; } else { s += std::to_string(memory); s += "B"; } } // Boolean else if(ch == 'b'){ bool value= va_arg(va, int); if(value){ s += "true"; } else { s += "false"; } } // Binary else if(ch == 'B'){ size_t value= va_arg(va, size_t); uint8_t bits[64]; size_t top = 0; bits[0] = 0; while(value){ bits[top++] = value & 1; value >>= 1; } s += "0b"; for(size_t i = top; i > 0; --i){ s += bits[i] ? '1' : '0'; } s += bits[0] ? '1' : '0'; } //String else if(ch == 's'){ const char* arg = va_arg(va, const char*); if(arg){ s += arg; } } if(min_width > 0){ size_t width = s.size() - prev; if(min_width > width){ min_width -= width; while(min_width > 0){ s += ' '; --min_width; } } } } } return std::move(s); } std::string sprintf(const std::string& format, ...){ va_list va; va_start(va, format); auto s = vsprintf(format, va); va_end(va); return std::move(s); } void vprintf(const std::string& format, va_list va){ __printf(vsprintf(format, va)); } void printf(const std::string& format, ...){ va_list va; va_start(va, format); vprintf(format, va); va_end(va); } // Raw versions //TODO Check for n void vsprintf_raw(char* out_buffer, size_t /*n*/, const char* format, va_list va){ char ch; int fi = 0; size_t out_i = 0; while ((ch = format[fi++])) { if(ch != '%'){ out_buffer[out_i++] = ch; } else { ch = format[fi++]; size_t min_width = 0; while(ch >= '0' && ch <= '9'){ min_width = 10 * min_width + (ch - '0'); ch = format[fi++]; } size_t min_digits = 0; if(ch == '.'){ ch = format[fi++]; while(ch >= '0' && ch <= '9'){ min_digits = 10 * min_digits + (ch - '0'); ch = format[fi++]; } } auto prev = out_i; //Signed decimal if(ch == 'd'){ int64_t arg = va_arg(va, int64_t); if(min_digits > 0){ size_t d = std::digits(arg); if(min_digits > d){ min_digits -= d; if(arg < 0){ arg *= -1; out_buffer[out_i++] = '-'; } while(min_digits > 0){ out_buffer[out_i++] = '0'; --min_digits; } } } char buffer[32]; std::to_raw_string(arg, buffer, 32); out_i += str_cat(out_buffer + out_i, buffer); } //Unsigned Decimal else if(ch == 'u'){ uint64_t arg = va_arg(va, uint64_t); if(min_digits > 0){ size_t d = std::digits(arg); if(min_digits > d){ min_digits -= d; while(min_digits > 0){ out_buffer[out_i++] = '0'; --min_digits; } } } char buffer[32]; std::to_raw_string(arg, buffer, 32); out_i += str_cat(out_buffer + out_i, buffer); } //Hexadecimal else if(ch == 'h' || ch == 'x' || ch == 'p'){ if(ch == 'h' || ch == 'p'){ out_buffer[out_i++] = '0'; out_buffer[out_i++] = 'x'; } uint8_t buffer[20]; uint64_t arg = va_arg(va, uint64_t); size_t i = 0; while(arg / 16 != 0){ buffer[i++] = arg % 16; arg /= 16; } buffer[i] = arg; if(min_digits > 0 && min_digits > i){ min_digits -= i + 1; while(min_digits > 0){ out_buffer[out_i++] = '0'; --min_digits; } } while(true){ uint8_t digit = buffer[i]; if(digit < 10){ out_buffer[out_i++] = static_cast<char>('0' + digit); } else { switch(digit){ case 10: out_buffer[out_i++] = 'A'; break; case 11: out_buffer[out_i++] = 'B'; break; case 12: out_buffer[out_i++] = 'C'; break; case 13: out_buffer[out_i++] = 'D'; break; case 14: out_buffer[out_i++] = 'E'; break; case 15: out_buffer[out_i++] = 'F'; break; } } if(i == 0){ break; } --i; } } //Memory else if(ch == 'm'){ uint64_t memory= va_arg(va, uint64_t); char buffer[32]; if(memory >= 1024 * 1024 * 1024){ std::to_raw_string(memory / (1024 * 1024 * 1024), buffer, 32); out_i += str_cat(out_buffer + out_i, buffer); out_i += str_cat(out_buffer + out_i, "GiB"); } else if(memory >= 1024 * 1024){ std::to_raw_string(memory / (1024 * 1024), buffer, 32); out_i += str_cat(out_buffer + out_i, buffer); out_i += str_cat(out_buffer + out_i, "MiB"); } else if(memory >= 1024){ std::to_raw_string(memory / 1024, buffer, 32); out_i += str_cat(out_buffer + out_i, buffer); out_i += str_cat(out_buffer + out_i, "KiB"); } else { std::to_raw_string(memory, buffer, 32); out_i += str_cat(out_buffer + out_i, buffer); out_i += str_cat(out_buffer + out_i, "B"); } } // Boolean else if(ch == 'b'){ bool value= va_arg(va, int); if(value){ out_i += str_cat(out_buffer + out_i, "true"); } else { out_i += str_cat(out_buffer + out_i, "false"); } } // Binary else if(ch == 'B'){ size_t value= va_arg(va, size_t); uint8_t bits[64]; size_t top = 0; bits[0] = 0; while(value){ bits[top++] = value & 1; value >>= 1; } out_buffer[out_i++] = '0'; out_buffer[out_i++] = 'b'; for(size_t i = top; i > 0; --i){ out_buffer[out_i++] = bits[i] ? '1' : '0'; } out_buffer[out_i++] = bits[0] ? '1' : '0'; } //String else if(ch == 's'){ const char* arg = va_arg(va, const char*); out_i += str_cat(out_buffer + out_i, arg); } if(min_width > 0){ size_t width = out_i - prev; if(min_width > width){ min_width -= width; while(min_width > 0){ out_buffer[out_i++] = ' '; --min_width; } } } } } out_buffer[out_i++] = '\0'; } void sprintf_raw(char* buffer, size_t n, const char* format, ...){ va_list va; va_start(va, format); vsprintf_raw(buffer, n, format, va); va_end(va); } void vprintf_raw(const char* format, va_list va){ char buffer[1024]; vsprintf_raw(buffer, 1024, format, va); __printf_raw(buffer); } void printf_raw(const char* format, ...){ va_list va; va_start(va, format); vprintf_raw(format, va); va_end(va); } <commit_msg>Add support for variable length string in printf<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2018. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= inline size_t str_cat(char* destination, const char* source){ size_t n = 0; while(*source){ *destination++ = *source++; ++n; } return n; } inline size_t str_cat(char* destination, const char* source, size_t length){ size_t n = 0; while(n < length){ *destination++ = *source++; ++n; } return n; } std::string vsprintf(const std::string& format, va_list va){ std::string s(format.size()); char ch; int fi = 0; while ((ch = format[fi++])) { if(ch != '%'){ s += ch; } else { ch = format[fi++]; size_t min_width = 0; while(ch >= '0' && ch <= '9'){ min_width = 10 * min_width + (ch - '0'); ch = format[fi++]; } size_t min_digits = 0; bool variable_length = false; if (ch == '.') { ch = format[fi++]; if (ch == '*') { variable_length = true; ch = format[fi++]; } else { while (ch >= '0' && ch <= '9') { min_digits = 10 * min_digits + (ch - '0'); ch = format[fi++]; } } } auto prev = s.size(); //Signed decimal if(ch == 'd'){ int64_t arg = va_arg(va, int64_t); if(min_digits > 0){ size_t d = std::digits(arg); if(min_digits > d){ min_digits -= d; if(arg < 0){ arg *= -1; s += '-'; } while(min_digits > 0){ s += '0'; --min_digits; } } } s += std::to_string(arg); } //Unsigned Decimal else if(ch == 'u'){ uint64_t arg = va_arg(va, uint64_t); if(min_digits > 0){ size_t d = std::digits(arg); if(min_digits > d){ min_digits -= d; while(min_digits > 0){ s += '0'; --min_digits; } } } s += std::to_string(arg); } //Hexadecimal else if(ch == 'h' || ch == 'x' || ch == 'p'){ if(ch == 'h' || ch == 'p'){ s += "0x"; } uint8_t buffer[20]; uint64_t arg = va_arg(va, uint64_t); size_t i = 0; while(arg / 16 != 0){ buffer[i++] = arg % 16; arg /= 16; } buffer[i] = arg; if(min_digits > 0 && min_digits > i){ min_digits -= i + 1; while(min_digits > 0){ arg += '0'; --min_digits; } } while(true){ uint8_t digit = buffer[i]; if(digit < 10){ s += static_cast<char>('0' + digit); } else { switch(digit){ case 10: s += 'A'; break; case 11: s += 'B'; break; case 12: s += 'C'; break; case 13: s += 'D'; break; case 14: s += 'E'; break; case 15: s += 'F'; break; } } if(i == 0){ break; } --i; } } //Memory else if(ch == 'm'){ uint64_t memory= va_arg(va, uint64_t); if(memory >= 1024 * 1024 * 1024){ s += std::to_string(memory / (1024 * 1024 * 1024)); s += "GiB"; } else if(memory >= 1024 * 1024){ s += std::to_string(memory / (1024 * 1024)); s += "MiB"; } else if(memory >= 1024){ s += std::to_string(memory / 1024); s += "KiB"; } else { s += std::to_string(memory); s += "B"; } } // Boolean else if(ch == 'b'){ bool value= va_arg(va, int); if(value){ s += "true"; } else { s += "false"; } } // Binary else if(ch == 'B'){ size_t value= va_arg(va, size_t); uint8_t bits[64]; size_t top = 0; bits[0] = 0; while(value){ bits[top++] = value & 1; value >>= 1; } s += "0b"; for(size_t i = top; i > 0; --i){ s += bits[i] ? '1' : '0'; } s += bits[0] ? '1' : '0'; } //String else if(ch == 's'){ if (variable_length) { size_t size_arg = va_arg(va, size_t); const char* arg = va_arg(va, const char*); if (arg) { s.append(arg, arg + size_arg); } } else { const char* arg = va_arg(va, const char*); if (arg) { s += arg; } } } if(min_width > 0){ size_t width = s.size() - prev; if(min_width > width){ min_width -= width; while(min_width > 0){ s += ' '; --min_width; } } } } } return std::move(s); } std::string sprintf(const std::string& format, ...){ va_list va; va_start(va, format); auto s = vsprintf(format, va); va_end(va); return std::move(s); } void vprintf(const std::string& format, va_list va){ __printf(vsprintf(format, va)); } void printf(const std::string& format, ...){ va_list va; va_start(va, format); vprintf(format, va); va_end(va); } // Raw versions //TODO Check for n void vsprintf_raw(char* out_buffer, size_t /*n*/, const char* format, va_list va){ char ch; int fi = 0; size_t out_i = 0; while ((ch = format[fi++])) { if(ch != '%'){ out_buffer[out_i++] = ch; } else { ch = format[fi++]; size_t min_width = 0; while(ch >= '0' && ch <= '9'){ min_width = 10 * min_width + (ch - '0'); ch = format[fi++]; } size_t min_digits = 0; bool variable_length = false; if (ch == '.') { ch = format[fi++]; if (ch == '*') { variable_length = true; ch = format[fi++]; } else { while (ch >= '0' && ch <= '9') { min_digits = 10 * min_digits + (ch - '0'); ch = format[fi++]; } } } auto prev = out_i; //Signed decimal if(ch == 'd'){ int64_t arg = va_arg(va, int64_t); if(min_digits > 0){ size_t d = std::digits(arg); if(min_digits > d){ min_digits -= d; if(arg < 0){ arg *= -1; out_buffer[out_i++] = '-'; } while(min_digits > 0){ out_buffer[out_i++] = '0'; --min_digits; } } } char buffer[32]; std::to_raw_string(arg, buffer, 32); out_i += str_cat(out_buffer + out_i, buffer); } //Unsigned Decimal else if(ch == 'u'){ uint64_t arg = va_arg(va, uint64_t); if(min_digits > 0){ size_t d = std::digits(arg); if(min_digits > d){ min_digits -= d; while(min_digits > 0){ out_buffer[out_i++] = '0'; --min_digits; } } } char buffer[32]; std::to_raw_string(arg, buffer, 32); out_i += str_cat(out_buffer + out_i, buffer); } //Hexadecimal else if(ch == 'h' || ch == 'x' || ch == 'p'){ if(ch == 'h' || ch == 'p'){ out_buffer[out_i++] = '0'; out_buffer[out_i++] = 'x'; } uint8_t buffer[20]; uint64_t arg = va_arg(va, uint64_t); size_t i = 0; while(arg / 16 != 0){ buffer[i++] = arg % 16; arg /= 16; } buffer[i] = arg; if(min_digits > 0 && min_digits > i){ min_digits -= i + 1; while(min_digits > 0){ out_buffer[out_i++] = '0'; --min_digits; } } while(true){ uint8_t digit = buffer[i]; if(digit < 10){ out_buffer[out_i++] = static_cast<char>('0' + digit); } else { switch(digit){ case 10: out_buffer[out_i++] = 'A'; break; case 11: out_buffer[out_i++] = 'B'; break; case 12: out_buffer[out_i++] = 'C'; break; case 13: out_buffer[out_i++] = 'D'; break; case 14: out_buffer[out_i++] = 'E'; break; case 15: out_buffer[out_i++] = 'F'; break; } } if(i == 0){ break; } --i; } } //Memory else if(ch == 'm'){ uint64_t memory= va_arg(va, uint64_t); char buffer[32]; if(memory >= 1024 * 1024 * 1024){ std::to_raw_string(memory / (1024 * 1024 * 1024), buffer, 32); out_i += str_cat(out_buffer + out_i, buffer); out_i += str_cat(out_buffer + out_i, "GiB"); } else if(memory >= 1024 * 1024){ std::to_raw_string(memory / (1024 * 1024), buffer, 32); out_i += str_cat(out_buffer + out_i, buffer); out_i += str_cat(out_buffer + out_i, "MiB"); } else if(memory >= 1024){ std::to_raw_string(memory / 1024, buffer, 32); out_i += str_cat(out_buffer + out_i, buffer); out_i += str_cat(out_buffer + out_i, "KiB"); } else { std::to_raw_string(memory, buffer, 32); out_i += str_cat(out_buffer + out_i, buffer); out_i += str_cat(out_buffer + out_i, "B"); } } // Boolean else if(ch == 'b'){ bool value= va_arg(va, int); if(value){ out_i += str_cat(out_buffer + out_i, "true"); } else { out_i += str_cat(out_buffer + out_i, "false"); } } // Binary else if(ch == 'B'){ size_t value= va_arg(va, size_t); uint8_t bits[64]; size_t top = 0; bits[0] = 0; while(value){ bits[top++] = value & 1; value >>= 1; } out_buffer[out_i++] = '0'; out_buffer[out_i++] = 'b'; for(size_t i = top; i > 0; --i){ out_buffer[out_i++] = bits[i] ? '1' : '0'; } out_buffer[out_i++] = bits[0] ? '1' : '0'; } //String else if(ch == 's'){ if (variable_length) { size_t size_arg = va_arg(va, size_t); const char* arg = va_arg(va, const char*); if (arg) { out_i += str_cat(out_buffer + out_i, arg, size_arg); } } else { const char* arg = va_arg(va, const char*); if (arg) { out_i += str_cat(out_buffer + out_i, arg); } } } if(min_width > 0){ size_t width = out_i - prev; if(min_width > width){ min_width -= width; while(min_width > 0){ out_buffer[out_i++] = ' '; --min_width; } } } } } out_buffer[out_i++] = '\0'; } void sprintf_raw(char* buffer, size_t n, const char* format, ...){ va_list va; va_start(va, format); vsprintf_raw(buffer, n, format, va); va_end(va); } void vprintf_raw(const char* format, va_list va){ char buffer[1024]; vsprintf_raw(buffer, 1024, format, va); __printf_raw(buffer); } void printf_raw(const char* format, ...){ va_list va; va_start(va, format); vprintf_raw(format, va); va_end(va); } <|endoftext|>
<commit_before>#pragma once #include "common.hpp" #include "components/x11/connection.hpp" #include "utils/memory.hpp" LEMONBUDDY_NS struct randr_output { string name; int w = 0; int h = 0; int x = 0; int y = 0; }; using monitor_t = shared_ptr<randr_output>; namespace randr_util { /** * Define monitor */ inline monitor_t make_monitor(string name, int w, int h, int x, int y) { monitor_t mon{new monitor_t::element_type{}}; mon->name = name; mon->x = x; mon->y = y; mon->h = h; mon->w = w; return mon; } /** * Create a list of all available randr outputs */ inline vector<monitor_t> get_monitors(connection& conn, xcb_window_t root) { vector<monitor_t> monitors; auto outputs = conn.get_screen_resources(root).outputs(); for (auto it = outputs.begin(); it != outputs.end(); it++) { auto info = conn.get_output_info(*it); if (info->connection != XCB_RANDR_CONNECTION_CONNECTED) continue; auto crtc = conn.get_crtc_info(info->crtc); string name{info.name().begin(), info.name().end()}; monitors.emplace_back(make_monitor(name, crtc->width, crtc->height, crtc->x, crtc->y)); } // use the same sort algo as lemonbar, to match the defaults sort(monitors.begin(), monitors.end(), [](monitor_t& m1, monitor_t& m2) -> bool { if (m1->x < m2->x || m1->y + m1->h <= m2->y) return 1; if (m1->x > m2->x || m1->y + m1->h > m2->y) return -1; return 0; }); return monitors; } } LEMONBUDDY_NS_END <commit_msg>fix(xrandr): Ignore harmless extension errors<commit_after>#pragma once #include "common.hpp" #include "components/x11/connection.hpp" #include "utils/memory.hpp" LEMONBUDDY_NS struct randr_output { string name; int w = 0; int h = 0; int x = 0; int y = 0; }; using monitor_t = shared_ptr<randr_output>; namespace randr_util { /** * Define monitor */ inline monitor_t make_monitor(string name, int w, int h, int x, int y) { monitor_t mon{new monitor_t::element_type{}}; mon->name = name; mon->x = x; mon->y = y; mon->h = h; mon->w = w; return mon; } /** * Create a list of all available randr outputs */ inline vector<monitor_t> get_monitors(connection& conn, xcb_window_t root) { vector<monitor_t> monitors; auto outputs = conn.get_screen_resources(root).outputs(); for (auto it = outputs.begin(); it != outputs.end(); it++) { try { auto info = conn.get_output_info(*it); if (info->connection != XCB_RANDR_CONNECTION_CONNECTED) continue; auto crtc = conn.get_crtc_info(info->crtc); string name{info.name().begin(), info.name().end()}; monitors.emplace_back(make_monitor(name, crtc->width, crtc->height, crtc->x, crtc->y)); } catch (const xpp::randr::error::bad_crtc&) { } catch (const xpp::randr::error::bad_output&) { } } // use the same sort algo as lemonbar, to match the defaults sort(monitors.begin(), monitors.end(), [](monitor_t& m1, monitor_t& m2) -> bool { if (m1->x < m2->x || m1->y + m1->h <= m2->y) return 1; if (m1->x > m2->x || m1->y + m1->h > m2->y) return -1; return 0; }); return monitors; } } LEMONBUDDY_NS_END <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2020 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include "cufft.h" namespace etl::impl::cufft { /*! * \brief Returns the string representation of the given * CUFFT status code. * * \param code The CUFFT status code * * \return the string representation of the given status code */ inline const char* cufft_str(cufftResult code) { switch (code) { case CUFFT_SUCCESS: return "CUFFT_SUCCESS"; case CUFFT_INVALID_PLAN: return "CUFFT_INVALID_PLAN"; case CUFFT_ALLOC_FAILED: return "CUFFT_ALLOC_FAILED"; case CUFFT_INVALID_TYPE: return "CUFFT_INVALID_TYPE"; case CUFFT_INVALID_VALUE: return "CUFFT_INVALID_VALUE"; case CUFFT_INTERNAL_ERROR: return "CUFFT_INTERNAL_ERROR"; case CUFFT_EXEC_FAILED: return "CUFFT_EXEC_FAILED"; case CUFFT_SETUP_FAILED: return "CUFFT_SETUP_FAILED"; case CUFFT_INVALID_SIZE: return "CUFFT_INVALID_SIZE"; case CUFFT_UNALIGNED_DATA: return "CUFFT_UNALIGNED_DATA"; default: return "unknown CUFFT error"; } } #define cufft_check(call) \ { \ auto status = call; \ if (status != CUFFT_SUCCESS) { \ std::cerr << "CUDA error: " << etl::impl::cufft::cufft_str(status) << " from " << #call << std::endl \ << "from " << __FILE__ << ":" << __LINE__ << std::endl; \ } \ } /*! * \brief RAII wrapper for CUFFT context */ struct cufft_handle { cufftHandle handle; ///< The CUFFT context handle /*! * \brief Create a new cufft_handle. */ cufft_handle() { cufft_check(cufftCreate(&handle)); } cufft_handle(const cufft_handle& rhs) = delete; cufft_handle& operator=(const cufft_handle& rhs) = delete; cufft_handle(cufft_handle&& rhs) = default; cufft_handle& operator=(cufft_handle&& rhs) = default; /*! * \brief Returns the CUFFT context * \return the CUFFT context */ cufftHandle& get() { return handle; } /*! * \brief Destroy the handle and release the CUFFT context */ ~cufft_handle() { cufft_check(cufftDestroy(handle)); } }; /*! * \brief Obtain an handle to the CUFFT context * \return An handle to the CUFFT context */ inline cufft_handle start_cufft() { return {}; } /*! * \brief cast a etl::complex to its CUFFT equivalent * \param ptr Pointer the memory to cast * \return Pointer to the same memory but casted to CUFFT equivalent */ inline cufftComplex* complex_cast(etl::complex<float>* ptr) { return reinterpret_cast<cufftComplex*>(ptr); } /*! * \brief cast a etl::complex to its CUFFT equivalent * \param ptr Pointer the memory to cast * \return Pointer to the same memory but casted to CUFFT equivalent */ inline cufftDoubleComplex* complex_cast(etl::complex<double>* ptr) { return reinterpret_cast<cufftDoubleComplex*>(ptr); } /*! * \brief cast a std::complex to its CUFFT equivalent * \param ptr Pointer the memory to cast * \return Pointer to the same memory but casted to CUFFT equivalent */ inline cufftComplex* complex_cast(std::complex<float>* ptr) { return reinterpret_cast<cufftComplex*>(ptr); } /*! * \brief cast a std::complex to its CUFFT equivalent * \param ptr Pointer the memory to cast * \return Pointer to the same memory but casted to CUFFT equivalent */ inline cufftDoubleComplex* complex_cast(std::complex<double>* ptr) { return reinterpret_cast<cufftDoubleComplex*>(ptr); } } //end of namespace etl::impl::cufft <commit_msg>Cleanup code<commit_after>//======================================================================= // Copyright (c) 2014-2020 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include "cufft.h" namespace etl::impl::cufft { /*! * \brief Returns the string representation of the given * CUFFT status code. * * \param code The CUFFT status code * * \return the string representation of the given status code */ inline const char* cufft_str(cufftResult code) { switch (code) { case CUFFT_SUCCESS: return "CUFFT_SUCCESS"; case CUFFT_INVALID_PLAN: return "CUFFT_INVALID_PLAN"; case CUFFT_ALLOC_FAILED: return "CUFFT_ALLOC_FAILED"; case CUFFT_INVALID_TYPE: return "CUFFT_INVALID_TYPE"; case CUFFT_INVALID_VALUE: return "CUFFT_INVALID_VALUE"; case CUFFT_INTERNAL_ERROR: return "CUFFT_INTERNAL_ERROR"; case CUFFT_EXEC_FAILED: return "CUFFT_EXEC_FAILED"; case CUFFT_SETUP_FAILED: return "CUFFT_SETUP_FAILED"; case CUFFT_INVALID_SIZE: return "CUFFT_INVALID_SIZE"; case CUFFT_UNALIGNED_DATA: return "CUFFT_UNALIGNED_DATA"; default: return "unknown CUFFT error"; } } #define cufft_check(call) \ if (auto status = call; status != CUFFT_SUCCESS) { \ std::cerr << "CUDA error: " << etl::impl::cufft::cufft_str(status) << " from " << #call << std::endl \ << "from " << __FILE__ << ":" << __LINE__ << std::endl; \ } /*! * \brief RAII wrapper for CUFFT context */ struct cufft_handle { cufftHandle handle; ///< The CUFFT context handle /*! * \brief Create a new cufft_handle. */ cufft_handle() { cufft_check(cufftCreate(&handle)); } cufft_handle(const cufft_handle& rhs) = delete; cufft_handle& operator=(const cufft_handle& rhs) = delete; cufft_handle(cufft_handle&& rhs) = default; cufft_handle& operator=(cufft_handle&& rhs) = default; /*! * \brief Returns the CUFFT context * \return the CUFFT context */ cufftHandle& get() { return handle; } /*! * \brief Destroy the handle and release the CUFFT context */ ~cufft_handle() { cufft_check(cufftDestroy(handle)); } }; /*! * \brief Obtain an handle to the CUFFT context * \return An handle to the CUFFT context */ inline cufft_handle start_cufft() { return {}; } /*! * \brief cast a etl::complex to its CUFFT equivalent * \param ptr Pointer the memory to cast * \return Pointer to the same memory but casted to CUFFT equivalent */ inline cufftComplex* complex_cast(etl::complex<float>* ptr) { return reinterpret_cast<cufftComplex*>(ptr); } /*! * \brief cast a etl::complex to its CUFFT equivalent * \param ptr Pointer the memory to cast * \return Pointer to the same memory but casted to CUFFT equivalent */ inline cufftDoubleComplex* complex_cast(etl::complex<double>* ptr) { return reinterpret_cast<cufftDoubleComplex*>(ptr); } /*! * \brief cast a std::complex to its CUFFT equivalent * \param ptr Pointer the memory to cast * \return Pointer to the same memory but casted to CUFFT equivalent */ inline cufftComplex* complex_cast(std::complex<float>* ptr) { return reinterpret_cast<cufftComplex*>(ptr); } /*! * \brief cast a std::complex to its CUFFT equivalent * \param ptr Pointer the memory to cast * \return Pointer to the same memory but casted to CUFFT equivalent */ inline cufftDoubleComplex* complex_cast(std::complex<double>* ptr) { return reinterpret_cast<cufftDoubleComplex*>(ptr); } } //end of namespace etl::impl::cufft <|endoftext|>
<commit_before>//====================================================================== //----------------------------------------------------------------------- /** * @file iutest_port.hpp * @brief portable * * @author t.shirayanagi * @par copyright * Copyright (C) 2011-2018, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== #ifndef INCG_IRIS_IUTEST_PORT_HPP_7893F685_A1A9_477A_82E8_BF06237697FF_ #define INCG_IRIS_IUTEST_PORT_HPP_7893F685_A1A9_477A_82E8_BF06237697FF_ //====================================================================== // include #if defined(__MWERKS__) # define _MSL_USING_NAMESPACE #endif #include "iutest_internal_defs.hpp" #if defined(IUTEST_OS_LINUX) || defined(IUTEST_OS_CYGWIN) || defined(IUTEST_OS_MAC) # include <unistd.h> # include <locale.h> #endif #if IUTEST_HAS_FILE_STAT # include <sys/stat.h> #endif //====================================================================== // define #if !defined(IUTEST_MAX_PATH) # if defined(MAX_PATH) && MAX_PATH # define IUTEST_MAX_PATH MAX_PATH # elif defined(PATH_MAX) && PATH_MAX # define IUTEST_MAX_PATH PATH_MAX # elif defined(FILENAME_MAX) && FILENAME_MAX # define IUTEST_MAX_PATH FILENAME_MAX # else # define IUTEST_MAX_PATH 1024 # endif #endif /** * @brief ログメッセージストリーム */ #define IUTEST_LOG_(level) \ ::iutest::detail::IUTestLog( \ ::iutest::detail::IUTestLog::LOG_##level, __FILE__, __LINE__).GetStream() /** * @brief 内部エラーチェック */ #define IUTEST_CHECK_(condition) \ IUTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if( !::iutest::detail::IsTrue(condition) ) \ IUTEST_LOG_(FATAL) << "Condition " #condition " failed. " namespace iutest { #ifdef IUTEST_OS_NACL namespace nacl { /** * @brief printf */ void vprint_message(const char *fmt, va_list va); void print_message(const char *fmt, ...); } #endif namespace internal { namespace posix { const char* GetEnv(const char* name); int PutEnv(const char* expr); int SetEnv(const char* name, const char* value, int overwrite); const char* GetCWD(char* buf, size_t length); ::std::string GetCWD(); void SleepMillisec(unsigned int millisec); #if defined(IUTEST_OS_WINDOWS_MOBILE) void Abort(); #else IUTEST_ATTRIBUTE_NORETURN_ void Abort(); inline void Abort() { abort(); } #endif #if IUTEST_HAS_FILENO #if defined(_MSC_VER) inline int Fileno(FILE* fp) { return _fileno(fp); } #else inline int Fileno(FILE* fp) { return fileno(fp); } #endif #else inline int Fileno(FILE*) { return -1; } #endif #if IUTEST_HAS_FILE_STAT #if defined(IUTEST_OS_WINDOWS) && !defined(IUTEST_OS_WINDOWS_WINE) typedef struct _stat StatStruct; inline int FileStat(int fd, StatStruct* buf) { return _fstat(fd, buf); } inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } inline bool IsDir(const StatStruct& st) { return (st.st_mode & _S_IFDIR) != 0; } #else typedef struct stat StatStruct; inline int FileStat(int fd, StatStruct* buf) { return fstat(fd, buf); } inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); } inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } #endif inline int Stat(FILE* fp, StatStruct* buf) { int fd = Fileno(fp); return fd >= 0 ? FileStat(fd, buf) : fd; } #endif } // end of namespace posix inline void SleepMilliseconds(int n) { posix::SleepMillisec(static_cast<unsigned int>(n)); } } // end of namespace internal namespace detail { namespace posix = internal::posix; /** * @brief パス区切り文字の取得 */ char GetPathSeparator() IUTEST_CXX_NOEXCEPT_SPEC; /** * @brief パス区切り文字かどうか */ bool IsPathSeparator(char c) IUTEST_CXX_NOEXCEPT_SPEC; /** * @brief パス区切り文字かどうか */ bool IsAltPathSeparator(char c) IUTEST_CXX_NOEXCEPT_SPEC; /** * @brief 一番後ろのパスセパレータのアドレスを取得 */ const char* FindLastPathSeparator(const char* path, size_t length) IUTEST_CXX_NOEXCEPT_SPEC; /** * @brief 環境変数の設定 */ bool SetEnvironmentVariable(const char* name, const char* value); /** * @brief 環境変数の取得 * @param [in] name = 環境変数名 * @param [out] buf = 出力バッファ * @return 成否 */ bool GetEnvironmentVariable(const char* name, char* buf, size_t size); #if !defined(IUTEST_NO_FUNCTION_TEMPLATE_ORDERING) template<size_t SIZE> inline bool GetEnvironmentVariable(const char* name, char (&buf)[SIZE]) { return GetEnvironmentVariable(name, buf, SIZE); } #endif /** * @brief 環境変数の取得 * @param [in] name = 環境変数名 * @param [out] var = 出力文字列 * @return 成否 */ bool IUTEST_ATTRIBUTE_UNUSED_ GetEnvironmentVariable(const char* name, ::std::string& var); /** * @brief 環境変数の取得 * @param [in] name = 環境変数名 * @param [out] var = 出力数値 * @return 成否 */ bool IUTEST_ATTRIBUTE_UNUSED_ GetEnvironmentInt(const char* name, int& var); #if defined(IUTEST_OS_WINDOWS) namespace win { /** * @brief 文字列変換 */ ::std::string IUTEST_ATTRIBUTE_UNUSED_ WideStringToMultiByteString(const wchar_t* wide_c_str); /** * @brief HRESULT のエラー文字列を取得 * @param [in] hr = エラー値 * @return 文字列 */ ::std::string IUTEST_ATTRIBUTE_UNUSED_ GetHResultString(HRESULT hr); } // end of namespace win #endif /** * @brief ログ */ class IUTestLog { public: enum Level { LOG_INFO , LOG_WARNING , LOG_ERROR , LOG_FATAL , LOG_LEVEL_NUM }; public: IUTestLog(Level level, const char* file, int line); ~IUTestLog(); public: iu_stringstream& GetStream() { return m_stream; } public: static int GetCount(Level level) { return GetCountTable().count[level]; } static bool HasWarning() { return GetCount(LOG_WARNING) > 0; } static bool HasError() { return GetCount(LOG_ERROR) > 0 || GetCount(LOG_FATAL) > 0; } private: struct Count { int count[LOG_LEVEL_NUM]; }; static Count& GetCountTable() { static Count count = { {0} }; return count; } static void CountUp(int level); private: const Level kLevel; iu_stringstream m_stream; IUTEST_PP_DISALLOW_COPY_AND_ASSIGN(IUTestLog); }; #if IUTEST_HAS_STREAM_BUFFER /** * @brief stream buffer */ template<int SIZE=BUFSIZ> class IUStreamBuffer { public: explicit IUStreamBuffer(FILE* fp) : m_fp(fp) { m_buf[0] = '\0'; fflush(fp); setvbuf(fp, m_buf, _IOFBF, SIZE); } ~IUStreamBuffer() { IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_BEGIN() fflush(m_fp); setbuf(m_fp, NULL); IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_END() } public: ::std::string GetStreamString() { return m_buf; } private: FILE* m_fp; char m_buf[SIZE]; }; /** * @brief stream capture */ #endif } // end of namespace detail } // end of namespace iutest #if !IUTEST_HAS_LIB # include "../impl/iutest_port.ipp" #endif #endif // INCG_IRIS_IUTEST_PORT_HPP_7893F685_A1A9_477A_82E8_BF06237697FF_ <commit_msg>fix cpplint<commit_after>//====================================================================== //----------------------------------------------------------------------- /** * @file iutest_port.hpp * @brief portable * * @author t.shirayanagi * @par copyright * Copyright (C) 2011-2018, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== #ifndef INCG_IRIS_IUTEST_PORT_HPP_7893F685_A1A9_477A_82E8_BF06237697FF_ #define INCG_IRIS_IUTEST_PORT_HPP_7893F685_A1A9_477A_82E8_BF06237697FF_ //====================================================================== // include #if defined(__MWERKS__) # define _MSL_USING_NAMESPACE #endif #include "iutest_internal_defs.hpp" #if defined(IUTEST_OS_LINUX) || defined(IUTEST_OS_CYGWIN) || defined(IUTEST_OS_MAC) # include <unistd.h> # include <locale.h> #endif #if IUTEST_HAS_FILE_STAT # include <sys/stat.h> #endif //====================================================================== // define #if !defined(IUTEST_MAX_PATH) # if defined(MAX_PATH) && MAX_PATH # define IUTEST_MAX_PATH MAX_PATH # elif defined(PATH_MAX) && PATH_MAX # define IUTEST_MAX_PATH PATH_MAX # elif defined(FILENAME_MAX) && FILENAME_MAX # define IUTEST_MAX_PATH FILENAME_MAX # else # define IUTEST_MAX_PATH 1024 # endif #endif /** * @brief ログメッセージストリーム */ #define IUTEST_LOG_(level) \ ::iutest::detail::IUTestLog( \ ::iutest::detail::IUTestLog::LOG_##level, __FILE__, __LINE__).GetStream() /** * @brief 内部エラーチェック */ #define IUTEST_CHECK_(condition) \ IUTEST_AMBIGUOUS_ELSE_BLOCKER_ \ if( !::iutest::detail::IsTrue(condition) ) \ IUTEST_LOG_(FATAL) << "Condition " #condition " failed. " namespace iutest { #ifdef IUTEST_OS_NACL namespace nacl { /** * @brief printf */ void vprint_message(const char *fmt, va_list va); void print_message(const char *fmt, ...); } #endif namespace internal { namespace posix { const char* GetEnv(const char* name); int PutEnv(const char* expr); int SetEnv(const char* name, const char* value, int overwrite); const char* GetCWD(char* buf, size_t length); ::std::string GetCWD(); void SleepMillisec(unsigned int millisec); #if defined(IUTEST_OS_WINDOWS_MOBILE) void Abort(); #else IUTEST_ATTRIBUTE_NORETURN_ void Abort(); inline void Abort() { abort(); } #endif #if IUTEST_HAS_FILENO #if defined(_MSC_VER) inline int Fileno(FILE* fp) { return _fileno(fp); } #else inline int Fileno(FILE* fp) { return fileno(fp); } #endif #else inline int Fileno(FILE*) { return -1; } #endif #if IUTEST_HAS_FILE_STAT #if defined(IUTEST_OS_WINDOWS) && !defined(IUTEST_OS_WINDOWS_WINE) typedef struct _stat StatStruct; inline int FileStat(int fd, StatStruct* buf) { return _fstat(fd, buf); } inline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); } inline bool IsDir(const StatStruct& st) { return (st.st_mode & _S_IFDIR) != 0; } #else typedef struct stat StatStruct; inline int FileStat(int fd, StatStruct* buf) { return fstat(fd, buf); } inline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); } inline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); } #endif inline int Stat(FILE* fp, StatStruct* buf) { int fd = Fileno(fp); return fd >= 0 ? FileStat(fd, buf) : fd; } #endif } // end of namespace posix inline void SleepMilliseconds(int n) { posix::SleepMillisec(static_cast<unsigned int>(n)); } } // end of namespace internal namespace detail { namespace posix = internal::posix; /** * @brief パス区切り文字の取得 */ char GetPathSeparator() IUTEST_CXX_NOEXCEPT_SPEC; /** * @brief パス区切り文字かどうか */ bool IsPathSeparator(char c) IUTEST_CXX_NOEXCEPT_SPEC; /** * @brief パス区切り文字かどうか */ bool IsAltPathSeparator(char c) IUTEST_CXX_NOEXCEPT_SPEC; /** * @brief 一番後ろのパスセパレータのアドレスを取得 */ const char* FindLastPathSeparator(const char* path, size_t length) IUTEST_CXX_NOEXCEPT_SPEC; /** * @brief 環境変数の設定 */ bool SetEnvironmentVariable(const char* name, const char* value); /** * @brief 環境変数の取得 * @param [in] name = 環境変数名 * @param [out] buf = 出力バッファ * @return 成否 */ bool GetEnvironmentVariable(const char* name, char* buf, size_t size); #if !defined(IUTEST_NO_FUNCTION_TEMPLATE_ORDERING) template<size_t SIZE> inline bool GetEnvironmentVariable(const char* name, char (&buf)[SIZE]) { return GetEnvironmentVariable(name, buf, SIZE); } #endif /** * @brief 環境変数の取得 * @param [in] name = 環境変数名 * @param [out] var = 出力文字列 * @return 成否 */ bool IUTEST_ATTRIBUTE_UNUSED_ GetEnvironmentVariable(const char* name, ::std::string& var); /** * @brief 環境変数の取得 * @param [in] name = 環境変数名 * @param [out] var = 出力数値 * @return 成否 */ bool IUTEST_ATTRIBUTE_UNUSED_ GetEnvironmentInt(const char* name, int& var); #if defined(IUTEST_OS_WINDOWS) namespace win { /** * @brief 文字列変換 */ ::std::string IUTEST_ATTRIBUTE_UNUSED_ WideStringToMultiByteString(const wchar_t* wide_c_str); /** * @brief HRESULT のエラー文字列を取得 * @param [in] hr = エラー値 * @return 文字列 */ ::std::string IUTEST_ATTRIBUTE_UNUSED_ GetHResultString(HRESULT hr); } // end of namespace win #endif /** * @brief ログ */ class IUTestLog { public: enum Level { LOG_INFO , LOG_WARNING , LOG_ERROR , LOG_FATAL , LOG_LEVEL_NUM }; public: IUTestLog(Level level, const char* file, int line); ~IUTestLog(); public: iu_stringstream& GetStream() { return m_stream; } public: static int GetCount(Level level) { return GetCountTable().count[level]; } static bool HasWarning() { return GetCount(LOG_WARNING) > 0; } static bool HasError() { return GetCount(LOG_ERROR) > 0 || GetCount(LOG_FATAL) > 0; } private: struct Count { int count[LOG_LEVEL_NUM]; }; static Count& GetCountTable() { static Count count = { {0} }; return count; } static void CountUp(int level); private: const Level kLevel; iu_stringstream m_stream; IUTEST_PP_DISALLOW_COPY_AND_ASSIGN(IUTestLog); }; #if IUTEST_HAS_STREAM_BUFFER /** * @brief stream buffer */ template<int SIZE=BUFSIZ> class IUStreamBuffer { public: explicit IUStreamBuffer(FILE* fp) : m_fp(fp) { m_buf[0] = '\0'; fflush(fp); setvbuf(fp, m_buf, _IOFBF, SIZE); } ~IUStreamBuffer() { IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_BEGIN() fflush(m_fp); setbuf(m_fp, NULL); IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_END() } public: ::std::string GetStreamString() { return m_buf; } private: FILE* m_fp; char m_buf[SIZE]; }; /** * @brief stream capture */ #endif } // end of namespace detail } // end of namespace iutest #if !IUTEST_HAS_LIB # include "../impl/iutest_port.ipp" #endif #endif // INCG_IRIS_IUTEST_PORT_HPP_7893F685_A1A9_477A_82E8_BF06237697FF_ <|endoftext|>
<commit_before>#include "ClientSocket.hh" #include "Server.hh" #include <signal.h> #include <fstream> #include <random> #include <string> #include <vector> #include <iostream> Server server; void handleExitSignal( int /* signal */ ) { server.close(); } int main( int argc, char** argv ) { signal( SIGINT, handleExitSignal ); server.setPort( 1031 ); server.onAccept( [&] ( std::weak_ptr<ClientSocket> /* socket */ ) { } ); server.onRead( [&] ( std::weak_ptr<ClientSocket> socket ) { if( auto s = socket.lock() ) { auto data = s->read(); s->write( data ); } } ); server.listen(); return 0; } <commit_msg>Fixed unused parameter warnings for echo service<commit_after>#include "ClientSocket.hh" #include "Server.hh" #include <signal.h> #include <fstream> #include <random> #include <string> #include <vector> #include <iostream> Server server; void handleExitSignal( int /* signal */ ) { server.close(); } int main( int /* argc */, char** /* argv */ ) { signal( SIGINT, handleExitSignal ); server.setPort( 1031 ); server.onAccept( [&] ( std::weak_ptr<ClientSocket> /* socket */ ) { } ); server.onRead( [&] ( std::weak_ptr<ClientSocket> socket ) { if( auto s = socket.lock() ) { auto data = s->read(); s->write( data ); } } ); server.listen(); return 0; } <|endoftext|>
<commit_before>#define THEWIZARDPLUSPLUS_WIZARD_PARSER_PARSER_MACROSES #include "vendor/better-enums/enum_strict.hpp" #include "vendor/range/v3/view/drop.hpp" #include "vendor/range/v3/view/transform.hpp" #include "vendor/fmt/format.hpp" #include "vendor/range/v3/view/chunk.hpp" #include "vendor/range/v3/to_container.hpp" #include "vendor/range/v3/numeric/accumulate.hpp" #include "vendor/docopt/docopt.hpp" #include "vendor/range/v3/algorithm/find_if.hpp" #include <thewizardplusplus/wizard_parser/exceptions/unexpected_entity_exception.hpp> #include <thewizardplusplus/wizard_parser/lexer/lexeme.hpp> #include <thewizardplusplus/wizard_parser/lexer/tokenize.hpp> #include <thewizardplusplus/wizard_parser/parser/rule_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/dummy_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/typing_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/match_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/concatenation_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/lookahead_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/repetition_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/alternation_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/ast_node.hpp> #include <thewizardplusplus/wizard_parser/exceptions/positional_exception.hpp> #include <thewizardplusplus/wizard_parser/parser/parse.hpp> #include <thewizardplusplus/wizard_parser/utilities/utilities.hpp> #include <unordered_map> #include <string> #include <cstddef> #include <functional> #include <vector> #include <cstdint> #include <regex> #include <cstdlib> #include <iostream> #include <stdexcept> #include <string_view> #include <iterator> #include <sstream> #include <limits> #include <iomanip> #include <exception> using namespace thewizardplusplus::wizard_parser; using namespace thewizardplusplus::wizard_parser::parser::operators; using namespace std::literals::string_literals; using constant_group = std::unordered_map<std::string, double>; struct function final { const std::size_t arity; const std::function<double(const std::vector<double>&)> handler; }; using function_group = std::unordered_map<std::string, function>; BETTER_ENUM(entity_type, std::uint8_t, node = exceptions::entity_type::_size(), constant, function ) template<entity_type::_integral type> using unexpected_entity_exception = exceptions::base_unexpected_entity_exception<entity_type, type>; const auto usage = R"(Usage: ./example [options] [--] [<expression>] Options: -h, --help - show this message; -t TARGET, --target TARGET - preliminary target of processing (allowed: tokens, cst); -p PRECISION, --precision PRECISION - precision of a result; -s, --stdin - read an expression from stdin; -V, --verbose - mark an error.)"; const auto lexemes = lexer::lexeme_group{ {std::regex{R"(\+)"}, "plus"}, {std::regex{"-"}, "minus"}, {std::regex{R"(\*)"}, "star"}, {std::regex{"/"}, "slash"}, {std::regex{"%"}, "percent"}, {std::regex{R"(\()"}, "opening_parenthesis"}, {std::regex{R"(\))"}, "closing_parenthesis"}, {std::regex{","}, "comma"}, {std::regex{R"(\d+(?:\.\d+)?(?:e-?\d+)?)"}, "number"}, {std::regex{R"([A-Za-z_]\w*)"}, "identifier"}, {std::regex{R"(\s+)"}, "whitespace"} }; const auto lexemes_exceptions = lexer::exception_group{"whitespace"}; // Boost 1.70.0, Math Toolkit 2.9.0 const auto constants = constant_group{ {"pi", 3.141592653589793238462643383279502884}, {"e", 2.718281828459045235360287471352662497} }; const auto functions = function_group{ {"+", {2, [] (const auto& arguments) { return arguments.front() + arguments.back(); }}}, {"-", {2, [] (const auto& arguments) { return arguments.front() - arguments.back(); }}}, {"*", {2, [] (const auto& arguments) { return arguments.front() * arguments.back(); }}}, {"/", {2, [] (const auto& arguments) { return arguments.front() / arguments.back(); }}}, {"%", {2, [] (const auto& arguments) { return static_cast<std::int64_t>(arguments.front()) % static_cast<std::int64_t>(arguments.back()); }}}, {"floor", {1, [] (const auto& arguments) { return std::floor(arguments.front()); }}}, {"ceil", {1, [] (const auto& arguments) { return std::ceil(arguments.front()); }}}, {"trunc", {1, [] (const auto& arguments) { return std::trunc(arguments.front()); }}}, {"round", {1, [] (const auto& arguments) { return std::round(arguments.front()); }}}, {"sin", {1, [] (const auto& arguments) { return std::sin(arguments.front()); }}}, {"cos", {1, [] (const auto& arguments) { return std::cos(arguments.front()); }}}, {"tn", {1, [] (const auto& arguments) { return std::tan(arguments.front()); }}}, {"arcsin", {1, [] (const auto& arguments) { return std::asin(arguments.front()); }}}, {"arccos", {1, [] (const auto& arguments) { return std::acos(arguments.front()); }}}, {"arctn", {1, [] (const auto& arguments) { return std::atan(arguments.front()); }}}, {"angle", {2, [] (const auto& arguments) { return std::atan2(arguments.back(), arguments.front()); }}}, {"pow", {2, [] (const auto& arguments) { return std::pow(arguments.front(), arguments.back()); }}}, {"sqrt", {1, [] (const auto& arguments) { return std::sqrt(arguments.front()); }}}, {"exp", {1, [] (const auto& arguments) { return std::exp(arguments.front()); }}}, {"ln", {1, [] (const auto& arguments) { return std::log(arguments.front()); }}}, {"lg", {1, [] (const auto& arguments) { return std::log10(arguments.front()); }}}, {"abs", {1, [] (const auto& arguments) { return std::abs(arguments.front()); }}}, }; template<typename streamable> void exit(const int& code, const streamable& message) { (code == EXIT_SUCCESS ? std::cout : std::cerr) << message << '\n'; std::exit(code); } parser::rule_parser::pointer make_parser() { const auto expression_dummy = parser::dummy(); RULE(function_call) = "identifier"_t >> &"("_v >> -(expression_dummy >> *(&","_v >> expression_dummy)) >> &")"_v; RULE(atom) = "number"_t | function_call | "identifier"_t | (&"("_v >> expression_dummy >> &")"_v); RULE(unary) = *("-"_v) >> atom; RULE(product) = unary >> *(("*"_v | "/"_v | "%"_v) >> unary); RULE(sum) = product >> *(("+"_v | "-"_v) >> product); expression_dummy->set_parser(sum); return sum; } double evaluate_ast_node( const parser::ast_node& ast, const constant_group& constants, const function_group& functions ) { const auto inspect_sequence = [] (const auto& ast) -> const auto& { return ast.children[0].children; }; const auto evaluate_with_context = [&] (const auto& ast) { return evaluate_ast_node(ast, constants, functions); }; if (ast.type == "number") { return std::stod(ast.value, nullptr); } else if (ast.type == "identifier") { try { return constants.at(ast.value); } catch (const std::out_of_range& exception) { const auto offset = parser::get_offset(ast); throw unexpected_entity_exception<entity_type::constant>{offset}; } } else if (ast.type == "atom") { const auto type = (+parser::ast_node_type::sequence)._to_string(); const auto first_child = ast.children[0].type == type ? inspect_sequence(ast)[0] : ast.children[0]; return evaluate_with_context(first_child); } else if (ast.type == "unary") { const auto result = evaluate_with_context(inspect_sequence(ast).back()); const auto sign = (inspect_sequence(ast).size() - 1) % 2 ? -1 : 1; return sign * result; } else if (ast.type == "function_call") { try { const auto name = inspect_sequence(ast)[0].value; const auto arguments = inspect_sequence(ast) | ranges::view::drop(1) | ranges::view::transform([&] (const auto& ast) { return evaluate_with_context(ast); }); const auto function = functions.at(name); if (arguments.size() != function.arity) { const auto unit = function.arity == 1 ? "argument" : "arguments"; const auto description = fmt::format("function requires {:d} {:s}", function.arity, unit); const auto offset = parser::get_offset(ast); throw exceptions::positional_exception{description, offset}; } return function.handler(arguments); } catch (const std::out_of_range& exception) { const auto offset = parser::get_offset(ast); throw unexpected_entity_exception<entity_type::function>{offset}; } } else if (ast.type == "product" || ast.type == "sum") { const auto first_operand = evaluate_with_context(inspect_sequence(ast)[0]); const auto children_chunks = inspect_sequence(ast) | ranges::view::drop(1) | ranges::view::chunk(2) | ranges::view::transform([] (const auto& chunk) { return chunk | ranges::to_<parser::ast_node_group>(); }); return ranges::accumulate( children_chunks, first_operand, [&] (const auto& result, const auto& chunk) { const auto name = chunk[0].value; const auto second_operand = evaluate_with_context(chunk[1]); return functions.at(name).handler({result, second_operand}); } ); } else { const auto offset = parser::get_offset(ast); throw unexpected_entity_exception<entity_type::node>{offset}; } } std::runtime_error enrich_exception( const exceptions::positional_exception& exception, const std::string_view& code, const std::size_t& mark_length ) { const auto mark_offset = std::string(exception.offset, ' '); const auto mark = std::string(mark_length, '^'); return std::runtime_error{fmt::format( "{:s}\n| \"{:s}\"\n| {:s}{:s}", exception.what(), code, mark_offset, mark )}; } int main(int argc, char* argv[]) try { const auto options = docopt::docopt(usage, {argv+1, argv+argc}, true); const auto expression = options.at("<expression>") ? options.at("<expression>").asString() : ""; const auto code = options.at("--stdin").asBool() ? std::string{std::istreambuf_iterator<char>{std::cin}, {}} : expression; const auto enrich = options.at("--verbose").asBool() ? std::function{enrich_exception} : [] ( const exceptions::positional_exception& exception, const std::string_view& code, const std::size_t& mark_length ) { return exception; }; try { auto tokens = lexer::tokenize_all(lexemes, lexemes_exceptions, code); if (options.at("--target") == "tokens"s) { exit(EXIT_SUCCESS, tokens); } const auto eoi = exceptions::entity_type::eoi; try { const auto ast = parser::parse_all(make_parser(), tokens); if (options.at("--target") == "cst"s) { exit(EXIT_SUCCESS, ast); } auto buffer = std::ostringstream{}; const auto precision = options.at("--precision") ? options.at("--precision").asLong() : std::numeric_limits<double>::max_digits10; const auto result = evaluate_ast_node(ast, constants, functions); buffer << std::setprecision(precision) << result; exit(EXIT_SUCCESS, buffer.str()); } catch (const exceptions::unexpected_entity_exception<eoi>& exception) { const auto offset = exception.offset == utilities::integral_infinity ? code.size() : exception.offset; throw exceptions::unexpected_entity_exception<eoi>{offset}; } catch (const exceptions::positional_exception& exception) { const auto token = ranges::find_if(tokens, [&] (const auto& token) { return token.offset == exception.offset; }); throw enrich(exception, code, token->value.size()); } } catch (const exceptions::positional_exception& exception) { throw enrich(exception, code, 1); } } catch (const std::exception& exception) { exit(EXIT_FAILURE, fmt::format("error: {:s}", exception.what())); } <commit_msg>Refactor of the example, built-in functions: fix a code style<commit_after>#define THEWIZARDPLUSPLUS_WIZARD_PARSER_PARSER_MACROSES #include "vendor/better-enums/enum_strict.hpp" #include "vendor/range/v3/view/drop.hpp" #include "vendor/range/v3/view/transform.hpp" #include "vendor/fmt/format.hpp" #include "vendor/range/v3/view/chunk.hpp" #include "vendor/range/v3/to_container.hpp" #include "vendor/range/v3/numeric/accumulate.hpp" #include "vendor/docopt/docopt.hpp" #include "vendor/range/v3/algorithm/find_if.hpp" #include <thewizardplusplus/wizard_parser/exceptions/unexpected_entity_exception.hpp> #include <thewizardplusplus/wizard_parser/lexer/lexeme.hpp> #include <thewizardplusplus/wizard_parser/lexer/tokenize.hpp> #include <thewizardplusplus/wizard_parser/parser/rule_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/dummy_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/typing_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/match_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/concatenation_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/lookahead_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/repetition_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/alternation_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/ast_node.hpp> #include <thewizardplusplus/wizard_parser/exceptions/positional_exception.hpp> #include <thewizardplusplus/wizard_parser/parser/parse.hpp> #include <thewizardplusplus/wizard_parser/utilities/utilities.hpp> #include <unordered_map> #include <string> #include <cstddef> #include <functional> #include <vector> #include <cstdint> #include <regex> #include <cstdlib> #include <iostream> #include <stdexcept> #include <string_view> #include <iterator> #include <sstream> #include <limits> #include <iomanip> #include <exception> using namespace thewizardplusplus::wizard_parser; using namespace thewizardplusplus::wizard_parser::parser::operators; using namespace std::literals::string_literals; using constant_group = std::unordered_map<std::string, double>; struct function final { const std::size_t arity; const std::function<double(const std::vector<double>&)> handler; }; using function_group = std::unordered_map<std::string, function>; BETTER_ENUM(entity_type, std::uint8_t, node = exceptions::entity_type::_size(), constant, function ) template<entity_type::_integral type> using unexpected_entity_exception = exceptions::base_unexpected_entity_exception<entity_type, type>; const auto usage = R"(Usage: ./example [options] [--] [<expression>] Options: -h, --help - show this message; -t TARGET, --target TARGET - preliminary target of processing (allowed: tokens, cst); -p PRECISION, --precision PRECISION - precision of a result; -s, --stdin - read an expression from stdin; -V, --verbose - mark an error.)"; const auto lexemes = lexer::lexeme_group{ {std::regex{R"(\+)"}, "plus"}, {std::regex{"-"}, "minus"}, {std::regex{R"(\*)"}, "star"}, {std::regex{"/"}, "slash"}, {std::regex{"%"}, "percent"}, {std::regex{R"(\()"}, "opening_parenthesis"}, {std::regex{R"(\))"}, "closing_parenthesis"}, {std::regex{","}, "comma"}, {std::regex{R"(\d+(?:\.\d+)?(?:e-?\d+)?)"}, "number"}, {std::regex{R"([A-Za-z_]\w*)"}, "identifier"}, {std::regex{R"(\s+)"}, "whitespace"} }; const auto lexemes_exceptions = lexer::exception_group{"whitespace"}; // Boost 1.70.0, Math Toolkit 2.9.0 const auto constants = constant_group{ {"pi", 3.141592653589793238462643383279502884}, {"e", 2.718281828459045235360287471352662497} }; const auto functions = function_group{ {"+", {2, [] (const auto& args) { return args[0] + args[1]; }}}, {"-", {2, [] (const auto& args) { return args[0] - args[1]; }}}, {"*", {2, [] (const auto& args) { return args[0] * args[1]; }}}, {"/", {2, [] (const auto& args) { return args[0] / args[1]; }}}, {"%", {2, [] (const auto& arguments) { return static_cast<std::int64_t>(arguments.front()) % static_cast<std::int64_t>(arguments.back()); }}}, {"floor", {1, [] (const auto& args) { return std::floor(args[0]); }}}, {"ceil", {1, [] (const auto& args) { return std::ceil(args[0]); }}}, {"trunc", {1, [] (const auto& args) { return std::trunc(args[0]); }}}, {"round", {1, [] (const auto& args) { return std::round(args[0]); }}}, {"sin", {1, [] (const auto& args) { return std::sin(args[0]); }}}, {"cos", {1, [] (const auto& args) { return std::cos(args[0]); }}}, {"tn", {1, [] (const auto& args) { return std::tan(args[0]); }}}, {"arcsin", {1, [] (const auto& args) { return std::asin(args[0]); }}}, {"arccos", {1, [] (const auto& args) { return std::acos(args[0]); }}}, {"arctn", {1, [] (const auto& args) { return std::atan(args[0]); }}}, {"angle", {2, [] (const auto& args) { return std::atan2(args[1], args[0]); }}}, {"pow", {2, [] (const auto& args) { return std::pow(args[0], args[1]); }}}, {"sqrt", {1, [] (const auto& args) { return std::sqrt(args[0]); }}}, {"exp", {1, [] (const auto& args) { return std::exp(args[0]); }}}, {"ln", {1, [] (const auto& args) { return std::log(args[0]); }}}, {"lg", {1, [] (const auto& args) { return std::log10(args[0]); }}}, {"abs", {1, [] (const auto& args) { return std::abs(args[0]); }}}, }; template<typename streamable> void exit(const int& code, const streamable& message) { (code == EXIT_SUCCESS ? std::cout : std::cerr) << message << '\n'; std::exit(code); } parser::rule_parser::pointer make_parser() { const auto expression_dummy = parser::dummy(); RULE(function_call) = "identifier"_t >> &"("_v >> -(expression_dummy >> *(&","_v >> expression_dummy)) >> &")"_v; RULE(atom) = "number"_t | function_call | "identifier"_t | (&"("_v >> expression_dummy >> &")"_v); RULE(unary) = *("-"_v) >> atom; RULE(product) = unary >> *(("*"_v | "/"_v | "%"_v) >> unary); RULE(sum) = product >> *(("+"_v | "-"_v) >> product); expression_dummy->set_parser(sum); return sum; } double evaluate_ast_node( const parser::ast_node& ast, const constant_group& constants, const function_group& functions ) { const auto inspect_sequence = [] (const auto& ast) -> const auto& { return ast.children[0].children; }; const auto evaluate_with_context = [&] (const auto& ast) { return evaluate_ast_node(ast, constants, functions); }; if (ast.type == "number") { return std::stod(ast.value, nullptr); } else if (ast.type == "identifier") { try { return constants.at(ast.value); } catch (const std::out_of_range& exception) { const auto offset = parser::get_offset(ast); throw unexpected_entity_exception<entity_type::constant>{offset}; } } else if (ast.type == "atom") { const auto type = (+parser::ast_node_type::sequence)._to_string(); const auto first_child = ast.children[0].type == type ? inspect_sequence(ast)[0] : ast.children[0]; return evaluate_with_context(first_child); } else if (ast.type == "unary") { const auto result = evaluate_with_context(inspect_sequence(ast).back()); const auto sign = (inspect_sequence(ast).size() - 1) % 2 ? -1 : 1; return sign * result; } else if (ast.type == "function_call") { try { const auto name = inspect_sequence(ast)[0].value; const auto arguments = inspect_sequence(ast) | ranges::view::drop(1) | ranges::view::transform([&] (const auto& ast) { return evaluate_with_context(ast); }); const auto function = functions.at(name); if (arguments.size() != function.arity) { const auto unit = function.arity == 1 ? "argument" : "arguments"; const auto description = fmt::format("function requires {:d} {:s}", function.arity, unit); const auto offset = parser::get_offset(ast); throw exceptions::positional_exception{description, offset}; } return function.handler(arguments); } catch (const std::out_of_range& exception) { const auto offset = parser::get_offset(ast); throw unexpected_entity_exception<entity_type::function>{offset}; } } else if (ast.type == "product" || ast.type == "sum") { const auto first_operand = evaluate_with_context(inspect_sequence(ast)[0]); const auto children_chunks = inspect_sequence(ast) | ranges::view::drop(1) | ranges::view::chunk(2) | ranges::view::transform([] (const auto& chunk) { return chunk | ranges::to_<parser::ast_node_group>(); }); return ranges::accumulate( children_chunks, first_operand, [&] (const auto& result, const auto& chunk) { const auto name = chunk[0].value; const auto second_operand = evaluate_with_context(chunk[1]); return functions.at(name).handler({result, second_operand}); } ); } else { const auto offset = parser::get_offset(ast); throw unexpected_entity_exception<entity_type::node>{offset}; } } std::runtime_error enrich_exception( const exceptions::positional_exception& exception, const std::string_view& code, const std::size_t& mark_length ) { const auto mark_offset = std::string(exception.offset, ' '); const auto mark = std::string(mark_length, '^'); return std::runtime_error{fmt::format( "{:s}\n| \"{:s}\"\n| {:s}{:s}", exception.what(), code, mark_offset, mark )}; } int main(int argc, char* argv[]) try { const auto options = docopt::docopt(usage, {argv+1, argv+argc}, true); const auto expression = options.at("<expression>") ? options.at("<expression>").asString() : ""; const auto code = options.at("--stdin").asBool() ? std::string{std::istreambuf_iterator<char>{std::cin}, {}} : expression; const auto enrich = options.at("--verbose").asBool() ? std::function{enrich_exception} : [] ( const exceptions::positional_exception& exception, const std::string_view& code, const std::size_t& mark_length ) { return exception; }; try { auto tokens = lexer::tokenize_all(lexemes, lexemes_exceptions, code); if (options.at("--target") == "tokens"s) { exit(EXIT_SUCCESS, tokens); } const auto eoi = exceptions::entity_type::eoi; try { const auto ast = parser::parse_all(make_parser(), tokens); if (options.at("--target") == "cst"s) { exit(EXIT_SUCCESS, ast); } auto buffer = std::ostringstream{}; const auto precision = options.at("--precision") ? options.at("--precision").asLong() : std::numeric_limits<double>::max_digits10; const auto result = evaluate_ast_node(ast, constants, functions); buffer << std::setprecision(precision) << result; exit(EXIT_SUCCESS, buffer.str()); } catch (const exceptions::unexpected_entity_exception<eoi>& exception) { const auto offset = exception.offset == utilities::integral_infinity ? code.size() : exception.offset; throw exceptions::unexpected_entity_exception<eoi>{offset}; } catch (const exceptions::positional_exception& exception) { const auto token = ranges::find_if(tokens, [&] (const auto& token) { return token.offset == exception.offset; }); throw enrich(exception, code, token->value.size()); } } catch (const exceptions::positional_exception& exception) { throw enrich(exception, code, 1); } } catch (const std::exception& exception) { exit(EXIT_FAILURE, fmt::format("error: {:s}", exception.what())); } <|endoftext|>
<commit_before>#define THEWIZARDPLUSPLUS_WIZARD_PARSER_PARSER_MACROSES #include "vendor/better-enums/enum_strict.hpp" #include "vendor/range/v3/view/drop.hpp" #include "vendor/range/v3/view/transform.hpp" #include "vendor/fmt/format.hpp" #include "vendor/range/v3/view/chunk.hpp" #include "vendor/range/v3/to_container.hpp" #include "vendor/range/v3/numeric/accumulate.hpp" #include "vendor/docopt/docopt.hpp" #include "vendor/range/v3/algorithm/find_if.hpp" #include <thewizardplusplus/wizard_parser/exceptions/unexpected_entity_exception.hpp> #include <thewizardplusplus/wizard_parser/lexer/lexeme.hpp> #include <thewizardplusplus/wizard_parser/lexer/tokenize.hpp> #include <thewizardplusplus/wizard_parser/parser/rule_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/dummy_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/typing_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/match_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/concatenation_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/lookahead_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/repetition_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/alternation_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/ast_node.hpp> #include <thewizardplusplus/wizard_parser/exceptions/positional_exception.hpp> #include <thewizardplusplus/wizard_parser/parser/parse.hpp> #include <thewizardplusplus/wizard_parser/utilities/utilities.hpp> #include <unordered_map> #include <string> #include <cstddef> #include <functional> #include <vector> #include <cstdint> #include <regex> #include <cstdlib> #include <iostream> #include <stdexcept> #include <string_view> #include <iterator> #include <sstream> #include <limits> #include <iomanip> #include <exception> using namespace thewizardplusplus::wizard_parser; using namespace thewizardplusplus::wizard_parser::parser::operators; using namespace std::literals::string_literals; using constant_group = std::unordered_map<std::string, double>; struct function final { const std::size_t arity; const std::function<double(const std::vector<double>&)> handler; }; using function_group = std::unordered_map<std::string, function>; BETTER_ENUM(entity_type, std::uint8_t, node = exceptions::entity_type::_size(), constant, function ) template<entity_type::_integral type> using unexpected_entity_exception = exceptions::base_unexpected_entity_exception<entity_type, type>; const auto usage = R"(Usage: ./example [options] [--] [<expression>] Options: -h, --help - show this message; -t TARGET, --target TARGET - preliminary target of processing (allowed: tokens, cst); -p PRECISION, --precision PRECISION - precision of a result; -s, --stdin - read an expression from stdin; -V, --verbose - mark an error.)"; const auto lexemes = lexer::lexeme_group{ {std::regex{R"(\+)"}, "plus"}, {std::regex{"-"}, "minus"}, {std::regex{R"(\*)"}, "star"}, {std::regex{"/"}, "slash"}, {std::regex{"%"}, "percent"}, {std::regex{R"(\()"}, "opening_parenthesis"}, {std::regex{R"(\))"}, "closing_parenthesis"}, {std::regex{","}, "comma"}, {std::regex{R"(\d+(?:\.\d+)?(?:e-?\d+)?)"}, "number"}, {std::regex{R"([A-Za-z_]\w*)"}, "identifier"}, {std::regex{R"(\s+)"}, "whitespace"} }; const auto lexemes_exceptions = lexer::exception_group{"whitespace"}; // Boost 1.70.0, Math Toolkit 2.9.0 const auto constants = constant_group{ {"pi", 3.141592653589793238462643383279502884}, {"e", 2.718281828459045235360287471352662497} }; const auto functions = function_group{ {"+", {2, [] (const auto& args) { return args[0] + args[1]; }}}, {"-", {2, [] (const auto& args) { return args[0] - args[1]; }}}, {"*", {2, [] (const auto& args) { return args[0] * args[1]; }}}, {"/", {2, [] (const auto& args) { return args[0] / args[1]; }}}, {"%", {2, [] (const auto& args) { return std::fmod(args[0], args[1]); }}}, {"floor", {1, [] (const auto& args) { return std::floor(args[0]); }}}, {"ceil", {1, [] (const auto& args) { return std::ceil(args[0]); }}}, {"trunc", {1, [] (const auto& args) { return std::trunc(args[0]); }}}, {"round", {1, [] (const auto& args) { return std::round(args[0]); }}}, {"sin", {1, [] (const auto& args) { return std::sin(args[0]); }}}, {"cos", {1, [] (const auto& args) { return std::cos(args[0]); }}}, {"tn", {1, [] (const auto& args) { return std::tan(args[0]); }}}, {"arcsin", {1, [] (const auto& args) { return std::asin(args[0]); }}}, {"arccos", {1, [] (const auto& args) { return std::acos(args[0]); }}}, {"arctn", {1, [] (const auto& args) { return std::atan(args[0]); }}}, {"angle", {2, [] (const auto& args) { return std::atan2(args[1], args[0]); }}}, {"pow", {2, [] (const auto& args) { return std::pow(args[0], args[1]); }}}, {"sqrt", {1, [] (const auto& args) { return std::sqrt(args[0]); }}}, {"exp", {1, [] (const auto& args) { return std::exp(args[0]); }}}, {"ln", {1, [] (const auto& args) { return std::log(args[0]); }}}, {"lg", {1, [] (const auto& args) { return std::log10(args[0]); }}}, {"abs", {1, [] (const auto& args) { return std::abs(args[0]); }}}, }; template<typename streamable> void exit(const int& code, const streamable& message) { (code == EXIT_SUCCESS ? std::cout : std::cerr) << message << '\n'; std::exit(code); } parser::rule_parser::pointer make_parser() { const auto expression_dummy = parser::dummy(); RULE(function_call) = "identifier"_t >> &"("_v >> -(expression_dummy >> *(&","_v >> expression_dummy)) >> &")"_v; RULE(atom) = "number"_t | function_call | "identifier"_t | (&"("_v >> expression_dummy >> &")"_v); RULE(unary) = *("-"_v) >> atom; RULE(product) = unary >> *(("*"_v | "/"_v | "%"_v) >> unary); RULE(sum) = product >> *(("+"_v | "-"_v) >> product); expression_dummy->set_parser(sum); return sum; } double evaluate_ast_node( const parser::ast_node& ast, const constant_group& constants, const function_group& functions ) { const auto inspect_sequence = [] (const auto& ast) -> const auto& { return ast.children[0].children; }; const auto evaluate_with_context = [&] (const auto& ast) { return evaluate_ast_node(ast, constants, functions); }; if (ast.type == "number") { return std::stod(ast.value, nullptr); } else if (ast.type == "identifier") { try { return constants.at(ast.value); } catch (const std::out_of_range& exception) { const auto offset = parser::get_offset(ast); throw unexpected_entity_exception<entity_type::constant>{offset}; } } else if (ast.type == "atom") { const auto type = (+parser::ast_node_type::sequence)._to_string(); const auto first_child = ast.children[0].type == type ? inspect_sequence(ast)[0] : ast.children[0]; return evaluate_with_context(first_child); } else if (ast.type == "unary") { const auto result = evaluate_with_context(inspect_sequence(ast).back()); const auto sign = (inspect_sequence(ast).size() - 1) % 2 ? -1 : 1; return sign * result; } else if (ast.type == "function_call") { try { const auto name = inspect_sequence(ast)[0].value; const auto arguments = inspect_sequence(ast) | ranges::view::drop(1) | ranges::view::transform([&] (const auto& ast) { return evaluate_with_context(ast); }); const auto function = functions.at(name); if (arguments.size() != function.arity) { const auto unit = function.arity == 1 ? "argument" : "arguments"; const auto description = fmt::format("function requires {:d} {:s}", function.arity, unit); const auto offset = parser::get_offset(ast); throw exceptions::positional_exception{description, offset}; } return function.handler(arguments); } catch (const std::out_of_range& exception) { const auto offset = parser::get_offset(ast); throw unexpected_entity_exception<entity_type::function>{offset}; } } else if (ast.type == "product" || ast.type == "sum") { const auto first_operand = evaluate_with_context(inspect_sequence(ast)[0]); const auto children_chunks = inspect_sequence(ast) | ranges::view::drop(1) | ranges::view::chunk(2) | ranges::view::transform([] (const auto& chunk) { return chunk | ranges::to_<parser::ast_node_group>(); }); return ranges::accumulate( children_chunks, first_operand, [&] (const auto& result, const auto& chunk) { const auto name = chunk[0].value; const auto second_operand = evaluate_with_context(chunk[1]); return functions.at(name).handler({result, second_operand}); } ); } else { const auto offset = parser::get_offset(ast); throw unexpected_entity_exception<entity_type::node>{offset}; } } std::runtime_error enrich_exception( const exceptions::positional_exception& exception, const std::string_view& code, const std::size_t& mark_length ) { const auto mark_offset = std::string(exception.offset, ' '); const auto mark = std::string(mark_length, '^'); return std::runtime_error{fmt::format( "{:s}\n| \"{:s}\"\n| {:s}{:s}", exception.what(), code, mark_offset, mark )}; } int main(int argc, char* argv[]) try { const auto options = docopt::docopt(usage, {argv+1, argv+argc}, true); const auto expression = options.at("<expression>") ? options.at("<expression>").asString() : ""; const auto code = options.at("--stdin").asBool() ? std::string{std::istreambuf_iterator<char>{std::cin}, {}} : expression; const auto enrich = options.at("--verbose").asBool() ? std::function{enrich_exception} : [] ( const exceptions::positional_exception& exception, const std::string_view& code, const std::size_t& mark_length ) { return exception; }; try { auto tokens = lexer::tokenize_all(lexemes, lexemes_exceptions, code); if (options.at("--target") == "tokens"s) { exit(EXIT_SUCCESS, tokens); } const auto eoi = exceptions::entity_type::eoi; try { const auto ast = parser::parse_all(make_parser(), tokens); if (options.at("--target") == "cst"s) { exit(EXIT_SUCCESS, ast); } auto buffer = std::ostringstream{}; const auto precision = options.at("--precision") ? options.at("--precision").asLong() : std::numeric_limits<double>::max_digits10; const auto result = evaluate_ast_node(ast, constants, functions); buffer << std::setprecision(precision) << result; exit(EXIT_SUCCESS, buffer.str()); } catch (const exceptions::unexpected_entity_exception<eoi>& exception) { const auto offset = exception.offset == utilities::integral_infinity ? code.size() : exception.offset; throw exceptions::unexpected_entity_exception<eoi>{offset}; } catch (const exceptions::positional_exception& exception) { const auto token = ranges::find_if(tokens, [&] (const auto& token) { return token.offset == exception.offset; }); throw enrich(exception, code, token->value.size()); } } catch (const exceptions::positional_exception& exception) { throw enrich(exception, code, 1); } } catch (const std::exception& exception) { exit(EXIT_FAILURE, fmt::format("error: {:s}", exception.what())); } <commit_msg>Refactor of the example, built-in constants: fix the explanatory comment<commit_after>#define THEWIZARDPLUSPLUS_WIZARD_PARSER_PARSER_MACROSES #include "vendor/better-enums/enum_strict.hpp" #include "vendor/range/v3/view/drop.hpp" #include "vendor/range/v3/view/transform.hpp" #include "vendor/fmt/format.hpp" #include "vendor/range/v3/view/chunk.hpp" #include "vendor/range/v3/to_container.hpp" #include "vendor/range/v3/numeric/accumulate.hpp" #include "vendor/docopt/docopt.hpp" #include "vendor/range/v3/algorithm/find_if.hpp" #include <thewizardplusplus/wizard_parser/exceptions/unexpected_entity_exception.hpp> #include <thewizardplusplus/wizard_parser/lexer/lexeme.hpp> #include <thewizardplusplus/wizard_parser/lexer/tokenize.hpp> #include <thewizardplusplus/wizard_parser/parser/rule_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/dummy_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/typing_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/match_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/concatenation_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/lookahead_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/repetition_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/alternation_parser.hpp> #include <thewizardplusplus/wizard_parser/parser/ast_node.hpp> #include <thewizardplusplus/wizard_parser/exceptions/positional_exception.hpp> #include <thewizardplusplus/wizard_parser/parser/parse.hpp> #include <thewizardplusplus/wizard_parser/utilities/utilities.hpp> #include <unordered_map> #include <string> #include <cstddef> #include <functional> #include <vector> #include <cstdint> #include <regex> #include <cstdlib> #include <iostream> #include <stdexcept> #include <string_view> #include <iterator> #include <sstream> #include <limits> #include <iomanip> #include <exception> using namespace thewizardplusplus::wizard_parser; using namespace thewizardplusplus::wizard_parser::parser::operators; using namespace std::literals::string_literals; using constant_group = std::unordered_map<std::string, double>; struct function final { const std::size_t arity; const std::function<double(const std::vector<double>&)> handler; }; using function_group = std::unordered_map<std::string, function>; BETTER_ENUM(entity_type, std::uint8_t, node = exceptions::entity_type::_size(), constant, function ) template<entity_type::_integral type> using unexpected_entity_exception = exceptions::base_unexpected_entity_exception<entity_type, type>; const auto usage = R"(Usage: ./example [options] [--] [<expression>] Options: -h, --help - show this message; -t TARGET, --target TARGET - preliminary target of processing (allowed: tokens, cst); -p PRECISION, --precision PRECISION - precision of a result; -s, --stdin - read an expression from stdin; -V, --verbose - mark an error.)"; const auto lexemes = lexer::lexeme_group{ {std::regex{R"(\+)"}, "plus"}, {std::regex{"-"}, "minus"}, {std::regex{R"(\*)"}, "star"}, {std::regex{"/"}, "slash"}, {std::regex{"%"}, "percent"}, {std::regex{R"(\()"}, "opening_parenthesis"}, {std::regex{R"(\))"}, "closing_parenthesis"}, {std::regex{","}, "comma"}, {std::regex{R"(\d+(?:\.\d+)?(?:e-?\d+)?)"}, "number"}, {std::regex{R"([A-Za-z_]\w*)"}, "identifier"}, {std::regex{R"(\s+)"}, "whitespace"} }; const auto lexemes_exceptions = lexer::exception_group{"whitespace"}; // precision is taken from Boost 1.70.0, Math Toolkit 2.9.0 const auto constants = constant_group{ {"pi", 3.141592653589793238462643383279502884}, {"e", 2.718281828459045235360287471352662497} }; const auto functions = function_group{ {"+", {2, [] (const auto& args) { return args[0] + args[1]; }}}, {"-", {2, [] (const auto& args) { return args[0] - args[1]; }}}, {"*", {2, [] (const auto& args) { return args[0] * args[1]; }}}, {"/", {2, [] (const auto& args) { return args[0] / args[1]; }}}, {"%", {2, [] (const auto& args) { return std::fmod(args[0], args[1]); }}}, {"floor", {1, [] (const auto& args) { return std::floor(args[0]); }}}, {"ceil", {1, [] (const auto& args) { return std::ceil(args[0]); }}}, {"trunc", {1, [] (const auto& args) { return std::trunc(args[0]); }}}, {"round", {1, [] (const auto& args) { return std::round(args[0]); }}}, {"sin", {1, [] (const auto& args) { return std::sin(args[0]); }}}, {"cos", {1, [] (const auto& args) { return std::cos(args[0]); }}}, {"tn", {1, [] (const auto& args) { return std::tan(args[0]); }}}, {"arcsin", {1, [] (const auto& args) { return std::asin(args[0]); }}}, {"arccos", {1, [] (const auto& args) { return std::acos(args[0]); }}}, {"arctn", {1, [] (const auto& args) { return std::atan(args[0]); }}}, {"angle", {2, [] (const auto& args) { return std::atan2(args[1], args[0]); }}}, {"pow", {2, [] (const auto& args) { return std::pow(args[0], args[1]); }}}, {"sqrt", {1, [] (const auto& args) { return std::sqrt(args[0]); }}}, {"exp", {1, [] (const auto& args) { return std::exp(args[0]); }}}, {"ln", {1, [] (const auto& args) { return std::log(args[0]); }}}, {"lg", {1, [] (const auto& args) { return std::log10(args[0]); }}}, {"abs", {1, [] (const auto& args) { return std::abs(args[0]); }}}, }; template<typename streamable> void exit(const int& code, const streamable& message) { (code == EXIT_SUCCESS ? std::cout : std::cerr) << message << '\n'; std::exit(code); } parser::rule_parser::pointer make_parser() { const auto expression_dummy = parser::dummy(); RULE(function_call) = "identifier"_t >> &"("_v >> -(expression_dummy >> *(&","_v >> expression_dummy)) >> &")"_v; RULE(atom) = "number"_t | function_call | "identifier"_t | (&"("_v >> expression_dummy >> &")"_v); RULE(unary) = *("-"_v) >> atom; RULE(product) = unary >> *(("*"_v | "/"_v | "%"_v) >> unary); RULE(sum) = product >> *(("+"_v | "-"_v) >> product); expression_dummy->set_parser(sum); return sum; } double evaluate_ast_node( const parser::ast_node& ast, const constant_group& constants, const function_group& functions ) { const auto inspect_sequence = [] (const auto& ast) -> const auto& { return ast.children[0].children; }; const auto evaluate_with_context = [&] (const auto& ast) { return evaluate_ast_node(ast, constants, functions); }; if (ast.type == "number") { return std::stod(ast.value, nullptr); } else if (ast.type == "identifier") { try { return constants.at(ast.value); } catch (const std::out_of_range& exception) { const auto offset = parser::get_offset(ast); throw unexpected_entity_exception<entity_type::constant>{offset}; } } else if (ast.type == "atom") { const auto type = (+parser::ast_node_type::sequence)._to_string(); const auto first_child = ast.children[0].type == type ? inspect_sequence(ast)[0] : ast.children[0]; return evaluate_with_context(first_child); } else if (ast.type == "unary") { const auto result = evaluate_with_context(inspect_sequence(ast).back()); const auto sign = (inspect_sequence(ast).size() - 1) % 2 ? -1 : 1; return sign * result; } else if (ast.type == "function_call") { try { const auto name = inspect_sequence(ast)[0].value; const auto arguments = inspect_sequence(ast) | ranges::view::drop(1) | ranges::view::transform([&] (const auto& ast) { return evaluate_with_context(ast); }); const auto function = functions.at(name); if (arguments.size() != function.arity) { const auto unit = function.arity == 1 ? "argument" : "arguments"; const auto description = fmt::format("function requires {:d} {:s}", function.arity, unit); const auto offset = parser::get_offset(ast); throw exceptions::positional_exception{description, offset}; } return function.handler(arguments); } catch (const std::out_of_range& exception) { const auto offset = parser::get_offset(ast); throw unexpected_entity_exception<entity_type::function>{offset}; } } else if (ast.type == "product" || ast.type == "sum") { const auto first_operand = evaluate_with_context(inspect_sequence(ast)[0]); const auto children_chunks = inspect_sequence(ast) | ranges::view::drop(1) | ranges::view::chunk(2) | ranges::view::transform([] (const auto& chunk) { return chunk | ranges::to_<parser::ast_node_group>(); }); return ranges::accumulate( children_chunks, first_operand, [&] (const auto& result, const auto& chunk) { const auto name = chunk[0].value; const auto second_operand = evaluate_with_context(chunk[1]); return functions.at(name).handler({result, second_operand}); } ); } else { const auto offset = parser::get_offset(ast); throw unexpected_entity_exception<entity_type::node>{offset}; } } std::runtime_error enrich_exception( const exceptions::positional_exception& exception, const std::string_view& code, const std::size_t& mark_length ) { const auto mark_offset = std::string(exception.offset, ' '); const auto mark = std::string(mark_length, '^'); return std::runtime_error{fmt::format( "{:s}\n| \"{:s}\"\n| {:s}{:s}", exception.what(), code, mark_offset, mark )}; } int main(int argc, char* argv[]) try { const auto options = docopt::docopt(usage, {argv+1, argv+argc}, true); const auto expression = options.at("<expression>") ? options.at("<expression>").asString() : ""; const auto code = options.at("--stdin").asBool() ? std::string{std::istreambuf_iterator<char>{std::cin}, {}} : expression; const auto enrich = options.at("--verbose").asBool() ? std::function{enrich_exception} : [] ( const exceptions::positional_exception& exception, const std::string_view& code, const std::size_t& mark_length ) { return exception; }; try { auto tokens = lexer::tokenize_all(lexemes, lexemes_exceptions, code); if (options.at("--target") == "tokens"s) { exit(EXIT_SUCCESS, tokens); } const auto eoi = exceptions::entity_type::eoi; try { const auto ast = parser::parse_all(make_parser(), tokens); if (options.at("--target") == "cst"s) { exit(EXIT_SUCCESS, ast); } auto buffer = std::ostringstream{}; const auto precision = options.at("--precision") ? options.at("--precision").asLong() : std::numeric_limits<double>::max_digits10; const auto result = evaluate_ast_node(ast, constants, functions); buffer << std::setprecision(precision) << result; exit(EXIT_SUCCESS, buffer.str()); } catch (const exceptions::unexpected_entity_exception<eoi>& exception) { const auto offset = exception.offset == utilities::integral_infinity ? code.size() : exception.offset; throw exceptions::unexpected_entity_exception<eoi>{offset}; } catch (const exceptions::positional_exception& exception) { const auto token = ranges::find_if(tokens, [&] (const auto& token) { return token.offset == exception.offset; }); throw enrich(exception, code, token->value.size()); } } catch (const exceptions::positional_exception& exception) { throw enrich(exception, code, 1); } } catch (const std::exception& exception) { exit(EXIT_FAILURE, fmt::format("error: {:s}", exception.what())); } <|endoftext|>
<commit_before>// cinder #include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/gl.h" #include "cinder/Log.h" #include "cinder/qtime/QuickTimeGl.h" using namespace ci; using namespace ci::app; using namespace std; class VidFramesLoader { public: VidFramesLoader(const fs::path& path) : path(path) { try { // load up the movie, set it to loop, and begin playing mMovie = qtime::MovieGl::create(path); auto connection = mMovie->getNewFrameSignal().connect([this](){ auto tex = mMovie->getTexture(); mMovie->stop(); auto fbo = gl::Fbo::create(tex->getWidth(), tex->getHeight()); this->fbos.push_back(fbo); gl::ScopedFramebuffer fbScp( fbo ); gl::draw(tex); mMovie->play(); mMovie->seekToFrame(this->fbos.size()); // this->textures.push_back(newtex); this->bWaitingForFrame = false; CI_LOG_I("loaded tex #"<<this->fbos.size()); }); CI_LOG_I("movie loaded ("<<path<<"), number of frames: " <<mMovie->getNumFrames()); // //mMovie->setLoop(); mMovie->play(); } catch( ci::Exception &exc ) { console() << "Exception caught trying to load the movie from path: " << path << ", what: " << exc.what() << std::endl; mMovie = nullptr; } } void update(){ if(!mMovie || isComplete()) return; auto tex = mMovie->getTexture(); // int frameIndex = getLoadedFramesCount(); // mMovie->stop(); // mMovie->seekToFrame(frameIndex); // mMovie->play(); // CI_LOG_I("waiting for frame #" << frameIndex); // bWaitingForFrame = true; } unsigned int getLoadedFramesCount(){ return fbos.size(); } qtime::MovieGlRef getMovie(){ return this->mMovie; } bool isLoading(){ return !isComplete(); } bool isComplete(){ return mMovie && getLoadedFramesCount() >= mMovie->getNumFrames(); } gl::Texture2dRef getTexture(int idx){ return idx < 0 || idx >= this->fbos.size() ? nullptr : fbos[idx]->getColorTexture(); } gl::FboRef getFbo(int idx){ return idx < 0 || idx >= this->fbos.size() ? nullptr : fbos[idx]; } private: fs::path path; // std::vector<gl::TextureRef> textures; std::vector<gl::FboRef> fbos; qtime::MovieGlRef mMovie = nullptr; bool bWaitingForFrame = false; }; class MainApp : public App { public: MainApp(); void setup() override; void update() override; void draw() override; void keyDown(KeyEvent event) override; void next(); private: ci::Timer timer; std::vector<fs::path> paths; std::shared_ptr<VidFramesLoader> loader = nullptr; std::vector<gl::TextureRef> textures; int vidCursor = 0; }; MainApp::MainApp() { } void MainApp::setup(){ setWindowSize( 1280, 480 ); auto args = getCommandLineArgs(); // CI_LOG_I("args size: " << args.size()); // for(auto arg : args){ // CI_LOG_I("arg: " << arg); // } // fs::path moviePath = getAssetPath(args.size() > 1 ? args[1] : "_bar0.mov"); paths.push_back(getAssetPath("_bar0.mov")); paths.push_back(getAssetPath("_bar1.mov")); paths.push_back(getAssetPath("_bar2.mov")); paths.push_back(getAssetPath("_bar3.mov")); paths.push_back(getAssetPath("_bar4.mov")); paths.push_back(getAssetPath("_bar5.mov")); } void MainApp::update(){ // auto dt = this->timer.getSeconds(); // this->timer.start(); if(loader){ loader->update(); if(loader->isComplete()){ for(int i=0; i<loader->getLoadedFramesCount(); i++) textures.push_back(loader->getTexture(i)); loader = nullptr; } } if(!loader && vidCursor < paths.size()){ loader = std::make_shared<VidFramesLoader>(paths[vidCursor]); vidCursor += 1; } } void MainApp::draw(){ gl::clear(Color(0,0,0)); if(loader && loader->isLoading()){ auto tex = loader->getTexture(loader->getLoadedFramesCount()-1); if(tex){ gl::draw(tex); } else { tex = loader->getMovie()->getTexture(); if(tex){ gl::draw(tex); } } } else { float factor = (float)getMousePos().x / (float)getWindowSize().x; int frame = (int)((float)textures.size()*factor); auto tex = textures[frame]; gl::draw(tex, Rectf( 0, 0, getWindowSize().x, getWindowSize().y )); } } void MainApp::keyDown(KeyEvent event){ // switch(event.getChar()){ // case 'a': // } } CINDER_APP( MainApp, RendererGl ) <commit_msg>example app<commit_after>// cinder #include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/gl.h" #include "cinder/Log.h" #include "cinder/Rand.h" #include "cinder/qtime/QuickTimeGl.h" using namespace ci; using namespace ci::app; using namespace std; class VidFramesLoader { public: VidFramesLoader(const fs::path& path) : path(path) { try { // load up the movie, set it to loop, and begin playing mMovie = qtime::MovieGl::create(path); auto connection = mMovie->getNewFrameSignal().connect([this](){ auto tex = mMovie->getTexture(); mMovie->stop(); auto fbo = gl::Fbo::create(tex->getWidth(), tex->getHeight()); this->fbos.push_back(fbo); gl::ScopedFramebuffer fbScp( fbo ); gl::draw(tex); mMovie->play(); mMovie->seekToFrame(this->fbos.size()); // this->textures.push_back(newtex); this->bWaitingForFrame = false; CI_LOG_I("loaded tex #"<<this->fbos.size()); }); CI_LOG_I("movie loaded ("<<path<<"), number of frames: " <<mMovie->getNumFrames()); // //mMovie->setLoop(); mMovie->play(); } catch( ci::Exception &exc ) { console() << "Exception caught trying to load the movie from path: " << path << ", what: " << exc.what() << std::endl; mMovie = nullptr; } } void update(){ if(!mMovie || isComplete()) return; auto tex = mMovie->getTexture(); // int frameIndex = getLoadedFramesCount(); // mMovie->stop(); // mMovie->seekToFrame(frameIndex); // mMovie->play(); // CI_LOG_I("waiting for frame #" << frameIndex); // bWaitingForFrame = true; } unsigned int getLoadedFramesCount(){ return fbos.size(); } qtime::MovieGlRef getMovie(){ return this->mMovie; } bool isLoading(){ return !isComplete(); } bool isComplete(){ return mMovie && getLoadedFramesCount() >= mMovie->getNumFrames(); } gl::Texture2dRef getTexture(int idx){ return idx < 0 || idx >= this->fbos.size() ? nullptr : fbos[idx]->getColorTexture(); } gl::FboRef getFbo(int idx){ return idx < 0 || idx >= this->fbos.size() ? nullptr : fbos[idx]; } private: fs::path path; // std::vector<gl::TextureRef> textures; std::vector<gl::FboRef> fbos; qtime::MovieGlRef mMovie = nullptr; bool bWaitingForFrame = false; }; class GridView { }; class MainApp : public App { public: MainApp(); void setup() override; void update() override; void draw() override; void keyDown(KeyEvent event) override; private: void drawGrid(vec2 size, vec2 step, float fps, uint32_t seed=1462); ci::Timer timer; std::vector<fs::path> paths; std::shared_ptr<VidFramesLoader> loader = nullptr; std::vector<gl::TextureRef> textures; std::vector<std::shared_ptr<std::vector<gl::TextureRef>>> sequences; int vidCursor = 0; vec2 step = vec2(64,17); vec2 size = vec2(64,17); }; MainApp::MainApp() { } void MainApp::setup(){ setWindowSize( 1280, 480 ); timer.start(); auto args = getCommandLineArgs(); // CI_LOG_I("args size: " << args.size()); // for(auto arg : args){ // CI_LOG_I("arg: " << arg); // } // fs::path moviePath = getAssetPath(args.size() > 1 ? args[1] : "_bar0.mov"); paths.push_back(getAssetPath("_bar0.mov")); paths.push_back(getAssetPath("_bar1.mov")); paths.push_back(getAssetPath("_bar2.mov")); paths.push_back(getAssetPath("_bar3.mov")); paths.push_back(getAssetPath("_bar4.mov")); paths.push_back(getAssetPath("_bar5.mov")); } void MainApp::update(){ if(loader){ loader->update(); if(loader->isComplete()){ auto sequence = std::make_shared<std::vector<gl::TextureRef>>(); sequences.push_back(sequence); for(int i=0; i<loader->getLoadedFramesCount(); i++){ auto tex = loader->getTexture(i); textures.push_back(tex); sequence->push_back(tex); } loader = nullptr; } } if(!loader && vidCursor < paths.size()){ loader = std::make_shared<VidFramesLoader>(paths[vidCursor]); vidCursor += 1; } } void MainApp::draw(){ gl::clear(Color(0,0,0)); if(loader && loader->isLoading()){ auto tex = loader->getTexture(loader->getLoadedFramesCount()-1); if(tex){ gl::draw(tex); } else { tex = loader->getMovie()->getTexture(); if(tex){ gl::draw(tex); } } } else { // float factor = (float)getMousePos().x / (float)getWindowSize().x; // int frame = (int)((float)textures.size()*factor); // auto tex = textures[frame]; // gl::draw(tex, Rectf( 0, 0, getWindowSize().x, getWindowSize().y )); drawGrid(size, step, 25); } } void MainApp::keyDown(KeyEvent event){ switch(event.getChar()){ case 'l': { size = vec2(size.x*1.1f, size.y*1.1f); step = vec2(size.x, size.y*0.5f); return; } case 's': { size = vec2(size.x*0.9f, size.y*0.9f); step = vec2(size.x, size.y*0.5f); return; } } } void MainApp::drawGrid(vec2 size, vec2 step, float fps, uint32_t seed){ vec2 cursor = vec2(0.0f, 0.0f); const auto winsize = getWindowSize(); Rand rander; int counter = 0; // fill window veertically while(cursor.y < winsize.y){ // fill window horizontally while(cursor.x < winsize.x){ rander.seed(seed + counter); int startTex = (int)(rander.nextFloat() * (float)this->textures.size()); // CI_LOG_I("draw at: "<<cursor<<" startIdx: " << startTex); int texIdx = (int)std::fmod(startTex + this->timer.getSeconds() * fps, this->textures.size()); gl::draw(this->textures[texIdx], Rectf(cursor, cursor + size)); cursor.x += step.x; counter += 1; } cursor.x = 0.0f; cursor.y += step.y; } } CINDER_APP( MainApp, RendererGl ) <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ldapaccess.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:22:43 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef EXTENSIONS_CONFIG_LDAP_LDAPACCESS_HXX_ #define EXTENSIONS_CONFIG_LDAP_LDAPACCESS_HXX_ #ifdef WITH_OPENLDAP #include <ldap.h> #else #ifndef LDAP_INCLUDED #define LDAP_INCLUDED #include <ldap/ldap.h> #endif // LDAP_INCLUDED #endif #ifndef _COM_SUN_STAR_LDAP_LDAPGENERICEXCEPTION_HPP_ #include <com/sun/star/ldap/LdapGenericException.hpp> #endif // _COM_SUN_STAR_LDAP_LDAPGENERICEXCEPTION_HPP_ #ifndef _COM_SUN_STAR_LDAP_LDAP_CONNECTIONEXCEPTION_HPP_ #include <com/sun/star/ldap/LdapConnectionException.hpp> #endif // _COM_SUN_STAR_LDAP_LDAP_CONNECTIONEXCEPTION_HPP_ #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif // _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ namespace extensions { namespace config { namespace ldap { namespace css = com::sun::star ; namespace uno = css::uno ; namespace lang = css::lang ; namespace ldap = css::ldap ; //------------------------------------------------------------------------------ // LdapUserProfile classes struct LdapUserProfile; class LdapUserProfileMap; //------------------------------------------------------------------------------ /** Struct containing the information on LDAP connection */ struct LdapDefinition { /** LDAP server name */ rtl::OString mServer ; /** LDAP server port number */ sal_Int32 mPort ; /** Repository base DN */ rtl::OString mBaseDN ; /** DN to use for "anonymous" connection */ rtl::OString mAnonUser ; /** Credentials to use for "anonymous" connection */ rtl::OString mAnonCredentials ; /** User Entity Object Class */ rtl::OString mUserObjectClass; /** User Entity Unique Attribute */ rtl::OString mUserUniqueAttr; /** Mapping File */ rtl::OString mMapping; } ; /** Class encapulating all LDAP functionality */ class LdapConnection { public: /** Default constructor */ LdapConnection(void) : mConnection(NULL),mLdapDefinition() {} /** Destructor, releases the connection */ ~LdapConnection(void) ; /** Make connection to LDAP server */ void connectSimple(const LdapDefinition& aDefinition) throw (ldap::LdapConnectionException, ldap::LdapGenericException); /** query connection status */ bool isConnected() const { return isValid(); } /** Gets LdapUserProfile from LDAP repository for specified user @param aUser name of logged on user @param aUserProfileMap Map containing LDAP->00o mapping @param aUserProfile struct for holding OOo values @throws com::sun::star::ldap::LdapGenericException if an LDAP error occurs. */ void getUserProfile(const rtl::OUString& aUser, const LdapUserProfileMap& aUserProfileMap, LdapUserProfile& aUserProfile) throw (lang::IllegalArgumentException, ldap::LdapConnectionException, ldap::LdapGenericException); /** Retrieves a single attribute from a single entry. @param aDn entry DN @param aAttribute attribute name @throws com::sun::star::ldap::LdapGenericException if an LDAP error occurs. */ rtl::OString getSingleAttribute(const rtl::OString& aDn, const rtl::OString& aAttribute) throw (ldap::LdapConnectionException, ldap::LdapGenericException); /** finds DN of user @return DN of User */ rtl::OString findUserDn(const rtl::OString& aUser) throw (lang::IllegalArgumentException, ldap::LdapConnectionException, ldap::LdapGenericException); private: void initConnection() throw (ldap::LdapConnectionException); void disconnect(); /** Indicates whether the connection is in a valid state. @return sal_True if connection is valid, sal_False otherwise */ bool isValid(void) const { return mConnection != NULL ; } void connectSimple() throw (ldap::LdapConnectionException, ldap::LdapGenericException); /** LDAP connection object */ LDAP* mConnection ; LdapDefinition mLdapDefinition; } ; //------------------------------------------------------------------------------ }} } #endif // EXTENSIONS_CONFIG_LDAP_LDAPUSERPROFILE_HXX_ <commit_msg>INTEGRATION: CWS wae4extensions (1.6.388); FILE MERGED 2007/09/27 10:20:00 fs 1.6.388.1: #i81612# warning-free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ldapaccess.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: ihi $ $Date: 2008-01-14 14:41:11 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef EXTENSIONS_CONFIG_LDAP_LDAPACCESS_HXX_ #define EXTENSIONS_CONFIG_LDAP_LDAPACCESS_HXX_ #include "wrapldapinclude.hxx" #ifndef _COM_SUN_STAR_LDAP_LDAPGENERICEXCEPTION_HPP_ #include <com/sun/star/ldap/LdapGenericException.hpp> #endif // _COM_SUN_STAR_LDAP_LDAPGENERICEXCEPTION_HPP_ #ifndef _COM_SUN_STAR_LDAP_LDAP_CONNECTIONEXCEPTION_HPP_ #include <com/sun/star/ldap/LdapConnectionException.hpp> #endif // _COM_SUN_STAR_LDAP_LDAP_CONNECTIONEXCEPTION_HPP_ #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif // _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ namespace extensions { namespace config { namespace ldap { namespace css = com::sun::star ; namespace uno = css::uno ; namespace lang = css::lang ; namespace ldap = css::ldap ; //------------------------------------------------------------------------------ // LdapUserProfile classes struct LdapUserProfile; class LdapUserProfileMap; //------------------------------------------------------------------------------ /** Struct containing the information on LDAP connection */ struct LdapDefinition { /** LDAP server name */ rtl::OString mServer ; /** LDAP server port number */ sal_Int32 mPort ; /** Repository base DN */ rtl::OString mBaseDN ; /** DN to use for "anonymous" connection */ rtl::OString mAnonUser ; /** Credentials to use for "anonymous" connection */ rtl::OString mAnonCredentials ; /** User Entity Object Class */ rtl::OString mUserObjectClass; /** User Entity Unique Attribute */ rtl::OString mUserUniqueAttr; /** Mapping File */ rtl::OString mMapping; } ; /** Class encapulating all LDAP functionality */ class LdapConnection { public: /** Default constructor */ LdapConnection(void) : mConnection(NULL),mLdapDefinition() {} /** Destructor, releases the connection */ ~LdapConnection(void) ; /** Make connection to LDAP server */ void connectSimple(const LdapDefinition& aDefinition) throw (ldap::LdapConnectionException, ldap::LdapGenericException); /** query connection status */ bool isConnected() const { return isValid(); } /** Gets LdapUserProfile from LDAP repository for specified user @param aUser name of logged on user @param aUserProfileMap Map containing LDAP->00o mapping @param aUserProfile struct for holding OOo values @throws com::sun::star::ldap::LdapGenericException if an LDAP error occurs. */ void getUserProfile(const rtl::OUString& aUser, const LdapUserProfileMap& aUserProfileMap, LdapUserProfile& aUserProfile) throw (lang::IllegalArgumentException, ldap::LdapConnectionException, ldap::LdapGenericException); /** Retrieves a single attribute from a single entry. @param aDn entry DN @param aAttribute attribute name @throws com::sun::star::ldap::LdapGenericException if an LDAP error occurs. */ rtl::OString getSingleAttribute(const rtl::OString& aDn, const rtl::OString& aAttribute) throw (ldap::LdapConnectionException, ldap::LdapGenericException); /** finds DN of user @return DN of User */ rtl::OString findUserDn(const rtl::OString& aUser) throw (lang::IllegalArgumentException, ldap::LdapConnectionException, ldap::LdapGenericException); private: void initConnection() throw (ldap::LdapConnectionException); void disconnect(); /** Indicates whether the connection is in a valid state. @return sal_True if connection is valid, sal_False otherwise */ bool isValid(void) const { return mConnection != NULL ; } void connectSimple() throw (ldap::LdapConnectionException, ldap::LdapGenericException); /** LDAP connection object */ LDAP* mConnection ; LdapDefinition mLdapDefinition; } ; //------------------------------------------------------------------------------ }} } #endif // EXTENSIONS_CONFIG_LDAP_LDAPUSERPROFILE_HXX_ <|endoftext|>
<commit_before>/* * (C) Copyright 2016 Mirantis Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: * Radoslaw Zarzynski <rzarzynski@mirantis.com> */ #include <iostream> #include "static_ptr.hpp" class Interface { public: // virtual ~Interface() {}; virtual void print_name() const noexcept = 0; }; class Base1 : public Interface { long member[2]; public: virtual void print_name() const noexcept override { std::cout << "Base1" << std::endl; } }; class Base2 : public Interface { long member[4]; public: virtual ~Base2() { std::cout << "Base2 dted" << std::endl; } virtual void print_name() const noexcept override { std::cout << "Base2" << std::endl; } }; class Factory { static constexpr size_t max_size = sizeof(Base1) > sizeof(Base2) ? sizeof(Base1) : sizeof(Base2); public: static constexpr size_t get_max_size() { return max_size; } // cannot use get_max_size here due to a language quirk static static_ptr<Interface, max_size> make_instance(bool first_one) { if (first_one) { return Base1(); } else { return Base2(); } } }; int main (void) { std::cout << "max size: " << Factory::get_max_size() << std::endl; static_ptr<Interface, Factory::get_max_size()> ptr = Base2(); ptr->print_name(); return 0; } <commit_msg>Rework examples/basic_usage.cc.<commit_after>/* * (C) Copyright 2016 Mirantis Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: * Radoslaw Zarzynski <rzarzynski@mirantis.com> */ #include <iostream> #include "static_ptr.hpp" struct Interface { /* NOTE: the destructor is NOT virtual. */ virtual const char* get_name() const = 0; }; struct ConcreteA : public Interface { long member[4]; const char* get_name() const override { return "ConcreteA"; } }; struct ConcreteB : public Interface { long member[4]; const char* get_name() const override { return "ConcreteB"; } ~ConcreteB() { std::cout << "ConcreteB destructed" << std::endl; } }; struct Factory { static static_ptr<Interface, maxsizeof<ConcreteA, ConcreteB>() > make_instance(bool first_one) { if (first_one) { return ConcreteA(); } else { return ConcreteB(); } } }; int main (void) { auto ptrA = Factory::make_instance(true); auto ptrB = Factory::make_instance(false); /* Result: ptrA->get_name(): ConcreteA */ std::cout << "ptrA->get_name(): " << ptrA->get_name() << std::endl; /* Result: * ptrB->get_name(): ConcreteB * ConcreteB destructed */ std::cout << "ptrB->get_name(): " << ptrB->get_name() << std::endl; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xsddatatypes.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2006-07-26 08:02:08 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef EXTENSIONS_SOURCE_PROPCTRLR_XSDDATATYPES_HXX #define EXTENSIONS_SOURCE_PROPCTRLR_XSDDATATYPES_HXX /** === begin UNO includes === **/ #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif /** === end UNO includes === **/ #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif namespace com { namespace sun { namespace star { namespace xsd { class XDataType; } namespace beans { class XPropertySet; class XPropertySetInfo; } } } } //........................................................................ namespace pcr { //........................................................................ //==================================================================== //= XSDDataType //==================================================================== class XSDDataType : public ::rtl::IReference { private: ::com::sun::star::uno::Reference< ::com::sun::star::xsd::XDataType > m_xDataType; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > m_xFacetInfo; protected: oslInterlockedCount m_refCount; protected: inline ::com::sun::star::xsd::XDataType* getDataTypeInterface() const { return m_xDataType.get(); } public: XSDDataType( const ::com::sun::star::uno::Reference< ::com::sun::star::xsd::XDataType >& _rxDataType ); // IReference virtual oslInterlockedCount SAL_CALL acquire(); virtual oslInterlockedCount SAL_CALL release(); /// retrieves the underlying UNO component inline const ::com::sun::star::uno::Reference< ::com::sun::star::xsd::XDataType >& getUnoDataType() const { return m_xDataType; } /// classifies the data typ sal_Int16 classify() const SAL_THROW(()); // attribute access ::rtl::OUString getName() const SAL_THROW(()); bool isBasicType() const SAL_THROW(()); /// determines whether a given facet exists at the type bool hasFacet( const ::rtl::OUString& _rFacetName ) const SAL_THROW(()); /// determines the UNO type of a facet ::com::sun::star::uno::Type getFacetType( const ::rtl::OUString& _rFacetName ) const SAL_THROW(()); /// retrieves a facet value ::com::sun::star::uno::Any getFacet( const ::rtl::OUString& _rFacetName ) SAL_THROW(()); /// sets a facet value void setFacet( const ::rtl::OUString& _rFacetName, const ::com::sun::star::uno::Any& _rFacetValue ) SAL_THROW(()); /** copies as much facets (values, respectively) from a give data type instance */ void copyFacetsFrom( const ::rtl::Reference< XSDDataType >& _pSourceType ); protected: virtual ~XSDDataType(); private: XSDDataType(); // never implemented XSDDataType( const XSDDataType& ); // never implemented XSDDataType& operator=( const XSDDataType& ); // never implemented }; //........................................................................ } // namespace pcr //........................................................................ #endif // EXTENSIONS_SOURCE_PROPCTRLR_XSDDATATYPES_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.4.314); FILE MERGED 2008/04/01 15:15:22 thb 1.4.314.2: #i85898# Stripping all external header guards 2008/03/31 12:31:57 rt 1.4.314.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: xsddatatypes.hxx,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. * ************************************************************************/ #ifndef EXTENSIONS_SOURCE_PROPCTRLR_XSDDATATYPES_HXX #define EXTENSIONS_SOURCE_PROPCTRLR_XSDDATATYPES_HXX /** === begin UNO includes === **/ #include <com/sun/star/uno/Reference.hxx> /** === end UNO includes === **/ #include <rtl/ref.hxx> namespace com { namespace sun { namespace star { namespace xsd { class XDataType; } namespace beans { class XPropertySet; class XPropertySetInfo; } } } } //........................................................................ namespace pcr { //........................................................................ //==================================================================== //= XSDDataType //==================================================================== class XSDDataType : public ::rtl::IReference { private: ::com::sun::star::uno::Reference< ::com::sun::star::xsd::XDataType > m_xDataType; ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > m_xFacetInfo; protected: oslInterlockedCount m_refCount; protected: inline ::com::sun::star::xsd::XDataType* getDataTypeInterface() const { return m_xDataType.get(); } public: XSDDataType( const ::com::sun::star::uno::Reference< ::com::sun::star::xsd::XDataType >& _rxDataType ); // IReference virtual oslInterlockedCount SAL_CALL acquire(); virtual oslInterlockedCount SAL_CALL release(); /// retrieves the underlying UNO component inline const ::com::sun::star::uno::Reference< ::com::sun::star::xsd::XDataType >& getUnoDataType() const { return m_xDataType; } /// classifies the data typ sal_Int16 classify() const SAL_THROW(()); // attribute access ::rtl::OUString getName() const SAL_THROW(()); bool isBasicType() const SAL_THROW(()); /// determines whether a given facet exists at the type bool hasFacet( const ::rtl::OUString& _rFacetName ) const SAL_THROW(()); /// determines the UNO type of a facet ::com::sun::star::uno::Type getFacetType( const ::rtl::OUString& _rFacetName ) const SAL_THROW(()); /// retrieves a facet value ::com::sun::star::uno::Any getFacet( const ::rtl::OUString& _rFacetName ) SAL_THROW(()); /// sets a facet value void setFacet( const ::rtl::OUString& _rFacetName, const ::com::sun::star::uno::Any& _rFacetValue ) SAL_THROW(()); /** copies as much facets (values, respectively) from a give data type instance */ void copyFacetsFrom( const ::rtl::Reference< XSDDataType >& _pSourceType ); protected: virtual ~XSDDataType(); private: XSDDataType(); // never implemented XSDDataType( const XSDDataType& ); // never implemented XSDDataType& operator=( const XSDDataType& ); // never implemented }; //........................................................................ } // namespace pcr //........................................................................ #endif // EXTENSIONS_SOURCE_PROPCTRLR_XSDDATATYPES_HXX <|endoftext|>
<commit_before>/* * Fork a process and delegate open() to it. The subprocess returns * the file descriptor over a unix socket. * * author: Max Kellermann <mk@cm4all.com> */ #include "Client.hxx" #include "Handler.hxx" #include "Protocol.hxx" #include "async.hxx" #include "please.hxx" #include "fd_util.h" #include "pevent.hxx" #include "gerrno.h" #include "pool.hxx" #include "util/Macros.hxx" #include <assert.h> #include <string.h> #include <sys/socket.h> struct DelegateClient { struct lease_ref lease_ref; const int fd; struct event event; struct pool &pool; const struct delegate_handler &handler; void *handler_ctx; struct async_operation operation; DelegateClient(int _fd, const struct lease &lease, void *lease_ctx, struct pool &_pool, const struct delegate_handler &_handler, void *_handler_ctx) :fd(_fd), pool(_pool), handler(_handler), handler_ctx(_handler_ctx) { p_lease_ref_set(lease_ref, lease, lease_ctx, _pool, "delegate_client_lease"); operation.Init2<DelegateClient, &DelegateClient::operation>(); } ~DelegateClient() { pool_unref(&pool); } void Destroy() { this->~DelegateClient(); } void ReleaseSocket(bool reuse) { assert(fd >= 0); p_lease_release(lease_ref, reuse, pool); } void HandleFd(const struct msghdr &msg, size_t length); void HandleErrno(size_t length); void HandleMsg(const struct msghdr &msg, DelegateResponseCommand command, size_t length); void TryRead(); void Abort() { p_event_del(&event, &pool); ReleaseSocket(false); Destroy(); } }; inline void DelegateClient::HandleFd(const struct msghdr &msg, size_t length) { if (length != 0) { ReleaseSocket(false); GError *error = g_error_new_literal(delegate_client_quark(), 0, "Invalid message length"); handler.error(error, handler_ctx); Destroy(); return; } struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); if (cmsg == nullptr) { ReleaseSocket(false); GError *error = g_error_new_literal(delegate_client_quark(), 0, "No fd passed"); handler.error(error, handler_ctx); Destroy(); return; } if (cmsg->cmsg_type != SCM_RIGHTS) { ReleaseSocket(false); GError *error = g_error_new(delegate_client_quark(), 0, "got control message of unknown type %d", cmsg->cmsg_type); handler.error(error, handler_ctx); Destroy(); return; } ReleaseSocket(true); const void *data = CMSG_DATA(cmsg); const int *fd_p = (const int *)data; int new_fd = *fd_p; handler.success(new_fd, handler_ctx); Destroy(); } inline void DelegateClient::HandleErrno(size_t length) { int e; if (length != sizeof(e)) { ReleaseSocket(false); GError *error = g_error_new_literal(delegate_client_quark(), 0, "Invalid message length"); handler.error(error, handler_ctx); Destroy(); return; } ssize_t nbytes = recv(fd, &e, sizeof(e), 0); GError *error; if (nbytes == sizeof(e)) { ReleaseSocket(true); error = new_error_errno2(e); } else { ReleaseSocket(false); error = g_error_new_literal(delegate_client_quark(), 0, "Failed to receive errno"); } handler.error(error, handler_ctx); Destroy(); } inline void DelegateClient::HandleMsg(const struct msghdr &msg, DelegateResponseCommand command, size_t length) { switch (command) { case DelegateResponseCommand::FD: HandleFd(msg, length); return; case DelegateResponseCommand::ERRNO: /* i/o error */ HandleErrno(length); return; } ReleaseSocket(false); GError *error = g_error_new_literal(delegate_client_quark(), 0, "Invalid delegate response"); handler.error(error, handler_ctx); Destroy(); } inline void DelegateClient::TryRead() { operation.Finished(); struct iovec iov; int new_fd; char ccmsg[CMSG_SPACE(sizeof(new_fd))]; struct msghdr msg = { .msg_name = nullptr, .msg_namelen = 0, .msg_iov = &iov, .msg_iovlen = 1, .msg_control = ccmsg, .msg_controllen = sizeof(ccmsg), }; DelegateResponseHeader header; ssize_t nbytes; iov.iov_base = &header; iov.iov_len = sizeof(header); nbytes = recvmsg_cloexec(fd, &msg, 0); if (nbytes < 0) { ReleaseSocket(false); GError *error = new_error_errno_msg("recvmsg() failed"); handler.error(error, handler_ctx); Destroy(); return; } if ((size_t)nbytes != sizeof(header)) { ReleaseSocket(false); GError *error = g_error_new_literal(delegate_client_quark(), 0, "short recvmsg()"); handler.error(error, handler_ctx); Destroy(); return; } HandleMsg(msg, header.command, header.length); } static void delegate_read_event_callback(int fd gcc_unused, short event gcc_unused, void *ctx) { DelegateClient *d = (DelegateClient *)ctx; p_event_consumed(&d->event, &d->pool); assert(d->fd == fd); d->TryRead(); } /* * constructor * */ static bool SendDelegatePacket(int fd, DelegateRequestCommand cmd, const void *payload, size_t length, GError **error_r) { const DelegateRequestHeader header = { .length = (uint16_t)length, .command = cmd, }; struct iovec v[] = { { const_cast<void *>((const void *)&header), sizeof(header) }, { const_cast<void *>(payload), length }, }; struct msghdr msg = { .msg_name = nullptr, .msg_namelen = 0, .msg_iov = v, .msg_iovlen = ARRAY_SIZE(v), .msg_control = nullptr, .msg_controllen = 0, .msg_flags = 0, }; auto nbytes = sendmsg(fd, &msg, MSG_DONTWAIT); if (nbytes < 0) { set_error_errno_msg(error_r, "Failed to send to delegate"); return false; } if (size_t(nbytes) != sizeof(header) + length) { g_set_error_literal(error_r, delegate_client_quark(), 0, "Short send to delegate"); return false; } return true; } void delegate_open(int fd, const struct lease *lease, void *lease_ctx, struct pool *pool, const char *path, const struct delegate_handler *handler, void *ctx, struct async_operation_ref *async_ref) { GError *error = nullptr; if (!SendDelegatePacket(fd, DelegateRequestCommand::OPEN, path, strlen(path), &error)) { lease->Release(lease_ctx, false); handler->error(error, ctx); return; } auto d = NewFromPool<DelegateClient>(*pool, fd, *lease, lease_ctx, *pool, *handler, ctx); pool_ref(pool); async_ref->Set(d->operation); event_set(&d->event, d->fd, EV_READ, delegate_read_event_callback, d); p_event_add(&d->event, nullptr, pool, "delegate_client_event"); } <commit_msg>delegate/Client: add method DestroyError()<commit_after>/* * Fork a process and delegate open() to it. The subprocess returns * the file descriptor over a unix socket. * * author: Max Kellermann <mk@cm4all.com> */ #include "Client.hxx" #include "Handler.hxx" #include "Protocol.hxx" #include "async.hxx" #include "please.hxx" #include "fd_util.h" #include "pevent.hxx" #include "gerrno.h" #include "pool.hxx" #include "util/Macros.hxx" #include <assert.h> #include <string.h> #include <sys/socket.h> struct DelegateClient { struct lease_ref lease_ref; const int fd; struct event event; struct pool &pool; const struct delegate_handler &handler; void *handler_ctx; struct async_operation operation; DelegateClient(int _fd, const struct lease &lease, void *lease_ctx, struct pool &_pool, const struct delegate_handler &_handler, void *_handler_ctx) :fd(_fd), pool(_pool), handler(_handler), handler_ctx(_handler_ctx) { p_lease_ref_set(lease_ref, lease, lease_ctx, _pool, "delegate_client_lease"); operation.Init2<DelegateClient, &DelegateClient::operation>(); } ~DelegateClient() { pool_unref(&pool); } void Destroy() { this->~DelegateClient(); } void ReleaseSocket(bool reuse) { assert(fd >= 0); p_lease_release(lease_ref, reuse, pool); } void DestroyError(GError *error) { ReleaseSocket(false); handler.error(error, handler_ctx); Destroy(); } void HandleFd(const struct msghdr &msg, size_t length); void HandleErrno(size_t length); void HandleMsg(const struct msghdr &msg, DelegateResponseCommand command, size_t length); void TryRead(); void Abort() { p_event_del(&event, &pool); ReleaseSocket(false); Destroy(); } }; inline void DelegateClient::HandleFd(const struct msghdr &msg, size_t length) { if (length != 0) { GError *error = g_error_new_literal(delegate_client_quark(), 0, "Invalid message length"); DestroyError(error); return; } struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); if (cmsg == nullptr) { GError *error = g_error_new_literal(delegate_client_quark(), 0, "No fd passed"); DestroyError(error); return; } if (cmsg->cmsg_type != SCM_RIGHTS) { GError *error = g_error_new(delegate_client_quark(), 0, "got control message of unknown type %d", cmsg->cmsg_type); DestroyError(error); return; } ReleaseSocket(true); const void *data = CMSG_DATA(cmsg); const int *fd_p = (const int *)data; int new_fd = *fd_p; handler.success(new_fd, handler_ctx); Destroy(); } inline void DelegateClient::HandleErrno(size_t length) { int e; if (length != sizeof(e)) { GError *error = g_error_new_literal(delegate_client_quark(), 0, "Invalid message length"); DestroyError(error); return; } ssize_t nbytes = recv(fd, &e, sizeof(e), 0); GError *error; if (nbytes == sizeof(e)) { ReleaseSocket(true); error = new_error_errno2(e); } else { ReleaseSocket(false); error = g_error_new_literal(delegate_client_quark(), 0, "Failed to receive errno"); } handler.error(error, handler_ctx); Destroy(); } inline void DelegateClient::HandleMsg(const struct msghdr &msg, DelegateResponseCommand command, size_t length) { switch (command) { case DelegateResponseCommand::FD: HandleFd(msg, length); return; case DelegateResponseCommand::ERRNO: /* i/o error */ HandleErrno(length); return; } GError *error = g_error_new_literal(delegate_client_quark(), 0, "Invalid delegate response"); DestroyError(error); } inline void DelegateClient::TryRead() { operation.Finished(); struct iovec iov; int new_fd; char ccmsg[CMSG_SPACE(sizeof(new_fd))]; struct msghdr msg = { .msg_name = nullptr, .msg_namelen = 0, .msg_iov = &iov, .msg_iovlen = 1, .msg_control = ccmsg, .msg_controllen = sizeof(ccmsg), }; DelegateResponseHeader header; ssize_t nbytes; iov.iov_base = &header; iov.iov_len = sizeof(header); nbytes = recvmsg_cloexec(fd, &msg, 0); if (nbytes < 0) { GError *error = new_error_errno_msg("recvmsg() failed"); DestroyError(error); return; } if ((size_t)nbytes != sizeof(header)) { GError *error = g_error_new_literal(delegate_client_quark(), 0, "short recvmsg()"); DestroyError(error); return; } HandleMsg(msg, header.command, header.length); } static void delegate_read_event_callback(int fd gcc_unused, short event gcc_unused, void *ctx) { DelegateClient *d = (DelegateClient *)ctx; p_event_consumed(&d->event, &d->pool); assert(d->fd == fd); d->TryRead(); } /* * constructor * */ static bool SendDelegatePacket(int fd, DelegateRequestCommand cmd, const void *payload, size_t length, GError **error_r) { const DelegateRequestHeader header = { .length = (uint16_t)length, .command = cmd, }; struct iovec v[] = { { const_cast<void *>((const void *)&header), sizeof(header) }, { const_cast<void *>(payload), length }, }; struct msghdr msg = { .msg_name = nullptr, .msg_namelen = 0, .msg_iov = v, .msg_iovlen = ARRAY_SIZE(v), .msg_control = nullptr, .msg_controllen = 0, .msg_flags = 0, }; auto nbytes = sendmsg(fd, &msg, MSG_DONTWAIT); if (nbytes < 0) { set_error_errno_msg(error_r, "Failed to send to delegate"); return false; } if (size_t(nbytes) != sizeof(header) + length) { g_set_error_literal(error_r, delegate_client_quark(), 0, "Short send to delegate"); return false; } return true; } void delegate_open(int fd, const struct lease *lease, void *lease_ctx, struct pool *pool, const char *path, const struct delegate_handler *handler, void *ctx, struct async_operation_ref *async_ref) { GError *error = nullptr; if (!SendDelegatePacket(fd, DelegateRequestCommand::OPEN, path, strlen(path), &error)) { lease->Release(lease_ctx, false); handler->error(error, ctx); return; } auto d = NewFromPool<DelegateClient>(*pool, fd, *lease, lease_ctx, *pool, *handler, ctx); pool_ref(pool); async_ref->Set(d->operation); event_set(&d->event, d->fd, EV_READ, delegate_read_event_callback, d); p_event_add(&d->event, nullptr, pool, "delegate_client_event"); } <|endoftext|>
<commit_before>// Copyright 2015 Stanford University // // 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. // // test for Realm's serializing code #include "realm/serialize.h" #include <sys/resource.h> #include <string.h> #include <iostream> #include <iomanip> #include <vector> #include <string> #include <map> #include <list> #include <set> static bool verbose = false; static int error_count = 0; static void parse_args(int argc, const char *argv[]) { for(int i = 1; i < argc; i++) { if(!strcmp(argv[i], "-v")) { verbose = true; continue; } } } // helper functions to print out containers template <typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { os << '[' << v.size() << ']'; for(typename std::vector<T>::const_iterator it = v.begin(); it != v.end(); it++) os << ' ' << *it; return os; } template <typename T> std::ostream& operator<<(std::ostream& os, const std::list<T>& l) { os << '[' << l.size() << ']'; for(typename std::list<T>::const_iterator it = l.begin(); it != l.end(); it++) os << ' ' << *it; return os; } template <typename T> std::ostream& operator<<(std::ostream& os, const std::set<T>& s) { os << '[' << s.size() << ']'; for(typename std::set<T>::const_iterator it = s.begin(); it != s.end(); it++) os << ' ' << *it; return os; } template <typename T1, typename T2> std::ostream& operator<<(std::ostream& os, const std::map<T1, T2>& m) { os << '[' << m.size() << ']'; for(typename std::map<T1, T2>::const_iterator it = m.begin(); it != m.end(); it++) os << ' ' << it->first << '=' << it->second; return os; } template <typename T> size_t test_dynamic(const char *name, const T& input, size_t exp_size = 0) { // first serialize and check size Realm::Serialization::DynamicBufferSerializer dbs(0); bool ok1 = dbs << input; if(!ok1) { std::cout << "ERROR: " << name << "dynamic serialization failed!" << std::endl; error_count++; } size_t act_size = dbs.bytes_used(); if(exp_size > 0) { if(act_size != exp_size) { std::cout << "ERROR: " << name << "dynamic size = " << act_size << " (should be " << exp_size << ")" << std::endl; error_count++; } else { if(verbose) std::cout << "OK: " << name << " dynamic size = " << act_size << std::endl; } } void *buffer = dbs.detach_buffer(); // now deserialize into a new object and test for equality Realm::Serialization::FixedBufferDeserializer fbd(buffer, act_size); T output; bool ok2 = fbd >> output; if(!ok2) { std::cout << "ERROR: " << name << " dynamic deserialization failed!" << std::endl; error_count++; } ptrdiff_t leftover = fbd.bytes_left(); if(leftover != 0) { std::cout << "ERROR: " << name << " dynamic leftover = " << leftover << std::endl; error_count++; } bool ok3 = (input == output); if(ok3) { if(verbose) std::cout << "OK: " << name << " dynamic output matches" << std::endl; } else { std::cout << "ERROR: " << name << " dynamic output mismatch:" << std::endl; std::cout << "Input: " << input << std::endl; std::cout << "Buffer: [" << act_size << "]"; std::cout << std::hex; for(size_t i = 0; i < act_size; i++) std::cout << ' ' << std::setfill('0') << std::setw(2) << (int)((unsigned char *)buffer)[i]; std::cout << std::dec << std::endl; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" std::cout << "Output: " << output << std::endl; #pragma GCC diagnostic pop error_count++; } free(buffer); return act_size; } template <typename T> void test_size(const char *name, const T& input, size_t exp_size) { Realm::Serialization::ByteCountSerializer bcs; bool ok = bcs << input; if(!ok) { std::cout << "ERROR: " << name << "byetcount serialization failed!" << std::endl; error_count++; } size_t act_size = bcs.bytes_used(); if(act_size != exp_size) { std::cout << "ERROR: " << name << "bytecount size = " << act_size << " (should be " << exp_size << ")" << std::endl; error_count++; } else { if(verbose) std::cout << "OK: " << name << " bytecount size = " << act_size << std::endl; } } template <typename T> void test_fixed(const char *name, const T& input, size_t exp_size) { // first serialize and check size void *buffer = malloc(exp_size); Realm::Serialization::FixedBufferSerializer fbs(buffer, exp_size); bool ok1 = fbs << input; if(!ok1) { std::cout << "ERROR: " << name << "fixed serialization failed!" << std::endl; error_count++; } ptrdiff_t leftover = fbs.bytes_left(); if(leftover != 0) { std::cout << "ERROR: " << name << "fixed leftover = " << leftover << std::endl; error_count++; } else { if(verbose) std::cout << "OK: " << name << " fixed leftover = " << leftover << std::endl; } // now deserialize into a new object and test for equality Realm::Serialization::FixedBufferDeserializer fbd(buffer, exp_size); T output; bool ok2 = fbd >> output; if(!ok2) { std::cout << "ERROR: " << name << " fixed deserialization failed!" << std::endl; error_count++; } leftover = fbd.bytes_left(); if(leftover != 0) { std::cout << "ERROR: " << name << " fixed leftover = " << leftover << std::endl; error_count++; } bool ok3 = (input == output); if(ok3) { if(verbose) std::cout << "OK: " << name << " fixed output matches" << std::endl; } else { std::cout << "ERROR: " << name << " fixed output mismatch:" << std::endl; std::cout << "Input: " << input << std::endl; std::cout << "Buffer: [" << exp_size << "]"; std::cout << std::hex; for(size_t i = 0; i < exp_size; i++) std::cout << ' ' << std::setfill('0') << std::setw(2) << (int)((unsigned char *)buffer)[i]; std::cout << std::dec << std::endl; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" std::cout << "Output: " << output << std::endl; #pragma GCC diagnostic pop error_count++; } free(buffer); } template <typename T> void do_test(const char *name, const T& input, size_t exp_size = 0) { exp_size = test_dynamic(name, input, exp_size); test_size(name, input, exp_size); test_fixed(name, input, exp_size); } template <typename T1, typename T2> struct Pair { T1 x; T2 y; Pair(void) : x(), y() {} Pair(T1 _x, T2 _y) : x(_x), y(_y) {} bool operator==(const Pair<T1,T2>& rhs) const { return (x == rhs.x) && (y == rhs.y); } friend std::ostream& operator<<(std::ostream& os, const Pair<T1, T2>& p) { return os << '<' << p.x << ',' << p.y << '>'; } }; #if 0 template <typename T1, typename T2> std::ostream& operator<<(std::ostream& os, const Pair<T1, T2>& p) { return os << '<' << p.x << ',' << p.y << '>'; } #endif typedef Pair<double, int> PODStruct; TYPE_IS_SERIALIZABLE(PODStruct); typedef Pair<double, float> PODPacked; template <typename S> bool operator<<(S& s, const PODPacked& p) { return (s << p.x) && (s << p.y); } template <typename S> bool operator>>(S& s, PODPacked& p) { return (s >> p.x) && (s >> p.y); } typedef Pair<double, char> PODPacked2; template <typename S> bool operator&(S& s, const PODPacked2& p) { return (s & p.x) && (s & p.y); } typedef Pair<PODPacked, int> PP2; template <typename S> bool operator&(S& s, const PP2& p) { return (s & p.x) && (s & p.y); } int main(int argc, const char *argv[]) { parse_args(argc, argv); { // a common failure mode for the serialization logic is infinite recursion, // so set very tight bounds on our stack size and run time struct rlimit rl; int ret; rl.rlim_cur = rl.rlim_max = 16384; // 16KB ret = setrlimit(RLIMIT_STACK, &rl); assert(ret == 0); rl.rlim_cur = rl.rlim_max = 5; // 5 seconds ret = setrlimit(RLIMIT_CPU, &rl); assert(ret == 0); } int x = 5; do_test("int", x, sizeof(int)); do_test("double", double(4.5), sizeof(double)); //void *f = &x; //do_test("void*", f, sizeof(void *)); do_test("pod struct", PODStruct(6.5, 7), sizeof(PODStruct)); do_test("pod packed", PODPacked(8.5, 9.1), 12 /* not sizeof(PODPacked)*/); do_test("pod packed2", PODPacked2(10.5, 'z'), 9 /* not sizeof(PODPacked2)*/); do_test("pp2", PP2(PODPacked(44.3, 1), 9), 16 /* not sizeof(PP2) */); std::vector<int> a(3); a[0] = 1; a[1] = 2; a[2] = 3; do_test("vector<int>", a, sizeof(size_t) + a.size() * sizeof(int)); std::vector<PODStruct> a2(1); a2[0] = PODStruct(3, 4); do_test("vector<PODStruct>", a2, sizeof(size_t) + a2.size() * sizeof(PODStruct)); std::vector<PODPacked> a3(1); a3[0] = PODPacked(3, 4); do_test("vector<PODPacked>", a3, sizeof(size_t) + 12 /* not sizeof(PODPacked)*/); std::vector<PODPacked2> a4(1); a4[0] = PODPacked2(3, 4); do_test("vector<PODPacked2>", a4, sizeof(size_t) + 9 /* not sizeof(PODPacked2)*/); std::list<int> b; b.push_back(4); b.push_back(5); b.push_back(6); b.push_back(7); do_test("list<int>", b, sizeof(size_t) + b.size() * sizeof(int)); std::map<int, double> c; c[8] = 1.1; c[9] = 2.2; c[10] = 3.3; do_test("map<int,double>", c, sizeof(size_t) + c.size() * 16 /*alignment*/); std::vector<std::string> ss; ss.push_back("Hello"); ss.push_back("World"); do_test("vector<string>", ss, sizeof(size_t) + 12 + 9); std::set<int> s; s.insert(4); s.insert(2); s.insert(11); do_test("set<int>", s, sizeof(size_t) + s.size() * sizeof(int)); if(error_count > 0) { std::cout << "ERRORS FOUND" << std::endl; exit(1); } else { std::cout << "all tests passed" << std::endl; exit(0); } } <commit_msg>clang supports GCC's diagnostic pragmas but not the same names...<commit_after>// Copyright 2015 Stanford University // // 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. // // test for Realm's serializing code #include "realm/serialize.h" #include <sys/resource.h> #include <string.h> #include <iostream> #include <iomanip> #include <vector> #include <string> #include <map> #include <list> #include <set> static bool verbose = false; static int error_count = 0; static void parse_args(int argc, const char *argv[]) { for(int i = 1; i < argc; i++) { if(!strcmp(argv[i], "-v")) { verbose = true; continue; } } } // helper functions to print out containers template <typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { os << '[' << v.size() << ']'; for(typename std::vector<T>::const_iterator it = v.begin(); it != v.end(); it++) os << ' ' << *it; return os; } template <typename T> std::ostream& operator<<(std::ostream& os, const std::list<T>& l) { os << '[' << l.size() << ']'; for(typename std::list<T>::const_iterator it = l.begin(); it != l.end(); it++) os << ' ' << *it; return os; } template <typename T> std::ostream& operator<<(std::ostream& os, const std::set<T>& s) { os << '[' << s.size() << ']'; for(typename std::set<T>::const_iterator it = s.begin(); it != s.end(); it++) os << ' ' << *it; return os; } template <typename T1, typename T2> std::ostream& operator<<(std::ostream& os, const std::map<T1, T2>& m) { os << '[' << m.size() << ']'; for(typename std::map<T1, T2>::const_iterator it = m.begin(); it != m.end(); it++) os << ' ' << it->first << '=' << it->second; return os; } template <typename T> size_t test_dynamic(const char *name, const T& input, size_t exp_size = 0) { // first serialize and check size Realm::Serialization::DynamicBufferSerializer dbs(0); bool ok1 = dbs << input; if(!ok1) { std::cout << "ERROR: " << name << "dynamic serialization failed!" << std::endl; error_count++; } size_t act_size = dbs.bytes_used(); if(exp_size > 0) { if(act_size != exp_size) { std::cout << "ERROR: " << name << "dynamic size = " << act_size << " (should be " << exp_size << ")" << std::endl; error_count++; } else { if(verbose) std::cout << "OK: " << name << " dynamic size = " << act_size << std::endl; } } void *buffer = dbs.detach_buffer(); // now deserialize into a new object and test for equality Realm::Serialization::FixedBufferDeserializer fbd(buffer, act_size); T output; bool ok2 = fbd >> output; if(!ok2) { std::cout << "ERROR: " << name << " dynamic deserialization failed!" << std::endl; error_count++; } ptrdiff_t leftover = fbd.bytes_left(); if(leftover != 0) { std::cout << "ERROR: " << name << " dynamic leftover = " << leftover << std::endl; error_count++; } bool ok3 = (input == output); if(ok3) { if(verbose) std::cout << "OK: " << name << " dynamic output matches" << std::endl; } else { std::cout << "ERROR: " << name << " dynamic output mismatch:" << std::endl; std::cout << "Input: " << input << std::endl; std::cout << "Buffer: [" << act_size << "]"; std::cout << std::hex; for(size_t i = 0; i < act_size; i++) std::cout << ' ' << std::setfill('0') << std::setw(2) << (int)((unsigned char *)buffer)[i]; std::cout << std::dec << std::endl; #pragma GCC diagnostic push #ifdef __clang__ #pragma GCC diagnostic ignored "-Wuninitialized" #else #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #endif std::cout << "Output: " << output << std::endl; #pragma GCC diagnostic pop error_count++; } free(buffer); return act_size; } template <typename T> void test_size(const char *name, const T& input, size_t exp_size) { Realm::Serialization::ByteCountSerializer bcs; bool ok = bcs << input; if(!ok) { std::cout << "ERROR: " << name << "byetcount serialization failed!" << std::endl; error_count++; } size_t act_size = bcs.bytes_used(); if(act_size != exp_size) { std::cout << "ERROR: " << name << "bytecount size = " << act_size << " (should be " << exp_size << ")" << std::endl; error_count++; } else { if(verbose) std::cout << "OK: " << name << " bytecount size = " << act_size << std::endl; } } template <typename T> void test_fixed(const char *name, const T& input, size_t exp_size) { // first serialize and check size void *buffer = malloc(exp_size); Realm::Serialization::FixedBufferSerializer fbs(buffer, exp_size); bool ok1 = fbs << input; if(!ok1) { std::cout << "ERROR: " << name << "fixed serialization failed!" << std::endl; error_count++; } ptrdiff_t leftover = fbs.bytes_left(); if(leftover != 0) { std::cout << "ERROR: " << name << "fixed leftover = " << leftover << std::endl; error_count++; } else { if(verbose) std::cout << "OK: " << name << " fixed leftover = " << leftover << std::endl; } // now deserialize into a new object and test for equality Realm::Serialization::FixedBufferDeserializer fbd(buffer, exp_size); T output; bool ok2 = fbd >> output; if(!ok2) { std::cout << "ERROR: " << name << " fixed deserialization failed!" << std::endl; error_count++; } leftover = fbd.bytes_left(); if(leftover != 0) { std::cout << "ERROR: " << name << " fixed leftover = " << leftover << std::endl; error_count++; } bool ok3 = (input == output); if(ok3) { if(verbose) std::cout << "OK: " << name << " fixed output matches" << std::endl; } else { std::cout << "ERROR: " << name << " fixed output mismatch:" << std::endl; std::cout << "Input: " << input << std::endl; std::cout << "Buffer: [" << exp_size << "]"; std::cout << std::hex; for(size_t i = 0; i < exp_size; i++) std::cout << ' ' << std::setfill('0') << std::setw(2) << (int)((unsigned char *)buffer)[i]; std::cout << std::dec << std::endl; #pragma GCC diagnostic push #ifdef __clang__ #pragma GCC diagnostic ignored "-Wuninitialized" #else #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" #endif std::cout << "Output: " << output << std::endl; #pragma GCC diagnostic pop error_count++; } free(buffer); } template <typename T> void do_test(const char *name, const T& input, size_t exp_size = 0) { exp_size = test_dynamic(name, input, exp_size); test_size(name, input, exp_size); test_fixed(name, input, exp_size); } template <typename T1, typename T2> struct Pair { T1 x; T2 y; Pair(void) : x(), y() {} Pair(T1 _x, T2 _y) : x(_x), y(_y) {} bool operator==(const Pair<T1,T2>& rhs) const { return (x == rhs.x) && (y == rhs.y); } friend std::ostream& operator<<(std::ostream& os, const Pair<T1, T2>& p) { return os << '<' << p.x << ',' << p.y << '>'; } }; #if 0 template <typename T1, typename T2> std::ostream& operator<<(std::ostream& os, const Pair<T1, T2>& p) { return os << '<' << p.x << ',' << p.y << '>'; } #endif typedef Pair<double, int> PODStruct; TYPE_IS_SERIALIZABLE(PODStruct); typedef Pair<double, float> PODPacked; template <typename S> bool operator<<(S& s, const PODPacked& p) { return (s << p.x) && (s << p.y); } template <typename S> bool operator>>(S& s, PODPacked& p) { return (s >> p.x) && (s >> p.y); } typedef Pair<double, char> PODPacked2; template <typename S> bool operator&(S& s, const PODPacked2& p) { return (s & p.x) && (s & p.y); } typedef Pair<PODPacked, int> PP2; template <typename S> bool operator&(S& s, const PP2& p) { return (s & p.x) && (s & p.y); } int main(int argc, const char *argv[]) { parse_args(argc, argv); { // a common failure mode for the serialization logic is infinite recursion, // so set very tight bounds on our stack size and run time struct rlimit rl; int ret; rl.rlim_cur = rl.rlim_max = 16384; // 16KB ret = setrlimit(RLIMIT_STACK, &rl); assert(ret == 0); rl.rlim_cur = rl.rlim_max = 5; // 5 seconds ret = setrlimit(RLIMIT_CPU, &rl); assert(ret == 0); } int x = 5; do_test("int", x, sizeof(int)); do_test("double", double(4.5), sizeof(double)); //void *f = &x; //do_test("void*", f, sizeof(void *)); do_test("pod struct", PODStruct(6.5, 7), sizeof(PODStruct)); do_test("pod packed", PODPacked(8.5, 9.1), 12 /* not sizeof(PODPacked)*/); do_test("pod packed2", PODPacked2(10.5, 'z'), 9 /* not sizeof(PODPacked2)*/); do_test("pp2", PP2(PODPacked(44.3, 1), 9), 16 /* not sizeof(PP2) */); std::vector<int> a(3); a[0] = 1; a[1] = 2; a[2] = 3; do_test("vector<int>", a, sizeof(size_t) + a.size() * sizeof(int)); std::vector<PODStruct> a2(1); a2[0] = PODStruct(3, 4); do_test("vector<PODStruct>", a2, sizeof(size_t) + a2.size() * sizeof(PODStruct)); std::vector<PODPacked> a3(1); a3[0] = PODPacked(3, 4); do_test("vector<PODPacked>", a3, sizeof(size_t) + 12 /* not sizeof(PODPacked)*/); std::vector<PODPacked2> a4(1); a4[0] = PODPacked2(3, 4); do_test("vector<PODPacked2>", a4, sizeof(size_t) + 9 /* not sizeof(PODPacked2)*/); std::list<int> b; b.push_back(4); b.push_back(5); b.push_back(6); b.push_back(7); do_test("list<int>", b, sizeof(size_t) + b.size() * sizeof(int)); std::map<int, double> c; c[8] = 1.1; c[9] = 2.2; c[10] = 3.3; do_test("map<int,double>", c, sizeof(size_t) + c.size() * 16 /*alignment*/); std::vector<std::string> ss; ss.push_back("Hello"); ss.push_back("World"); do_test("vector<string>", ss, sizeof(size_t) + 12 + 9); std::set<int> s; s.insert(4); s.insert(2); s.insert(11); do_test("set<int>", s, sizeof(size_t) + s.size() * sizeof(int)); if(error_count > 0) { std::cout << "ERRORS FOUND" << std::endl; exit(1); } else { std::cout << "all tests passed" << std::endl; exit(0); } } <|endoftext|>
<commit_before>//===- llvm-profdata.cpp - LLVM profile data tool -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // llvm-profdata merges .profdata files. // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringRef.h" #include "llvm/ProfileData/InstrProfReader.h" #include "llvm/ProfileData/InstrProfWriter.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; static void exitWithError(const Twine &Message, StringRef Whence = "") { errs() << "error: "; if (!Whence.empty()) errs() << Whence << ": "; errs() << Message << "\n"; ::exit(1); } int merge_main(int argc, const char *argv[]) { cl::list<std::string> Inputs(cl::Positional, cl::Required, cl::OneOrMore, cl::desc("<filenames...>")); cl::opt<std::string> OutputFilename("output", cl::value_desc("output"), cl::init("-"), cl::desc("Output file")); cl::alias OutputFilenameA("o", cl::desc("Alias for --output"), cl::aliasopt(OutputFilename)); cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n"); if (OutputFilename.empty()) OutputFilename = "-"; std::string ErrorInfo; // FIXME: F_Text would be available if line_iterator could accept CRLF. raw_fd_ostream Output(OutputFilename.data(), ErrorInfo, sys::fs::F_None); if (!ErrorInfo.empty()) exitWithError(ErrorInfo, OutputFilename); InstrProfWriter Writer; for (const auto &Filename : Inputs) { std::unique_ptr<InstrProfReader> Reader; if (error_code ec = InstrProfReader::create(Filename, Reader)) exitWithError(ec.message(), Filename); for (const auto &I : *Reader) if (error_code EC = Writer.addFunctionCounts(I.Name, I.Hash, I.Counts)) errs() << Filename << ": " << I.Name << ": " << EC.message() << "\n"; if (Reader->hasError()) exitWithError(Reader->getError().message(), Filename); } Writer.write(Output); return 0; } struct HashPrinter { uint64_t Hash; HashPrinter(uint64_t Hash) : Hash(Hash) {} void print(raw_ostream &OS) const { char Buf[18], *Cur = Buf; *Cur++ = '0'; *Cur++ = 'x'; for (unsigned I = 16; I;) { char Digit = 0xF & (Hash >> (--I * 4)); *Cur++ = (Digit < 10 ? '0' + Digit : 'A' + Digit - 10); } OS.write(Buf, 18); } }; static raw_ostream &operator<<(raw_ostream &OS, const HashPrinter &Hash) { Hash.print(OS); return OS; } int show_main(int argc, const char *argv[]) { cl::opt<std::string> Filename(cl::Positional, cl::Required, cl::desc("<profdata-file>")); cl::opt<bool> ShowCounts("counts", cl::init(false), cl::desc("Show counter values for shown functions")); cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false), cl::desc("Details for every function")); cl::opt<std::string> ShowFunction("function", cl::desc("Details for matching functions")); cl::opt<std::string> OutputFilename("output", cl::value_desc("output"), cl::init("-"), cl::desc("Output file")); cl::alias OutputFilenameA("o", cl::desc("Alias for --output"), cl::aliasopt(OutputFilename)); cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n"); std::unique_ptr<InstrProfReader> Reader; if (error_code EC = InstrProfReader::create(Filename, Reader)) exitWithError(EC.message(), Filename); if (OutputFilename.empty()) OutputFilename = "-"; std::string ErrorInfo; raw_fd_ostream OS(OutputFilename.data(), ErrorInfo, sys::fs::F_Text); if (!ErrorInfo.empty()) exitWithError(ErrorInfo, OutputFilename); if (ShowAllFunctions && !ShowFunction.empty()) errs() << "warning: -function argument ignored: showing all functions\n"; uint64_t MaxFunctionCount = 0, MaxBlockCount = 0; size_t ShownFunctions = 0, TotalFunctions = 0; for (const auto &Func : *Reader) { bool Show = ShowAllFunctions || (!ShowFunction.empty() && Func.Name.find(ShowFunction) != Func.Name.npos); ++TotalFunctions; if (Func.Counts[0] > MaxFunctionCount) MaxFunctionCount = Func.Counts[0]; if (Show) { if (!ShownFunctions) OS << "Counters:\n"; ++ShownFunctions; OS << " " << Func.Name << ":\n" << " Hash: " << HashPrinter(Func.Hash) << "\n" << " Counters: " << Func.Counts.size() << "\n" << " Function count: " << Func.Counts[0] << "\n"; } if (Show && ShowCounts) OS << " Block counts: ["; for (size_t I = 1, E = Func.Counts.size(); I < E; ++I) { if (Func.Counts[I] > MaxBlockCount) MaxBlockCount = Func.Counts[I]; if (Show && ShowCounts) OS << (I == 1 ? "" : ", ") << Func.Counts[I]; } if (Show && ShowCounts) OS << "]\n"; } if (ShowAllFunctions || !ShowFunction.empty()) OS << "Functions shown: " << ShownFunctions << "\n"; OS << "Total functions: " << TotalFunctions << "\n"; OS << "Maximum function count: " << MaxFunctionCount << "\n"; OS << "Maximum internal block count: " << MaxBlockCount << "\n"; return 0; } int main(int argc, const char *argv[]) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. StringRef ProgName(sys::path::filename(argv[0])); if (argc > 1) { int (*func)(int, const char *[]) = 0; if (strcmp(argv[1], "merge") == 0) func = merge_main; else if (strcmp(argv[1], "show") == 0) func = show_main; if (func) { std::string Invocation(ProgName.str() + " " + argv[1]); argv[1] = Invocation.c_str(); return func(argc - 1, argv + 1); } if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 || strcmp(argv[1], "--help") == 0) { errs() << "OVERVIEW: LLVM profile data tools\n\n" << "USAGE: " << ProgName << " <command> [args...]\n" << "USAGE: " << ProgName << " <command> -help\n\n" << "Available commands: merge, show\n"; return 0; } } if (argc < 2) errs() << ProgName << ": No command specified!\n"; else errs() << ProgName << ": Unknown command!\n"; errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n"; return 1; } <commit_msg>llvm-profdata: Use Format.h instead of handrolling a formatter<commit_after>//===- llvm-profdata.cpp - LLVM profile data tool -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // llvm-profdata merges .profdata files. // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringRef.h" #include "llvm/ProfileData/InstrProfReader.h" #include "llvm/ProfileData/InstrProfWriter.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Format.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; static void exitWithError(const Twine &Message, StringRef Whence = "") { errs() << "error: "; if (!Whence.empty()) errs() << Whence << ": "; errs() << Message << "\n"; ::exit(1); } int merge_main(int argc, const char *argv[]) { cl::list<std::string> Inputs(cl::Positional, cl::Required, cl::OneOrMore, cl::desc("<filenames...>")); cl::opt<std::string> OutputFilename("output", cl::value_desc("output"), cl::init("-"), cl::desc("Output file")); cl::alias OutputFilenameA("o", cl::desc("Alias for --output"), cl::aliasopt(OutputFilename)); cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n"); if (OutputFilename.empty()) OutputFilename = "-"; std::string ErrorInfo; // FIXME: F_Text would be available if line_iterator could accept CRLF. raw_fd_ostream Output(OutputFilename.data(), ErrorInfo, sys::fs::F_None); if (!ErrorInfo.empty()) exitWithError(ErrorInfo, OutputFilename); InstrProfWriter Writer; for (const auto &Filename : Inputs) { std::unique_ptr<InstrProfReader> Reader; if (error_code ec = InstrProfReader::create(Filename, Reader)) exitWithError(ec.message(), Filename); for (const auto &I : *Reader) if (error_code EC = Writer.addFunctionCounts(I.Name, I.Hash, I.Counts)) errs() << Filename << ": " << I.Name << ": " << EC.message() << "\n"; if (Reader->hasError()) exitWithError(Reader->getError().message(), Filename); } Writer.write(Output); return 0; } int show_main(int argc, const char *argv[]) { cl::opt<std::string> Filename(cl::Positional, cl::Required, cl::desc("<profdata-file>")); cl::opt<bool> ShowCounts("counts", cl::init(false), cl::desc("Show counter values for shown functions")); cl::opt<bool> ShowAllFunctions("all-functions", cl::init(false), cl::desc("Details for every function")); cl::opt<std::string> ShowFunction("function", cl::desc("Details for matching functions")); cl::opt<std::string> OutputFilename("output", cl::value_desc("output"), cl::init("-"), cl::desc("Output file")); cl::alias OutputFilenameA("o", cl::desc("Alias for --output"), cl::aliasopt(OutputFilename)); cl::ParseCommandLineOptions(argc, argv, "LLVM profile data summary\n"); std::unique_ptr<InstrProfReader> Reader; if (error_code EC = InstrProfReader::create(Filename, Reader)) exitWithError(EC.message(), Filename); if (OutputFilename.empty()) OutputFilename = "-"; std::string ErrorInfo; raw_fd_ostream OS(OutputFilename.data(), ErrorInfo, sys::fs::F_Text); if (!ErrorInfo.empty()) exitWithError(ErrorInfo, OutputFilename); if (ShowAllFunctions && !ShowFunction.empty()) errs() << "warning: -function argument ignored: showing all functions\n"; uint64_t MaxFunctionCount = 0, MaxBlockCount = 0; size_t ShownFunctions = 0, TotalFunctions = 0; for (const auto &Func : *Reader) { bool Show = ShowAllFunctions || (!ShowFunction.empty() && Func.Name.find(ShowFunction) != Func.Name.npos); ++TotalFunctions; if (Func.Counts[0] > MaxFunctionCount) MaxFunctionCount = Func.Counts[0]; if (Show) { if (!ShownFunctions) OS << "Counters:\n"; ++ShownFunctions; OS << " " << Func.Name << ":\n" << " Hash: " << format("0x%016" PRIx64, Func.Hash) << "\n" << " Counters: " << Func.Counts.size() << "\n" << " Function count: " << Func.Counts[0] << "\n"; } if (Show && ShowCounts) OS << " Block counts: ["; for (size_t I = 1, E = Func.Counts.size(); I < E; ++I) { if (Func.Counts[I] > MaxBlockCount) MaxBlockCount = Func.Counts[I]; if (Show && ShowCounts) OS << (I == 1 ? "" : ", ") << Func.Counts[I]; } if (Show && ShowCounts) OS << "]\n"; } if (ShowAllFunctions || !ShowFunction.empty()) OS << "Functions shown: " << ShownFunctions << "\n"; OS << "Total functions: " << TotalFunctions << "\n"; OS << "Maximum function count: " << MaxFunctionCount << "\n"; OS << "Maximum internal block count: " << MaxBlockCount << "\n"; return 0; } int main(int argc, const char *argv[]) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. StringRef ProgName(sys::path::filename(argv[0])); if (argc > 1) { int (*func)(int, const char *[]) = 0; if (strcmp(argv[1], "merge") == 0) func = merge_main; else if (strcmp(argv[1], "show") == 0) func = show_main; if (func) { std::string Invocation(ProgName.str() + " " + argv[1]); argv[1] = Invocation.c_str(); return func(argc - 1, argv + 1); } if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0 || strcmp(argv[1], "--help") == 0) { errs() << "OVERVIEW: LLVM profile data tools\n\n" << "USAGE: " << ProgName << " <command> [args...]\n" << "USAGE: " << ProgName << " <command> -help\n\n" << "Available commands: merge, show\n"; return 0; } } if (argc < 2) errs() << ProgName << ": No command specified!\n"; else errs() << ProgName << ": Unknown command!\n"; errs() << "USAGE: " << ProgName << " <merge|show> [args...]\n"; return 1; } <|endoftext|>
<commit_before>//===-- OProfileJITEventListener.cpp - Tell OProfile about JITted code ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a JITEventListener object that calls into OProfile to tell // it about JITted functions. For now, we only record function names and sizes, // but eventually we'll also record line number information. // // See http://oprofile.sourceforge.net/doc/devel/jit-interface.html for the // definition of the interface we're using. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "oprofile-jit-event-listener" #include "llvm/Function.h" #include "llvm/Analysis/DebugInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/ExecutionEngine/JITEventListener.h" #include "llvm/Support/Debug.h" #include "llvm/System/Errno.h" #include "llvm/Config/config.h" #include <stddef.h> using namespace llvm; #if USE_OPROFILE #include <opagent.h> namespace { class OProfileJITEventListener : public JITEventListener { op_agent_t Agent; public: OProfileJITEventListener(); ~OProfileJITEventListener(); virtual void NotifyFunctionEmitted(const Function &F, void *FnStart, size_t FnSize, const EmittedFunctionDetails &Details); virtual void NotifyFreeingMachineCode(const Function &F, void *OldPtr); }; OProfileJITEventListener::OProfileJITEventListener() : Agent(op_open_agent()) { if (Agent == NULL) { const std::string err_str = sys::StrError(); DOUT << "Failed to connect to OProfile agent: " << err_str << "\n"; } else { DOUT << "Connected to OProfile agent.\n"; } } OProfileJITEventListener::~OProfileJITEventListener() { if (Agent != NULL) { if (op_close_agent(Agent) == -1) { const std::string err_str = sys::StrError(); DOUT << "Failed to disconnect from OProfile agent: " << err_str << "\n"; } else { DOUT << "Disconnected from OProfile agent.\n"; } } } class FilenameCache { // Holds the filename of each CompileUnit, so that we can pass the // pointer into oprofile. These char*s are freed in the destructor. DenseMap<GlobalVariable*, char*> Filenames; // Used as the scratch space in DICompileUnit::getFilename(). std::string TempFilename; public: const char* getFilename(GlobalVariable *CompileUnit) { char *&Filename = Filenames[CompileUnit]; if (Filename == NULL) { DICompileUnit CU(CompileUnit); Filename = strdup(CU.getFilename(TempFilename).c_str()); } return Filename; } ~FilenameCache() { for (DenseMap<GlobalVariable*, char*>::iterator I = Filenames.begin(), E = Filenames.end(); I != E;++I) { free(I->second); } } }; static debug_line_info LineStartToOProfileFormat( const MachineFunction &MF, FilenameCache &Filenames, uintptr_t Address, DebugLoc Loc) { debug_line_info Result; Result.vma = Address; const DebugLocTuple& tuple = MF.getDebugLocTuple(Loc); Result.lineno = tuple.Line; Result.filename = Filenames.getFilename(tuple.CompileUnit); DOUT << "Mapping " << reinterpret_cast<void*>(Result.vma) << " to " << Result.filename << ":" << Result.lineno << "\n"; return Result; } // Adds the just-emitted function to the symbol table. void OProfileJITEventListener::NotifyFunctionEmitted( const Function &F, void *FnStart, size_t FnSize, const EmittedFunctionDetails &Details) { assert(F.hasName() && FnStart != 0 && "Bad symbol to add"); if (op_write_native_code(Agent, F.getName().data(), reinterpret_cast<uint64_t>(FnStart), FnStart, FnSize) == -1) { DEBUG(errs() << "Failed to tell OProfile about native function " << Fn.getName() << " at [" << FnStart << "-" << ((char*)FnStart + FnSize) << "]\n"); return; } // Now we convert the line number information from the address/DebugLoc format // in Details to the address/filename/lineno format that OProfile expects. // OProfile 0.9.4 (and maybe later versions) has a bug that causes it to // ignore line numbers for addresses above 4G. FilenameCache Filenames; std::vector<debug_line_info> LineInfo; LineInfo.reserve(1 + Details.LineStarts.size()); if (!Details.MF->getDefaultDebugLoc().isUnknown()) { LineInfo.push_back(LineStartToOProfileFormat( *Details.MF, Filenames, reinterpret_cast<uintptr_t>(FnStart), Details.MF->getDefaultDebugLoc())); } for (std::vector<EmittedFunctionDetails::LineStart>::const_iterator I = Details.LineStarts.begin(), E = Details.LineStarts.end(); I != E; ++I) { LineInfo.push_back(LineStartToOProfileFormat( *Details.MF, Filenames, I->Address, I->Loc)); } if (!LineInfo.empty()) { if (op_write_debug_line_info(Agent, FnStart, LineInfo.size(), &*LineInfo.begin()) == -1) { DEBUG(errs() << "Failed to tell OProfile about line numbers for native function " << F.getName() << " at [" << FnStart << "-" << ((char*)FnStart + FnSize) << "]\n"); } } } // Removes the to-be-deleted function from the symbol table. void OProfileJITEventListener::NotifyFreeingMachineCode( const Function &F, void *FnStart) { assert(FnStart && "Invalid function pointer"); if (op_unload_native_code(Agent, reinterpret_cast<uint64_t>(FnStart)) == -1) { DOUT << "Failed to tell OProfile about unload of native function " << F.getName() << " at " << FnStart << "\n"; } } } // anonymous namespace. namespace llvm { JITEventListener *createOProfileJITEventListener() { return new OProfileJITEventListener; } } #else // USE_OPROFILE namespace llvm { // By defining this to return NULL, we can let clients call it unconditionally, // even if they haven't configured with the OProfile libraries. JITEventListener *createOProfileJITEventListener() { return NULL; } } // namespace llvm #endif // USE_OPROFILE <commit_msg>Fix the build for people with oprofile installed.<commit_after>//===-- OProfileJITEventListener.cpp - Tell OProfile about JITted code ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a JITEventListener object that calls into OProfile to tell // it about JITted functions. For now, we only record function names and sizes, // but eventually we'll also record line number information. // // See http://oprofile.sourceforge.net/doc/devel/jit-interface.html for the // definition of the interface we're using. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "oprofile-jit-event-listener" #include "llvm/Function.h" #include "llvm/Analysis/DebugInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/ExecutionEngine/JITEventListener.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Errno.h" #include "llvm/Config/config.h" #include <stddef.h> using namespace llvm; #if USE_OPROFILE #include <opagent.h> namespace { class OProfileJITEventListener : public JITEventListener { op_agent_t Agent; public: OProfileJITEventListener(); ~OProfileJITEventListener(); virtual void NotifyFunctionEmitted(const Function &F, void *FnStart, size_t FnSize, const EmittedFunctionDetails &Details); virtual void NotifyFreeingMachineCode(const Function &F, void *OldPtr); }; OProfileJITEventListener::OProfileJITEventListener() : Agent(op_open_agent()) { if (Agent == NULL) { const std::string err_str = sys::StrError(); DOUT << "Failed to connect to OProfile agent: " << err_str << "\n"; } else { DOUT << "Connected to OProfile agent.\n"; } } OProfileJITEventListener::~OProfileJITEventListener() { if (Agent != NULL) { if (op_close_agent(Agent) == -1) { const std::string err_str = sys::StrError(); DOUT << "Failed to disconnect from OProfile agent: " << err_str << "\n"; } else { DOUT << "Disconnected from OProfile agent.\n"; } } } class FilenameCache { // Holds the filename of each CompileUnit, so that we can pass the // pointer into oprofile. These char*s are freed in the destructor. DenseMap<GlobalVariable*, char*> Filenames; // Used as the scratch space in DICompileUnit::getFilename(). std::string TempFilename; public: const char* getFilename(GlobalVariable *CompileUnit) { char *&Filename = Filenames[CompileUnit]; if (Filename == NULL) { DICompileUnit CU(CompileUnit); Filename = strdup(CU.getFilename(TempFilename).c_str()); } return Filename; } ~FilenameCache() { for (DenseMap<GlobalVariable*, char*>::iterator I = Filenames.begin(), E = Filenames.end(); I != E;++I) { free(I->second); } } }; static debug_line_info LineStartToOProfileFormat( const MachineFunction &MF, FilenameCache &Filenames, uintptr_t Address, DebugLoc Loc) { debug_line_info Result; Result.vma = Address; const DebugLocTuple& tuple = MF.getDebugLocTuple(Loc); Result.lineno = tuple.Line; Result.filename = Filenames.getFilename(tuple.CompileUnit); DOUT << "Mapping " << reinterpret_cast<void*>(Result.vma) << " to " << Result.filename << ":" << Result.lineno << "\n"; return Result; } // Adds the just-emitted function to the symbol table. void OProfileJITEventListener::NotifyFunctionEmitted( const Function &F, void *FnStart, size_t FnSize, const EmittedFunctionDetails &Details) { assert(F.hasName() && FnStart != 0 && "Bad symbol to add"); if (op_write_native_code(Agent, F.getName().data(), reinterpret_cast<uint64_t>(FnStart), FnStart, FnSize) == -1) { DEBUG(errs() << "Failed to tell OProfile about native function " << F.getName() << " at [" << FnStart << "-" << ((char*)FnStart + FnSize) << "]\n"); return; } // Now we convert the line number information from the address/DebugLoc format // in Details to the address/filename/lineno format that OProfile expects. // OProfile 0.9.4 (and maybe later versions) has a bug that causes it to // ignore line numbers for addresses above 4G. FilenameCache Filenames; std::vector<debug_line_info> LineInfo; LineInfo.reserve(1 + Details.LineStarts.size()); if (!Details.MF->getDefaultDebugLoc().isUnknown()) { LineInfo.push_back(LineStartToOProfileFormat( *Details.MF, Filenames, reinterpret_cast<uintptr_t>(FnStart), Details.MF->getDefaultDebugLoc())); } for (std::vector<EmittedFunctionDetails::LineStart>::const_iterator I = Details.LineStarts.begin(), E = Details.LineStarts.end(); I != E; ++I) { LineInfo.push_back(LineStartToOProfileFormat( *Details.MF, Filenames, I->Address, I->Loc)); } if (!LineInfo.empty()) { if (op_write_debug_line_info(Agent, FnStart, LineInfo.size(), &*LineInfo.begin()) == -1) { DEBUG(errs() << "Failed to tell OProfile about line numbers for native function " << F.getName() << " at [" << FnStart << "-" << ((char*)FnStart + FnSize) << "]\n"); } } } // Removes the to-be-deleted function from the symbol table. void OProfileJITEventListener::NotifyFreeingMachineCode( const Function &F, void *FnStart) { assert(FnStart && "Invalid function pointer"); if (op_unload_native_code(Agent, reinterpret_cast<uint64_t>(FnStart)) == -1) { DEBUG(errs() << "Failed to tell OProfile about unload of native function " << F.getName() << " at " << FnStart << "\n"); } } } // anonymous namespace. namespace llvm { JITEventListener *createOProfileJITEventListener() { return new OProfileJITEventListener; } } #else // USE_OPROFILE namespace llvm { // By defining this to return NULL, we can let clients call it unconditionally, // even if they haven't configured with the OProfile libraries. JITEventListener *createOProfileJITEventListener() { return NULL; } } // namespace llvm #endif // USE_OPROFILE <|endoftext|>
<commit_before>/************************************************************************* * * Copyright (c) 2011-2012 Kohei Yoshida * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * ************************************************************************/ #ifndef __MDDS_GRID_MAP_COLUMN_HPP__ #define __MDDS_GRID_MAP_COLUMN_HPP__ #include "mdds/default_deleter.hpp" #include "mdds/compat/unique_ptr.hpp" #include <vector> #include <algorithm> #include <cassert> #include <boost/noncopyable.hpp> namespace mdds { namespace __gridmap { /** * Each column consists of a series of blocks, and each block stores a * series of non-empty cells of identical type. */ template<typename _Trait> class column { public: typedef typename _Trait::cell_type cell_type; typedef typename _Trait::cell_category_type cell_category_type; typedef typename _Trait::row_key_type row_key_type; private: typedef typename _Trait::cell_delete_handler cell_delete_handler; /** * Data for non-empty block. */ struct block_data : boost::noncopyable { cell_category_type m_type; std::vector<cell_type*> m_cells; block_data(cell_category_type _type, size_t _init_size = 0); ~block_data(); }; struct block : boost::noncopyable { row_key_type m_size; bool m_empty; block_data* mp_data; block(); block(row_key_type _size); ~block(); }; column(); // disabled public: column(row_key_type max_row); ~column(); void set_cell(row_key_type row, cell_category_type cat, cell_type* cell); const cell_type* get_cell(row_key_type row) const; private: std::vector<block*> m_blocks; row_key_type m_max_row; }; template<typename _Trait> column<_Trait>::block_data::block_data(cell_category_type _type, size_t _init_size) : m_type(_type), m_cells(_init_size, NULL) {} template<typename _Trait> column<_Trait>::block_data::~block_data() { std::for_each(m_cells.begin(), m_cells.end(), cell_delete_handler()); } template<typename _Trait> column<_Trait>::block::block() : m_size(0), m_empty(true), mp_data(NULL) {} template<typename _Trait> column<_Trait>::block::block(row_key_type _size) : m_size(_size), m_empty(true), mp_data(NULL) {} template<typename _Trait> column<_Trait>::block::~block() { delete mp_data; } template<typename _Trait> column<_Trait>::column(row_key_type max_row) : m_max_row(max_row) { // Initialize with an empty block that spans from 0 to max. m_blocks.push_back(new block(max_row)); } template<typename _Trait> column<_Trait>::~column() { std::for_each(m_blocks.begin(), m_blocks.end(), default_deleter<block>()); } template<typename _Trait> void column<_Trait>::set_cell(row_key_type row, cell_category_type cat, cell_type* cell) { unique_ptr<cell_type, cell_delete_handler> p(cell); } template<typename _Trait> const typename column<_Trait>::cell_type* column<_Trait>::get_cell(row_key_type row) const { row_key_type cur_index = 0; for (size_t i = 0, n = m_blocks.size(); i < n; ++i) { const block& blk = *m_blocks[i]; if (row >= cur_index + blk.m_size) { // Specified row is not in this block. cur_index += blk.m_size; continue; } if (blk.m_empty) // empty cell block. return NULL; assert(blk.mp_data); // data for non-empty blocks should never be NULL. assert(blk.m_size == static_cast<row_key_type>(blk.mp_data->m_cells.size())); row_key_type idx = row - cur_index; return blk.mp_data->m_cells[idx]; } return NULL; } }} #endif <commit_msg>Some comments...<commit_after>/************************************************************************* * * Copyright (c) 2011-2012 Kohei Yoshida * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * ************************************************************************/ #ifndef __MDDS_GRID_MAP_COLUMN_HPP__ #define __MDDS_GRID_MAP_COLUMN_HPP__ #include "mdds/default_deleter.hpp" #include "mdds/compat/unique_ptr.hpp" #include <vector> #include <algorithm> #include <cassert> #include <boost/noncopyable.hpp> namespace mdds { namespace __gridmap { /** * Each column consists of a series of blocks, and each block stores a * series of non-empty cells of identical type. */ template<typename _Trait> class column { public: typedef typename _Trait::cell_type cell_type; typedef typename _Trait::cell_category_type cell_category_type; typedef typename _Trait::row_key_type row_key_type; private: typedef typename _Trait::cell_delete_handler cell_delete_handler; /** * Data for non-empty block. Cells are stored here. */ struct block_data : boost::noncopyable { cell_category_type m_type; std::vector<cell_type*> m_cells; block_data(cell_category_type _type, size_t _init_size = 0); ~block_data(); }; /** * Empty or non-empty block. */ struct block : boost::noncopyable { row_key_type m_size; block_data* mp_data; bool m_empty; block(); block(row_key_type _size); ~block(); }; column(); // disabled public: column(row_key_type max_row); ~column(); void set_cell(row_key_type row, cell_category_type cat, cell_type* cell); const cell_type* get_cell(row_key_type row) const; private: std::vector<block*> m_blocks; row_key_type m_max_row; }; template<typename _Trait> column<_Trait>::block_data::block_data(cell_category_type _type, size_t _init_size) : m_type(_type), m_cells(_init_size, NULL) {} template<typename _Trait> column<_Trait>::block_data::~block_data() { std::for_each(m_cells.begin(), m_cells.end(), cell_delete_handler()); } template<typename _Trait> column<_Trait>::block::block() : m_size(0), m_empty(true), mp_data(NULL) {} template<typename _Trait> column<_Trait>::block::block(row_key_type _size) : m_size(_size), mp_data(NULL), m_empty(true) {} template<typename _Trait> column<_Trait>::block::~block() { delete mp_data; } template<typename _Trait> column<_Trait>::column(row_key_type max_row) : m_max_row(max_row) { // Initialize with an empty block that spans from 0 to max. m_blocks.push_back(new block(max_row)); } template<typename _Trait> column<_Trait>::~column() { std::for_each(m_blocks.begin(), m_blocks.end(), default_deleter<block>()); } template<typename _Trait> void column<_Trait>::set_cell(row_key_type row, cell_category_type cat, cell_type* cell) { unique_ptr<cell_type, cell_delete_handler> p(cell); // TODO: implement cell insertion... } template<typename _Trait> const typename column<_Trait>::cell_type* column<_Trait>::get_cell(row_key_type row) const { row_key_type cur_index = 0; for (size_t i = 0, n = m_blocks.size(); i < n; ++i) { const block& blk = *m_blocks[i]; if (row >= cur_index + blk.m_size) { // Specified row is not in this block. cur_index += blk.m_size; continue; } if (blk.m_empty) // empty cell block. return NULL; assert(blk.mp_data); // data for non-empty blocks should never be NULL. assert(blk.m_size == static_cast<row_key_type>(blk.mp_data->m_cells.size())); row_key_type idx = row - cur_index; return blk.mp_data->m_cells[idx]; } return NULL; } }} #endif <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Jolla Ltd. ** Contact: Dmitry Rozhkov <dmitry.rozhkov@jollamobile.com> ** ****************************************************************************/ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "downloadmanager.h" #include "qmozcontext.h" #include "browserpaths.h" #include <transferengineinterface.h> #include <transfertypes.h> #include <QDir> #include <QFile> #include <QDebug> #include <pwd.h> #include <grp.h> #include <unistd.h> static DownloadManager *gSingleton = 0; DownloadManager::DownloadManager() : QObject() , m_initialized(false) { m_transferClient = new TransferEngineInterface("org.nemo.transferengine", "/org/nemo/transferengine", QDBusConnection::sessionBus(), this); connect(QMozContext::GetInstance(), SIGNAL(recvObserve(const QString, const QVariant)), this, SLOT(recvObserve(const QString, const QVariant))); } DownloadManager::~DownloadManager() { gSingleton = 0; } void DownloadManager::recvObserve(const QString message, const QVariant data) { if (message == "download-manager-initialized" && !m_initialized) { m_initialized = true; emit initializedChanged(); } else if (message != "embed:download") { // here we are interested in download messages only return; } QVariantMap dataMap(data.toMap()); QString msg(dataMap.value("msg").toString()); qulonglong downloadId(dataMap.value("id").toULongLong()); if (msg == "dl-start" && m_download2transferMap.contains(downloadId)) { // restart existing transfer m_transferClient->startTransfer(m_download2transferMap.value(downloadId)); m_statusCache.insert(downloadId, DownloadStarted); } else if (msg == "dl-start") { // create new transfer emit downloadStarted(); QStringList callback; callback << "org.sailfishos.browser" << "/" << "org.sailfishos.browser"; QDBusPendingReply<int> reply = m_transferClient->createDownload(dataMap.value("displayName").toString(), QString("image://theme/icon-launcher-browser"), QString("image://theme/icon-launcher-browser"), dataMap.value("targetPath").toString(), dataMap.value("mimeType").toString(), dataMap.value("size").toULongLong(), callback, QString("cancelTransfer"), QString("restartTransfer")); reply.waitForFinished(); if (reply.isError()) { qWarning() << "DownloadManager::recvObserve: failed to get transfer ID!" << reply.error(); return; } int transferId(reply.value()); m_download2transferMap.insert(downloadId, transferId); m_transfer2downloadMap.insert(transferId, downloadId); m_transferClient->startTransfer(transferId); m_statusCache.insert(downloadId, DownloadStarted); } else if (msg == "dl-progress") { qreal progress(dataMap.value("percent").toULongLong() / 100.0); m_transferClient->updateTransferProgress(m_download2transferMap.value(downloadId), progress); } else if (msg == "dl-done") { m_transferClient->finishTransfer(m_download2transferMap.value(downloadId), TransferEngineData::TransferFinished, QString("success")); m_statusCache.insert(downloadId, DownloadDone); checkAllTransfers(); QString targetPath = dataMap.value("targetPath").toString(); QFileInfo fileInfo(targetPath); if (fileInfo.completeSuffix() == QLatin1Literal("myapp")) { QString packageName("com.aptoide.partners"); QString apkName = aptoideApk(packageName); if (apkName.isEmpty()) { qWarning() << "No aptoide client installed to handle package: " + targetPath; return; } if (moveMyAppPackage(targetPath)) { QProcess::execute("/usr/bin/apkd-launcher", QStringList() << apkName << QString("%1/%1.AptoideJollaSupport").arg(packageName)); } } } else if (msg == "dl-fail") { m_transferClient->finishTransfer(m_download2transferMap.value(downloadId), TransferEngineData::TransferInterrupted, QString("browser failure")); m_statusCache.insert(downloadId, DownloadFailed); checkAllTransfers(); } else if (msg == "dl-cancel") { m_transferClient->finishTransfer(m_download2transferMap.value(downloadId), TransferEngineData::TransferCanceled, QString("download canceled")); m_statusCache.insert(downloadId, DownloadCanceled); checkAllTransfers(); } } bool DownloadManager::moveMyAppPackage(QString path) { QString aptoideDownloadPath = QString("%1/.aptoide/").arg(BrowserPaths::downloadLocation()); QDir dir(aptoideDownloadPath); if (!dir.exists()) { if (!dir.mkpath(aptoideDownloadPath)) { qWarning() << "Failed to create path for myapp download, aborting"; return false; } uid_t uid = getuid(); // assumes that correct groupname is same as username (e.g. nemo:nemo) int gid = getgrnam(getpwuid(uid)->pw_name)->gr_gid; int success = chown(aptoideDownloadPath.toLatin1().data(), uid, gid); Q_UNUSED(success); QFile::Permissions permissions(QFile::ExeOwner | QFile::ExeGroup | QFile::ReadOwner | QFile::WriteOwner | QFile::ReadGroup | QFile::WriteGroup); QFile::setPermissions(aptoideDownloadPath, permissions); } QFile file(path); QFileInfo fileInfo(file); QString newPath(aptoideDownloadPath + fileInfo.fileName()); QFile obsoleteFile(newPath); if (obsoleteFile.exists() && !obsoleteFile.remove()) { qWarning() << "Failed to remove obsolete myapp file, aborting"; return false; } if (!file.rename(newPath)) { qWarning() << "Failed to move myapp file to aptoide's folder, aborting"; // Avoid generating ~/Downloads/<name>(2).myapp file in case user downloads the same file again file.remove(); return false; } return true; } QString DownloadManager::aptoideApk(QString packageName) { QString apkPath("/data/app/"); QString aptoideApk = QString("%1/%2.apk").arg(apkPath, packageName); if (!QFile(aptoideApk).exists()) { QDir apkDir(apkPath, QString("%1*.apk").arg(packageName)); if (apkDir.count() > 0) { aptoideApk = QString("%1/%2").arg(apkPath, apkDir.entryList().last()); } else { return QString(); } } return aptoideApk; } void DownloadManager::cancelActiveTransfers() { foreach (qulonglong downloadId, m_statusCache.keys()) { if (m_statusCache.value(downloadId) == DownloadStarted) { cancelTransfer(m_download2transferMap.value(downloadId)); } } } void DownloadManager::cancelTransfer(int transferId) { if (m_transfer2downloadMap.contains(transferId)) { QVariantMap data; data.insert("msg", "cancelDownload"); data.insert("id", m_transfer2downloadMap.value(transferId)); QMozContext::GetInstance()->sendObserve(QString("embedui:download"), QVariant(data)); } else { m_transferClient->finishTransfer(transferId, TransferEngineData::TransferInterrupted, QString("Transfer got unavailable")); } } void DownloadManager::restartTransfer(int transferId) { if (m_transfer2downloadMap.contains(transferId)) { QVariantMap data; data.insert("msg", "retryDownload"); data.insert("id", m_transfer2downloadMap.value(transferId)); QMozContext::GetInstance()->sendObserve(QString("embedui:download"), QVariant(data)); } else { m_transferClient->finishTransfer(transferId, TransferEngineData::TransferInterrupted, QString("Transfer got unavailable")); } } DownloadManager *DownloadManager::instance() { if (!gSingleton) { gSingleton = new DownloadManager(); } return gSingleton; } bool DownloadManager::existActiveTransfers() { bool exists(false); foreach (Status st, m_statusCache) { if (st == DownloadStarted) { exists = true; break; } } return exists; } bool DownloadManager::initialized() { return m_initialized; } void DownloadManager::checkAllTransfers() { if (!existActiveTransfers()) { emit allTransfersCompleted(); } } <commit_msg>Add QLatin1Literal and QStringLiteral when QString would be needed<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Jolla Ltd. ** Contact: Dmitry Rozhkov <dmitry.rozhkov@jollamobile.com> ** ****************************************************************************/ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "downloadmanager.h" #include "qmozcontext.h" #include "browserpaths.h" #include <transferengineinterface.h> #include <transfertypes.h> #include <QDir> #include <QFile> #include <QDebug> #include <pwd.h> #include <grp.h> #include <unistd.h> static DownloadManager *gSingleton = 0; DownloadManager::DownloadManager() : QObject() , m_initialized(false) { m_transferClient = new TransferEngineInterface("org.nemo.transferengine", "/org/nemo/transferengine", QDBusConnection::sessionBus(), this); connect(QMozContext::GetInstance(), SIGNAL(recvObserve(const QString, const QVariant)), this, SLOT(recvObserve(const QString, const QVariant))); } DownloadManager::~DownloadManager() { gSingleton = 0; } void DownloadManager::recvObserve(const QString message, const QVariant data) { if (message == "download-manager-initialized" && !m_initialized) { m_initialized = true; emit initializedChanged(); } else if (message != "embed:download") { // here we are interested in download messages only return; } QVariantMap dataMap(data.toMap()); QString msg(dataMap.value("msg").toString()); qulonglong downloadId(dataMap.value("id").toULongLong()); if (msg == QLatin1Literal("dl-start") && m_download2transferMap.contains(downloadId)) { // restart existing transfer m_transferClient->startTransfer(m_download2transferMap.value(downloadId)); m_statusCache.insert(downloadId, DownloadStarted); } else if (msg == QLatin1Literal("dl-start")) { // create new transfer emit downloadStarted(); QStringList callback; QLatin1Literal browserInterface("org.sailfishos.browser"); callback << browserInterface << QLatin1Literal("/") << browserInterface; QDBusPendingReply<int> reply = m_transferClient->createDownload(dataMap.value("displayName").toString(), QString("image://theme/icon-launcher-browser"), QString("image://theme/icon-launcher-browser"), dataMap.value("targetPath").toString(), dataMap.value("mimeType").toString(), dataMap.value("size").toULongLong(), callback, QString("cancelTransfer"), QString("restartTransfer")); reply.waitForFinished(); if (reply.isError()) { qWarning() << "DownloadManager::recvObserve: failed to get transfer ID!" << reply.error(); return; } int transferId(reply.value()); m_download2transferMap.insert(downloadId, transferId); m_transfer2downloadMap.insert(transferId, downloadId); m_transferClient->startTransfer(transferId); m_statusCache.insert(downloadId, DownloadStarted); } else if (msg == QLatin1Literal("dl-progress")) { qreal progress(dataMap.value(QStringLiteral("percent")).toULongLong() / 100.0); m_transferClient->updateTransferProgress(m_download2transferMap.value(downloadId), progress); } else if (msg == QLatin1Literal("dl-done")) { m_transferClient->finishTransfer(m_download2transferMap.value(downloadId), TransferEngineData::TransferFinished, QString("success")); m_statusCache.insert(downloadId, DownloadDone); checkAllTransfers(); QString targetPath = dataMap.value(QStringLiteral("targetPath")).toString(); QFileInfo fileInfo(targetPath); if (fileInfo.completeSuffix() == QLatin1Literal("myapp")) { QString packageName("com.aptoide.partners"); QString apkName = aptoideApk(packageName); if (apkName.isEmpty()) { qWarning() << "No aptoide client installed to handle package: " + targetPath; return; } if (moveMyAppPackage(targetPath)) { QProcess::execute("/usr/bin/apkd-launcher", QStringList() << apkName << QString("%1/%1.AptoideJollaSupport").arg(packageName)); } } } else if (msg == QLatin1Literal("dl-fail")) { m_transferClient->finishTransfer(m_download2transferMap.value(downloadId), TransferEngineData::TransferInterrupted, QString("browser failure")); m_statusCache.insert(downloadId, DownloadFailed); checkAllTransfers(); } else if (msg == QLatin1Literal("dl-cancel")) { m_transferClient->finishTransfer(m_download2transferMap.value(downloadId), TransferEngineData::TransferCanceled, QString("download canceled")); m_statusCache.insert(downloadId, DownloadCanceled); checkAllTransfers(); } } bool DownloadManager::moveMyAppPackage(QString path) { QString aptoideDownloadPath = QString("%1/.aptoide/").arg(BrowserPaths::downloadLocation()); QDir dir(aptoideDownloadPath); if (!dir.exists()) { if (!dir.mkpath(aptoideDownloadPath)) { qWarning() << "Failed to create path for myapp download, aborting"; return false; } uid_t uid = getuid(); // assumes that correct groupname is same as username (e.g. nemo:nemo) int gid = getgrnam(getpwuid(uid)->pw_name)->gr_gid; int success = chown(aptoideDownloadPath.toLatin1().data(), uid, gid); Q_UNUSED(success); QFile::Permissions permissions(QFile::ExeOwner | QFile::ExeGroup | QFile::ReadOwner | QFile::WriteOwner | QFile::ReadGroup | QFile::WriteGroup); QFile::setPermissions(aptoideDownloadPath, permissions); } QFile file(path); QFileInfo fileInfo(file); QString newPath(aptoideDownloadPath + fileInfo.fileName()); QFile obsoleteFile(newPath); if (obsoleteFile.exists() && !obsoleteFile.remove()) { qWarning() << "Failed to remove obsolete myapp file, aborting"; return false; } if (!file.rename(newPath)) { qWarning() << "Failed to move myapp file to aptoide's folder, aborting"; // Avoid generating ~/Downloads/<name>(2).myapp file in case user downloads the same file again file.remove(); return false; } return true; } QString DownloadManager::aptoideApk(QString packageName) { QString apkPath("/data/app/"); QString aptoideApk = QString("%1/%2.apk").arg(apkPath, packageName); if (!QFile(aptoideApk).exists()) { QDir apkDir(apkPath, QString("%1*.apk").arg(packageName)); if (apkDir.count() > 0) { aptoideApk = QString("%1/%2").arg(apkPath, apkDir.entryList().last()); } else { return QString(); } } return aptoideApk; } void DownloadManager::cancelActiveTransfers() { foreach (qulonglong downloadId, m_statusCache.keys()) { if (m_statusCache.value(downloadId) == DownloadStarted) { cancelTransfer(m_download2transferMap.value(downloadId)); } } } void DownloadManager::cancelTransfer(int transferId) { if (m_transfer2downloadMap.contains(transferId)) { QVariantMap data; data.insert("msg", "cancelDownload"); data.insert("id", m_transfer2downloadMap.value(transferId)); QMozContext::GetInstance()->sendObserve(QString("embedui:download"), QVariant(data)); } else { m_transferClient->finishTransfer(transferId, TransferEngineData::TransferInterrupted, QString("Transfer got unavailable")); } } void DownloadManager::restartTransfer(int transferId) { if (m_transfer2downloadMap.contains(transferId)) { QVariantMap data; data.insert("msg", "retryDownload"); data.insert("id", m_transfer2downloadMap.value(transferId)); QMozContext::GetInstance()->sendObserve(QString("embedui:download"), QVariant(data)); } else { m_transferClient->finishTransfer(transferId, TransferEngineData::TransferInterrupted, QString("Transfer got unavailable")); } } DownloadManager *DownloadManager::instance() { if (!gSingleton) { gSingleton = new DownloadManager(); } return gSingleton; } bool DownloadManager::existActiveTransfers() { bool exists(false); foreach (Status st, m_statusCache) { if (st == DownloadStarted) { exists = true; break; } } return exists; } bool DownloadManager::initialized() { return m_initialized; } void DownloadManager::checkAllTransfers() { if (!existActiveTransfers()) { emit allTransfersCompleted(); } } <|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 . */ #ifndef INCLUDED_O3TL_TYPED_FLAGS_SET_HXX #define INCLUDED_O3TL_TYPED_FLAGS_SET_HXX #include <sal/config.h> #include <cassert> #include <type_traits> namespace o3tl { template<typename T> struct typed_flags {}; #if defined __GNUC__ && __GNUC__ == 4 && __GNUC_MINOR__ <= 6 && \ !defined __clang__ #define O3TL_STD_UNDERLYING_TYPE_E unsigned int #else #define O3TL_STD_UNDERLYING_TYPE_E typename std::underlying_type<E>::type #endif /// Mark a (scoped) enumeration as a set of bit flags, with accompanying /// operations. /// /// template<> /// struct o3tl::typed_flags<TheE>: o3tl::is_typed_flags<TheE, TheM> {}; /// /// All relevant values must be non-negative. (Typically, the enumeration's /// underlying type will either be fixed and unsigned, or it will be unfixed--- /// and can thus default to a signed type---and all enumerators will have non- /// negative values.) /// /// \param E the enumeration type. /// \param M the all-bits-set value for the bit flags. template<typename E, O3TL_STD_UNDERLYING_TYPE_E M> struct is_typed_flags { static_assert( M >= 0, "is_typed_flags expects only non-negative bit values"); typedef E Self; class Wrap { public: explicit Wrap(O3TL_STD_UNDERLYING_TYPE_E value): value_(value) { assert(value >= 0); } operator E() { return static_cast<E>(value_); } #if !defined _MSC_VER || _MSC_VER > 1700 explicit #endif operator O3TL_STD_UNDERLYING_TYPE_E() { return value_; } #if !defined _MSC_VER || _MSC_VER > 1700 explicit #endif operator bool() { return value_ != 0; } private: O3TL_STD_UNDERLYING_TYPE_E value_; }; static O3TL_STD_UNDERLYING_TYPE_E const mask = M; }; } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator ~(E rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs) >= 0); return static_cast<typename o3tl::typed_flags<E>::Wrap>( o3tl::typed_flags<E>::mask & ~static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator ~( typename o3tl::typed_flags<E>::Wrap rhs) { return static_cast<typename o3tl::typed_flags<E>::Wrap>( o3tl::typed_flags<E>::mask & ~static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator &(E lhs, E rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) >= 0); assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs) >= 0); return static_cast<typename o3tl::typed_flags<E>::Wrap>( static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) & static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator &( E lhs, typename o3tl::typed_flags<E>::Wrap rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) >= 0); return static_cast<typename o3tl::typed_flags<E>::Wrap>( static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) & static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator &( typename o3tl::typed_flags<E>::Wrap lhs, E rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs) >= 0); return static_cast<typename o3tl::typed_flags<E>::Wrap>( static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) & static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator &( typename o3tl::typed_flags<E>::Wrap lhs, typename o3tl::typed_flags<E>::Wrap rhs) { return static_cast<typename o3tl::typed_flags<E>::Wrap>( static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) & static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator |(E lhs, E rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) >= 0); assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs) >= 0); return static_cast<typename o3tl::typed_flags<E>::Wrap>( static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) | static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator |( E lhs, typename o3tl::typed_flags<E>::Wrap rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) >= 0); return static_cast<typename o3tl::typed_flags<E>::Wrap>( static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) | static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator |( typename o3tl::typed_flags<E>::Wrap lhs, E rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs) >= 0); return static_cast<typename o3tl::typed_flags<E>::Wrap>( static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) | static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator |( typename o3tl::typed_flags<E>::Wrap lhs, typename o3tl::typed_flags<E>::Wrap rhs) { return static_cast<typename o3tl::typed_flags<E>::Wrap>( static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) | static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Self operator &=(E & lhs, E rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) >= 0); assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs) >= 0); lhs = lhs & rhs; return lhs; } template<typename E> inline typename o3tl::typed_flags<E>::Self operator &=( E & lhs, typename o3tl::typed_flags<E>::Wrap rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) >= 0); lhs = lhs & rhs; return lhs; } template<typename E> inline typename o3tl::typed_flags<E>::Self operator |=(E & lhs, E rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) >= 0); assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs) >= 0); lhs = lhs | rhs; return lhs; } template<typename E> inline typename o3tl::typed_flags<E>::Self operator |=( E & lhs, typename o3tl::typed_flags<E>::Wrap rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) >= 0); lhs = lhs | rhs; return lhs; } #undef O3TL_STD_UNDERLYING_TYPE_E #endif /* INCLUDED_O3TL_TYPED_FLAGS_SET_HXX */ /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>gcc4.7.3 complains about the asserts<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 . */ #ifndef INCLUDED_O3TL_TYPED_FLAGS_SET_HXX #define INCLUDED_O3TL_TYPED_FLAGS_SET_HXX #include <sal/config.h> #include <cassert> #include <type_traits> namespace o3tl { template<typename T> struct typed_flags {}; #if defined __GNUC__ && __GNUC__ == 4 && __GNUC_MINOR__ <= 7 && \ !defined __clang__ #define O3TL_STD_UNDERLYING_TYPE_E signed int #else #define O3TL_STD_UNDERLYING_TYPE_E typename std::underlying_type<E>::type #endif /// Mark a (scoped) enumeration as a set of bit flags, with accompanying /// operations. /// /// template<> /// struct o3tl::typed_flags<TheE>: o3tl::is_typed_flags<TheE, TheM> {}; /// /// All relevant values must be non-negative. (Typically, the enumeration's /// underlying type will either be fixed and unsigned, or it will be unfixed--- /// and can thus default to a signed type---and all enumerators will have non- /// negative values.) /// /// \param E the enumeration type. /// \param M the all-bits-set value for the bit flags. template<typename E, O3TL_STD_UNDERLYING_TYPE_E M> struct is_typed_flags { static_assert( M >= 0, "is_typed_flags expects only non-negative bit values"); typedef E Self; class Wrap { public: explicit Wrap(O3TL_STD_UNDERLYING_TYPE_E value): value_(value) { assert(value >= 0); } operator E() { return static_cast<E>(value_); } #if !defined _MSC_VER || _MSC_VER > 1700 explicit #endif operator O3TL_STD_UNDERLYING_TYPE_E() { return value_; } #if !defined _MSC_VER || _MSC_VER > 1700 explicit #endif operator bool() { return value_ != 0; } private: O3TL_STD_UNDERLYING_TYPE_E value_; }; static O3TL_STD_UNDERLYING_TYPE_E const mask = M; }; } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator ~(E rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs) >= 0); return static_cast<typename o3tl::typed_flags<E>::Wrap>( o3tl::typed_flags<E>::mask & ~static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator ~( typename o3tl::typed_flags<E>::Wrap rhs) { return static_cast<typename o3tl::typed_flags<E>::Wrap>( o3tl::typed_flags<E>::mask & ~static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator &(E lhs, E rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) >= 0); assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs) >= 0); return static_cast<typename o3tl::typed_flags<E>::Wrap>( static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) & static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator &( E lhs, typename o3tl::typed_flags<E>::Wrap rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) >= 0); return static_cast<typename o3tl::typed_flags<E>::Wrap>( static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) & static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator &( typename o3tl::typed_flags<E>::Wrap lhs, E rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs) >= 0); return static_cast<typename o3tl::typed_flags<E>::Wrap>( static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) & static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator &( typename o3tl::typed_flags<E>::Wrap lhs, typename o3tl::typed_flags<E>::Wrap rhs) { return static_cast<typename o3tl::typed_flags<E>::Wrap>( static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) & static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator |(E lhs, E rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) >= 0); assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs) >= 0); return static_cast<typename o3tl::typed_flags<E>::Wrap>( static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) | static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator |( E lhs, typename o3tl::typed_flags<E>::Wrap rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) >= 0); return static_cast<typename o3tl::typed_flags<E>::Wrap>( static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) | static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator |( typename o3tl::typed_flags<E>::Wrap lhs, E rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs) >= 0); return static_cast<typename o3tl::typed_flags<E>::Wrap>( static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) | static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Wrap operator |( typename o3tl::typed_flags<E>::Wrap lhs, typename o3tl::typed_flags<E>::Wrap rhs) { return static_cast<typename o3tl::typed_flags<E>::Wrap>( static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) | static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs)); } template<typename E> inline typename o3tl::typed_flags<E>::Self operator &=(E & lhs, E rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) >= 0); assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs) >= 0); lhs = lhs & rhs; return lhs; } template<typename E> inline typename o3tl::typed_flags<E>::Self operator &=( E & lhs, typename o3tl::typed_flags<E>::Wrap rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) >= 0); lhs = lhs & rhs; return lhs; } template<typename E> inline typename o3tl::typed_flags<E>::Self operator |=(E & lhs, E rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) >= 0); assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(rhs) >= 0); lhs = lhs | rhs; return lhs; } template<typename E> inline typename o3tl::typed_flags<E>::Self operator |=( E & lhs, typename o3tl::typed_flags<E>::Wrap rhs) { assert(static_cast<O3TL_STD_UNDERLYING_TYPE_E>(lhs) >= 0); lhs = lhs | rhs; return lhs; } #undef O3TL_STD_UNDERLYING_TYPE_E #endif /* INCLUDED_O3TL_TYPED_FLAGS_SET_HXX */ /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#ifndef MPU6000_HPP_ #define MPU6000_HPP_ #include <hal.h> #include <sensor/accelerometer.hpp> #include <sensor/gyroscope.hpp> class MPU6000 : public Accelerometer, public Gyroscope { public: MPU6000(SPIDriver *spi); void init() override; accelerometer_reading_t readAccel() override; gyroscope_reading_t readGyro() override; private: uint8_t readRegister(uint8_t reg); void writeRegister(uint8_t reg, uint8_t val); SPIDriver *spi; }; #endif <commit_msg>Add MPU-6000 register definitions.<commit_after>#ifndef MPU6000_HPP_ #define MPU6000_HPP_ #include <hal.h> #include <sensor/accelerometer.hpp> #include <sensor/gyroscope.hpp> #define MPU6000_AUX_VDDIO 0x01 // R/W #define MPU6000_SMPLRT_DIV 0x19 // R/W #define MPU6000_CONFIG 0x1A // R/W #define MPU6000_GYRO_CONFIG 0x1B // R/W #define MPU6000_ACCEL_CONFIG 0x1C // R/W #define MPU6000_FF_THR 0x1D // R/W #define MPU6000_FF_DUR 0x1E // R/W #define MPU6000_MOT_THR 0x1F // R/W #define MPU6000_MOT_DUR 0x20 // R/W #define MPU6000_ZRMOT_THR 0x21 // R/W #define MPU6000_ZRMOT_DUR 0x22 // R/W #define MPU6000_FIFO_EN 0x23 // R/W #define MPU6000_I2C_MST_CTRL 0x24 // R/W #define MPU6000_I2C_SLV0_ADDR 0x25 // R/W #define MPU6000_I2C_SLV0_REG 0x26 // R/W #define MPU6000_I2C_SLV0_CTRL 0x27 // R/W #define MPU6000_I2C_SLV1_ADDR 0x28 // R/W #define MPU6000_I2C_SLV1_REG 0x29 // R/W #define MPU6000_I2C_SLV1_CTRL 0x2A // R/W #define MPU6000_I2C_SLV2_ADDR 0x2B // R/W #define MPU6000_I2C_SLV2_REG 0x2C // R/W #define MPU6000_I2C_SLV2_CTRL 0x2D // R/W #define MPU6000_I2C_SLV3_ADDR 0x2E // R/W #define MPU6000_I2C_SLV3_REG 0x2F // R/W #define MPU6000_I2C_SLV3_CTRL 0x30 // R/W #define MPU6000_I2C_SLV4_ADDR 0x31 // R/W #define MPU6000_I2C_SLV4_REG 0x32 // R/W #define MPU6000_I2C_SLV4_DO 0x33 // R/W #define MPU6000_I2C_SLV4_CTRL 0x34 // R/W #define MPU6000_I2C_SLV4_DI 0x35 // R #define MPU6000_I2C_MST_STATUS 0x36 // R #define MPU6000_INT_PIN_CFG 0x37 // R/W #define MPU6000_INT_ENABLE 0x38 // R/W #define MPU6000_INT_STATUS 0x3A // R #define MPU6000_ACCEL_XOUT_H 0x3B // R #define MPU6000_ACCEL_XOUT_L 0x3C // R #define MPU6000_ACCEL_YOUT_H 0x3D // R #define MPU6000_ACCEL_YOUT_L 0x3E // R #define MPU6000_ACCEL_ZOUT_H 0x3F // R #define MPU6000_ACCEL_ZOUT_L 0x40 // R #define MPU6000_TEMP_OUT_H 0x41 // R #define MPU6000_TEMP_OUT_L 0x42 // R #define MPU6000_GYRO_XOUT_H 0x43 // R #define MPU6000_GYRO_XOUT_L 0x44 // R #define MPU6000_GYRO_YOUT_H 0x45 // R #define MPU6000_GYRO_YOUT_L 0x46 // R #define MPU6000_GYRO_ZOUT_H 0x47 // R #define MPU6000_GYRO_ZOUT_L 0x48 // R #define MPU6000_EXT_SENS_DATA_00 0x49 // R #define MPU6000_EXT_SENS_DATA_01 0x4A // R #define MPU6000_EXT_SENS_DATA_02 0x4B // R #define MPU6000_EXT_SENS_DATA_03 0x4C // R #define MPU6000_EXT_SENS_DATA_04 0x4D // R #define MPU6000_EXT_SENS_DATA_05 0x4E // R #define MPU6000_EXT_SENS_DATA_06 0x4F // R #define MPU6000_EXT_SENS_DATA_07 0x50 // R #define MPU6000_EXT_SENS_DATA_08 0x51 // R #define MPU6000_EXT_SENS_DATA_09 0x52 // R #define MPU6000_EXT_SENS_DATA_10 0x53 // R #define MPU6000_EXT_SENS_DATA_11 0x54 // R #define MPU6000_EXT_SENS_DATA_12 0x55 // R #define MPU6000_EXT_SENS_DATA_13 0x56 // R #define MPU6000_EXT_SENS_DATA_14 0x57 // R #define MPU6000_EXT_SENS_DATA_15 0x58 // R #define MPU6000_EXT_SENS_DATA_16 0x59 // R #define MPU6000_EXT_SENS_DATA_17 0x5A // R #define MPU6000_EXT_SENS_DATA_18 0x5B // R #define MPU6000_EXT_SENS_DATA_19 0x5C // R #define MPU6000_EXT_SENS_DATA_20 0x5D // R #define MPU6000_EXT_SENS_DATA_21 0x5E // R #define MPU6000_EXT_SENS_DATA_22 0x5F // R #define MPU6000_EXT_SENS_DATA_23 0x60 // R #define MPU6000_MOT_DETECT_STATUS 0x61 // R #define MPU6000_I2C_SLV0_DO 0x63 // R/W #define MPU6000_I2C_SLV1_DO 0x64 // R/W #define MPU6000_I2C_SLV2_DO 0x65 // R/W #define MPU6000_I2C_SLV3_DO 0x66 // R/W #define MPU6000_I2C_MST_DELAY_CTRL 0x67 // R/W #define MPU6000_SIGNAL_PATH_RESET 0x68 // R/W #define MPU6000_MOT_DETECT_CTRL 0x69 // R/W #define MPU6000_USER_CTRL 0x6A // R/W #define MPU6000_PWR_MGMT_1 0x6B // R/W #define MPU6000_PWR_MGMT_2 0x6C // R/W #define MPU6000_FIFO_COUNTH 0x72 // R/W #define MPU6000_FIFO_COUNTL 0x73 // R/W #define MPU6000_FIFO_R_W 0x74 // R/W #define MPU6000_WHO_AM_I 0x75 // R class MPU6000 : public Accelerometer, public Gyroscope { public: MPU6000(SPIDriver *spi); void init() override; accelerometer_reading_t readAccel() override; gyroscope_reading_t readGyro() override; private: uint8_t readRegister(uint8_t reg); void writeRegister(uint8_t reg, uint8_t val); SPIDriver *spi; }; #endif <|endoftext|>
<commit_before>//===- include/seec/clang/MappedAST.hpp -----------------------------------===// // // SeeC // // This file is distributed under The MIT License (MIT). See LICENSE.TXT for // details. // //===----------------------------------------------------------------------===// /// /// \file Support SeeC's indexing of Clang ASTs. /// //===----------------------------------------------------------------------===// #ifndef SEEC_CLANG_MAPPEDAST_HPP #define SEEC_CLANG_MAPPEDAST_HPP #include "clang/Frontend/ASTUnit.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/StringRef.h" #include <map> #include <memory> #include <string> #include <vector> namespace clang { class Decl; class DiagnosticsEngine; class FileSystemOptions; class Stmt; } namespace seec { /// Contains classes to assist with SeeC's usage of Clang. namespace seec_clang { /// class MappedAST { clang::ASTUnit *AST; std::vector<clang::Decl const *> Decls; std::vector<clang::Stmt const *> Stmts; /// Constructor. MappedAST(clang::ASTUnit *AST, std::vector<clang::Decl const *> &&Decls, std::vector<clang::Stmt const *> &&Stmts) : AST(AST), Decls(Decls), Stmts(Stmts) {} // Don't allow copying. MappedAST(MappedAST const &Other) = delete; MappedAST & operator=(MappedAST const &RHS) = delete; public: /// Destructor. ~MappedAST(); /// Factory. static std::unique_ptr<MappedAST> FromASTUnit(clang::ASTUnit *AST); /// Factory. static std::unique_ptr<MappedAST> LoadFromASTFile(llvm::StringRef Filename, llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> Diags, clang::FileSystemOptions const &FileSystemOpts); /// Factory. static std::unique_ptr<MappedAST> LoadFromCompilerInvocation( std::unique_ptr<clang::CompilerInvocation> Invocation, llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> Diags); /// \name Accessors /// @{ /// Get the underlying ASTUnit. clang::ASTUnit const &getASTUnit() const { return *AST; } /// Get all mapped clang::Decl pointers. decltype(Decls) const &getAllDecls() const { return Decls; } /// Get all mapped clang::Stmt pointers. decltype(Stmts) const &getAllStmts() const { return Stmts; } /// Get the clang::Decl at the given index. clang::Decl const *getDeclFromIdx(uint64_t DeclIdx) const { if (DeclIdx < Decls.size()) return Decls[DeclIdx]; return nullptr; } /// Get the clang::Stmt at the given index. clang::Stmt const *getStmtFromIdx(uint64_t StmtIdx) const { if (StmtIdx < Stmts.size()) return Stmts[StmtIdx]; return nullptr; } /// @} (Accessors) }; } // namespace clang (in seec) } // namespace seec #endif // SEEC_CLANG_MAPPEDAST_HPP <commit_msg>Return a non-const reference to clang::ASTUnit from MappedAST.<commit_after>//===- include/seec/clang/MappedAST.hpp -----------------------------------===// // // SeeC // // This file is distributed under The MIT License (MIT). See LICENSE.TXT for // details. // //===----------------------------------------------------------------------===// /// /// \file Support SeeC's indexing of Clang ASTs. /// //===----------------------------------------------------------------------===// #ifndef SEEC_CLANG_MAPPEDAST_HPP #define SEEC_CLANG_MAPPEDAST_HPP #include "clang/Frontend/ASTUnit.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/StringRef.h" #include <map> #include <memory> #include <string> #include <vector> namespace clang { class Decl; class DiagnosticsEngine; class FileSystemOptions; class Stmt; } namespace seec { /// Contains classes to assist with SeeC's usage of Clang. namespace seec_clang { /// class MappedAST { clang::ASTUnit *AST; std::vector<clang::Decl const *> Decls; std::vector<clang::Stmt const *> Stmts; /// Constructor. MappedAST(clang::ASTUnit *AST, std::vector<clang::Decl const *> &&Decls, std::vector<clang::Stmt const *> &&Stmts) : AST(AST), Decls(Decls), Stmts(Stmts) {} // Don't allow copying. MappedAST(MappedAST const &Other) = delete; MappedAST & operator=(MappedAST const &RHS) = delete; public: /// Destructor. ~MappedAST(); /// Factory. static std::unique_ptr<MappedAST> FromASTUnit(clang::ASTUnit *AST); /// Factory. static std::unique_ptr<MappedAST> LoadFromASTFile(llvm::StringRef Filename, llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> Diags, clang::FileSystemOptions const &FileSystemOpts); /// Factory. static std::unique_ptr<MappedAST> LoadFromCompilerInvocation( std::unique_ptr<clang::CompilerInvocation> Invocation, llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> Diags); /// \name Accessors /// @{ /// Get the underlying ASTUnit. clang::ASTUnit &getASTUnit() const { return *AST; } /// Get all mapped clang::Decl pointers. decltype(Decls) const &getAllDecls() const { return Decls; } /// Get all mapped clang::Stmt pointers. decltype(Stmts) const &getAllStmts() const { return Stmts; } /// Get the clang::Decl at the given index. clang::Decl const *getDeclFromIdx(uint64_t DeclIdx) const { if (DeclIdx < Decls.size()) return Decls[DeclIdx]; return nullptr; } /// Get the clang::Stmt at the given index. clang::Stmt const *getStmtFromIdx(uint64_t StmtIdx) const { if (StmtIdx < Stmts.size()) return Stmts[StmtIdx]; return nullptr; } /// @} (Accessors) }; } // namespace clang (in seec) } // namespace seec #endif // SEEC_CLANG_MAPPEDAST_HPP <|endoftext|>
<commit_before>// CxxSwizzle // Copyright (c) 2013-2015, Piotr Gwiazdowski <gwiazdorrr+github at gmail.com> #pragma once #include <algorithm> #include <cstdint> #include <swizzle/detail/utils.h> #include <swizzle/detail/vector_traits.h> namespace swizzle { using float_type = float; using int_type = int32_t; using uint_type = uint32_t; using bool_type = bool; struct partial_derivatives_dont_work_for_scalars {}; float dFdx(partial_derivatives_dont_work_for_scalars); float dFdy(partial_derivatives_dont_work_for_scalars); float fwidth(partial_derivatives_dont_work_for_scalars); // aux functions template <typename T, typename U, typename = std::enable_if_t<std::is_fundamental_v<T> && std::is_fundamental_v<U> && sizeof(T) == sizeof(U)>> inline void bitcast(T src, U& target) { target = *reinterpret_cast<U*>(src); } template <typename T, typename = std::enable_if_t<std::is_fundamental_v<T>>> inline void load_aligned(T& value, const T* ptr) { value = *ptr; } template <typename T, typename = std::enable_if_t<std::is_fundamental_v<T>>> inline void store_aligned(const T& value, T* ptr) { *ptr = value; } } #include <swizzle/detail/cmath_imports.hpp> #include <swizzle/detail/setup_common.hpp> <commit_msg>Temporarily enabled partial derivatives in scalar mode<commit_after>// CxxSwizzle // Copyright (c) 2013-2015, Piotr Gwiazdowski <gwiazdorrr+github at gmail.com> #pragma once #include <algorithm> #include <cstdint> #include <swizzle/detail/utils.h> #include <swizzle/detail/vector_traits.h> namespace swizzle { using float_type = float; using int_type = int32_t; using uint_type = uint32_t; using bool_type = bool; //struct partial_derivatives_dont_work_for_scalars //{}; inline float dFdx(float) { return 0; }; inline float dFdy(float) { return 0; }; inline float fwidth(float) { return 0; }; // aux functions template <typename T, typename U, typename = std::enable_if_t<std::is_fundamental_v<T> && std::is_fundamental_v<U> && sizeof(T) == sizeof(U)>> inline void bitcast(T src, U& target) { target = *reinterpret_cast<U*>(src); } template <typename T, typename = std::enable_if_t<std::is_fundamental_v<T>>> inline void load_aligned(T& value, const T* ptr) { value = *ptr; } template <typename T, typename = std::enable_if_t<std::is_fundamental_v<T>>> inline void store_aligned(const T& value, T* ptr) { *ptr = value; } } #include <swizzle/detail/cmath_imports.hpp> #include <swizzle/detail/setup_common.hpp> <|endoftext|>
<commit_before>#ifndef VSMC_INTERNAL_CONFIG_HPP #define VSMC_INTERNAL_CONFIG_HPP #include <vsmc/internal/compiler.hpp> #ifndef __STDC_CONSTANT_MACROS #define __STDC_CONSTANT_MACROS #endif // #if defined(__clang__) // #ifndef TBB_USE_CAPTURED_EXCEPTION // #define TBB_USE_CAPTURED_EXCEPTION 1 // #endif // #endif #if VSMC_HAS_CXX11_CONSTEXPR #define VSMC_CONSTEXPR constexpr #else #define VSMC_CONSTEXPR #endif #if VSMC_HAS_CXX11_EXPLICIT_CONVERSIONS #define VSMC_EXPLICIT_OPERATOR explicit #else #define VSMC_EXPLICIT_OPERATOR #endif #if VSMC_HAS_CXX11_NOEXCEPT #define VSMC_NOEXCEPT noexcept #else #define VSMC_NOEXCEPT #endif #if VSMC_HAS_CXX11_NULLPTR && VSMC_HAS_CXX11LIB_FUNCTIONAL #define VSMC_NULLPTR nullptr #else #define VSMC_NULLPTR 0 #endif /// \brief Turn vSMC runtime assertions into exceptions /// \ingroup Config #ifndef VSMC_RUNTIME_ASSERT_AS_EXCEPTION #define VSMC_RUNTIME_ASSERT_AS_EXCEPTION 0 #endif /// \brief Use Random123 for random number generating /// \ingroup Config #ifndef VSMC_USE_RANDOM123 #define VSMC_USE_RANDOM123 1 #endif /// \brief Use Intel MKL for BLAS level 2, level 3 and other computations /// \ingroup Config #ifndef VSMC_USE_MKL #define VSMC_USE_MKL 0 #endif /// \brief Use Apple vecLib for BLAS level 2 and level 3 computations /// \ingroup Config #ifndef VSMC_USE_VECLIB #define VSMC_USE_VECLIB 0 #endif /// \brief Use generic CBLAS for BLAS level 2 and level 3 computations /// \ingroup Config /// \note User has to include CLBAS header first /// \note Use `VSMC_GENERIC_CBLAS_INT` to define the CBLAS integer type #ifndef VSMC_USE_GENERIC_CBLAS #define VSMC_USE_GENERIC_CBLAS 0 #endif /// \brief Use the Armadillo library for BLAS level 2 and level 3 computations /// \ingroup Config #ifndef VSMC_USE_ARMADILLO #define VSMC_USE_ARMADILLO 0 #endif /// \brief Use the Eigen library for BLAS level 2 and level 3 computations /// \ingroup Config #ifndef VSMC_USE_EIGEN #define VSMC_USE_EIGEN 0 #endif /// \brief Use native timing library if `VSMC_HAS_CXX11LIB_CHRONO` is zero /// \ingroup Config #ifndef VSMC_HAS_NATIVE_TIME_LIBRARY #define VSMC_HAS_NATIVE_TIME_LIBRARY 1 #endif /// \brief The fallback StopWatch type /// \ingroup Config /// \note The class defined by `VSMC_STOP_WATCH_TYPE` need to be defined before /// including the `<vsmc/utility/stop_watch.hpp>` header. It shall provide the /// same interface as DummyStopWatch. This is only used when both /// `VSMC_HAS_CXX11LIB_CHRONO` and `VSMC_HAS_NATIVE_TIME_LIBRARY` are zero, in /// which case StopWatch is a typedef of this macro. #ifndef VSMC_STOP_WATCH_TYPE #define VSMC_STOP_WATCH_TYPE DummyStopWatch #endif #endif // VSMC_INTERNAL_CONFIG_HPP <commit_msg>add default for HDF5 config macro<commit_after>#ifndef VSMC_INTERNAL_CONFIG_HPP #define VSMC_INTERNAL_CONFIG_HPP #include <vsmc/internal/compiler.hpp> #ifndef __STDC_CONSTANT_MACROS #define __STDC_CONSTANT_MACROS #endif // #if defined(__clang__) // #ifndef TBB_USE_CAPTURED_EXCEPTION // #define TBB_USE_CAPTURED_EXCEPTION 1 // #endif // #endif #if VSMC_HAS_CXX11_CONSTEXPR #define VSMC_CONSTEXPR constexpr #else #define VSMC_CONSTEXPR #endif #if VSMC_HAS_CXX11_EXPLICIT_CONVERSIONS #define VSMC_EXPLICIT_OPERATOR explicit #else #define VSMC_EXPLICIT_OPERATOR #endif #if VSMC_HAS_CXX11_NOEXCEPT #define VSMC_NOEXCEPT noexcept #else #define VSMC_NOEXCEPT #endif #if VSMC_HAS_CXX11_NULLPTR && VSMC_HAS_CXX11LIB_FUNCTIONAL #define VSMC_NULLPTR nullptr #else #define VSMC_NULLPTR 0 #endif /// \brief Turn vSMC runtime assertions into exceptions /// \ingroup Config #ifndef VSMC_RUNTIME_ASSERT_AS_EXCEPTION #define VSMC_RUNTIME_ASSERT_AS_EXCEPTION 0 #endif /// \brief Use Random123 for random number generating /// \ingroup Config #ifndef VSMC_USE_RANDOM123 #define VSMC_USE_RANDOM123 1 #endif /// \brief Use Intel MKL for BLAS level 2, level 3 and other computations /// \ingroup Config #ifndef VSMC_USE_MKL #define VSMC_USE_MKL 0 #endif /// \brief Use Apple vecLib for BLAS level 2 and level 3 computations /// \ingroup Config #ifndef VSMC_USE_VECLIB #define VSMC_USE_VECLIB 0 #endif /// \brief Use generic CBLAS for BLAS level 2 and level 3 computations /// \ingroup Config /// \note User has to include CLBAS header first /// \note Use `VSMC_GENERIC_CBLAS_INT` to define the CBLAS integer type #ifndef VSMC_USE_GENERIC_CBLAS #define VSMC_USE_GENERIC_CBLAS 0 #endif /// \brief Use the Armadillo library for BLAS level 2 and level 3 computations /// \ingroup Config #ifndef VSMC_USE_ARMADILLO #define VSMC_USE_ARMADILLO 0 #endif /// \brief Use the Eigen library for BLAS level 2 and level 3 computations /// \ingroup Config #ifndef VSMC_USE_EIGEN #define VSMC_USE_EIGEN 0 #endif /// \brief Use HDF5 for saving data /// \ingroup Config #ifndef VSMC_USE_HDF5 #define VSMC_USE_HDF5 0 #endif /// \brief Use native timing library if `VSMC_HAS_CXX11LIB_CHRONO` is zero /// \ingroup Config #ifndef VSMC_HAS_NATIVE_TIME_LIBRARY #define VSMC_HAS_NATIVE_TIME_LIBRARY 1 #endif /// \brief The fallback StopWatch type /// \ingroup Config /// \note The class defined by `VSMC_STOP_WATCH_TYPE` need to be defined before /// including the `<vsmc/utility/stop_watch.hpp>` header. It shall provide the /// same interface as DummyStopWatch. This is only used when both /// `VSMC_HAS_CXX11LIB_CHRONO` and `VSMC_HAS_NATIVE_TIME_LIBRARY` are zero, in /// which case StopWatch is a typedef of this macro. #ifndef VSMC_STOP_WATCH_TYPE #define VSMC_STOP_WATCH_TYPE DummyStopWatch #endif #endif // VSMC_INTERNAL_CONFIG_HPP <|endoftext|>
<commit_before>//============================================================================ // include/vsmc/resample/common.hpp //---------------------------------------------------------------------------- // // vSMC: Scalable Monte Carlo // // This file is distribured under the 2-clauses BSD License. // See LICENSE for details. //============================================================================ #ifndef VSMC_RESAMPLE_COMMON_HPP #define VSMC_RESAMPLE_COMMON_HPP #include <cstring> #include <algorithm> #include <vector> #include <vsmc/internal/common.hpp> #include <vsmc/cxx11/random.hpp> #include <vsmc/rng/threefry.hpp> /// \brief Default RNG type for resampling /// \ingroup Config #ifndef VSMC_DEFAULT_RESAMPLE_RNG_TYPE #define VSMC_DEFAULT_RESAMPLE_RNG_TYPE vsmc::Threefry4x64 #endif namespace vsmc { namespace internal { class Inversion { public : // Given N U01 random variates, // Compute M counts based on M weights template <typename IntType> void operator() (std::size_t M, std::size_t N, const double *weight, const double *u01, IntType *count, bool usorted = false) { if (M == 0) return; if (M == 1) { *count = static_cast<IntType>(N); return; } accw_.resize(M); accw_[0] = weight[0]; for (std::size_t i = 1; i != M; ++i) accw_[i] = accw_[i - 1] + weight[i]; accw_.back() = 1; const double *uptr = VSMC_NULLPTR; if (usorted) { uptr = u01; } else { u01_.resize(N); std::memcpy(&u01_[0], u01, sizeof(double) * N); std::sort(u01_.begin(), u01_.end()); uptr = &u01_[0]; } std::size_t offset = 0; std::memset(count, 0, sizeof(IntType) * M); for (std::size_t i = 0; i != M; ++i) { while (offset != N && uptr[offset] <= accw_[i]) { ++count[i]; ++offset; } } } private : std::vector<double> accw_; std::vector<double> u01_; }; // class Inversion } // namespace vsmc::internal /// \brief Resampling schemes /// \ingroup Resample enum ResampleScheme { Multinomial, ///< Multinomial resampling Residual, ///< Residual resampling Stratified, ///< Stratified resampling Systematic, ///< Systematic resampling ResidualStratified, ///< Stratified resampling on residuals ResidualSystematic ///< Systematic resampling on residuals }; // enum ResampleScheme /// \brief Resample forward decleration /// \ingroup Resample template <typename> class Resample; /// \brief Resampling type of the built-in schemes /// \ingroup Resample template <ResampleScheme Scheme> struct ResampleType {typedef Resample<cxx11::integral_constant<ResampleScheme, Scheme> > type;}; /// \brief Transform replication numbers to parent particle locations /// \ingroup Resample /// /// \details This one shall be used in place of the default if resampling /// algorithms output parent locations directly instead of replication number class ResampleCopyFromReplicationNoAaction { public : template <typename IntType1, typename IntType2> void operator() (std::size_t, std::size_t, const IntType1 *, IntType2 *) const {} }; // class ResampleCopyFromReplicationNoAaction /// \brief Transform replication numbers to parent particle locations /// \ingroup Resample class ResampleCopyFromReplication { public : template <typename IntType1, typename IntType2> void operator() (std::size_t M, std::size_t N, const IntType1 *replication, IntType2 *copy_from) const { if (M == N) { std::size_t from = 0; std::size_t time = 0; for (std::size_t to = 0; to != N; ++to) { if (replication[to] != 0) { copy_from[to] = static_cast<IntType2>(to); } else { // replication[to] has zero child, copy from elsewhere if (replication[from] - time <= 1) { // only 1 child left on replication[from] time = 0; do // move from to a position with at least 2 children ++from; while (replication[from] < 2); } copy_from[to] = static_cast<IntType2>(from); ++time; } } } else { std::size_t to = 0; for (std::size_t from = 0; from != M; ++from) for (IntType1 i = 0; i != replication[from]; ++i) copy_from[to++] = static_cast<IntType2>(from); } } }; // class ResampleCopyFromReplication class ResamplePostCopy { public : template <typename WeightSetType> void operator() (WeightSetType &weight_set) const {weight_set.set_equal_weight();} }; // class ResamplePostCopy namespace traits { /// \brief Particle::resample_rng_type trait /// \ingroup Traits VSMC_DEFINE_TYPE_DISPATCH_TRAIT(ResampleRngType, resample_rng_type, VSMC_DEFAULT_RESAMPLE_RNG_TYPE) /// \brief Particle::resample_copy_from_replication_type trait /// \ingroup Traits VSMC_DEFINE_TYPE_DISPATCH_TRAIT(ResampleCopyFromReplicationType, resample_copy_from_replication_type, ResampleCopyFromReplication) /// \brief Particle::resample_post_copy_type trait /// \ingroup Traits VSMC_DEFINE_TYPE_DISPATCH_TRAIT(ResamplePostCopyType, resample_post_copy_type, ResamplePostCopy) } // namespace vsmc::traits } // namespace vsmc #endif // VSMC_RESAMPLE_COMMON_HPP <commit_msg>rename count variable to replication to be consistent<commit_after>//============================================================================ // include/vsmc/resample/common.hpp //---------------------------------------------------------------------------- // // vSMC: Scalable Monte Carlo // // This file is distribured under the 2-clauses BSD License. // See LICENSE for details. //============================================================================ #ifndef VSMC_RESAMPLE_COMMON_HPP #define VSMC_RESAMPLE_COMMON_HPP #include <cstring> #include <algorithm> #include <vector> #include <vsmc/internal/common.hpp> #include <vsmc/cxx11/random.hpp> #include <vsmc/rng/threefry.hpp> /// \brief Default RNG type for resampling /// \ingroup Config #ifndef VSMC_DEFAULT_RESAMPLE_RNG_TYPE #define VSMC_DEFAULT_RESAMPLE_RNG_TYPE vsmc::Threefry4x64 #endif namespace vsmc { namespace internal { class Inversion { public : // Given N U01 random variates, // Compute M replication numbers based on M weights template <typename IntType> void operator() (std::size_t M, std::size_t N, const double *weight, const double *u01, IntType *replication, bool usorted = false) { if (M == 0) return; if (M == 1) { *replication = static_cast<IntType>(N); return; } accw_.resize(M); accw_[0] = weight[0]; for (std::size_t i = 1; i != M; ++i) accw_[i] = accw_[i - 1] + weight[i]; accw_.back() = 1; const double *uptr = VSMC_NULLPTR; if (usorted) { uptr = u01; } else { u01_.resize(N); std::memcpy(&u01_[0], u01, sizeof(double) * N); std::sort(u01_.begin(), u01_.end()); uptr = &u01_[0]; } std::size_t offset = 0; std::memset(replication, 0, sizeof(IntType) * M); for (std::size_t i = 0; i != M; ++i) { while (offset != N && uptr[offset] <= accw_[i]) { ++replication[i]; ++offset; } } } private : std::vector<double> accw_; std::vector<double> u01_; }; // class Inversion } // namespace vsmc::internal /// \brief Resampling schemes /// \ingroup Resample enum ResampleScheme { Multinomial, ///< Multinomial resampling Residual, ///< Residual resampling Stratified, ///< Stratified resampling Systematic, ///< Systematic resampling ResidualStratified, ///< Stratified resampling on residuals ResidualSystematic ///< Systematic resampling on residuals }; // enum ResampleScheme /// \brief Resample forward decleration /// \ingroup Resample template <typename> class Resample; /// \brief Resampling type of the built-in schemes /// \ingroup Resample template <ResampleScheme Scheme> struct ResampleType {typedef Resample<cxx11::integral_constant<ResampleScheme, Scheme> > type;}; /// \brief Transform replication numbers to parent particle locations /// \ingroup Resample /// /// \details This one shall be used in place of the default if resampling /// algorithms output parent locations directly instead of replication number class ResampleCopyFromReplicationNoAaction { public : template <typename IntType1, typename IntType2> void operator() (std::size_t, std::size_t, const IntType1 *, IntType2 *) const {} }; // class ResampleCopyFromReplicationNoAaction /// \brief Transform replication numbers to parent particle locations /// \ingroup Resample class ResampleCopyFromReplication { public : template <typename IntType1, typename IntType2> void operator() (std::size_t M, std::size_t N, const IntType1 *replication, IntType2 *copy_from) const { if (M == N) { std::size_t from = 0; std::size_t time = 0; for (std::size_t to = 0; to != N; ++to) { if (replication[to] != 0) { copy_from[to] = static_cast<IntType2>(to); } else { // replication[to] has zero child, copy from elsewhere if (replication[from] - time <= 1) { // only 1 child left on replication[from] time = 0; do // move from to a position with at least 2 children ++from; while (replication[from] < 2); } copy_from[to] = static_cast<IntType2>(from); ++time; } } } else { std::size_t to = 0; for (std::size_t from = 0; from != M; ++from) for (IntType1 i = 0; i != replication[from]; ++i) copy_from[to++] = static_cast<IntType2>(from); } } }; // class ResampleCopyFromReplication class ResamplePostCopy { public : template <typename WeightSetType> void operator() (WeightSetType &weight_set) const {weight_set.set_equal_weight();} }; // class ResamplePostCopy namespace traits { /// \brief Particle::resample_rng_type trait /// \ingroup Traits VSMC_DEFINE_TYPE_DISPATCH_TRAIT(ResampleRngType, resample_rng_type, VSMC_DEFAULT_RESAMPLE_RNG_TYPE) /// \brief Particle::resample_copy_from_replication_type trait /// \ingroup Traits VSMC_DEFINE_TYPE_DISPATCH_TRAIT(ResampleCopyFromReplicationType, resample_copy_from_replication_type, ResampleCopyFromReplication) /// \brief Particle::resample_post_copy_type trait /// \ingroup Traits VSMC_DEFINE_TYPE_DISPATCH_TRAIT(ResamplePostCopyType, resample_post_copy_type, ResamplePostCopy) } // namespace vsmc::traits } // namespace vsmc #endif // VSMC_RESAMPLE_COMMON_HPP <|endoftext|>
<commit_before>#include "html.h" #include "el_before_after.h" #include "el_text.h" #include "el_space.h" #include "el_image.h" #include "utf8_strings.h" litehtml::el_before_after_base::el_before_after_base(const std::shared_ptr<litehtml::document>& doc, bool before) : html_tag(doc) { if(before) { set_tagName(_t("::before")); } else { set_tagName(_t("::after")); } } litehtml::el_before_after_base::~el_before_after_base() { } void litehtml::el_before_after_base::add_style(const litehtml::style& st) { html_tag::add_style(st); tstring content = get_style_property(_t("content"), false, _t("")); if(!content.empty()) { int idx = value_index(content.c_str(), content_property_string); if(idx < 0) { tstring fnc; tstring::size_type i = 0; while(i < content.length() && i != tstring::npos) { if(content.at(i) == _t('"')) { fnc.clear(); i++; tstring::size_type pos = content.find(_t('"'), i); tstring txt; if(pos == tstring::npos) { txt = content.substr(i); i = tstring::npos; } else { txt = content.substr(i, pos - i); i = pos + 1; } add_text(txt); } else if(content.at(i) == _t('(')) { i++; litehtml::trim(fnc); litehtml::lcase(fnc); tstring::size_type pos = content.find(_t(')'), i); tstring params; if(pos == tstring::npos) { params = content.substr(i); i = tstring::npos; } else { params = content.substr(i, pos - i); i = pos + 1; } add_function(fnc, params); fnc.clear(); } else { fnc += content.at(i); i++; } } } } } void litehtml::el_before_after_base::add_text( const tstring& txt ) { tstring word; tstring esc; for(tstring::size_type i = 0; i < txt.length(); i++) { if( (txt.at(i) == _t(' ')) || (txt.at(i) == _t('\t')) || (txt.at(i) == _t('\\') && !esc.empty()) ) { if(esc.empty()) { if(!word.empty()) { element::ptr el = std::make_shared<el_text>(word.c_str(), get_document()); appendChild(el); word.clear(); } element::ptr el = std::make_shared<el_space>(txt.substr(i, 1).c_str(), get_document()); appendChild(el); } else { word += convert_escape(esc.c_str() + 1); esc.clear(); if(txt.at(i) == _t('\\')) { esc += txt.at(i); } } } else { if(!esc.empty() || txt.at(i) == _t('\\')) { esc += txt.at(i); } else { word += txt.at(i); } } } if(!esc.empty()) { word += convert_escape(esc.c_str() + 1); } if(!word.empty()) { element::ptr el = std::make_shared<el_text>(word.c_str(), get_document()); appendChild(el); word.clear(); } } void litehtml::el_before_after_base::add_function( const tstring& fnc, const tstring& params ) { int idx = value_index(fnc.c_str(), _t("attr;counter;url")); switch(idx) { // attr case 0: { tstring p_name = params; trim(p_name); lcase(p_name); element::ptr el_parent = parent(); if (el_parent) { const tchar_t* attr_value = el_parent->get_attr(p_name.c_str()); if (attr_value) { add_text(attr_value); } } } break; // counter case 1: break; // url case 2: { tstring p_url = params; trim(p_url); if(!p_url.empty()) { if(p_url.at(0) == _t('\'') || p_url.at(0) == _t('\"')) { p_url.erase(0, 1); } } if(!p_url.empty()) { if(p_url.at(p_url.length() - 1) == _t('\'') || p_url.at(p_url.length() - 1) == _t('\"')) { p_url.erase(p_url.length() - 1, 1); } } if(!p_url.empty()) { element::ptr el = std::make_shared<el_image>(get_document()); el->set_attr(_t("src"), p_url.c_str()); el->set_attr(_t("style"), _t("display:inline-block")); el->set_tagName(_t("img")); appendChild(el); el->parse_attributes(); } } break; } } litehtml::tstring litehtml::el_before_after_base::convert_escape( const tchar_t* txt ) { tchar_t* str_end; wchar_t u_str[2]; u_str[0] = (wchar_t) t_strtol(txt, &str_end, 16); u_str[1] = 0; return litehtml_from_wchar(u_str).c_str(); } void litehtml::el_before_after_base::apply_stylesheet( const litehtml::css& stylesheet ) { } <commit_msg>Fixed compilation error on Windows without LITEHTML_UTF8<commit_after>#include "html.h" #include "el_before_after.h" #include "el_text.h" #include "el_space.h" #include "el_image.h" #include "utf8_strings.h" litehtml::el_before_after_base::el_before_after_base(const std::shared_ptr<litehtml::document>& doc, bool before) : html_tag(doc) { if(before) { set_tagName(_t("::before")); } else { set_tagName(_t("::after")); } } litehtml::el_before_after_base::~el_before_after_base() { } void litehtml::el_before_after_base::add_style(const litehtml::style& st) { html_tag::add_style(st); tstring content = get_style_property(_t("content"), false, _t("")); if(!content.empty()) { int idx = value_index(content.c_str(), content_property_string); if(idx < 0) { tstring fnc; tstring::size_type i = 0; while(i < content.length() && i != tstring::npos) { if(content.at(i) == _t('"')) { fnc.clear(); i++; tstring::size_type pos = content.find(_t('"'), i); tstring txt; if(pos == tstring::npos) { txt = content.substr(i); i = tstring::npos; } else { txt = content.substr(i, pos - i); i = pos + 1; } add_text(txt); } else if(content.at(i) == _t('(')) { i++; litehtml::trim(fnc); litehtml::lcase(fnc); tstring::size_type pos = content.find(_t(')'), i); tstring params; if(pos == tstring::npos) { params = content.substr(i); i = tstring::npos; } else { params = content.substr(i, pos - i); i = pos + 1; } add_function(fnc, params); fnc.clear(); } else { fnc += content.at(i); i++; } } } } } void litehtml::el_before_after_base::add_text( const tstring& txt ) { tstring word; tstring esc; for(tstring::size_type i = 0; i < txt.length(); i++) { if( (txt.at(i) == _t(' ')) || (txt.at(i) == _t('\t')) || (txt.at(i) == _t('\\') && !esc.empty()) ) { if(esc.empty()) { if(!word.empty()) { element::ptr el = std::make_shared<el_text>(word.c_str(), get_document()); appendChild(el); word.clear(); } element::ptr el = std::make_shared<el_space>(txt.substr(i, 1).c_str(), get_document()); appendChild(el); } else { word += convert_escape(esc.c_str() + 1); esc.clear(); if(txt.at(i) == _t('\\')) { esc += txt.at(i); } } } else { if(!esc.empty() || txt.at(i) == _t('\\')) { esc += txt.at(i); } else { word += txt.at(i); } } } if(!esc.empty()) { word += convert_escape(esc.c_str() + 1); } if(!word.empty()) { element::ptr el = std::make_shared<el_text>(word.c_str(), get_document()); appendChild(el); word.clear(); } } void litehtml::el_before_after_base::add_function( const tstring& fnc, const tstring& params ) { int idx = value_index(fnc.c_str(), _t("attr;counter;url")); switch(idx) { // attr case 0: { tstring p_name = params; trim(p_name); lcase(p_name); element::ptr el_parent = parent(); if (el_parent) { const tchar_t* attr_value = el_parent->get_attr(p_name.c_str()); if (attr_value) { add_text(attr_value); } } } break; // counter case 1: break; // url case 2: { tstring p_url = params; trim(p_url); if(!p_url.empty()) { if(p_url.at(0) == _t('\'') || p_url.at(0) == _t('\"')) { p_url.erase(0, 1); } } if(!p_url.empty()) { if(p_url.at(p_url.length() - 1) == _t('\'') || p_url.at(p_url.length() - 1) == _t('\"')) { p_url.erase(p_url.length() - 1, 1); } } if(!p_url.empty()) { element::ptr el = std::make_shared<el_image>(get_document()); el->set_attr(_t("src"), p_url.c_str()); el->set_attr(_t("style"), _t("display:inline-block")); el->set_tagName(_t("img")); appendChild(el); el->parse_attributes(); } } break; } } litehtml::tstring litehtml::el_before_after_base::convert_escape( const tchar_t* txt ) { tchar_t* str_end; wchar_t u_str[2]; u_str[0] = (wchar_t) t_strtol(txt, &str_end, 16); u_str[1] = 0; return litehtml::tstring(litehtml_from_wchar(u_str)); } void litehtml::el_before_after_base::apply_stylesheet( const litehtml::css& stylesheet ) { } <|endoftext|>
<commit_before>#include "App.h" int main() { /* ws->getUserData returns one of these */ struct PerSocketData { }; /* Very simple WebSocket echo server */ uWS::App().ws<PerSocketData>("/*", { /* Settings */ .compression = true, .maxPayloadLength = 16 * 1024, /* Handlers */ .open = [](auto *ws, auto *req) { }, .message = [](auto *ws, std::string_view message, uWS::OpCode opCode) { ws->send(message, opCode); }, .drain = [](auto *ws) { /* Check getBufferedAmount here */ }, .ping = [](auto *ws) { }, .pong = [](auto *ws) { }, .close = [](auto *ws, int code, std::string_view message) { } }).listen(9001, [](auto *token) { if (token) { std::cout << "Listening on port " << 9001 << std::endl; } }).run(); } <commit_msg>Update EchoServer example<commit_after>#include "App.h" int main() { /* ws->getUserData returns one of these */ struct PerSocketData { }; /* Very simple WebSocket echo server */ uWS::App().ws<PerSocketData>("/*", { /* Settings */ .compression = uWS::SHARED_COMPRESSOR, .maxPayloadLength = 16 * 1024, /* Handlers */ .open = [](auto *ws, auto *req) { }, .message = [](auto *ws, std::string_view message, uWS::OpCode opCode) { ws->send(message, opCode); }, .drain = [](auto *ws) { /* Check getBufferedAmount here */ }, .ping = [](auto *ws) { }, .pong = [](auto *ws) { }, .close = [](auto *ws, int code, std::string_view message) { } }).listen(9001, [](auto *token) { if (token) { std::cout << "Listening on port " << 9001 << std::endl; } }).run(); } <|endoftext|>
<commit_before><commit_msg>commenting<commit_after><|endoftext|>
<commit_before>//===---- ReleaseDevirtualizer.cpp - Devirtualizes release-instructions ---===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "release-devirtualizer" #include "swift/SILOptimizer/PassManager/Passes.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "swift/SILOptimizer/Analysis/RCIdentityAnalysis.h" #include "swift/SIL/SILBuilder.h" #include "llvm/ADT/Statistic.h" STATISTIC(NumReleasesDevirtualized, "Number of devirtualized releases"); using namespace swift; namespace { /// Devirtualizes release instructions which are known to destruct the object. /// This means, it replaces a sequence of /// %x = alloc_ref [stack] $X /// ... /// strong_release %x /// dealloc_ref [stack] %x /// with /// %x = alloc_ref [stack] $X /// ... /// %d = function_ref @deinit_of_X /// %a = apply %d(%x) /// dealloc_ref [stack] %x /// /// It also works for array buffers, where the allocation/deallocation is done /// by calls to the swift_bufferAllocateOnStack/swift_bufferDeallocateFromStack /// functions. /// /// The optimization is only done for stack promoted objects because they are /// known to have no associated objects (which are not explicitly released /// in the deinit method). class ReleaseDevirtualizer : public SILFunctionTransform { public: ReleaseDevirtualizer() {} private: /// The entry point to the transformation. void run() override; /// Devirtualize releases of array buffers. bool devirtualizeReleaseOfObject(SILInstruction *ReleaseInst, DeallocRefInst *DeallocInst); /// Devirtualize releases of swift objects. bool devirtualizeReleaseOfBuffer(SILInstruction *ReleaseInst, ApplyInst *DeallocCall); /// Replace the release-instruction \p ReleaseInst with an explicit call to /// the destructor of \p AllocType for \p object. bool createDeinitCall(SILType AllocType, SILInstruction *ReleaseInst, SILValue object); StringRef getName() override { return "Release Devirtualizer"; } RCIdentityFunctionInfo *RCIA = nullptr; }; void ReleaseDevirtualizer::run() { DEBUG(llvm::dbgs() << "** ReleaseDevirtualizer **\n"); SILFunction *F = getFunction(); RCIA = PM->getAnalysis<RCIdentityAnalysis>()->get(F); bool Changed = false; for (SILBasicBlock &BB : *F) { // The last release_value or strong_release instruction before the // deallocation. SILInstruction *LastRelease = nullptr; for (SILInstruction &I : BB) { if (LastRelease) { if (auto *DRI = dyn_cast<DeallocRefInst>(&I)) { Changed |= devirtualizeReleaseOfObject(LastRelease, DRI); continue; } if (auto *AI = dyn_cast<ApplyInst>(&I)) { Changed |= devirtualizeReleaseOfBuffer(LastRelease, AI); continue; } } if (isa<ReleaseValueInst>(&I) || isa<StrongReleaseInst>(&I)) { LastRelease = &I; } else if (I.mayReleaseOrReadRefCount()) { LastRelease = nullptr; } } } if (Changed) { invalidateAnalysis(SILAnalysis::InvalidationKind::CallsAndInstructions); } } bool ReleaseDevirtualizer:: devirtualizeReleaseOfObject(SILInstruction *ReleaseInst, DeallocRefInst *DeallocInst) { // We only do the optimization for stack promoted object, because for these // we know that they don't have associated objects, which are _not_ released // by the deinit method. // This restriction is no problem because only stack promotion result in this // alloc-release-dealloc pattern. if (!DeallocInst->canAllocOnStack()) return false; // Is the dealloc_ref paired with an alloc_ref? AllocRefInst *ARI = dyn_cast<AllocRefInst>(DeallocInst->getOperand()); if (!ARI) return false; // Does the last release really release the allocated object? SILValue rcRoot = RCIA->getRCIdentityRoot(ReleaseInst->getOperand(0)); if (rcRoot != ARI) return false; SILType AllocType = ARI->getType(); return createDeinitCall(AllocType, ReleaseInst, ARI); } bool ReleaseDevirtualizer:: devirtualizeReleaseOfBuffer(SILInstruction *ReleaseInst, ApplyInst *DeallocCall) { // Is this a deallocation of a buffer? SILFunction *DeallocFn = DeallocCall->getCalleeFunction(); if (!DeallocFn || DeallocFn->getName() != "swift_bufferDeallocateFromStack") return false; // Is the deallocation call paired with an allocation call? ApplyInst *AllocAI = dyn_cast<ApplyInst>(DeallocCall->getArgument(0)); if (!AllocAI || AllocAI->getNumArguments() < 1) return false; SILFunction *AllocFunc = AllocAI->getCalleeFunction(); if (!AllocFunc || AllocFunc->getName() != "swift_bufferAllocateOnStack") return false; // Can we find the buffer type which is allocated? It's metatype is passed // as first argument to the allocation function. auto *IEMTI = dyn_cast<InitExistentialMetatypeInst>(AllocAI->getArgument(0)); if (!IEMTI) return false; SILType MType = IEMTI->getOperand().getType(); auto *MetaType = MType.getSwiftRValueType()->getAs<AnyMetatypeType>(); if (!MetaType) return false; // Is the allocated buffer a class type? This should always be the case. auto *ClType = MetaType->getInstanceType()->getAs<BoundGenericClassType>(); if (!ClType) return false; // Does the last release really release the allocated buffer? SILValue rcRoot = RCIA->getRCIdentityRoot(ReleaseInst->getOperand(0)); if (rcRoot != AllocAI) return false; SILType SILClType = SILType::getPrimitiveObjectType(CanType(ClType)); return createDeinitCall(SILClType, ReleaseInst, AllocAI); } bool ReleaseDevirtualizer::createDeinitCall(SILType AllocType, SILInstruction *ReleaseInst, SILValue object) { ClassDecl *Cl = AllocType.getClassOrBoundGenericClass(); assert(Cl && "no class type allocated with alloc_ref"); // Find the destructor of the type. DestructorDecl *Destructor = Cl->getDestructor(); SILDeclRef DeinitRef(Destructor, SILDeclRef::Kind::Destroyer); SILModule &M = ReleaseInst->getFunction()->getModule(); SILFunction *Deinit = M.lookUpFunction(DeinitRef); if (!Deinit) return false; CanSILFunctionType DeinitType = Deinit->getLoweredFunctionType(); ArrayRef<Substitution> AllocSubsts = AllocType.gatherAllSubstitutions(M); assert(!AllocSubsts.empty() == DeinitType->isPolymorphic() && "deinit of generic class is not polymorphic or vice versa"); if (DeinitType->isPolymorphic()) DeinitType = DeinitType->substGenericArgs(M, M.getSwiftModule(), AllocSubsts); SILType ReturnType = DeinitType->getResult().getSILType(); SILType DeinitSILType = SILType::getPrimitiveObjectType(DeinitType); SILBuilder B(ReleaseInst); if (object.getType() != AllocType) object = B.createUncheckedRefCast(ReleaseInst->getLoc(), object, AllocType); // Create the call to the destructor with the allocated object as self // argument. auto *MI = B.createFunctionRef(ReleaseInst->getLoc(), Deinit); B.createApply(ReleaseInst->getLoc(), MI, DeinitSILType, ReturnType, AllocSubsts, { object }, false); NumReleasesDevirtualized++; ReleaseInst->eraseFromParent(); return true; } } // end anonymous namespace SILTransform *swift::createReleaseDevirtualizer() { return new ReleaseDevirtualizer(); } <commit_msg>[ReleaseDevirtualizer] fix non-detriministic crash.<commit_after>//===---- ReleaseDevirtualizer.cpp - Devirtualizes release-instructions ---===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "release-devirtualizer" #include "swift/SILOptimizer/PassManager/Passes.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "swift/SILOptimizer/Analysis/RCIdentityAnalysis.h" #include "swift/SIL/SILBuilder.h" #include "llvm/ADT/Statistic.h" STATISTIC(NumReleasesDevirtualized, "Number of devirtualized releases"); using namespace swift; namespace { /// Devirtualizes release instructions which are known to destruct the object. /// This means, it replaces a sequence of /// %x = alloc_ref [stack] $X /// ... /// strong_release %x /// dealloc_ref [stack] %x /// with /// %x = alloc_ref [stack] $X /// ... /// %d = function_ref @deinit_of_X /// %a = apply %d(%x) /// dealloc_ref [stack] %x /// /// It also works for array buffers, where the allocation/deallocation is done /// by calls to the swift_bufferAllocateOnStack/swift_bufferDeallocateFromStack /// functions. /// /// The optimization is only done for stack promoted objects because they are /// known to have no associated objects (which are not explicitly released /// in the deinit method). class ReleaseDevirtualizer : public SILFunctionTransform { public: ReleaseDevirtualizer() {} private: /// The entry point to the transformation. void run() override; /// Devirtualize releases of array buffers. bool devirtualizeReleaseOfObject(SILInstruction *ReleaseInst, DeallocRefInst *DeallocInst); /// Devirtualize releases of swift objects. bool devirtualizeReleaseOfBuffer(SILInstruction *ReleaseInst, ApplyInst *DeallocCall); /// Replace the release-instruction \p ReleaseInst with an explicit call to /// the destructor of \p AllocType for \p object. bool createDeinitCall(SILType AllocType, SILInstruction *ReleaseInst, SILValue object); StringRef getName() override { return "Release Devirtualizer"; } RCIdentityFunctionInfo *RCIA = nullptr; }; void ReleaseDevirtualizer::run() { DEBUG(llvm::dbgs() << "** ReleaseDevirtualizer **\n"); SILFunction *F = getFunction(); RCIA = PM->getAnalysis<RCIdentityAnalysis>()->get(F); bool Changed = false; for (SILBasicBlock &BB : *F) { // The last release_value or strong_release instruction before the // deallocation. SILInstruction *LastRelease = nullptr; for (SILInstruction &I : BB) { if (LastRelease) { if (auto *DRI = dyn_cast<DeallocRefInst>(&I)) { Changed |= devirtualizeReleaseOfObject(LastRelease, DRI); LastRelease = nullptr; continue; } if (auto *AI = dyn_cast<ApplyInst>(&I)) { Changed |= devirtualizeReleaseOfBuffer(LastRelease, AI); LastRelease = nullptr; continue; } } if (isa<ReleaseValueInst>(&I) || isa<StrongReleaseInst>(&I)) { LastRelease = &I; } else if (I.mayReleaseOrReadRefCount()) { LastRelease = nullptr; } } } if (Changed) { invalidateAnalysis(SILAnalysis::InvalidationKind::CallsAndInstructions); } } bool ReleaseDevirtualizer:: devirtualizeReleaseOfObject(SILInstruction *ReleaseInst, DeallocRefInst *DeallocInst) { DEBUG(llvm::dbgs() << " try to devirtualize " << *ReleaseInst); // We only do the optimization for stack promoted object, because for these // we know that they don't have associated objects, which are _not_ released // by the deinit method. // This restriction is no problem because only stack promotion result in this // alloc-release-dealloc pattern. if (!DeallocInst->canAllocOnStack()) return false; // Is the dealloc_ref paired with an alloc_ref? AllocRefInst *ARI = dyn_cast<AllocRefInst>(DeallocInst->getOperand()); if (!ARI) return false; // Does the last release really release the allocated object? SILValue rcRoot = RCIA->getRCIdentityRoot(ReleaseInst->getOperand(0)); if (rcRoot != ARI) return false; SILType AllocType = ARI->getType(); return createDeinitCall(AllocType, ReleaseInst, ARI); } bool ReleaseDevirtualizer:: devirtualizeReleaseOfBuffer(SILInstruction *ReleaseInst, ApplyInst *DeallocCall) { DEBUG(llvm::dbgs() << " try to devirtualize " << *ReleaseInst); // Is this a deallocation of a buffer? SILFunction *DeallocFn = DeallocCall->getCalleeFunction(); if (!DeallocFn || DeallocFn->getName() != "swift_bufferDeallocateFromStack") return false; // Is the deallocation call paired with an allocation call? ApplyInst *AllocAI = dyn_cast<ApplyInst>(DeallocCall->getArgument(0)); if (!AllocAI || AllocAI->getNumArguments() < 1) return false; SILFunction *AllocFunc = AllocAI->getCalleeFunction(); if (!AllocFunc || AllocFunc->getName() != "swift_bufferAllocateOnStack") return false; // Can we find the buffer type which is allocated? It's metatype is passed // as first argument to the allocation function. auto *IEMTI = dyn_cast<InitExistentialMetatypeInst>(AllocAI->getArgument(0)); if (!IEMTI) return false; SILType MType = IEMTI->getOperand().getType(); auto *MetaType = MType.getSwiftRValueType()->getAs<AnyMetatypeType>(); if (!MetaType) return false; // Is the allocated buffer a class type? This should always be the case. auto *ClType = MetaType->getInstanceType()->getAs<BoundGenericClassType>(); if (!ClType) return false; // Does the last release really release the allocated buffer? SILValue rcRoot = RCIA->getRCIdentityRoot(ReleaseInst->getOperand(0)); if (rcRoot != AllocAI) return false; SILType SILClType = SILType::getPrimitiveObjectType(CanType(ClType)); return createDeinitCall(SILClType, ReleaseInst, AllocAI); } bool ReleaseDevirtualizer::createDeinitCall(SILType AllocType, SILInstruction *ReleaseInst, SILValue object) { DEBUG(llvm::dbgs() << " create deinit call\n"); ClassDecl *Cl = AllocType.getClassOrBoundGenericClass(); assert(Cl && "no class type allocated with alloc_ref"); // Find the destructor of the type. DestructorDecl *Destructor = Cl->getDestructor(); SILDeclRef DeinitRef(Destructor, SILDeclRef::Kind::Destroyer); SILModule &M = ReleaseInst->getFunction()->getModule(); SILFunction *Deinit = M.lookUpFunction(DeinitRef); if (!Deinit) return false; CanSILFunctionType DeinitType = Deinit->getLoweredFunctionType(); ArrayRef<Substitution> AllocSubsts = AllocType.gatherAllSubstitutions(M); assert(!AllocSubsts.empty() == DeinitType->isPolymorphic() && "deinit of generic class is not polymorphic or vice versa"); if (DeinitType->isPolymorphic()) DeinitType = DeinitType->substGenericArgs(M, M.getSwiftModule(), AllocSubsts); SILType ReturnType = DeinitType->getResult().getSILType(); SILType DeinitSILType = SILType::getPrimitiveObjectType(DeinitType); SILBuilder B(ReleaseInst); if (object.getType() != AllocType) object = B.createUncheckedRefCast(ReleaseInst->getLoc(), object, AllocType); // Create the call to the destructor with the allocated object as self // argument. auto *MI = B.createFunctionRef(ReleaseInst->getLoc(), Deinit); B.createApply(ReleaseInst->getLoc(), MI, DeinitSILType, ReturnType, AllocSubsts, { object }, false); NumReleasesDevirtualized++; ReleaseInst->eraseFromParent(); return true; } } // end anonymous namespace SILTransform *swift::createReleaseDevirtualizer() { return new ReleaseDevirtualizer(); } <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2011 \file rdobase.cpp \author (rdo@rk9.bmstu.ru) \date 11.06.2006 \brief \indent 4T */ // ----------------------------------------------------------------------- PLATFORM #include "utils/platform.h" // ---------------------------------------------------------------------------- PCH #include "simulator/runtime/pch.h" // ----------------------------------------------------------------------- INCLUDES #include <limits> #ifndef OST_WINDOWS #include <float.h> #endif // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/runtime/rdobase.h" #include "simulator/runtime/calc/operation_type.h" // -------------------------------------------------------------------------------- #ifdef OST_WINDOWS #pragma warning(disable : 4786) #endif OPEN_RDO_RUNTIME_NAMESPACE // -------------------------------------------------------------------------------- // -------------------- RDOSimulatorBase // -------------------------------------------------------------------------------- RDOSimulatorBase::RDOSimulatorBase() : m_startTime (0 ) , m_currentTime (0 ) , m_nextTime (0 ) , m_mode (rdoRuntime::RTM_MaxSpeed) , m_speed (1 ) , m_speed_range_max (500000 ) , m_next_delay_count (0 ) , m_next_delay_current(0 ) , m_showRate (60 ) , m_msec_wait (0 ) , m_msec_prev (0 ) , m_cnt_events (0 ) , m_cnt_choice_from (0 ) , m_checkOperation (true ) {} ruint RDOSimulatorBase::get_cnt_calc_arithm() const { return OperatorType::getCalcCounter<OperatorType::OT_ARITHM>(); } ruint RDOSimulatorBase::get_cnt_calc_logic() const { return OperatorType::getCalcCounter<OperatorType::OT_LOGIC>(); } void RDOSimulatorBase::rdoInit() { m_currentTime = m_startTime; m_nextTime = m_currentTime; m_checkOperation = true; onInit(); OperatorType::getCalcCounter<OperatorType::OT_ARITHM>() = 0; OperatorType::getCalcCounter<OperatorType::OT_LOGIC> () = 0; if (m_timePoints.find(m_currentTime) == m_timePoints.end()) m_timePoints[m_currentTime] = NULL; preProcess(); m_speed = 1; m_next_delay_count = 0; m_next_delay_current = 0; m_showRate = 60; m_msec_wait = 0; onNewTimeNow(); } rbool RDOSimulatorBase::rdoNext() { if (m_mode == rdoRuntime::RTM_Pause || m_mode == rdoRuntime::RTM_BreakPoint) { ::Sleep(1); return true; } // , rbool keyboard = isKeyDown(); if (!keyboard) { // // mode == rdoRuntime::RTM_Jump || mode == rdoRuntime::RTM_Sync if (m_mode != rdoRuntime::RTM_MaxSpeed && m_next_delay_count) { ++m_next_delay_current; if (m_next_delay_current < m_next_delay_count) return true; m_next_delay_current = 0; } // ( ) // mode == rdoRuntime::RTM_Sync, .. msec_wait, // setMode . if (m_msec_wait > 1) { boost::posix_time::ptime systime_current = boost::posix_time::microsec_clock::local_time(); ruint msec_curr = getMSec(systime_current); ruint msec_delta; // , , // . // ELSE. // , . // ( ), // , // , . . // - , , // , . SYSTEMTIME . if (msec_curr >= m_msec_prev) { msec_delta = msec_curr - m_msec_prev; } else { msec_delta = UINT_MAX - m_msec_prev + msec_curr; } if (msec_delta <= m_msec_wait) return true; m_msec_wait -= msec_delta; } } // - if (endCondition()) { onEndCondition(); return false; } if (m_currentTime != m_nextTime) { m_currentTime = m_nextTime; onNewTimeNow(); } // if (doOperation()) { if (breakPoints()) { setMode(RTM_BreakPoint); } return true; } else { // if (!m_timePoints.empty()) { double newTime = m_timePoints.begin()->first; BOPlannedItem* list = m_timePoints.begin()->second; if (!list || list->empty()) { delete m_timePoints.begin()->second; m_timePoints.erase(m_timePoints.begin()); } if (m_currentTime > newTime) { newTime = m_currentTime; } if (m_mode == rdoRuntime::RTM_Sync) { m_msec_wait += (newTime - m_nextTime) * 3600.0 * 1000.0 / m_showRate; if (m_msec_wait > 0) { if (newTime != m_startTime) { if (m_speed > DBL_MIN) { m_msec_wait = m_msec_wait / m_speed; } else { m_msec_wait = m_msec_wait / DBL_MIN; } boost::posix_time::ptime systime_current = boost::posix_time::microsec_clock::local_time(); m_msec_prev = getMSec(systime_current); } else { m_msec_wait = 0; } } } m_nextTime = newTime; return true; } else { // - onNothingMoreToDo(); return false; } } return true; } void RDOSimulatorBase::setMode(rdoRuntime::RunTimeMode _mode) { if (m_mode == rdoRuntime::RTM_Pause) { // ' ' m_next_delay_current = m_next_delay_count; m_msec_wait = 0; } m_mode = _mode; if (m_mode == rdoRuntime::RTM_MaxSpeed || m_mode == rdoRuntime::RTM_Jump) { // m_next_delay_current = m_next_delay_count; m_msec_wait = 0; } } void RDOSimulatorBase::setSpeed( double value ) { if (value < 0) value = 0; if (value > 1) value = 1; m_speed = value; m_next_delay_count = (unsigned int)((1 - m_speed) * m_speed_range_max); // m_next_delay_current = m_next_delay_count; m_msec_wait = 0; } void RDOSimulatorBase::setShowRate( double value ) { if (value < DBL_MIN) value = DBL_MIN; if (value > DBL_MAX) value = DBL_MAX; m_showRate = value; // m_next_delay_current = m_next_delay_count; m_msec_wait = 0; } void RDOSimulatorBase::rdoPostProcess() { postProcess(); while (!m_timePoints.empty()) { delete m_timePoints.begin()->second; m_timePoints.erase(m_timePoints.begin()); } } void RDOSimulatorBase::addTimePoint(double timePoint, CREF(LPIBaseOperation) opr, void* param) { BOPlannedItem* list = NULL; if (opr && (m_timePoints.find(timePoint) == m_timePoints.end() || m_timePoints[timePoint] == NULL)) { list = new BOPlannedItem(); m_timePoints[timePoint] = list; } if (opr) { m_timePoints[timePoint]->push_back(BOPlanned(opr, param)); } } void RDOSimulatorBase::removeTimePoint(CREF(LPIBaseOperation) opr) { BOPlannedMap::iterator it = m_timePoints.begin(); while (it != m_timePoints.end()) { BOPlannedItem* list = it->second; BOPlannedItem::iterator item = list->begin(); while (item != list->end()) { // if (item->m_opr == opr) { item = list->erase(item); continue; } ++item; } // , if (list->empty()) { it = m_timePoints.erase(it); continue; } else { ++it; } } } CLOSE_RDO_RUNTIME_NAMESPACE <commit_msg> - using boost<commit_after>/*! \copyright (c) RDO-Team, 2011 \file rdobase.cpp \author (rdo@rk9.bmstu.ru) \date 11.06.2006 \brief \indent 4T */ // ----------------------------------------------------------------------- PLATFORM #include "utils/platform.h" // ---------------------------------------------------------------------------- PCH #include "simulator/runtime/pch.h" // ----------------------------------------------------------------------- INCLUDES #include <limits> #ifndef OST_WINDOWS #include <float.h> #endif #include <boost/thread.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/runtime/rdobase.h" #include "simulator/runtime/calc/operation_type.h" // -------------------------------------------------------------------------------- #ifdef OST_WINDOWS #pragma warning(disable : 4786) #endif OPEN_RDO_RUNTIME_NAMESPACE // -------------------------------------------------------------------------------- // -------------------- RDOSimulatorBase // -------------------------------------------------------------------------------- RDOSimulatorBase::RDOSimulatorBase() : m_startTime (0 ) , m_currentTime (0 ) , m_nextTime (0 ) , m_mode (rdoRuntime::RTM_MaxSpeed) , m_speed (1 ) , m_speed_range_max (500000 ) , m_next_delay_count (0 ) , m_next_delay_current(0 ) , m_showRate (60 ) , m_msec_wait (0 ) , m_msec_prev (0 ) , m_cnt_events (0 ) , m_cnt_choice_from (0 ) , m_checkOperation (true ) {} ruint RDOSimulatorBase::get_cnt_calc_arithm() const { return OperatorType::getCalcCounter<OperatorType::OT_ARITHM>(); } ruint RDOSimulatorBase::get_cnt_calc_logic() const { return OperatorType::getCalcCounter<OperatorType::OT_LOGIC>(); } void RDOSimulatorBase::rdoInit() { m_currentTime = m_startTime; m_nextTime = m_currentTime; m_checkOperation = true; onInit(); OperatorType::getCalcCounter<OperatorType::OT_ARITHM>() = 0; OperatorType::getCalcCounter<OperatorType::OT_LOGIC> () = 0; if (m_timePoints.find(m_currentTime) == m_timePoints.end()) m_timePoints[m_currentTime] = NULL; preProcess(); m_speed = 1; m_next_delay_count = 0; m_next_delay_current = 0; m_showRate = 60; m_msec_wait = 0; onNewTimeNow(); } rbool RDOSimulatorBase::rdoNext() { if (m_mode == rdoRuntime::RTM_Pause || m_mode == rdoRuntime::RTM_BreakPoint) { boost::this_thread::sleep(boost::posix_time::milliseconds(1)); return true; } // , rbool keyboard = isKeyDown(); if (!keyboard) { // // mode == rdoRuntime::RTM_Jump || mode == rdoRuntime::RTM_Sync if (m_mode != rdoRuntime::RTM_MaxSpeed && m_next_delay_count) { ++m_next_delay_current; if (m_next_delay_current < m_next_delay_count) return true; m_next_delay_current = 0; } // ( ) // mode == rdoRuntime::RTM_Sync, .. msec_wait, // setMode . if (m_msec_wait > 1) { boost::posix_time::ptime systime_current = boost::posix_time::microsec_clock::local_time(); ruint msec_curr = getMSec(systime_current); ruint msec_delta; // , , // . // ELSE. // , . // ( ), // , // , . . // - , , // , . SYSTEMTIME . if (msec_curr >= m_msec_prev) { msec_delta = msec_curr - m_msec_prev; } else { msec_delta = UINT_MAX - m_msec_prev + msec_curr; } if (msec_delta <= m_msec_wait) return true; m_msec_wait -= msec_delta; } } // - if (endCondition()) { onEndCondition(); return false; } if (m_currentTime != m_nextTime) { m_currentTime = m_nextTime; onNewTimeNow(); } // if (doOperation()) { if (breakPoints()) { setMode(RTM_BreakPoint); } return true; } else { // if (!m_timePoints.empty()) { double newTime = m_timePoints.begin()->first; BOPlannedItem* list = m_timePoints.begin()->second; if (!list || list->empty()) { delete m_timePoints.begin()->second; m_timePoints.erase(m_timePoints.begin()); } if (m_currentTime > newTime) { newTime = m_currentTime; } if (m_mode == rdoRuntime::RTM_Sync) { m_msec_wait += (newTime - m_nextTime) * 3600.0 * 1000.0 / m_showRate; if (m_msec_wait > 0) { if (newTime != m_startTime) { if (m_speed > DBL_MIN) { m_msec_wait = m_msec_wait / m_speed; } else { m_msec_wait = m_msec_wait / DBL_MIN; } boost::posix_time::ptime systime_current = boost::posix_time::microsec_clock::local_time(); m_msec_prev = getMSec(systime_current); } else { m_msec_wait = 0; } } } m_nextTime = newTime; return true; } else { // - onNothingMoreToDo(); return false; } } return true; } void RDOSimulatorBase::setMode(rdoRuntime::RunTimeMode _mode) { if (m_mode == rdoRuntime::RTM_Pause) { // ' ' m_next_delay_current = m_next_delay_count; m_msec_wait = 0; } m_mode = _mode; if (m_mode == rdoRuntime::RTM_MaxSpeed || m_mode == rdoRuntime::RTM_Jump) { // m_next_delay_current = m_next_delay_count; m_msec_wait = 0; } } void RDOSimulatorBase::setSpeed( double value ) { if (value < 0) value = 0; if (value > 1) value = 1; m_speed = value; m_next_delay_count = (unsigned int)((1 - m_speed) * m_speed_range_max); // m_next_delay_current = m_next_delay_count; m_msec_wait = 0; } void RDOSimulatorBase::setShowRate( double value ) { if (value < DBL_MIN) value = DBL_MIN; if (value > DBL_MAX) value = DBL_MAX; m_showRate = value; // m_next_delay_current = m_next_delay_count; m_msec_wait = 0; } void RDOSimulatorBase::rdoPostProcess() { postProcess(); while (!m_timePoints.empty()) { delete m_timePoints.begin()->second; m_timePoints.erase(m_timePoints.begin()); } } void RDOSimulatorBase::addTimePoint(double timePoint, CREF(LPIBaseOperation) opr, void* param) { BOPlannedItem* list = NULL; if (opr && (m_timePoints.find(timePoint) == m_timePoints.end() || m_timePoints[timePoint] == NULL)) { list = new BOPlannedItem(); m_timePoints[timePoint] = list; } if (opr) { m_timePoints[timePoint]->push_back(BOPlanned(opr, param)); } } void RDOSimulatorBase::removeTimePoint(CREF(LPIBaseOperation) opr) { BOPlannedMap::iterator it = m_timePoints.begin(); while (it != m_timePoints.end()) { BOPlannedItem* list = it->second; BOPlannedItem::iterator item = list->begin(); while (item != list->end()) { // if (item->m_opr == opr) { item = list->erase(item); continue; } ++item; } // , if (list->empty()) { it = m_timePoints.erase(it); continue; } else { ++it; } } } CLOSE_RDO_RUNTIME_NAMESPACE <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tabletree.hxx,v $ * * $Revision: 1.16 $ * * last change: $Author: kz $ $Date: 2006-10-05 13:06:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _DBAUI_TABLETREE_HXX_ #define _DBAUI_TABLETREE_HXX_ #ifndef _DBAUI_MARKTREE_HXX_ #include "marktree.hxx" #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_ #include <com/sun/star/sdbc/XDatabaseMetaData.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_ #include <com/sun/star/sdbc/XConnection.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XDRIVER_HPP_ #include <com/sun/star/sdbc/XDriver.hpp> #endif #include <memory> //......................................................................... namespace dbaui { //......................................................................... class ImageProvider; //======================================================================== //= OTableTreeListBox //======================================================================== class OTableTreeListBox : public OMarkableTreeListBox { protected: ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xConnection; // the connection we're working for, set in implOnNewConnection, called by UpdateTableList ::std::auto_ptr< ImageProvider > m_pImageProvider; // provider for our images sal_Bool m_bVirtualRoot; // should the first entry be visible public: OTableTreeListBox( Window* pParent, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB, WinBits nWinStyle, sal_Bool _bVirtualRoot ); OTableTreeListBox( Window* pParent, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB, const ResId& rResId, sal_Bool _bVirtualRoot ); ~OTableTreeListBox(); typedef ::std::pair< ::rtl::OUString,sal_Bool> TTableViewName; typedef ::std::vector< TTableViewName > TNames; /** call when HiContrast change. */ void notifyHiContrastChanged(); /** determines whether the given entry denotes a tables folder */ bool isFolderEntry( const SvLBoxEntry* _pEntry ) const; /** determines whether the given entry denotes a table or view */ bool isTableOrViewEntry( const SvLBoxEntry* _pEntry ) const { return !isFolderEntry( _pEntry ); } /** fill the table list with the tables belonging to the connection described by the parameters @param _rxConnection the connection, which must support the service com.sun.star.sdb.Connection @throws <type scope="com::sun::star::sdbc">SQLException</type> if no connection could be created */ void UpdateTableList( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection ) throw(::com::sun::star::sdbc::SQLException); /** fill the table list with the tables and views determined by the two given containers. The views sequence is used to determine which table is of type view. @param _rxConnection the connection where you got the object names from. Must not be NULL. Used to split the full qualified names into it's parts. @param _rTables table/view sequence @param _rViews view sequence */ void UpdateTableList( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection, const ::com::sun::star::uno::Sequence< ::rtl::OUString>& _rTables, const ::com::sun::star::uno::Sequence< ::rtl::OUString>& _rViews ); /** to be used if a foreign instance added a table */ SvLBoxEntry* addedTable( const ::rtl::OUString& _rName ); /** to be used if a foreign instance removed a table */ void removedTable( const ::rtl::OUString& _rName ); /** returns the fully qualified name of a table entry @param _pEntry the entry whose name is to be obtained. Must not denote a folder entry. */ String getQualifiedTableName( SvLBoxEntry* _pEntry ) const; SvLBoxEntry* getEntryByQualifiedName( const ::rtl::OUString& _rName ); SvLBoxEntry* getAllObjectsEntry() const; /** does a wildcard check of the given entry <p>There are two different 'checked' states: If the user checks all children of an entry, this is different from checking the entry itself. The second is called 'wildcard' checking, 'cause in the resulting table filter it's represented by a wildcard.</p> */ void checkWildcard(SvLBoxEntry* _pEntry); /** determine if the given entry is 'wildcard checked' @see checkWildcard */ sal_Bool isWildcardChecked(SvLBoxEntry* _pEntry) const; protected: virtual void InitEntry(SvLBoxEntry* _pEntry, const XubString& _rString, const Image& _rCollapsedBitmap, const Image& _rExpandedBitmap); virtual void checkedButton_noBroadcast(SvLBoxEntry* _pEntry); void implEmphasize(SvLBoxEntry* _pEntry, sal_Bool _bChecked, sal_Bool _bUpdateDescendants = sal_True, sal_Bool _bUpdateAncestors = sal_True); /** adds the given entry to our list @precond our image provider must already have been reset to the connection to which the meta data belong. */ SvLBoxEntry* implAddEntry( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rxMeta, const ::rtl::OUString& _rTableName, sal_Bool _bCheckName = sal_True ); void implSetDefaultImages(); void implOnNewConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection ); bool impl_getAndAssertMetaData( ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _out_rMetaData ) const; sal_Bool haveVirtualRoot() const { return m_bVirtualRoot; } /** fill the table list with the tables and views determined by the two given containers @param _rxConnection the connection where you got the object names from. Must not be NULL. Used to split the full qualified names into it's parts. @param _rTables table/view sequence, the second argument is <TRUE/> if it is a table, otherwise it is a view. */ void UpdateTableList( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection, const TNames& _rTables ); }; //......................................................................... } // namespace dbaui //......................................................................... #endif // _DBAUI_TABLETREE_HXX_ <commit_msg>INTEGRATION: CWS jl49 (1.16.44); FILE MERGED 2006/12/01 12:18:08 sb 1.16.44.1: #i70481# Extended SvLBoxButton.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tabletree.hxx,v $ * * $Revision: 1.17 $ * * last change: $Author: ihi $ $Date: 2006-12-20 14:14:46 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _DBAUI_TABLETREE_HXX_ #define _DBAUI_TABLETREE_HXX_ #ifndef _DBAUI_MARKTREE_HXX_ #include "marktree.hxx" #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_ #include <com/sun/star/sdbc/XDatabaseMetaData.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_ #include <com/sun/star/sdbc/XConnection.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XDRIVER_HPP_ #include <com/sun/star/sdbc/XDriver.hpp> #endif #include <memory> //......................................................................... namespace dbaui { //......................................................................... class ImageProvider; //======================================================================== //= OTableTreeListBox //======================================================================== class OTableTreeListBox : public OMarkableTreeListBox { protected: ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xConnection; // the connection we're working for, set in implOnNewConnection, called by UpdateTableList ::std::auto_ptr< ImageProvider > m_pImageProvider; // provider for our images sal_Bool m_bVirtualRoot; // should the first entry be visible public: OTableTreeListBox( Window* pParent, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB, WinBits nWinStyle, sal_Bool _bVirtualRoot ); OTableTreeListBox( Window* pParent, const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB, const ResId& rResId, sal_Bool _bVirtualRoot ); ~OTableTreeListBox(); typedef ::std::pair< ::rtl::OUString,sal_Bool> TTableViewName; typedef ::std::vector< TTableViewName > TNames; /** call when HiContrast change. */ void notifyHiContrastChanged(); /** determines whether the given entry denotes a tables folder */ bool isFolderEntry( const SvLBoxEntry* _pEntry ) const; /** determines whether the given entry denotes a table or view */ bool isTableOrViewEntry( const SvLBoxEntry* _pEntry ) const { return !isFolderEntry( _pEntry ); } /** fill the table list with the tables belonging to the connection described by the parameters @param _rxConnection the connection, which must support the service com.sun.star.sdb.Connection @throws <type scope="com::sun::star::sdbc">SQLException</type> if no connection could be created */ void UpdateTableList( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection ) throw(::com::sun::star::sdbc::SQLException); /** fill the table list with the tables and views determined by the two given containers. The views sequence is used to determine which table is of type view. @param _rxConnection the connection where you got the object names from. Must not be NULL. Used to split the full qualified names into it's parts. @param _rTables table/view sequence @param _rViews view sequence */ void UpdateTableList( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection, const ::com::sun::star::uno::Sequence< ::rtl::OUString>& _rTables, const ::com::sun::star::uno::Sequence< ::rtl::OUString>& _rViews ); /** to be used if a foreign instance added a table */ SvLBoxEntry* addedTable( const ::rtl::OUString& _rName ); /** to be used if a foreign instance removed a table */ void removedTable( const ::rtl::OUString& _rName ); /** returns the fully qualified name of a table entry @param _pEntry the entry whose name is to be obtained. Must not denote a folder entry. */ String getQualifiedTableName( SvLBoxEntry* _pEntry ) const; SvLBoxEntry* getEntryByQualifiedName( const ::rtl::OUString& _rName ); SvLBoxEntry* getAllObjectsEntry() const; /** does a wildcard check of the given entry <p>There are two different 'checked' states: If the user checks all children of an entry, this is different from checking the entry itself. The second is called 'wildcard' checking, 'cause in the resulting table filter it's represented by a wildcard.</p> */ void checkWildcard(SvLBoxEntry* _pEntry); /** determine if the given entry is 'wildcard checked' @see checkWildcard */ sal_Bool isWildcardChecked(SvLBoxEntry* _pEntry) const; protected: virtual void InitEntry(SvLBoxEntry* _pEntry, const XubString& _rString, const Image& _rCollapsedBitmap, const Image& _rExpandedBitmap, SvLBoxButtonKind _eButtonKind); virtual void checkedButton_noBroadcast(SvLBoxEntry* _pEntry); void implEmphasize(SvLBoxEntry* _pEntry, sal_Bool _bChecked, sal_Bool _bUpdateDescendants = sal_True, sal_Bool _bUpdateAncestors = sal_True); /** adds the given entry to our list @precond our image provider must already have been reset to the connection to which the meta data belong. */ SvLBoxEntry* implAddEntry( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rxMeta, const ::rtl::OUString& _rTableName, sal_Bool _bCheckName = sal_True ); void implSetDefaultImages(); void implOnNewConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection ); bool impl_getAndAssertMetaData( ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _out_rMetaData ) const; sal_Bool haveVirtualRoot() const { return m_bVirtualRoot; } /** fill the table list with the tables and views determined by the two given containers @param _rxConnection the connection where you got the object names from. Must not be NULL. Used to split the full qualified names into it's parts. @param _rTables table/view sequence, the second argument is <TRUE/> if it is a table, otherwise it is a view. */ void UpdateTableList( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection, const TNames& _rTables ); }; //......................................................................... } // namespace dbaui //......................................................................... #endif // _DBAUI_TABLETREE_HXX_ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: charsets.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: hr $ $Date: 2006-06-20 03:22:45 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _DBAUI_CHARSETS_HXX_ #include "charsets.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _DBU_MISCRES_HRC_ #include "dbumiscres.hrc" #endif #ifndef _DBU_MISC_HRC_ #include "dbu_misc.hrc" #endif #ifndef _RTL_TENCINFO_H #include <rtl/tencinfo.h> #endif #ifndef _TOOLS_RCID_H #include <tools/rcid.h> #endif #ifndef _DBAUI_LOCALRESACCESS_HXX_ #include "localresaccess.hxx" #endif //......................................................................... namespace dbaui { //......................................................................... using namespace ::dbtools; //========================================================================= //= OCharsetDisplay //========================================================================= //------------------------------------------------------------------------- OCharsetDisplay::OCharsetDisplay() :OCharsetMap() ,SvxTextEncodingTable() { { LocalResourceAccess aCharsetStrings( RSC_CHARSETS, RSC_RESOURCE ); m_aSystemDisplayName = String( ResId( 1 ) ); } } //------------------------------------------------------------------------- sal_Bool OCharsetDisplay::approveEncoding( const rtl_TextEncoding _eEncoding, const rtl_TextEncodingInfo& _rInfo ) const { if ( !OCharsetMap::approveEncoding( _eEncoding, _rInfo ) ) return sal_False; if ( RTL_TEXTENCODING_DONTKNOW == _eEncoding ) return sal_True; return 0 != GetTextString( _eEncoding ).Len(); } //------------------------------------------------------------------------- OCharsetDisplay::const_iterator OCharsetDisplay::begin() const { return const_iterator( this, OCharsetMap::begin() ); } //------------------------------------------------------------------------- OCharsetDisplay::const_iterator OCharsetDisplay::end() const { return const_iterator( this, OCharsetMap::end() ); } //------------------------------------------------------------------------- OCharsetDisplay::const_iterator OCharsetDisplay::findEncoding(const rtl_TextEncoding _eEncoding) const { OCharsetMap::const_iterator aBaseIter = OCharsetMap::find(_eEncoding); return const_iterator( this, aBaseIter ); } //------------------------------------------------------------------------- OCharsetDisplay::const_iterator OCharsetDisplay::findIanaName(const ::rtl::OUString& _rIanaName) const { OCharsetMap::const_iterator aBaseIter = OCharsetMap::find(_rIanaName, OCharsetMap::IANA()); return const_iterator( this, aBaseIter ); } //------------------------------------------------------------------------- OCharsetDisplay::const_iterator OCharsetDisplay::findDisplayName(const ::rtl::OUString& _rDisplayName) const { rtl_TextEncoding eEncoding = RTL_TEXTENCODING_DONTKNOW; if ( _rDisplayName != m_aSystemDisplayName ) { eEncoding = GetTextEncoding( _rDisplayName ); OSL_ENSURE( RTL_TEXTENCODING_DONTKNOW != eEncoding, "OCharsetDisplay::find: non-empty display name, but DONTKNOW!" ); } return const_iterator( this, OCharsetMap::find( eEncoding ) ); } //========================================================================= //= CharsetDisplayDerefHelper //========================================================================= //------------------------------------------------------------------------- CharsetDisplayDerefHelper::CharsetDisplayDerefHelper(const CharsetDisplayDerefHelper& _rSource) :CharsetDisplayDerefHelper_Base(_rSource) ,m_sDisplayName(m_sDisplayName) { } //------------------------------------------------------------------------- CharsetDisplayDerefHelper::CharsetDisplayDerefHelper(const CharsetDisplayDerefHelper_Base& _rBase, const ::rtl::OUString& _rDisplayName) :CharsetDisplayDerefHelper_Base(_rBase) ,m_sDisplayName(_rDisplayName) { DBG_ASSERT( m_sDisplayName.getLength(), "CharsetDisplayDerefHelper::CharsetDisplayDerefHelper: invalid display name!" ); } //------------------------------------------------------------------------- CharsetDisplayDerefHelper::CharsetDisplayDerefHelper() { } //========================================================================= //= OCharsetDisplay::ExtendedCharsetIterator //========================================================================= //------------------------------------------------------------------------- OCharsetDisplay::ExtendedCharsetIterator::ExtendedCharsetIterator( const OCharsetDisplay* _pContainer, const base_iterator& _rPosition ) :m_pContainer(_pContainer) ,m_aPosition(_rPosition) { DBG_ASSERT(m_pContainer, "OCharsetDisplay::ExtendedCharsetIterator::ExtendedCharsetIterator : invalid container!"); } //------------------------------------------------------------------------- OCharsetDisplay::ExtendedCharsetIterator::ExtendedCharsetIterator(const ExtendedCharsetIterator& _rSource) :m_pContainer( _rSource.m_pContainer ) ,m_aPosition( _rSource.m_aPosition ) { } //------------------------------------------------------------------------- CharsetDisplayDerefHelper OCharsetDisplay::ExtendedCharsetIterator::operator*() const { DBG_ASSERT( m_aPosition != m_pContainer->OCharsetDisplay_Base::end(), "OCharsetDisplay::ExtendedCharsetIterator::operator* : invalid position!"); rtl_TextEncoding eEncoding = (*m_aPosition).getEncoding(); return CharsetDisplayDerefHelper( *m_aPosition, RTL_TEXTENCODING_DONTKNOW == eEncoding ? m_pContainer->m_aSystemDisplayName : (::rtl::OUString)m_pContainer->GetTextString( eEncoding ) ); } //------------------------------------------------------------------------- const OCharsetDisplay::ExtendedCharsetIterator& OCharsetDisplay::ExtendedCharsetIterator::operator++() { DBG_ASSERT( m_aPosition != m_pContainer->OCharsetDisplay_Base::end(), "OCharsetDisplay::ExtendedCharsetIterator::operator++ : invalid position!"); if ( m_aPosition != m_pContainer->OCharsetDisplay_Base::end() ) ++m_aPosition; return *this; } //------------------------------------------------------------------------- const OCharsetDisplay::ExtendedCharsetIterator& OCharsetDisplay::ExtendedCharsetIterator::operator--() { DBG_ASSERT( m_aPosition != m_pContainer->OCharsetDisplay_Base::begin(), "OCharsetDisplay::ExtendedCharsetIterator::operator-- : invalid position!"); if ( m_aPosition != m_pContainer->OCharsetDisplay_Base::begin() ) --m_aPosition; return *this; } //------------------------------------------------------------------------- bool operator==(const OCharsetDisplay::ExtendedCharsetIterator& lhs, const OCharsetDisplay::ExtendedCharsetIterator& rhs) { return (lhs.m_pContainer == rhs.m_pContainer) && (lhs.m_aPosition == rhs.m_aPosition); } //......................................................................... } // namespace dbaui //......................................................................... <commit_msg>INTEGRATION: CWS pchfix02 (1.10.52); FILE MERGED 2006/09/01 17:24:33 kaib 1.10.52.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: charsets.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: obo $ $Date: 2006-09-17 07:15:48 $ * * 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_dbaccess.hxx" #ifndef _DBAUI_CHARSETS_HXX_ #include "charsets.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _DBU_MISCRES_HRC_ #include "dbumiscres.hrc" #endif #ifndef _DBU_MISC_HRC_ #include "dbu_misc.hrc" #endif #ifndef _RTL_TENCINFO_H #include <rtl/tencinfo.h> #endif #ifndef _TOOLS_RCID_H #include <tools/rcid.h> #endif #ifndef _DBAUI_LOCALRESACCESS_HXX_ #include "localresaccess.hxx" #endif //......................................................................... namespace dbaui { //......................................................................... using namespace ::dbtools; //========================================================================= //= OCharsetDisplay //========================================================================= //------------------------------------------------------------------------- OCharsetDisplay::OCharsetDisplay() :OCharsetMap() ,SvxTextEncodingTable() { { LocalResourceAccess aCharsetStrings( RSC_CHARSETS, RSC_RESOURCE ); m_aSystemDisplayName = String( ResId( 1 ) ); } } //------------------------------------------------------------------------- sal_Bool OCharsetDisplay::approveEncoding( const rtl_TextEncoding _eEncoding, const rtl_TextEncodingInfo& _rInfo ) const { if ( !OCharsetMap::approveEncoding( _eEncoding, _rInfo ) ) return sal_False; if ( RTL_TEXTENCODING_DONTKNOW == _eEncoding ) return sal_True; return 0 != GetTextString( _eEncoding ).Len(); } //------------------------------------------------------------------------- OCharsetDisplay::const_iterator OCharsetDisplay::begin() const { return const_iterator( this, OCharsetMap::begin() ); } //------------------------------------------------------------------------- OCharsetDisplay::const_iterator OCharsetDisplay::end() const { return const_iterator( this, OCharsetMap::end() ); } //------------------------------------------------------------------------- OCharsetDisplay::const_iterator OCharsetDisplay::findEncoding(const rtl_TextEncoding _eEncoding) const { OCharsetMap::const_iterator aBaseIter = OCharsetMap::find(_eEncoding); return const_iterator( this, aBaseIter ); } //------------------------------------------------------------------------- OCharsetDisplay::const_iterator OCharsetDisplay::findIanaName(const ::rtl::OUString& _rIanaName) const { OCharsetMap::const_iterator aBaseIter = OCharsetMap::find(_rIanaName, OCharsetMap::IANA()); return const_iterator( this, aBaseIter ); } //------------------------------------------------------------------------- OCharsetDisplay::const_iterator OCharsetDisplay::findDisplayName(const ::rtl::OUString& _rDisplayName) const { rtl_TextEncoding eEncoding = RTL_TEXTENCODING_DONTKNOW; if ( _rDisplayName != m_aSystemDisplayName ) { eEncoding = GetTextEncoding( _rDisplayName ); OSL_ENSURE( RTL_TEXTENCODING_DONTKNOW != eEncoding, "OCharsetDisplay::find: non-empty display name, but DONTKNOW!" ); } return const_iterator( this, OCharsetMap::find( eEncoding ) ); } //========================================================================= //= CharsetDisplayDerefHelper //========================================================================= //------------------------------------------------------------------------- CharsetDisplayDerefHelper::CharsetDisplayDerefHelper(const CharsetDisplayDerefHelper& _rSource) :CharsetDisplayDerefHelper_Base(_rSource) ,m_sDisplayName(m_sDisplayName) { } //------------------------------------------------------------------------- CharsetDisplayDerefHelper::CharsetDisplayDerefHelper(const CharsetDisplayDerefHelper_Base& _rBase, const ::rtl::OUString& _rDisplayName) :CharsetDisplayDerefHelper_Base(_rBase) ,m_sDisplayName(_rDisplayName) { DBG_ASSERT( m_sDisplayName.getLength(), "CharsetDisplayDerefHelper::CharsetDisplayDerefHelper: invalid display name!" ); } //------------------------------------------------------------------------- CharsetDisplayDerefHelper::CharsetDisplayDerefHelper() { } //========================================================================= //= OCharsetDisplay::ExtendedCharsetIterator //========================================================================= //------------------------------------------------------------------------- OCharsetDisplay::ExtendedCharsetIterator::ExtendedCharsetIterator( const OCharsetDisplay* _pContainer, const base_iterator& _rPosition ) :m_pContainer(_pContainer) ,m_aPosition(_rPosition) { DBG_ASSERT(m_pContainer, "OCharsetDisplay::ExtendedCharsetIterator::ExtendedCharsetIterator : invalid container!"); } //------------------------------------------------------------------------- OCharsetDisplay::ExtendedCharsetIterator::ExtendedCharsetIterator(const ExtendedCharsetIterator& _rSource) :m_pContainer( _rSource.m_pContainer ) ,m_aPosition( _rSource.m_aPosition ) { } //------------------------------------------------------------------------- CharsetDisplayDerefHelper OCharsetDisplay::ExtendedCharsetIterator::operator*() const { DBG_ASSERT( m_aPosition != m_pContainer->OCharsetDisplay_Base::end(), "OCharsetDisplay::ExtendedCharsetIterator::operator* : invalid position!"); rtl_TextEncoding eEncoding = (*m_aPosition).getEncoding(); return CharsetDisplayDerefHelper( *m_aPosition, RTL_TEXTENCODING_DONTKNOW == eEncoding ? m_pContainer->m_aSystemDisplayName : (::rtl::OUString)m_pContainer->GetTextString( eEncoding ) ); } //------------------------------------------------------------------------- const OCharsetDisplay::ExtendedCharsetIterator& OCharsetDisplay::ExtendedCharsetIterator::operator++() { DBG_ASSERT( m_aPosition != m_pContainer->OCharsetDisplay_Base::end(), "OCharsetDisplay::ExtendedCharsetIterator::operator++ : invalid position!"); if ( m_aPosition != m_pContainer->OCharsetDisplay_Base::end() ) ++m_aPosition; return *this; } //------------------------------------------------------------------------- const OCharsetDisplay::ExtendedCharsetIterator& OCharsetDisplay::ExtendedCharsetIterator::operator--() { DBG_ASSERT( m_aPosition != m_pContainer->OCharsetDisplay_Base::begin(), "OCharsetDisplay::ExtendedCharsetIterator::operator-- : invalid position!"); if ( m_aPosition != m_pContainer->OCharsetDisplay_Base::begin() ) --m_aPosition; return *this; } //------------------------------------------------------------------------- bool operator==(const OCharsetDisplay::ExtendedCharsetIterator& lhs, const OCharsetDisplay::ExtendedCharsetIterator& rhs) { return (lhs.m_pContainer == rhs.m_pContainer) && (lhs.m_aPosition == rhs.m_aPosition); } //......................................................................... } // namespace dbaui //......................................................................... <|endoftext|>
<commit_before>#include "display.h" #include "gdt.h" #include "idt.h" #include "interrupts.h" #include "multiboot.h" #include "ports.h" #include "types.h" extern "C" void kmain(const multiboot::Info* mbinfo, u32 magic) { display::init(); if (magic != multiboot::BOOTLOADER_MAGIC) { // Something went not according to specs. Do not rely on the // multiboot data structure. display::println("error: The bootloader's magic number didn't match. Something must have gone wrong."); return; } // Print to screen to see everything is working. display::clearScreen(); display::println("Welcome to spideros"); display::println("==================="); display::println("This is", " a", ' ', 't', "est", '.'); const int a = 12, b = 3; display::println("Hey look, numbers: ", a, " * ", b, " = ", a * b); display::println(); if (mbinfo->hasFlag(multiboot::BOOTLOADER_NAME)) { display::println("Bootloader:\t", (const char*) mbinfo->bootloaderName); } if (mbinfo->hasFlag(multiboot::COMMAND_LINE)) { display::println("Command line:\t", (const char*) mbinfo->commandLine); } display::println("Integer printing tests:"); display::println("Hex: 0x", display::hex(42)); display::println("Oct: 0", display::oct(42)); display::println("Bin: 0b", display::bin(42)); display::println("Dec: ", 42); display::println(); display::print("Initializing GDT... "); gdt::init(); display::println("done."); display::print("Initializing IDT... "); idt::init(); display::println("done."); display::print("Initializing interrupt handlers... "); interrupts::init(); display::println("done."); interrupts::enable(); while (true) { // Flush keyboard buffer. while(ports::inb(0x64) & 1) { ports::inb(0x60); } } } <commit_msg>Factor out initialization messages in kmain.<commit_after>#include "display.h" #include "gdt.h" #include "idt.h" #include "interrupts.h" #include "multiboot.h" #include "ports.h" #include "types.h" static void runInit(const char* stage, void (*initFn)()) { display::print("Initializing ", stage, "... "); initFn(); display::println("done."); } extern "C" void kmain(const multiboot::Info* mbinfo, u32 magic) { display::init(); if (magic != multiboot::BOOTLOADER_MAGIC) { // Something went not according to specs. Do not rely on the // multiboot data structure. display::println("error: The bootloader's magic number didn't match. Something must have gone wrong."); return; } // Print to screen to see everything is working. display::clearScreen(); display::println("Welcome to spideros"); display::println("==================="); display::println("This is", " a", ' ', 't', "est", '.'); const int a = 12, b = 3; display::println("Hey look, numbers: ", a, " * ", b, " = ", a * b); display::println(); if (mbinfo->hasFlag(multiboot::BOOTLOADER_NAME)) { display::println("Bootloader:\t", (const char*) mbinfo->bootloaderName); } if (mbinfo->hasFlag(multiboot::COMMAND_LINE)) { display::println("Command line:\t", (const char*) mbinfo->commandLine); } display::println("Integer printing tests:"); display::println("Hex: 0x", display::hex(42)); display::println("Oct: 0", display::oct(42)); display::println("Bin: 0b", display::bin(42)); display::println("Dec: ", 42); display::println(); runInit("GDT", gdt::init); runInit("IDT", idt::init); runInit("interrupt handlers", interrupts::init); interrupts::enable(); while (true) { // Flush keyboard buffer. while(ports::inb(0x64) & 1) { ports::inb(0x60); } } } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "test.hpp" #include <vector> //TODO The tests are a bit poor TEMPLATE_TEST_CASE_2("pooling/deep/max2/1", "[pooling]", Z, float, double) { etl::fast_matrix<Z, 4, 4> aa({1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0}); etl::fast_matrix<Z, 2, 4, 4> a; a(0) = aa; a(1) = aa; etl::fast_matrix<Z, 2, 2, 2> b(etl::max_pool_2d<2, 2>(a)); REQUIRE_EQUALS(b(0, 0, 0), 6.0); REQUIRE_EQUALS(b(0, 0, 1), 8.0); REQUIRE_EQUALS(b(0, 1, 0), 14.0); REQUIRE_EQUALS(b(0, 1, 1), 16.0); REQUIRE_EQUALS(b(1, 0, 0), 6.0); REQUIRE_EQUALS(b(1, 0, 1), 8.0); REQUIRE_EQUALS(b(1, 1, 0), 14.0); REQUIRE_EQUALS(b(1, 1, 1), 16.0); } <commit_msg>Tester for deep pooling<commit_after>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "test.hpp" #include <vector> //TODO The tests are a bit poor TEMPLATE_TEST_CASE_2("pooling/deep/max2/1", "[pooling]", Z, float, double) { etl::fast_matrix<Z, 4, 4> aa({1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0}); etl::fast_matrix<Z, 2, 4, 4> a; a(0) = aa; a(1) = aa; etl::fast_matrix<Z, 2, 2, 2> b(etl::max_pool_2d<2, 2>(a)); REQUIRE_EQUALS(b(0, 0, 0), 6.0); REQUIRE_EQUALS(b(0, 0, 1), 8.0); REQUIRE_EQUALS(b(0, 1, 0), 14.0); REQUIRE_EQUALS(b(0, 1, 1), 16.0); REQUIRE_EQUALS(b(1, 0, 0), 6.0); REQUIRE_EQUALS(b(1, 0, 1), 8.0); REQUIRE_EQUALS(b(1, 1, 0), 14.0); REQUIRE_EQUALS(b(1, 1, 1), 16.0); } TEMPLATE_TEST_CASE_2("pooling/deep/max2/2", "[pooling]", Z, float, double) { etl::fast_matrix<Z, 4, 4> aa({1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0}); etl::fast_matrix<Z, 2, 2, 4, 4> a; a(0)(0) = aa; a(0)(1) = aa; a(1)(0) = aa; a(1)(1) = aa; etl::fast_matrix<Z, 2, 2, 2, 2> b(etl::max_pool_2d<2, 2>(a)); REQUIRE_EQUALS(b(0, 0, 0, 0), 6.0); REQUIRE_EQUALS(b(0, 0, 0, 1), 8.0); REQUIRE_EQUALS(b(0, 0, 1, 0), 14.0); REQUIRE_EQUALS(b(0, 0, 1, 1), 16.0); REQUIRE_EQUALS(b(0, 1, 0, 0), 6.0); REQUIRE_EQUALS(b(0, 1, 0, 1), 8.0); REQUIRE_EQUALS(b(0, 1, 1, 0), 14.0); REQUIRE_EQUALS(b(0, 1, 1, 1), 16.0); REQUIRE_EQUALS(b(1, 0, 0, 0), 6.0); REQUIRE_EQUALS(b(1, 0, 0, 1), 8.0); REQUIRE_EQUALS(b(1, 0, 1, 0), 14.0); REQUIRE_EQUALS(b(1, 0, 1, 1), 16.0); REQUIRE_EQUALS(b(1, 1, 0, 0), 6.0); REQUIRE_EQUALS(b(1, 1, 0, 1), 8.0); REQUIRE_EQUALS(b(1, 1, 1, 0), 14.0); REQUIRE_EQUALS(b(1, 1, 1, 1), 16.0); } <|endoftext|>
<commit_before>//Moose Includes #include "Moose.h" #include "KernelFactory.h" #include "BCFactory.h" #include "MaterialFactory.h" #include "AuxFactory.h" #include "ComputeResidual.h" #include "ComputeJacobian.h" // C++ include files that we need #include <iostream> #include <fstream> // libMesh includes #include "libmesh.h" #include "perf_log.h" #include "mesh.h" #include "boundary_info.h" #include "exodusII_io.h" #include "equation_systems.h" #include "nonlinear_solver.h" #include "nonlinear_implicit_system.h" #include "linear_implicit_system.h" #include "transient_system.h" PerfLog Moose::perf_log("Example1"); // Begin the main program. int main (int argc, char** argv) { { // Initialize libMesh and any dependent libaries LibMeshInit init (argc, argv); // This registers a bunch of common objects that exist in Moose with the factories. // that includes several Kernels, BoundaryConditions, AuxKernels and Materials Moose::registerObjects(); // Create the mesh object Mesh *mesh = new Mesh(2); // MUST set the global mesh! Moose::mesh = mesh; ExodusII_IO exreader(*mesh); exreader.read("square.e"); mesh->prepare_for_use(false); //This is necessary for Dirichlet BCs mesh->boundary_info->build_node_list_from_side_list(); mesh->print_info(); EquationSystems equation_systems (*mesh); // MUST set the global equation_systems! Moose::equation_system = &equation_systems; TransientNonlinearImplicitSystem& system = equation_systems.add_system<TransientNonlinearImplicitSystem> ("NonlinearSystem"); system.add_variable("u", FIRST, LAGRANGE); system.nonlinear_solver->residual = Moose::compute_residual; system.nonlinear_solver->jacobian = Moose::compute_jacobian; TransientExplicitSystem& aux_system = equation_systems.add_system<TransientExplicitSystem> ("AuxiliarySystem"); equation_systems.init(); equation_systems.print_info(); //Initialize common data structures for Kernels Kernel::init(&equation_systems); BoundaryCondition::init(); AuxKernel::init(); Parameters params; Parameters left_bc_params; left_bc_params.set<Real>("value") = 0.0; Parameters right_bc_params; right_bc_params.set<Real>("value") = 1.0; KernelFactory::instance()->add("Diffusion", "diff", params, "u"); BCFactory::instance()->add("DirichletBC", "left", left_bc_params, "u", 1); BCFactory::instance()->add("DirichletBC", "right", right_bc_params, "u", 2); MaterialFactory::instance()->add("EmptyMaterial", "empty", params, 1); system.solve(); ExodusII_IO(*mesh).write_equation_systems("out.e", equation_systems); } return 0; } <commit_msg>add more comments<commit_after>//Moose Includes #include "Moose.h" #include "KernelFactory.h" #include "BCFactory.h" #include "MaterialFactory.h" #include "AuxFactory.h" #include "ComputeResidual.h" #include "ComputeJacobian.h" // C++ include files that we need #include <iostream> #include <fstream> // libMesh includes #include "libmesh.h" #include "perf_log.h" #include "mesh.h" #include "boundary_info.h" #include "exodusII_io.h" #include "equation_systems.h" #include "nonlinear_solver.h" #include "nonlinear_implicit_system.h" #include "linear_implicit_system.h" #include "transient_system.h" // Initialize default Performance Logging PerfLog Moose::perf_log("Example1"); // Begin the main program. int main (int argc, char** argv) { { // Initialize libMesh and any dependent libaries LibMeshInit init (argc, argv); // This registers a bunch of common objects that exist in Moose with the factories. // that includes several Kernels, BoundaryConditions, AuxKernels and Materials Moose::registerObjects(); // Create the mesh object Mesh *mesh = new Mesh(2); // MUST set the global mesh! Moose::mesh = mesh; // Read the mesh from an Exodus file and prepare it for use ExodusII_IO exreader(*mesh); exreader.read("square.e"); /** * The "false" specifies _not_ to renumber nodes and elements * this could be a slight hit to performance, but it means that your * output file will have the same node and element numbering as the input */ mesh->prepare_for_use(false); /** * This builds nodesets from your sidesets * these autogenerated nodesets are used for Dirichlet * boundary conditions * NEVER manually create nodesets... always let the code autogenerate them * note that if the mesh changes (such as after adaptivity) you have to */ mesh->boundary_info->build_node_list_from_side_list(); // Print some useful information about the mesh mesh->print_info(); // The equation_systems holds all the Systems we want to solve EquationSystems equation_systems (*mesh); // MUST set the global equation_systems! Moose::equation_system = &equation_systems; // This is the actual Nonlinear System we are going to solve TransientNonlinearImplicitSystem& system = equation_systems.add_system<TransientNonlinearImplicitSystem> ("NonlinearSystem"); /** * Add a variable named "u" to solve for. * We are going to approximate it using First order Lagrange FEs */ system.add_variable("u", FIRST, LAGRANGE); // Set the residual and jacobian functions to the default ones provided by MOOSE system.nonlinear_solver->residual = Moose::compute_residual; system.nonlinear_solver->jacobian = Moose::compute_jacobian; /** * This is a NECESSARY auxiliary system for computing auxiliary variables * Even though we're not going to have any of those we MUST create this system. */ TransientExplicitSystem& aux_system = equation_systems.add_system<TransientExplicitSystem> ("AuxiliarySystem"); // Initialize the Systems and print some info out equation_systems.init(); equation_systems.print_info(); /** * Initialize common data structures for Kernels. * These MUST be called in this order... and at this point. */ Kernel::init(&equation_systems); BoundaryCondition::init(); AuxKernel::init(); // Blank params to use for Kernels that don't need params Parameters params; // Parameters for DirichletBC's Parameters left_bc_params; left_bc_params.set<Real>("value") = 0.0; Parameters right_bc_params; right_bc_params.set<Real>("value") = 1.0; // Add a Diffusion Kernel from MOOSE into the calculation. KernelFactory::instance()->add("Diffusion", "diff", params, "u"); // Add the two boundary conditions using the DirichletBC object from MOOSE BCFactory::instance()->add("DirichletBC", "left", left_bc_params, "u", 1); BCFactory::instance()->add("DirichletBC", "right", right_bc_params, "u", 2); // Every calculation MUST add at least one Material // Here we use the EmptyMaterial from MOOSE because we don't need material properties. MaterialFactory::instance()->add("EmptyMaterial", "empty", params, 1); // Solve the Nonlinear System system.solve(); // Write the solution out. ExodusII_IO(*mesh).write_equation_systems("out.e", equation_systems); } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/inference/api/api_anakin_engine.h" #ifdef PADDLE_WITH_CUDA #include <cuda.h> #endif #include <mkl_service.h> #include <omp.h> #include <map> #include <string> #include <utility> #include <vector> #include "framework/core/net/net.h" #include "framework/operators/ops.h" #include "saber/funcs/timer.h" namespace paddle { using paddle::contrib::AnakinConfig; template <typename Target> PaddleInferenceAnakinPredictor<Target>::PaddleInferenceAnakinPredictor( const contrib::AnakinConfig &config) { CHECK(Init(config)); } template <> PaddleInferenceAnakinPredictor<anakin::X86>::PaddleInferenceAnakinPredictor( const contrib::AnakinConfig &config) { omp_set_dynamic(0); omp_set_num_threads(1); mkl_set_num_threads(1); CHECK(Init(config)); } template <typename Target> bool PaddleInferenceAnakinPredictor<Target>::Init( const contrib::AnakinConfig &config) { if (!(graph_.load(config.model_file))) { VLOG(3) << "fail to load graph from " << config.model_file; return false; } auto inputs = graph_.get_ins(); for (auto &input_str : inputs) { graph_.ResetBatchSize(input_str, config.max_batch_size); max_batch_size_ = config.max_batch_size; } // optimization for graph if (!(graph_.Optimize())) { return false; } // construct executer if (executor_p_ == nullptr) { executor_p_ = new anakin::Net<Target, anakin::saber::AK_FLOAT, anakin::Precision::FP32>(graph_, true); } return true; } template <typename Target> bool PaddleInferenceAnakinPredictor<Target>::Run( const std::vector<PaddleTensor> &inputs, std::vector<PaddleTensor> *output_data, int batch_size) { for (const auto &input : inputs) { if (input.dtype != PaddleDType::FLOAT32) { VLOG(3) << "Only support float type inputs. " << input.name << "'s type is not float"; return false; } auto d_tensor_in_p = executor_p_->get_in(input.name); auto net_shape = d_tensor_in_p->shape(); if (net_shape.size() != input.shape.size()) { VLOG(3) << " input " << input.name << "'s shape size should be equal to that of net"; return false; } int sum = 1; for_each(input.shape.begin(), input.shape.end(), [&](int n) { sum *= n; }); if (sum > net_shape.count()) { graph_.Reshape(input.name, input.shape); delete executor_p_; executor_p_ = new anakin::Net<Target, anakin::saber::AK_FLOAT, anakin::Precision::FP32>(graph_, true); d_tensor_in_p = executor_p_->get_in(input.name); } anakin::saber::Shape tmp_shape; for (auto s : input.shape) { tmp_shape.push_back(s); } d_tensor_in_p->reshape(tmp_shape); if (input.lod.size() > 0) { if (input.lod.size() > 1) { VLOG(3) << " input lod first dim should <=1, but you set " << input.lod.size(); return false; } std::vector<int> offset(input.lod[0].begin(), input.lod[0].end()); d_tensor_in_p->set_seq_offset(offset); VLOG(3) << "offset.size(): " << offset.size(); for (int i = 0; i < offset.size(); i++) { VLOG(3) << offset[i]; } } float *d_data_p = d_tensor_in_p->mutable_data(); #ifdef PADDLE_WITH_CUDA if (std::is_same<anakin::NV, Target>::value) { if (cudaMemcpy(d_data_p, static_cast<float *>(input.data.data()), d_tensor_in_p->valid_size() * sizeof(float), cudaMemcpyHostToDevice) != 0) { VLOG(3) << "copy data from CPU to GPU error"; return false; } } #endif if (std::is_same<anakin::X86, Target>::value) { memcpy(d_data_p, static_cast<float *>(input.data.data()), d_tensor_in_p->valid_size() * sizeof(float)); } } #ifdef PADDLE_WITH_CUDA cudaDeviceSynchronize(); executor_p_->prediction(); cudaDeviceSynchronize(); #endif if (output_data->empty()) { VLOG(3) << "At least one output should be set with tensors' names."; return false; } for (auto &output : *output_data) { auto *tensor = executor_p_->get_out(output.name); output.shape = tensor->valid_shape(); if (output.data.length() < tensor->valid_size() * sizeof(float)) { output.data.Resize(tensor->valid_size() * sizeof(float)); } #if PADDLE_WITH_CUDA if (std::is_same<anakin::NV, Target>::value) { // Copy data from GPU -> CPU if (cudaMemcpy(output.data.data(), tensor->mutable_data(), tensor->valid_size() * sizeof(float), cudaMemcpyDeviceToHost) != 0) { VLOG(3) << "copy data from GPU to CPU error"; return false; } } #endif if (std::is_same<anakin::X86, Target>::value) { memcpy(output.data.data(), tensor->mutable_data(), tensor->valid_size() * sizeof(float)); } } return true; } template <typename Target> anakin::Net<Target, anakin::saber::AK_FLOAT, anakin::Precision::FP32> &PaddleInferenceAnakinPredictor<Target>::get_executer() { return *executor_p_; } // the cloned new Predictor of anakin share the same net weights from original // Predictor template <typename Target> std::unique_ptr<PaddlePredictor> PaddleInferenceAnakinPredictor<Target>::Clone() { VLOG(3) << "Anakin Predictor::clone"; std::unique_ptr<PaddlePredictor> cls( new PaddleInferenceAnakinPredictor<Target>()); // construct executer from other graph auto anakin_predictor_p = dynamic_cast<PaddleInferenceAnakinPredictor<Target> *>(cls.get()); if (!anakin_predictor_p) { VLOG(3) << "fail to call Init"; return nullptr; } anakin_predictor_p->get_executer().init(graph_); return std::move(cls); } #ifdef PADDLE_WITH_CUDA template class PaddleInferenceAnakinPredictor<anakin::NV>; #endif template class PaddleInferenceAnakinPredictor<anakin::X86>; // A factory to help create difference predictor. template <> std::unique_ptr<PaddlePredictor> CreatePaddlePredictor<contrib::AnakinConfig, PaddleEngineKind::kAnakin>( const contrib::AnakinConfig &config) { VLOG(3) << "Anakin Predictor create."; if (config.target_type == contrib::AnakinConfig::NVGPU) { #ifdef PADDLE_WITH_CUDA VLOG(3) << "Anakin Predictor create on [ NVIDIA GPU ]."; std::unique_ptr<PaddlePredictor> x( new PaddleInferenceAnakinPredictor<anakin::NV>(config)); return x; #else LOG(ERROR) << "AnakinConfig::NVGPU could not used in ONLY-CPU environment"; return nullptr; #endif } else if (config.target_type == contrib::AnakinConfig::X86) { VLOG(3) << "Anakin Predictor create on [ Intel X86 ]."; std::unique_ptr<PaddlePredictor> x( new PaddleInferenceAnakinPredictor<anakin::X86>(config)); return x; } else { VLOG(3) << "Anakin Predictor create on unknown platform."; return nullptr; } } #ifdef PADDLE_ANAKIN_ENABLE_OP_TIMER template <typename Target> using executor_t = anakin::Net<Target, anakin::saber::AK_FLOAT, anakin::Precision::FP32>; template <typename Target> void DisplayOpTimer(executor_t<Target> *net_executor, int epoch) { std::vector<float> op_time = net_executor->get_op_time(); auto exec_funcs = net_executor->get_exec_funcs(); auto op_param = net_executor->get_op_param(); for (int i = 0; i < op_time.size(); i++) { LOG(INFO) << "name: " << exec_funcs[i].name << " op_type: " << exec_funcs[i].op_name << " op_param: " << op_param[i] << " time " << op_time[i] / epoch; } std::map<std::string, float> op_map; for (int i = 0; i < op_time.size(); i++) { auto it = op_map.find(op_param[i]); if (it != op_map.end()) op_map[op_param[i]] += op_time[i]; else op_map.insert(std::pair<std::string, float>(op_param[i], op_time[i])); } for (auto it = op_map.begin(); it != op_map.end(); ++it) { LOG(INFO) << it->first << " " << (it->second) / epoch << " ms"; } } #endif template <typename Target> PaddleInferenceAnakinPredictor<Target>::~PaddleInferenceAnakinPredictor() { #ifdef PADDLE_ANAKIN_ENABLE_OP_TIMER DisplayOpTimer<Target>(executor_p_, max_batch_size_); #endif delete executor_p_; executor_p_ = nullptr; } } // namespace paddle <commit_msg>update<commit_after>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/inference/api/api_anakin_engine.h" #ifdef PADDLE_WITH_CUDA #include <cuda.h> #endif #include <mkl_service.h> #include <omp.h> #include <map> #include <string> #include <utility> #include <vector> #include "framework/core/net/net.h" #include "framework/operators/ops.h" #include "saber/funcs/timer.h" namespace paddle { using paddle::contrib::AnakinConfig; template <typename Target> PaddleInferenceAnakinPredictor<Target>::PaddleInferenceAnakinPredictor( const contrib::AnakinConfig &config) { CHECK(Init(config)); } template <> PaddleInferenceAnakinPredictor<anakin::X86>::PaddleInferenceAnakinPredictor( const contrib::AnakinConfig &config) { omp_set_dynamic(0); omp_set_num_threads(1); mkl_set_num_threads(1); CHECK(Init(config)); } template <typename Target> bool PaddleInferenceAnakinPredictor<Target>::Init( const contrib::AnakinConfig &config) { if (!(graph_.load(config.model_file))) { VLOG(3) << "fail to load graph from " << config.model_file; return false; } auto inputs = graph_.get_ins(); for (auto &input_str : inputs) { graph_.ResetBatchSize(input_str, config.max_batch_size); max_batch_size_ = config.max_batch_size; } // optimization for graph if (!(graph_.Optimize())) { return false; } // construct executer if (executor_p_ == nullptr) { executor_p_ = new anakin::Net<Target, anakin::saber::AK_FLOAT, anakin::Precision::FP32>(graph_, true); } return true; } template <typename Target> bool PaddleInferenceAnakinPredictor<Target>::Run( const std::vector<PaddleTensor> &inputs, std::vector<PaddleTensor> *output_data, int batch_size) { for (const auto &input : inputs) { if (input.dtype != PaddleDType::FLOAT32) { VLOG(3) << "Only support float type inputs. " << input.name << "'s type is not float"; return false; } auto d_tensor_in_p = executor_p_->get_in(input.name); auto net_shape = d_tensor_in_p->shape(); if (net_shape.size() != input.shape.size()) { VLOG(3) << " input " << input.name << "'s shape size should be equal to that of net"; return false; } int sum = 1; for_each(input.shape.begin(), input.shape.end(), [&](int n) { sum *= n; }); if (sum > net_shape.count()) { graph_.Reshape(input.name, input.shape); delete executor_p_; executor_p_ = new anakin::Net<Target, anakin::saber::AK_FLOAT, anakin::Precision::FP32>(graph_, true); d_tensor_in_p = executor_p_->get_in(input.name); } anakin::saber::Shape tmp_shape; for (auto s : input.shape) { tmp_shape.push_back(s); } d_tensor_in_p->reshape(tmp_shape); if (input.lod.size() > 0) { if (input.lod.size() > 1) { VLOG(3) << " input lod first dim should <=1, but you set " << input.lod.size(); return false; } std::vector<int> offset(input.lod[0].begin(), input.lod[0].end()); d_tensor_in_p->set_seq_offset(offset); VLOG(3) << "offset.size(): " << offset.size(); for (int i = 0; i < offset.size(); i++) { VLOG(3) << offset[i]; } } float *d_data_p = d_tensor_in_p->mutable_data(); #ifdef PADDLE_WITH_CUDA if (std::is_same<anakin::NV, Target>::value) { if (cudaMemcpy(d_data_p, static_cast<float *>(input.data.data()), d_tensor_in_p->valid_size() * sizeof(float), cudaMemcpyHostToDevice) != 0) { VLOG(3) << "copy data from CPU to GPU error"; return false; } } #endif if (std::is_same<anakin::X86, Target>::value) { memcpy(d_data_p, static_cast<float *>(input.data.data()), d_tensor_in_p->valid_size() * sizeof(float)); } } #ifdef PADDLE_WITH_CUDA cudaDeviceSynchronize(); executor_p_->prediction(); cudaDeviceSynchronize(); #endif if (output_data->empty()) { VLOG(3) << "At least one output should be set with tensors' names."; return false; } for (auto &output : *output_data) { auto *tensor = executor_p_->get_out(output.name); output.shape = tensor->valid_shape(); if (output.data.length() < tensor->valid_size() * sizeof(float)) { output.data.Resize(tensor->valid_size() * sizeof(float)); } #if PADDLE_WITH_CUDA if (std::is_same<anakin::NV, Target>::value) { // Copy data from GPU -> CPU if (cudaMemcpy(output.data.data(), tensor->mutable_data(), tensor->valid_size() * sizeof(float), cudaMemcpyDeviceToHost) != 0) { VLOG(3) << "copy data from GPU to CPU error"; return false; } } #endif if (std::is_same<anakin::X86, Target>::value) { memcpy(output.data.data(), tensor->mutable_data(), tensor->valid_size() * sizeof(float)); } } return true; } template <typename Target> anakin::Net<Target, anakin::saber::AK_FLOAT, anakin::Precision::FP32> &PaddleInferenceAnakinPredictor<Target>::get_executer() { return *executor_p_; } // the cloned new Predictor of anakin share the same net weights from original // Predictor template <typename Target> std::unique_ptr<PaddlePredictor> PaddleInferenceAnakinPredictor<Target>::Clone() { VLOG(3) << "Anakin Predictor::clone"; std::unique_ptr<PaddlePredictor> cls( new PaddleInferenceAnakinPredictor<Target>()); // construct executer from other graph auto anakin_predictor_p = dynamic_cast<PaddleInferenceAnakinPredictor<Target> *>(cls.get()); if (!anakin_predictor_p) { VLOG(3) << "fail to call Init"; return nullptr; } anakin_predictor_p->get_executer().init(graph_); return std::move(cls); } #ifdef PADDLE_WITH_CUDA template class PaddleInferenceAnakinPredictor<anakin::NV>; #endif template class PaddleInferenceAnakinPredictor<anakin::X86>; // A factory to help create difference predictor. template <> std::unique_ptr<PaddlePredictor> CreatePaddlePredictor<contrib::AnakinConfig, PaddleEngineKind::kAnakin>( const contrib::AnakinConfig &config) { VLOG(3) << "Anakin Predictor create."; if (config.target_type == contrib::AnakinConfig::NVGPU) { #ifdef PADDLE_WITH_CUDA VLOG(3) << "Anakin Predictor create on [ NVIDIA GPU ]."; std::unique_ptr<PaddlePredictor> x( new PaddleInferenceAnakinPredictor<anakin::NV>(config)); return x; #else LOG(ERROR) << "AnakinConfig::NVGPU could not used in ONLY-CPU environment"; return nullptr; #endif } else if (config.target_type == contrib::AnakinConfig::X86) { VLOG(3) << "Anakin Predictor create on [ Intel X86 ]."; std::unique_ptr<PaddlePredictor> x( new PaddleInferenceAnakinPredictor<anakin::X86>(config)); return x; } else { VLOG(3) << "Anakin Predictor create on unknown platform."; return nullptr; } } template <> std::unique_ptr<PaddlePredictor> CreatePaddlePredictor<contrib::AnakinConfig>( const contrib::AnakinConfig &config) { return CreatePaddlePredictor(config); }; #ifdef PADDLE_ANAKIN_ENABLE_OP_TIMER template <typename Target> using executor_t = anakin::Net<Target, anakin::saber::AK_FLOAT, anakin::Precision::FP32>; template <typename Target> void DisplayOpTimer(executor_t<Target> *net_executor, int epoch) { std::vector<float> op_time = net_executor->get_op_time(); auto exec_funcs = net_executor->get_exec_funcs(); auto op_param = net_executor->get_op_param(); for (int i = 0; i < op_time.size(); i++) { LOG(INFO) << "name: " << exec_funcs[i].name << " op_type: " << exec_funcs[i].op_name << " op_param: " << op_param[i] << " time " << op_time[i] / epoch; } std::map<std::string, float> op_map; for (int i = 0; i < op_time.size(); i++) { auto it = op_map.find(op_param[i]); if (it != op_map.end()) op_map[op_param[i]] += op_time[i]; else op_map.insert(std::pair<std::string, float>(op_param[i], op_time[i])); } for (auto it = op_map.begin(); it != op_map.end(); ++it) { LOG(INFO) << it->first << " " << (it->second) / epoch << " ms"; } } #endif template <typename Target> PaddleInferenceAnakinPredictor<Target>::~PaddleInferenceAnakinPredictor() { #ifdef PADDLE_ANAKIN_ENABLE_OP_TIMER DisplayOpTimer<Target>(executor_p_, max_batch_size_); #endif delete executor_p_; executor_p_ = nullptr; } } // namespace paddle <|endoftext|>
<commit_before>#include "kl/file_view.hpp" #include <system_error> #include <cassert> struct IUnknown; // Required for /permissive- and WinSDK 8.1 #include <Windows.h> namespace kl { namespace { template <typename NullPolicy> class handle { public: handle(HANDLE h = null()) noexcept : h_{h} {} ~handle() { reset(); } handle(const handle&) = delete; handle& operator=(const handle&) = delete; handle(handle&& other) noexcept : h_{std::exchange(other.h_, null())} {} handle& operator=(handle&& other) noexcept { assert(this != &other); swap(*this, other); return *this; } friend void swap(handle& l, handle& r) noexcept { using std::swap; swap(l.h_, r.h_); } void reset(HANDLE h = null()) noexcept { if (h_ != null()) ::CloseHandle(h_); h_ = h; } explicit operator bool() const noexcept { return h_ != null(); } HANDLE get() const noexcept { return h_; } private: static HANDLE null() { return reinterpret_cast<HANDLE>(NullPolicy::empty); } private: HANDLE h_; }; struct null_handle_policy { static constexpr LONG_PTR empty{}; }; struct invalid_handle_value_policy { // INVALID_HANDLE_VALUE cannot be assigned to HANDLE in constexpr context static constexpr LONG_PTR empty = static_cast<LONG_PTR>(-1); }; } // namespace file_view::file_view(const char* file_path) { handle<invalid_handle_value_policy> file_handle{::CreateFileA( file_path, GENERIC_READ, 0x0, nullptr, OPEN_EXISTING, 0x0, nullptr)}; if (!file_handle) throw std::system_error{static_cast<int>(::GetLastError()), std::system_category()}; LARGE_INTEGER file_size = {}; ::GetFileSizeEx(file_handle.get(), &file_size); if (!file_size.QuadPart) return; // Empty file handle<null_handle_policy> mapping_handle{::CreateFileMappingA( file_handle.get(), nullptr, PAGE_READONLY, 0, 0, nullptr)}; if (!mapping_handle) throw std::system_error{static_cast<int>(::GetLastError()), std::system_category()}; void* file_view = ::MapViewOfFile(mapping_handle.get(), FILE_MAP_READ, 0, 0, 0); if (!file_view) throw std::system_error{static_cast<int>(::GetLastError()), std::system_category()}; contents_ = gsl::make_span(static_cast<const byte*>(file_view), file_size.QuadPart); } file_view::~file_view() { if (!contents_.empty()) ::UnmapViewOfFile(contents_.data()); } } // namespace kl <commit_msg>Explicitly narrow cast the file size<commit_after>#include "kl/file_view.hpp" #include <system_error> #include <cassert> struct IUnknown; // Required for /permissive- and WinSDK 8.1 #include <Windows.h> namespace kl { namespace { template <typename NullPolicy> class handle { public: handle(HANDLE h = null()) noexcept : h_{h} {} ~handle() { reset(); } handle(const handle&) = delete; handle& operator=(const handle&) = delete; handle(handle&& other) noexcept : h_{std::exchange(other.h_, null())} {} handle& operator=(handle&& other) noexcept { assert(this != &other); swap(*this, other); return *this; } friend void swap(handle& l, handle& r) noexcept { using std::swap; swap(l.h_, r.h_); } void reset(HANDLE h = null()) noexcept { if (h_ != null()) ::CloseHandle(h_); h_ = h; } explicit operator bool() const noexcept { return h_ != null(); } HANDLE get() const noexcept { return h_; } private: static HANDLE null() { return reinterpret_cast<HANDLE>(NullPolicy::empty); } private: HANDLE h_; }; struct null_handle_policy { static constexpr LONG_PTR empty{}; }; struct invalid_handle_value_policy { // INVALID_HANDLE_VALUE cannot be assigned to HANDLE in constexpr context static constexpr LONG_PTR empty = static_cast<LONG_PTR>(-1); }; } // namespace file_view::file_view(const char* file_path) { handle<invalid_handle_value_policy> file_handle{::CreateFileA( file_path, GENERIC_READ, 0x0, nullptr, OPEN_EXISTING, 0x0, nullptr)}; if (!file_handle) throw std::system_error{static_cast<int>(::GetLastError()), std::system_category()}; LARGE_INTEGER file_size = {}; ::GetFileSizeEx(file_handle.get(), &file_size); if (!file_size.QuadPart) return; // Empty file handle<null_handle_policy> mapping_handle{::CreateFileMappingA( file_handle.get(), nullptr, PAGE_READONLY, 0, 0, nullptr)}; if (!mapping_handle) throw std::system_error{static_cast<int>(::GetLastError()), std::system_category()}; void* file_view = ::MapViewOfFile(mapping_handle.get(), FILE_MAP_READ, 0, 0, 0); if (!file_view) throw std::system_error{static_cast<int>(::GetLastError()), std::system_category()}; contents_ = gsl::make_span(static_cast<const byte*>(file_view), gsl::narrow_cast<std::ptrdiff_t>(file_size.QuadPart)); } file_view::~file_view() { if (!contents_.empty()) ::UnmapViewOfFile(contents_.data()); } } // namespace kl <|endoftext|>
<commit_before><commit_msg>Update GdiExp.cc<commit_after><|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "NetHandler.h" // system headers #include <errno.h> NetHandler::NetHandler(PlayerInfo* _info, const struct sockaddr_in &clientAddr, int _playerIndex, int _fd) : info(_info), playerIndex(_playerIndex), fd(_fd), tcplen(0), outmsgOffset(0), outmsgSize(0), outmsgCapacity(0), outmsg(NULL), toBeKicked(false) { // store address information for player AddrLen addr_len = sizeof(clientAddr); memcpy(&uaddr, &clientAddr, addr_len); peer = Address(uaddr); // update player state time = TimeKeeper::getCurrent(); #ifdef NETWORK_STATS int i; struct MessageCount *statMsg; int direction; for (direction = 0; direction <= 1; direction++) { statMsg = msg[direction]; for (i = 0; i < MessageTypes && statMsg[i].code != 0; i++) { statMsg[i].count = 0; statMsg[i].code = 0; } msgBytes[direction] = 0; perSecondTime[direction] = time; perSecondCurrentMsg[direction] = 0; perSecondMaxMsg[direction] = 0; perSecondCurrentBytes[direction] = 0; perSecondMaxBytes[direction] = 0; } #endif } NetHandler::~NetHandler() { // shutdown TCP socket shutdown(fd, 2); close(fd); delete[] outmsg; } void NetHandler::fdSet(fd_set *read_set, fd_set *write_set, int &maxFile) { _FD_SET(fd, read_set); if (outmsgSize > 0) _FD_SET(fd, write_set); if (fd > maxFile) maxFile = fd; } int NetHandler::fdIsSet(fd_set *set) { return FD_ISSET(fd, set); } int NetHandler::send(const void *buffer, size_t length) { int n = ::send(fd, (const char *)buffer, (int)length, 0); if (n >= 0) return n; // get error code const int err = getErrno(); // if socket is closed then give up if (err == ECONNRESET || err == EPIPE) { return -1; } // just try again later if it's one of these errors if (err != EAGAIN && err != EINTR) { // dump other errors and remove the player nerror("error on write"); toBeKicked = true; toBeKickedReason = "Write error"; } return 0; } void NetHandler::setUdpOut() { udpout = true; DEBUG2("Player %s [%d] outbound UDP up\n", info->getCallSign(), playerIndex); } bool NetHandler::setUdpIn(struct sockaddr_in &_uaddr) { if (udpin) return false; bool same = !memcmp(&uaddr.sin_addr, &_uaddr.sin_addr, sizeof(uaddr.sin_addr)); if (same) { DEBUG2("Player %s [%d] inbound UDP up %s:%d actual %d\n", info->getCallSign(), playerIndex, inet_ntoa(uaddr.sin_addr), ntohs(uaddr.sin_port), ntohs(_uaddr.sin_port)); if (_uaddr.sin_port) { uaddr.sin_port = _uaddr.sin_port; udpin = true; } } else { DEBUG2 ("Player %s [%d] inbound UDP rejected %s:%d different IP than %s:%d\n", info->getCallSign(), playerIndex, inet_ntoa(uaddr.sin_addr), ntohs(uaddr.sin_port), inet_ntoa(_uaddr.sin_addr), ntohs(_uaddr.sin_port)); } return same; } int NetHandler::bufferedSend(const void *buffer, size_t length) { // try flushing buffered data if (outmsgSize != 0) { const int n = send(outmsg + outmsgOffset, outmsgSize); if (n == -1) { return -1; } if (n > 0) { outmsgOffset += n; outmsgSize -= n; } } // if the buffer is empty try writing the data immediately if ((outmsgSize == 0) && length > 0) { const int n = send(buffer, length); if (n == -1) { return -1; } if (n > 0) { buffer = (void*)(((const char*)buffer) + n); length -= n; } } // write leftover data to the buffer if (length > 0) { // is there enough room in buffer? if (outmsgCapacity < outmsgSize + (int)length) { // double capacity until it's big enough int newCapacity = (outmsgCapacity == 0) ? 512 : outmsgCapacity; while (newCapacity < outmsgSize + (int)length) newCapacity <<= 1; // if the buffer is getting too big then drop the player. chances // are the network is down or too unreliable to that player. // FIXME -- is 20kB too big? too small? if (newCapacity >= 20 * 1024) { DEBUG2("Player %s [%d] drop, unresponsive with %d bytes queued\n", info->getCallSign(), playerIndex, outmsgSize + length); toBeKicked = true; toBeKickedReason = "send queue too big"; return 0; } // allocate memory char *newbuf = new char[newCapacity]; // copy old data over memmove(newbuf, outmsg + outmsgOffset, outmsgSize); // cutover delete[] outmsg; outmsg = newbuf; outmsgOffset = 0; outmsgCapacity = newCapacity; } // if we can't fit new data at the end of the buffer then move existing // data to head of buffer // FIXME -- use a ring buffer to avoid moving memory if (outmsgOffset + outmsgSize + (int)length > outmsgCapacity) { memmove(outmsg, outmsg + outmsgOffset, outmsgSize); outmsgOffset = 0; } // append data memmove(outmsg + outmsgOffset + outmsgSize, buffer, length); outmsgSize += (int)length; } return 0; } int NetHandler::pwrite(const void *b, int l, int udpSocket) { if (l == 0) { return 0; } void *buf = (void *)b; uint16_t len, code; buf = nboUnpackUShort(buf, len); buf = nboUnpackUShort(buf, code); #ifdef NETWORK_STATS countMessage(code, len, 1); #endif // Check if UDP Link is used instead of TCP, if so jump into udpSend if (udpout) { // only send bulk messages by UDP switch (code) { case MsgShotBegin: case MsgShotEnd: case MsgPlayerUpdate: case MsgGMUpdate: case MsgLagPing: udpSend(udpSocket, b, l); return 0; } } // always sent MsgUDPLinkRequest over udp with udpSend if (code == MsgUDPLinkRequest) { udpSend(udpSocket, b, l); return 0; } return bufferedSend(b, l); } int NetHandler::pflush(fd_set *set) { if (FD_ISSET(fd, set)) return bufferedSend(NULL, 0); else return 0; } RxStatus NetHandler::receive(size_t length) { RxStatus returnValue; if ((int)length <= tcplen) return ReadAll; int size = recv(fd, tcpmsg + tcplen, length - tcplen, 0); if (size > 0) { tcplen += size; if (tcplen == (int)length) returnValue = ReadAll; else returnValue = ReadPart; } else if (size < 0) { // handle errors // get error code const int err = getErrno(); // ignore if it's one of these errors if (err == EAGAIN || err == EINTR) returnValue = ReadPart; // if socket is closed then give up if (err == ECONNRESET || err == EPIPE) { returnValue = ReadReset; } else { returnValue = ReadError; } } else { // if (size == 0) returnValue = ReadDiscon; } return returnValue; }; void *NetHandler::getTcpBuffer() { return tcpmsg; }; void NetHandler::cleanTcp() { tcplen = 0; }; std::string NetHandler::reasonToKick() { std::string reason; if (toBeKicked) { reason = toBeKickedReason; } toBeKicked = false; return reason; } #ifdef NETWORK_STATS void NetHandler::countMessage(uint16_t code, int len, int direction) { // add length of type and length len += 4; msgBytes[direction] += len; int i; struct MessageCount *msg1; msg1 = msg[direction]; for (i = 0; i < MessageTypes && msg1[i].code != 0; i++) if (msg1[i].code == code) break; msg1[i].code = code; if (msg1[i].maxSize < len) msg1[i].maxSize = len; msg1[i].count++; TimeKeeper now = TimeKeeper::getCurrent(); if (now - perSecondTime[direction] < 1.0f) { perSecondCurrentMsg[direction]++; perSecondCurrentBytes[direction] += len; } else { perSecondTime[direction] = now; if (perSecondMaxMsg[direction] < perSecondCurrentMsg[direction]) perSecondMaxMsg[direction] = perSecondCurrentMsg[direction]; if (perSecondMaxBytes[direction] < perSecondCurrentBytes[direction]) perSecondMaxBytes[direction] = perSecondCurrentBytes[direction]; perSecondCurrentMsg[direction] = 0; perSecondCurrentBytes[direction] = 0; } } void NetHandler::dumpMessageStats() { int i; struct MessageCount *msgStats; int total; int direction; DEBUG1("Player connect time: %f\n", TimeKeeper::getCurrent() - time); for (direction = 0; direction <= 1; direction++) { total = 0; DEBUG1("Player messages %s:", direction ? "out" : "in"); msgStats = msg[direction]; for (i = 0; i < MessageTypes && msgStats[i].code != 0; i++) { DEBUG1(" %c%c:%u(%u)", msgStats[i].code >> 8, msgStats[i].code & 0xff, msgStats[i].count, msgStats[i].maxSize); total += msgStats[i].count; } DEBUG1(" total:%u(%u) ", total, msgBytes[direction]); DEBUG1("max msgs/bytes per second: %u/%u\n", perSecondMaxMsg[direction], perSecondMaxBytes[direction]); } fflush(stdout); } #endif void NetHandler::udpSend(int udpSocket, const void *b, size_t l) { #ifdef TESTLINK if ((random()%LINKQUALITY) == 0) { DEBUG1("Drop Packet due to Test\n"); return; } #endif sendto(udpSocket, (const char *)b, (int)l, 0, (struct sockaddr*)&uaddr, sizeof(uaddr)); } bool NetHandler::isMyUdpAddrPort(struct sockaddr_in &_uaddr) { return udpin && (uaddr.sin_port == _uaddr.sin_port) && (memcmp(&uaddr.sin_addr, &_uaddr.sin_addr, sizeof(uaddr.sin_addr)) == 0); } void NetHandler::UdpInfo() { DEBUG3(" %d(%d-%d) %s:%d", playerIndex, udpin, udpout, inet_ntoa(uaddr.sin_addr), ntohs(uaddr.sin_port)); } void NetHandler::debugUdpRead(int n, struct sockaddr_in &_uaddr, int udpSocket) { DEBUG4("Player %s [%d] uread() %s:%d len %d from %s:%d on %i\n", info->getCallSign(), playerIndex, inet_ntoa(uaddr.sin_addr), ntohs(uaddr.sin_port), n, inet_ntoa(_uaddr.sin_addr), ntohs(_uaddr.sin_port), udpSocket); } void NetHandler::getPlayerList(char *list) { sprintf(list, "[%d]%-16s: %s%s%s%s%s%s", playerIndex, info->getCallSign(), peer.getDotNotation().c_str(), #ifdef HAVE_ADNS_H info->getHostname() ? " (" : "", info->getHostname() ? info->getHostname() : "", info->getHostname() ? ")" : "", #else "", "", "", #endif udpin ? " udp" : "", udpout ? "+" : ""); }; // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>dot net warnings<commit_after>/* bzflag * Copyright (c) 1993 - 2004 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /* interface header */ #include "NetHandler.h" // system headers #include <errno.h> NetHandler::NetHandler(PlayerInfo* _info, const struct sockaddr_in &clientAddr, int _playerIndex, int _fd) : info(_info), playerIndex(_playerIndex), fd(_fd), tcplen(0), outmsgOffset(0), outmsgSize(0), outmsgCapacity(0), outmsg(NULL), toBeKicked(false) { // store address information for player AddrLen addr_len = sizeof(clientAddr); memcpy(&uaddr, &clientAddr, addr_len); peer = Address(uaddr); // update player state time = TimeKeeper::getCurrent(); #ifdef NETWORK_STATS int i; struct MessageCount *statMsg; int direction; for (direction = 0; direction <= 1; direction++) { statMsg = msg[direction]; for (i = 0; i < MessageTypes && statMsg[i].code != 0; i++) { statMsg[i].count = 0; statMsg[i].code = 0; } msgBytes[direction] = 0; perSecondTime[direction] = time; perSecondCurrentMsg[direction] = 0; perSecondMaxMsg[direction] = 0; perSecondCurrentBytes[direction] = 0; perSecondMaxBytes[direction] = 0; } #endif } NetHandler::~NetHandler() { // shutdown TCP socket shutdown(fd, 2); close(fd); delete[] outmsg; } void NetHandler::fdSet(fd_set *read_set, fd_set *write_set, int &maxFile) { _FD_SET(fd, read_set); if (outmsgSize > 0) _FD_SET(fd, write_set); if (fd > maxFile) maxFile = fd; } int NetHandler::fdIsSet(fd_set *set) { return FD_ISSET(fd, set); } int NetHandler::send(const void *buffer, size_t length) { int n = ::send(fd, (const char *)buffer, (int)length, 0); if (n >= 0) return n; // get error code const int err = getErrno(); // if socket is closed then give up if (err == ECONNRESET || err == EPIPE) { return -1; } // just try again later if it's one of these errors if (err != EAGAIN && err != EINTR) { // dump other errors and remove the player nerror("error on write"); toBeKicked = true; toBeKickedReason = "Write error"; } return 0; } void NetHandler::setUdpOut() { udpout = true; DEBUG2("Player %s [%d] outbound UDP up\n", info->getCallSign(), playerIndex); } bool NetHandler::setUdpIn(struct sockaddr_in &_uaddr) { if (udpin) return false; bool same = !memcmp(&uaddr.sin_addr, &_uaddr.sin_addr, sizeof(uaddr.sin_addr)); if (same) { DEBUG2("Player %s [%d] inbound UDP up %s:%d actual %d\n", info->getCallSign(), playerIndex, inet_ntoa(uaddr.sin_addr), ntohs(uaddr.sin_port), ntohs(_uaddr.sin_port)); if (_uaddr.sin_port) { uaddr.sin_port = _uaddr.sin_port; udpin = true; } } else { DEBUG2 ("Player %s [%d] inbound UDP rejected %s:%d different IP than %s:%d\n", info->getCallSign(), playerIndex, inet_ntoa(uaddr.sin_addr), ntohs(uaddr.sin_port), inet_ntoa(_uaddr.sin_addr), ntohs(_uaddr.sin_port)); } return same; } int NetHandler::bufferedSend(const void *buffer, size_t length) { // try flushing buffered data if (outmsgSize != 0) { const int n = send(outmsg + outmsgOffset, outmsgSize); if (n == -1) { return -1; } if (n > 0) { outmsgOffset += n; outmsgSize -= n; } } // if the buffer is empty try writing the data immediately if ((outmsgSize == 0) && length > 0) { const int n = send(buffer, length); if (n == -1) { return -1; } if (n > 0) { buffer = (void*)(((const char*)buffer) + n); length -= n; } } // write leftover data to the buffer if (length > 0) { // is there enough room in buffer? if (outmsgCapacity < outmsgSize + (int)length) { // double capacity until it's big enough int newCapacity = (outmsgCapacity == 0) ? 512 : outmsgCapacity; while (newCapacity < outmsgSize + (int)length) newCapacity <<= 1; // if the buffer is getting too big then drop the player. chances // are the network is down or too unreliable to that player. // FIXME -- is 20kB too big? too small? if (newCapacity >= 20 * 1024) { DEBUG2("Player %s [%d] drop, unresponsive with %d bytes queued\n", info->getCallSign(), playerIndex, outmsgSize + length); toBeKicked = true; toBeKickedReason = "send queue too big"; return 0; } // allocate memory char *newbuf = new char[newCapacity]; // copy old data over memmove(newbuf, outmsg + outmsgOffset, outmsgSize); // cutover delete[] outmsg; outmsg = newbuf; outmsgOffset = 0; outmsgCapacity = newCapacity; } // if we can't fit new data at the end of the buffer then move existing // data to head of buffer // FIXME -- use a ring buffer to avoid moving memory if (outmsgOffset + outmsgSize + (int)length > outmsgCapacity) { memmove(outmsg, outmsg + outmsgOffset, outmsgSize); outmsgOffset = 0; } // append data memmove(outmsg + outmsgOffset + outmsgSize, buffer, length); outmsgSize += (int)length; } return 0; } int NetHandler::pwrite(const void *b, int l, int udpSocket) { if (l == 0) { return 0; } void *buf = (void *)b; uint16_t len, code; buf = nboUnpackUShort(buf, len); buf = nboUnpackUShort(buf, code); #ifdef NETWORK_STATS countMessage(code, len, 1); #endif // Check if UDP Link is used instead of TCP, if so jump into udpSend if (udpout) { // only send bulk messages by UDP switch (code) { case MsgShotBegin: case MsgShotEnd: case MsgPlayerUpdate: case MsgGMUpdate: case MsgLagPing: udpSend(udpSocket, b, l); return 0; } } // always sent MsgUDPLinkRequest over udp with udpSend if (code == MsgUDPLinkRequest) { udpSend(udpSocket, b, l); return 0; } return bufferedSend(b, l); } int NetHandler::pflush(fd_set *set) { if (FD_ISSET(fd, set)) return bufferedSend(NULL, 0); else return 0; } RxStatus NetHandler::receive(size_t length) { RxStatus returnValue; if ((int)length <= tcplen) return ReadAll; int size = recv(fd, tcpmsg + tcplen, (int)length - tcplen, 0); if (size > 0) { tcplen += size; if (tcplen == (int)length) returnValue = ReadAll; else returnValue = ReadPart; } else if (size < 0) { // handle errors // get error code const int err = getErrno(); // ignore if it's one of these errors if (err == EAGAIN || err == EINTR) returnValue = ReadPart; // if socket is closed then give up if (err == ECONNRESET || err == EPIPE) { returnValue = ReadReset; } else { returnValue = ReadError; } } else { // if (size == 0) returnValue = ReadDiscon; } return returnValue; }; void *NetHandler::getTcpBuffer() { return tcpmsg; }; void NetHandler::cleanTcp() { tcplen = 0; }; std::string NetHandler::reasonToKick() { std::string reason; if (toBeKicked) { reason = toBeKickedReason; } toBeKicked = false; return reason; } #ifdef NETWORK_STATS void NetHandler::countMessage(uint16_t code, int len, int direction) { // add length of type and length len += 4; msgBytes[direction] += len; int i; struct MessageCount *msg1; msg1 = msg[direction]; for (i = 0; i < MessageTypes && msg1[i].code != 0; i++) if (msg1[i].code == code) break; msg1[i].code = code; if (msg1[i].maxSize < len) msg1[i].maxSize = len; msg1[i].count++; TimeKeeper now = TimeKeeper::getCurrent(); if (now - perSecondTime[direction] < 1.0f) { perSecondCurrentMsg[direction]++; perSecondCurrentBytes[direction] += len; } else { perSecondTime[direction] = now; if (perSecondMaxMsg[direction] < perSecondCurrentMsg[direction]) perSecondMaxMsg[direction] = perSecondCurrentMsg[direction]; if (perSecondMaxBytes[direction] < perSecondCurrentBytes[direction]) perSecondMaxBytes[direction] = perSecondCurrentBytes[direction]; perSecondCurrentMsg[direction] = 0; perSecondCurrentBytes[direction] = 0; } } void NetHandler::dumpMessageStats() { int i; struct MessageCount *msgStats; int total; int direction; DEBUG1("Player connect time: %f\n", TimeKeeper::getCurrent() - time); for (direction = 0; direction <= 1; direction++) { total = 0; DEBUG1("Player messages %s:", direction ? "out" : "in"); msgStats = msg[direction]; for (i = 0; i < MessageTypes && msgStats[i].code != 0; i++) { DEBUG1(" %c%c:%u(%u)", msgStats[i].code >> 8, msgStats[i].code & 0xff, msgStats[i].count, msgStats[i].maxSize); total += msgStats[i].count; } DEBUG1(" total:%u(%u) ", total, msgBytes[direction]); DEBUG1("max msgs/bytes per second: %u/%u\n", perSecondMaxMsg[direction], perSecondMaxBytes[direction]); } fflush(stdout); } #endif void NetHandler::udpSend(int udpSocket, const void *b, size_t l) { #ifdef TESTLINK if ((random()%LINKQUALITY) == 0) { DEBUG1("Drop Packet due to Test\n"); return; } #endif sendto(udpSocket, (const char *)b, (int)l, 0, (struct sockaddr*)&uaddr, sizeof(uaddr)); } bool NetHandler::isMyUdpAddrPort(struct sockaddr_in &_uaddr) { return udpin && (uaddr.sin_port == _uaddr.sin_port) && (memcmp(&uaddr.sin_addr, &_uaddr.sin_addr, sizeof(uaddr.sin_addr)) == 0); } void NetHandler::UdpInfo() { DEBUG3(" %d(%d-%d) %s:%d", playerIndex, udpin, udpout, inet_ntoa(uaddr.sin_addr), ntohs(uaddr.sin_port)); } void NetHandler::debugUdpRead(int n, struct sockaddr_in &_uaddr, int udpSocket) { DEBUG4("Player %s [%d] uread() %s:%d len %d from %s:%d on %i\n", info->getCallSign(), playerIndex, inet_ntoa(uaddr.sin_addr), ntohs(uaddr.sin_port), n, inet_ntoa(_uaddr.sin_addr), ntohs(_uaddr.sin_port), udpSocket); } void NetHandler::getPlayerList(char *list) { sprintf(list, "[%d]%-16s: %s%s%s%s%s%s", playerIndex, info->getCallSign(), peer.getDotNotation().c_str(), #ifdef HAVE_ADNS_H info->getHostname() ? " (" : "", info->getHostname() ? info->getHostname() : "", info->getHostname() ? ")" : "", #else "", "", "", #endif udpin ? " udp" : "", udpout ? "+" : ""); }; // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#include "fractile.h" #include <algorithm> #include <boost/algorithm/string.hpp> #include "logger.h" #include "plugin_factory.h" #include "lagged_ensemble.h" #include "time_ensemble.h" #include "fetcher.h" #include "radon.h" #include "numerical_functions.h" #include "util.h" namespace himan { namespace plugin { fractile::fractile() : itsFractiles({0., 10., 25., 50., 75., 90., 100.}) { itsCudaEnabledCalculation = false; itsLogger = logger("fractile"); } std::unique_ptr<ensemble> CreateEnsemble(const std::shared_ptr<const plugin_configuration> conf) { logger log("fractile"); std::string paramName = conf->GetValue("param"); auto ensTypestr = conf->GetValue("ensemble_type"); HPEnsembleType ensType = kPerturbedEnsemble; if (!ensTypestr.empty()) { ensType = HPStringToEnsembleType.at(ensTypestr); } size_t ensSize = 0; if (conf->Exists("ensemble_size")) { ensSize = std::stoi(conf->GetValue("ensemble_size")); } else if (ensType == kPerturbedEnsemble || ensType == kLaggedEnsemble) { // Regular ensemble size is static, get it from database if user // hasn't specified any size auto r = GET_PLUGIN(radon); std::string ensembleSizeStr = r->RadonDB().GetProducerMetaData(conf->SourceProducer(0).Id(), "ensemble size"); if (ensembleSizeStr.empty()) { log.Error("Unable to find ensemble size from database"); himan::Abort(); } ensSize = std::stoi(ensembleSizeStr); } std::unique_ptr<ensemble> ens = nullptr; switch (ensType) { case kPerturbedEnsemble: ens = std::unique_ptr<ensemble>(new ensemble(param(paramName), ensSize)); break; case kTimeEnsemble: { int secondaryLen = 0, secondaryStep = 1; HPTimeResolution secondarySpan = kHourResolution; if (conf->Exists(("secondary_time_len"))) { secondaryLen = std::stoi(conf->GetValue("secondary_time_len")); } if (conf->Exists(("secondary_time_step"))) { secondaryStep = std::stoi(conf->GetValue("secondary_time_step")); } if (conf->Exists(("secondary_time_span"))) { secondarySpan = HPStringToTimeResolution.at(conf->GetValue("secondary_time_span")); } ens = std::unique_ptr<time_ensemble>(new time_ensemble(param(paramName), ensSize, kYearResolution, secondaryLen, secondaryStep, secondarySpan)); } break; case kLaggedEnsemble: { auto name = conf->GetValue("named_ensemble"); if (name.empty() == false) { ens = std::unique_ptr<lagged_ensemble>(new lagged_ensemble(param(paramName), name)); } else { auto lagstr = conf->GetValue("lag"); if (lagstr.empty()) { log.Fatal("specify lag value for lagged_ensemble"); himan::Abort(); } int lag = std::stoi(conf->GetValue("lag")); if (lag == 0) { log.Fatal("lag value needs to be negative integer"); himan::Abort(); } else if (lag > 0) { log.Warning("negating lag value " + std::to_string(-lag)); lag = -lag; } auto stepsstr = conf->GetValue("lagged_steps"); if (stepsstr.empty()) { log.Fatal("specify lagged_steps value for lagged_ensemble"); himan::Abort(); } int steps = std::stoi(conf->GetValue("lagged_steps")); if (steps <= 0) { log.Fatal("invalid lagged_steps value. Allowed range >= 0"); himan::Abort(); } steps++; ens = std::unique_ptr<lagged_ensemble>( new lagged_ensemble(param(paramName), ensSize, time_duration(kHourResolution, lag), steps)); } } break; default: log.Fatal("Unknown ensemble type: " + ensType); himan::Abort(); } if (conf->Exists("max_missing_forecasts")) { ens->MaximumMissingForecasts(std::stoi(conf->GetValue("max_missing_forecasts"))); } return std::move(ens); } void fractile::SetParams() { auto fractiles = itsConfiguration->GetValue("fractiles"); if (!fractiles.empty()) { itsFractiles.clear(); auto list = util::Split(fractiles, ","); for (std::string& val : list) { boost::trim(val); try { itsFractiles.push_back(std::stof(val)); } catch (const std::invalid_argument& e) { itsLogger.Fatal("Invalid fractile value: '" + val + "'"); himan::Abort(); } } } params calculatedParams; std::string paramName = itsConfiguration->GetValue("param"); if (paramName.empty()) { itsLogger.Fatal("param not specified"); himan::Abort(); } for (float frac : itsFractiles) { auto name = "F" + boost::lexical_cast<std::string>(frac) + "-" + paramName; param p(name); p.ProcessingType(processing_type(kFractile, frac, kHPMissingValue, kHPMissingInt)); calculatedParams.push_back(p); } auto name = util::Split(paramName, "-"); param mean(name[0] + "-MEAN-" + name[1]); mean.ProcessingType(processing_type(kEnsembleMean, kHPMissingInt, kHPMissingInt, kHPMissingInt)); calculatedParams.push_back(mean); param stdev(name[0] + "-STDDEV-" + name[1]); stdev.ProcessingType(processing_type(kStandardDeviation, kHPMissingInt, kHPMissingInt, kHPMissingInt)); calculatedParams.push_back(stdev); compiled_plugin_base::SetParams(calculatedParams); } void fractile::SetForecastType() { if (itsForecastTypeIterator.Size() > 1) { itsLogger.Warning("More than one forecast type defined - fractile can only produce 'statistical processing'"); } const std::vector<forecast_type> type({forecast_type(kStatisticalProcessing)}); itsForecastTypeIterator = forecast_type_iter(type); std::const_pointer_cast<himan::plugin_configuration>(itsConfiguration)->ForecastTypes(type); } void fractile::Process(const std::shared_ptr<const plugin_configuration> conf) { Init(conf); SetParams(); SetForecastType(); Start<float>(); } void fractile::Calculate(std::shared_ptr<info<float>> myTargetInfo, uint16_t threadIndex) { const std::string deviceType = "CPU"; auto ens = CreateEnsemble(itsConfiguration); auto threadedLogger = logger("fractileThread # " + std::to_string(threadIndex)); forecast_time forecastTime = myTargetInfo->Time(); level forecastLevel = myTargetInfo->Level(); threadedLogger.Info("Calculating time " + static_cast<std::string>(forecastTime.ValidDateTime()) + " level " + static_cast<std::string>(forecastLevel)); try { ens->Fetch(itsConfiguration, forecastTime, forecastLevel); } catch (const HPExceptionType& e) { if (e == kFileDataNotFound) { itsLogger.Error("Failed to find ensemble data"); return; } } myTargetInfo->ResetLocation(); ens->ResetLocation(); while (myTargetInfo->NextLocation() && ens->NextLocation()) { auto sortedValues = ens->SortedValues(); const size_t ensembleSize = sortedValues.size(); // Skip this step if we didn't get any valid fields if (ensembleSize == 0) { continue; } // process mean&var before hanging size of sortedValues float mean = numerical_functions::Mean<float>(sortedValues); if (!std::isfinite(mean)) { mean = MissingFloat(); } float var = std::sqrt(numerical_functions::Variance<float>(sortedValues)); if (!std::isfinite(var)) { var = MissingFloat(); } // sortedValues needs to have one element at the back for correct array indexing // NOTE: `ensembleSize` stays the same sortedValues.push_back(0.0); ASSERT(!itsFractiles.empty()); size_t targetInfoIndex = 0; for (auto P : itsFractiles) { // use the linear interpolation between closest ranks method recommended by NIST // http://www.itl.nist.gov/div898/handbook/prc/section2/prc262.htm float x; // check lower corner case p E [0,1/(N+1)] if (P / 100.0 <= 1.0 / static_cast<float>(ensembleSize + 1)) { x = 1; } // check upper corner case p E [N/(N+1),1] else if (P / 100.0f >= static_cast<float>(ensembleSize) / static_cast<float>(ensembleSize + 1)) { x = static_cast<float>(ensembleSize); } // everything that happens on the interval between else { x = P / 100.0f * static_cast<float>(ensembleSize + 1); } // floor x explicitly before casting to int int i = static_cast<int>(std::floor(x)); myTargetInfo->Index<param>(targetInfoIndex); myTargetInfo->Value(sortedValues[i - 1] + std::fmod(x, 1.0f) * (sortedValues[i] - sortedValues[i - 1])); ++targetInfoIndex; } myTargetInfo->Index<param>(targetInfoIndex); myTargetInfo->Value(mean); ++targetInfoIndex; myTargetInfo->Index<param>(targetInfoIndex); myTargetInfo->Value(var); } threadedLogger.Info("[" + deviceType + "] Missing values: " + std::to_string(myTargetInfo->Data().MissingCount()) + "/" + std::to_string(myTargetInfo->Data().Size())); } } // plugin } // namespace <commit_msg>Remove boost::lexical_cast calls<commit_after>#include "fractile.h" #include <algorithm> #include <boost/algorithm/string.hpp> #include "logger.h" #include "plugin_factory.h" #include "lagged_ensemble.h" #include "time_ensemble.h" #include "fetcher.h" #include "radon.h" #include "numerical_functions.h" #include "util.h" namespace himan { namespace plugin { fractile::fractile() : itsFractiles({0., 10., 25., 50., 75., 90., 100.}) { itsCudaEnabledCalculation = false; itsLogger = logger("fractile"); } std::unique_ptr<ensemble> CreateEnsemble(const std::shared_ptr<const plugin_configuration> conf) { logger log("fractile"); std::string paramName = conf->GetValue("param"); auto ensTypestr = conf->GetValue("ensemble_type"); HPEnsembleType ensType = kPerturbedEnsemble; if (!ensTypestr.empty()) { ensType = HPStringToEnsembleType.at(ensTypestr); } size_t ensSize = 0; if (conf->Exists("ensemble_size")) { ensSize = std::stoi(conf->GetValue("ensemble_size")); } else if (ensType == kPerturbedEnsemble || ensType == kLaggedEnsemble) { // Regular ensemble size is static, get it from database if user // hasn't specified any size auto r = GET_PLUGIN(radon); std::string ensembleSizeStr = r->RadonDB().GetProducerMetaData(conf->SourceProducer(0).Id(), "ensemble size"); if (ensembleSizeStr.empty()) { log.Error("Unable to find ensemble size from database"); himan::Abort(); } ensSize = std::stoi(ensembleSizeStr); } std::unique_ptr<ensemble> ens = nullptr; switch (ensType) { case kPerturbedEnsemble: ens = std::unique_ptr<ensemble>(new ensemble(param(paramName), ensSize)); break; case kTimeEnsemble: { int secondaryLen = 0, secondaryStep = 1; HPTimeResolution secondarySpan = kHourResolution; if (conf->Exists(("secondary_time_len"))) { secondaryLen = std::stoi(conf->GetValue("secondary_time_len")); } if (conf->Exists(("secondary_time_step"))) { secondaryStep = std::stoi(conf->GetValue("secondary_time_step")); } if (conf->Exists(("secondary_time_span"))) { secondarySpan = HPStringToTimeResolution.at(conf->GetValue("secondary_time_span")); } ens = std::unique_ptr<time_ensemble>(new time_ensemble(param(paramName), ensSize, kYearResolution, secondaryLen, secondaryStep, secondarySpan)); } break; case kLaggedEnsemble: { auto name = conf->GetValue("named_ensemble"); if (name.empty() == false) { ens = std::unique_ptr<lagged_ensemble>(new lagged_ensemble(param(paramName), name)); } else { auto lagstr = conf->GetValue("lag"); if (lagstr.empty()) { log.Fatal("specify lag value for lagged_ensemble"); himan::Abort(); } int lag = std::stoi(conf->GetValue("lag")); if (lag == 0) { log.Fatal("lag value needs to be negative integer"); himan::Abort(); } else if (lag > 0) { log.Warning("negating lag value " + std::to_string(-lag)); lag = -lag; } auto stepsstr = conf->GetValue("lagged_steps"); if (stepsstr.empty()) { log.Fatal("specify lagged_steps value for lagged_ensemble"); himan::Abort(); } int steps = std::stoi(conf->GetValue("lagged_steps")); if (steps <= 0) { log.Fatal("invalid lagged_steps value. Allowed range >= 0"); himan::Abort(); } steps++; ens = std::unique_ptr<lagged_ensemble>( new lagged_ensemble(param(paramName), ensSize, time_duration(kHourResolution, lag), steps)); } } break; default: log.Fatal("Unknown ensemble type: " + ensType); himan::Abort(); } if (conf->Exists("max_missing_forecasts")) { ens->MaximumMissingForecasts(std::stoi(conf->GetValue("max_missing_forecasts"))); } return std::move(ens); } void fractile::SetParams() { auto fractiles = itsConfiguration->GetValue("fractiles"); if (!fractiles.empty()) { itsFractiles.clear(); auto list = util::Split(fractiles, ","); for (std::string& val : list) { boost::trim(val); try { itsFractiles.push_back(std::stof(val)); } catch (const std::invalid_argument& e) { itsLogger.Fatal("Invalid fractile value: '" + val + "'"); himan::Abort(); } } } params calculatedParams; std::string paramName = itsConfiguration->GetValue("param"); if (paramName.empty()) { itsLogger.Fatal("param not specified"); himan::Abort(); } for (float frac : itsFractiles) { auto name = fmt::format("F{}-{}", frac, paramName); param p(name); p.ProcessingType(processing_type(kFractile, frac, kHPMissingValue, kHPMissingInt)); calculatedParams.push_back(p); } auto name = util::Split(paramName, "-"); param mean(name[0] + "-MEAN-" + name[1]); mean.ProcessingType(processing_type(kEnsembleMean, kHPMissingInt, kHPMissingInt, kHPMissingInt)); calculatedParams.push_back(mean); param stdev(name[0] + "-STDDEV-" + name[1]); stdev.ProcessingType(processing_type(kStandardDeviation, kHPMissingInt, kHPMissingInt, kHPMissingInt)); calculatedParams.push_back(stdev); compiled_plugin_base::SetParams(calculatedParams); } void fractile::SetForecastType() { if (itsForecastTypeIterator.Size() > 1) { itsLogger.Warning("More than one forecast type defined - fractile can only produce 'statistical processing'"); } const std::vector<forecast_type> type({forecast_type(kStatisticalProcessing)}); itsForecastTypeIterator = forecast_type_iter(type); std::const_pointer_cast<himan::plugin_configuration>(itsConfiguration)->ForecastTypes(type); } void fractile::Process(const std::shared_ptr<const plugin_configuration> conf) { Init(conf); SetParams(); SetForecastType(); Start<float>(); } void fractile::Calculate(std::shared_ptr<info<float>> myTargetInfo, uint16_t threadIndex) { const std::string deviceType = "CPU"; auto ens = CreateEnsemble(itsConfiguration); auto threadedLogger = logger("fractileThread # " + std::to_string(threadIndex)); forecast_time forecastTime = myTargetInfo->Time(); level forecastLevel = myTargetInfo->Level(); threadedLogger.Info("Calculating time " + static_cast<std::string>(forecastTime.ValidDateTime()) + " level " + static_cast<std::string>(forecastLevel)); try { ens->Fetch(itsConfiguration, forecastTime, forecastLevel); } catch (const HPExceptionType& e) { if (e == kFileDataNotFound) { itsLogger.Error("Failed to find ensemble data"); return; } } myTargetInfo->ResetLocation(); ens->ResetLocation(); while (myTargetInfo->NextLocation() && ens->NextLocation()) { auto sortedValues = ens->SortedValues(); const size_t ensembleSize = sortedValues.size(); // Skip this step if we didn't get any valid fields if (ensembleSize == 0) { continue; } // process mean&var before hanging size of sortedValues float mean = numerical_functions::Mean<float>(sortedValues); if (!std::isfinite(mean)) { mean = MissingFloat(); } float var = std::sqrt(numerical_functions::Variance<float>(sortedValues)); if (!std::isfinite(var)) { var = MissingFloat(); } // sortedValues needs to have one element at the back for correct array indexing // NOTE: `ensembleSize` stays the same sortedValues.push_back(0.0); ASSERT(!itsFractiles.empty()); size_t targetInfoIndex = 0; for (auto P : itsFractiles) { // use the linear interpolation between closest ranks method recommended by NIST // http://www.itl.nist.gov/div898/handbook/prc/section2/prc262.htm float x; // check lower corner case p E [0,1/(N+1)] if (P / 100.0 <= 1.0 / static_cast<float>(ensembleSize + 1)) { x = 1; } // check upper corner case p E [N/(N+1),1] else if (P / 100.0f >= static_cast<float>(ensembleSize) / static_cast<float>(ensembleSize + 1)) { x = static_cast<float>(ensembleSize); } // everything that happens on the interval between else { x = P / 100.0f * static_cast<float>(ensembleSize + 1); } // floor x explicitly before casting to int int i = static_cast<int>(std::floor(x)); myTargetInfo->Index<param>(targetInfoIndex); myTargetInfo->Value(sortedValues[i - 1] + std::fmod(x, 1.0f) * (sortedValues[i] - sortedValues[i - 1])); ++targetInfoIndex; } myTargetInfo->Index<param>(targetInfoIndex); myTargetInfo->Value(mean); ++targetInfoIndex; myTargetInfo->Index<param>(targetInfoIndex); myTargetInfo->Value(var); } threadedLogger.Info("[" + deviceType + "] Missing values: " + std::to_string(myTargetInfo->Data().MissingCount()) + "/" + std::to_string(myTargetInfo->Data().Size())); } } // namespace plugin } // namespace himan <|endoftext|>
<commit_before>/** * @file llfloaterabout.cpp * @author James Cook * @brief The about box from Help->About * * $LicenseInfo:firstyear=2001&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llfloaterabout.h" // Viewer includes #include "llagent.h" #include "llappviewer.h" #include "llsecondlifeurls.h" #include "llvoiceclient.h" #include "lluictrlfactory.h" #include "llviewertexteditor.h" #include "llviewercontrol.h" #include "llviewerstats.h" #include "llviewerregion.h" #include "llversioninfo.h" #include "llweb.h" // [RLVa:KB] - Checked: 2010-04-18 (RLVa-1.2.0e) #include "rlvhandler.h" // [/RLVa:KB] // Linden library includes #include "llaudioengine.h" #include "llbutton.h" #include "llcurl.h" #include "llglheaders.h" #include "llfloater.h" #include "llfloaterreg.h" #include "llimagej2c.h" #include "llsys.h" #include "lltrans.h" #include "lluri.h" #include "v3dmath.h" #include "llwindow.h" #include "stringize.h" #include "llsdutil_math.h" #include "lleventapi.h" #if LL_WINDOWS #include "lldxhardware.h" #endif extern LLMemoryInfo gSysMemory; extern U32 gPacketsIn; static std::string get_viewer_release_notes_url(); ///---------------------------------------------------------------------------- /// Class LLFloaterAbout ///---------------------------------------------------------------------------- class LLFloaterAbout : public LLFloater { friend class LLFloaterReg; private: LLFloaterAbout(const LLSD& key); virtual ~LLFloaterAbout(); public: /*virtual*/ BOOL postBuild(); /// Obtain the data used to fill out the contents string. This is /// separated so that we can programmatically access the same info. static LLSD getInfo(); void onClickCopyToClipboard(); }; // Default constructor LLFloaterAbout::LLFloaterAbout(const LLSD& key) : LLFloater(key) { } // Destroys the object LLFloaterAbout::~LLFloaterAbout() { } BOOL LLFloaterAbout::postBuild() { center(); LLViewerTextEditor *support_widget = getChild<LLViewerTextEditor>("support_editor", true); LLViewerTextEditor *credits_widget = getChild<LLViewerTextEditor>("credits_editor", true); getChild<LLUICtrl>("copy_btn")->setCommitCallback( boost::bind(&LLFloaterAbout::onClickCopyToClipboard, this)); #if LL_WINDOWS getWindow()->incBusyCount(); getWindow()->setCursor(UI_CURSOR_ARROW); #endif LLSD info(getInfo()); #if LL_WINDOWS getWindow()->decBusyCount(); getWindow()->setCursor(UI_CURSOR_ARROW); #endif std::ostringstream support; // Render the LLSD from getInfo() as a format_map_t LLStringUtil::format_map_t args; // allow the "Release Notes" URL label to be localized args["ReleaseNotes"] = LLTrans::getString("ReleaseNotes"); for (LLSD::map_const_iterator ii(info.beginMap()), iend(info.endMap()); ii != iend; ++ii) { if (! ii->second.isArray()) { // Scalar value if (ii->second.isUndefined()) { args[ii->first] = getString("none"); } else { // don't forget to render value asString() // NOTE: the default string conversion for LLSD real is "%g" so we'll convert those ourselves args[ii->first] = (!ii->second.isReal()) ? ii->second.asString() : llformat("%f", ii->second.asReal()); } } else { // array value: build KEY_0, KEY_1 etc. entries for (LLSD::Integer n(0), size(ii->second.size()); n < size; ++n) { args[STRINGIZE(ii->first << '_' << n)] = (!ii->second[n].isReal()) ? ii->second[n].asString() : llformat("%f", ii->second[n].asReal()); } } } // Now build the various pieces support << getString("AboutHeader", args); if (info.has("REGION")) { support << "\n\n" << getString("AboutPosition", args); } support << "\n\n" << getString("AboutSystem", args); support << "\n"; if (info.has("GRAPHICS_DRIVER_VERSION")) { support << "\n" << getString("AboutDriver", args); } support << "\n" << getString("AboutLibs", args); if (info.has("COMPILER")) { support << "\n" << getString("AboutCompiler", args); } if (info.has("PACKETS_IN")) { support << '\n' << getString("AboutTraffic", args); } support_widget->appendText(support.str(), FALSE, LLStyle::Params() .color(LLUIColorTable::instance().getColor("TextFgReadOnlyColor"))); support_widget->blockUndo(); // Fix views support_widget->setEnabled(FALSE); support_widget->startOfDoc(); credits_widget->setEnabled(FALSE); credits_widget->startOfDoc(); return TRUE; } // static LLSD LLFloaterAbout::getInfo() { // The point of having one method build an LLSD info block and the other // construct the user-visible About string is to ensure that the same info // is available to a getInfo() caller as to the user opening // LLFloaterAbout. LLSD info; LLSD version; version.append(LLVersionInfo::getMajor()); version.append(LLVersionInfo::getMinor()); version.append(LLVersionInfo::getPatch()); version.append(LLVersionInfo::getBuild()); info["VIEWER_VERSION"] = version; info["VIEWER_VERSION_STR"] = LLVersionInfo::getVersion(); info["BUILD_DATE"] = __DATE__; info["BUILD_TIME"] = __TIME__; info["CHANNEL"] = LLVersionInfo::getChannel(); info["SKIN"] = gSavedSettings.getString("SkinCurrent"); info["THEME"] = gSavedSettings.getString("SkinCurrentTheme"); info["VIEWER_RELEASE_NOTES_URL"] = get_viewer_release_notes_url(); #if LL_MSVC info["COMPILER"] = "MSVC"; info["COMPILER_VERSION"] = _MSC_VER; #elif LL_GNUC info["COMPILER"] = "GCC"; info["COMPILER_VERSION"] = GCC_VERSION; #endif // Position LLViewerRegion* region = gAgent.getRegion(); if (region) { const LLVector3d &pos = gAgent.getPositionGlobal(); info["POSITION"] = ll_sd_from_vector3d(pos); info["REGION"] = gAgent.getRegion()->getName(); info["HOSTNAME"] = gAgent.getRegion()->getHost().getHostName(); info["HOSTIP"] = gAgent.getRegion()->getHost().getString(); info["SERVER_VERSION"] = gLastVersionChannel; info["SERVER_RELEASE_NOTES_URL"] = LLWeb::escapeURL(region->getCapability("ServerReleaseNotes")); } // CPU info["CPU"] = gSysCPU.getCPUString(); info["MEMORY_MB"] = LLSD::Integer(gSysMemory.getPhysicalMemoryKB() / 1024); // Moved hack adjustment to Windows memory size into llsys.cpp info["OS_VERSION"] = LLAppViewer::instance()->getOSInfo().getOSString(); info["GRAPHICS_CARD_VENDOR"] = (const char*)(glGetString(GL_VENDOR)); info["GRAPHICS_CARD"] = (const char*)(glGetString(GL_RENDERER)); #if LL_WINDOWS LLSD driver_info = gDXHardware.getDisplayInfo(); if (driver_info.has("DriverVersion")) { info["GRAPHICS_DRIVER_VERSION"] = driver_info["DriverVersion"]; } #endif // [RLVa:KB] - Checked: 2010-04-18 (RLVa-1.2.0e) | Added: RLVa-1.2.0e if (rlv_handler_t::isEnabled()) info["RLV_VERSION"] = RlvStrings::getVersionAbout(); else info["RLV_VERSION"] = "(disabled)"; // [/RLVa:KB] info["OPENGL_VERSION"] = (const char*)(glGetString(GL_VERSION)); info["LIBCURL_VERSION"] = LLCurl::getVersionString(); info["J2C_VERSION"] = LLImageJ2C::getEngineInfo(); bool want_fullname = true; info["AUDIO_DRIVER_VERSION"] = gAudiop ? LLSD(gAudiop->getDriverName(want_fullname)) : LLSD(); if(LLVoiceClient::getInstance()->voiceEnabled()) { LLVoiceVersionInfo version = LLVoiceClient::getInstance()->getVersion(); std::ostringstream version_string; version_string << version.serverType << " " << version.serverVersion << std::endl; info["VOICE_VERSION"] = version_string.str(); } else { info["VOICE_VERSION"] = LLTrans::getString("NotConnected"); } // TODO: Implement media plugin version query info["QT_WEBKIT_VERSION"] = "4.7.1 (version number hard-coded)"; if (gPacketsIn > 0) { info["PACKETS_LOST"] = LLViewerStats::getInstance()->mPacketsLostStat.getCurrent(); info["PACKETS_IN"] = F32(gPacketsIn); info["PACKETS_PCT"] = 100.f*info["PACKETS_LOST"].asReal() / info["PACKETS_IN"].asReal(); } return info; } static std::string get_viewer_release_notes_url() { // return a URL to the release notes for this viewer, such as: // http://wiki.secondlife.com/wiki/Release_Notes/Second Life Beta Viewer/2.1.0 std::string url = LLTrans::getString("RELEASE_NOTES_BASE_URL"); if (! LLStringUtil::endsWith(url, "/")) url += "/"; url += LLVersionInfo::getChannel() + "/"; url += LLVersionInfo::getShortVersion(); return LLWeb::escapeURL(url); } class LLFloaterAboutListener: public LLEventAPI { public: LLFloaterAboutListener(): LLEventAPI("LLFloaterAbout", "LLFloaterAbout listener to retrieve About box info") { add("getInfo", "Request an LLSD::Map containing information used to populate About box", &LLFloaterAboutListener::getInfo, LLSD().with("reply", LLSD())); } private: void getInfo(const LLSD& request) const { LLReqID reqid(request); LLSD reply(LLFloaterAbout::getInfo()); reqid.stamp(reply); LLEventPumps::instance().obtain(request["reply"]).post(reply); } }; static LLFloaterAboutListener floaterAboutListener; void LLFloaterAbout::onClickCopyToClipboard() { LLViewerTextEditor *support_widget = getChild<LLViewerTextEditor>("support_editor", true); support_widget->selectAll(); support_widget->copy(); support_widget->deselect(); } ///---------------------------------------------------------------------------- /// LLFloaterAboutUtil ///---------------------------------------------------------------------------- void LLFloaterAboutUtil::registerFloater() { LLFloaterReg::add("sl_about", "floater_about.xml", &LLFloaterReg::build<LLFloaterAbout>); } <commit_msg>FIRE-1030 Fix ReleaseNotes Link<commit_after>/** * @file llfloaterabout.cpp * @author James Cook * @brief The about box from Help->About * * $LicenseInfo:firstyear=2001&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * 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 * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llfloaterabout.h" // Viewer includes #include "llagent.h" #include "llappviewer.h" #include "llsecondlifeurls.h" #include "llvoiceclient.h" #include "lluictrlfactory.h" #include "llviewertexteditor.h" #include "llviewercontrol.h" #include "llviewerstats.h" #include "llviewerregion.h" #include "llversioninfo.h" #include "llweb.h" // [RLVa:KB] - Checked: 2010-04-18 (RLVa-1.2.0e) #include "rlvhandler.h" // [/RLVa:KB] // Linden library includes #include "llaudioengine.h" #include "llbutton.h" #include "llcurl.h" #include "llglheaders.h" #include "llfloater.h" #include "llfloaterreg.h" #include "llimagej2c.h" #include "llsys.h" #include "lltrans.h" #include "lluri.h" #include "v3dmath.h" #include "llwindow.h" #include "stringize.h" #include "llsdutil_math.h" #include "lleventapi.h" #if LL_WINDOWS #include "lldxhardware.h" #endif extern LLMemoryInfo gSysMemory; extern U32 gPacketsIn; static std::string get_viewer_release_notes_url(); ///---------------------------------------------------------------------------- /// Class LLFloaterAbout ///---------------------------------------------------------------------------- class LLFloaterAbout : public LLFloater { friend class LLFloaterReg; private: LLFloaterAbout(const LLSD& key); virtual ~LLFloaterAbout(); public: /*virtual*/ BOOL postBuild(); /// Obtain the data used to fill out the contents string. This is /// separated so that we can programmatically access the same info. static LLSD getInfo(); void onClickCopyToClipboard(); }; // Default constructor LLFloaterAbout::LLFloaterAbout(const LLSD& key) : LLFloater(key) { } // Destroys the object LLFloaterAbout::~LLFloaterAbout() { } BOOL LLFloaterAbout::postBuild() { center(); LLViewerTextEditor *support_widget = getChild<LLViewerTextEditor>("support_editor", true); LLViewerTextEditor *credits_widget = getChild<LLViewerTextEditor>("credits_editor", true); getChild<LLUICtrl>("copy_btn")->setCommitCallback( boost::bind(&LLFloaterAbout::onClickCopyToClipboard, this)); #if LL_WINDOWS getWindow()->incBusyCount(); getWindow()->setCursor(UI_CURSOR_ARROW); #endif LLSD info(getInfo()); #if LL_WINDOWS getWindow()->decBusyCount(); getWindow()->setCursor(UI_CURSOR_ARROW); #endif std::ostringstream support; // Render the LLSD from getInfo() as a format_map_t LLStringUtil::format_map_t args; // allow the "Release Notes" URL label to be localized args["ReleaseNotes"] = LLTrans::getString("ReleaseNotes"); for (LLSD::map_const_iterator ii(info.beginMap()), iend(info.endMap()); ii != iend; ++ii) { if (! ii->second.isArray()) { // Scalar value if (ii->second.isUndefined()) { args[ii->first] = getString("none"); } else { // don't forget to render value asString() // NOTE: the default string conversion for LLSD real is "%g" so we'll convert those ourselves args[ii->first] = (!ii->second.isReal()) ? ii->second.asString() : llformat("%f", ii->second.asReal()); } } else { // array value: build KEY_0, KEY_1 etc. entries for (LLSD::Integer n(0), size(ii->second.size()); n < size; ++n) { args[STRINGIZE(ii->first << '_' << n)] = (!ii->second[n].isReal()) ? ii->second[n].asString() : llformat("%f", ii->second[n].asReal()); } } } // Now build the various pieces support << getString("AboutHeader", args); if (info.has("REGION")) { support << "\n\n" << getString("AboutPosition", args); } support << "\n\n" << getString("AboutSystem", args); support << "\n"; if (info.has("GRAPHICS_DRIVER_VERSION")) { support << "\n" << getString("AboutDriver", args); } support << "\n" << getString("AboutLibs", args); if (info.has("COMPILER")) { support << "\n" << getString("AboutCompiler", args); } if (info.has("PACKETS_IN")) { support << '\n' << getString("AboutTraffic", args); } support_widget->appendText(support.str(), FALSE, LLStyle::Params() .color(LLUIColorTable::instance().getColor("TextFgReadOnlyColor"))); support_widget->blockUndo(); // Fix views support_widget->setEnabled(FALSE); support_widget->startOfDoc(); credits_widget->setEnabled(FALSE); credits_widget->startOfDoc(); return TRUE; } // static LLSD LLFloaterAbout::getInfo() { // The point of having one method build an LLSD info block and the other // construct the user-visible About string is to ensure that the same info // is available to a getInfo() caller as to the user opening // LLFloaterAbout. LLSD info; LLSD version; version.append(LLVersionInfo::getMajor()); version.append(LLVersionInfo::getMinor()); version.append(LLVersionInfo::getPatch()); version.append(LLVersionInfo::getBuild()); info["VIEWER_VERSION"] = version; info["VIEWER_VERSION_STR"] = LLVersionInfo::getVersion(); info["BUILD_DATE"] = __DATE__; info["BUILD_TIME"] = __TIME__; info["CHANNEL"] = LLVersionInfo::getChannel(); info["SKIN"] = gSavedSettings.getString("SkinCurrent"); info["THEME"] = gSavedSettings.getString("SkinCurrentTheme"); info["VIEWER_RELEASE_NOTES_URL"] = get_viewer_release_notes_url(); #if LL_MSVC info["COMPILER"] = "MSVC"; info["COMPILER_VERSION"] = _MSC_VER; #elif LL_GNUC info["COMPILER"] = "GCC"; info["COMPILER_VERSION"] = GCC_VERSION; #endif // Position LLViewerRegion* region = gAgent.getRegion(); if (region) { const LLVector3d &pos = gAgent.getPositionGlobal(); info["POSITION"] = ll_sd_from_vector3d(pos); info["REGION"] = gAgent.getRegion()->getName(); info["HOSTNAME"] = gAgent.getRegion()->getHost().getHostName(); info["HOSTIP"] = gAgent.getRegion()->getHost().getString(); info["SERVER_VERSION"] = gLastVersionChannel; info["SERVER_RELEASE_NOTES_URL"] = LLWeb::escapeURL(region->getCapability("ServerReleaseNotes")); } // CPU info["CPU"] = gSysCPU.getCPUString(); info["MEMORY_MB"] = LLSD::Integer(gSysMemory.getPhysicalMemoryKB() / 1024); // Moved hack adjustment to Windows memory size into llsys.cpp info["OS_VERSION"] = LLAppViewer::instance()->getOSInfo().getOSString(); info["GRAPHICS_CARD_VENDOR"] = (const char*)(glGetString(GL_VENDOR)); info["GRAPHICS_CARD"] = (const char*)(glGetString(GL_RENDERER)); #if LL_WINDOWS LLSD driver_info = gDXHardware.getDisplayInfo(); if (driver_info.has("DriverVersion")) { info["GRAPHICS_DRIVER_VERSION"] = driver_info["DriverVersion"]; } #endif // [RLVa:KB] - Checked: 2010-04-18 (RLVa-1.2.0e) | Added: RLVa-1.2.0e if (rlv_handler_t::isEnabled()) info["RLV_VERSION"] = RlvStrings::getVersionAbout(); else info["RLV_VERSION"] = "(disabled)"; // [/RLVa:KB] info["OPENGL_VERSION"] = (const char*)(glGetString(GL_VERSION)); info["LIBCURL_VERSION"] = LLCurl::getVersionString(); info["J2C_VERSION"] = LLImageJ2C::getEngineInfo(); bool want_fullname = true; info["AUDIO_DRIVER_VERSION"] = gAudiop ? LLSD(gAudiop->getDriverName(want_fullname)) : LLSD(); if(LLVoiceClient::getInstance()->voiceEnabled()) { LLVoiceVersionInfo version = LLVoiceClient::getInstance()->getVersion(); std::ostringstream version_string; version_string << version.serverType << " " << version.serverVersion << std::endl; info["VOICE_VERSION"] = version_string.str(); } else { info["VOICE_VERSION"] = LLTrans::getString("NotConnected"); } // TODO: Implement media plugin version query info["QT_WEBKIT_VERSION"] = "4.7.1 (version number hard-coded)"; if (gPacketsIn > 0) { info["PACKETS_LOST"] = LLViewerStats::getInstance()->mPacketsLostStat.getCurrent(); info["PACKETS_IN"] = F32(gPacketsIn); info["PACKETS_PCT"] = 100.f*info["PACKETS_LOST"].asReal() / info["PACKETS_IN"].asReal(); } return info; } static std::string get_viewer_release_notes_url() { // return a URL to the release notes for this viewer, such as: // http://wiki.secondlife.com/wiki/Release_Notes/Second Life Beta Viewer/2.1.0 //std::string url = LLTrans::getString("RELEASE_NOTES_BASE_URL"); //if (! LLStringUtil::endsWith(url, "/")) // url += "/"; //url += LLVersionInfo::getChannel() + "/"; //url += LLVersionInfo::getShortVersion(); std::string url = "http://wiki.phoenixviewer.com/doku.php?id=firestorm"; return LLWeb::escapeURL(url); } class LLFloaterAboutListener: public LLEventAPI { public: LLFloaterAboutListener(): LLEventAPI("LLFloaterAbout", "LLFloaterAbout listener to retrieve About box info") { add("getInfo", "Request an LLSD::Map containing information used to populate About box", &LLFloaterAboutListener::getInfo, LLSD().with("reply", LLSD())); } private: void getInfo(const LLSD& request) const { LLReqID reqid(request); LLSD reply(LLFloaterAbout::getInfo()); reqid.stamp(reply); LLEventPumps::instance().obtain(request["reply"]).post(reply); } }; static LLFloaterAboutListener floaterAboutListener; void LLFloaterAbout::onClickCopyToClipboard() { LLViewerTextEditor *support_widget = getChild<LLViewerTextEditor>("support_editor", true); support_widget->selectAll(); support_widget->copy(); support_widget->deselect(); } ///---------------------------------------------------------------------------- /// LLFloaterAboutUtil ///---------------------------------------------------------------------------- void LLFloaterAboutUtil::registerFloater() { LLFloaterReg::add("sl_about", "floater_about.xml", &LLFloaterReg::build<LLFloaterAbout>); } <|endoftext|>
<commit_before> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrPathUtils.h" #include "GrPoint.h" #include "SkGeometry.h" GrScalar GrPathUtils::scaleToleranceToSrc(GrScalar devTol, const GrMatrix& viewM, const GrRect& pathBounds) { // In order to tesselate the path we get a bound on how much the matrix can // stretch when mapping to screen coordinates. GrScalar stretch = viewM.getMaxStretch(); GrScalar srcTol = devTol; if (stretch < 0) { // take worst case mapRadius amoung four corners. // (less than perfect) for (int i = 0; i < 4; ++i) { GrMatrix mat; mat.setTranslate((i % 2) ? pathBounds.fLeft : pathBounds.fRight, (i < 2) ? pathBounds.fTop : pathBounds.fBottom); mat.postConcat(viewM); stretch = SkMaxScalar(stretch, mat.mapRadius(SK_Scalar1)); } } srcTol = GrScalarDiv(srcTol, stretch); return srcTol; } static const int MAX_POINTS_PER_CURVE = 1 << 10; static const GrScalar gMinCurveTol = GrFloatToScalar(0.0001f); uint32_t GrPathUtils::quadraticPointCount(const GrPoint points[], GrScalar tol) { if (tol < gMinCurveTol) { tol = gMinCurveTol; } GrAssert(tol > 0); GrScalar d = points[1].distanceToLineSegmentBetween(points[0], points[2]); if (d <= tol) { return 1; } else { // Each time we subdivide, d should be cut in 4. So we need to // subdivide x = log4(d/tol) times. x subdivisions creates 2^(x) // points. // 2^(log4(x)) = sqrt(x); int temp = SkScalarCeil(SkScalarSqrt(SkScalarDiv(d, tol))); int pow2 = GrNextPow2(temp); // Because of NaNs & INFs we can wind up with a degenerate temp // such that pow2 comes out negative. Also, our point generator // will always output at least one pt. if (pow2 < 1) { pow2 = 1; } return GrMin(pow2, MAX_POINTS_PER_CURVE); } } uint32_t GrPathUtils::generateQuadraticPoints(const GrPoint& p0, const GrPoint& p1, const GrPoint& p2, GrScalar tolSqd, GrPoint** points, uint32_t pointsLeft) { if (pointsLeft < 2 || (p1.distanceToLineSegmentBetweenSqd(p0, p2)) < tolSqd) { (*points)[0] = p2; *points += 1; return 1; } GrPoint q[] = { { GrScalarAve(p0.fX, p1.fX), GrScalarAve(p0.fY, p1.fY) }, { GrScalarAve(p1.fX, p2.fX), GrScalarAve(p1.fY, p2.fY) }, }; GrPoint r = { GrScalarAve(q[0].fX, q[1].fX), GrScalarAve(q[0].fY, q[1].fY) }; pointsLeft >>= 1; uint32_t a = generateQuadraticPoints(p0, q[0], r, tolSqd, points, pointsLeft); uint32_t b = generateQuadraticPoints(r, q[1], p2, tolSqd, points, pointsLeft); return a + b; } uint32_t GrPathUtils::cubicPointCount(const GrPoint points[], GrScalar tol) { if (tol < gMinCurveTol) { tol = gMinCurveTol; } GrAssert(tol > 0); GrScalar d = GrMax( points[1].distanceToLineSegmentBetweenSqd(points[0], points[3]), points[2].distanceToLineSegmentBetweenSqd(points[0], points[3])); d = SkScalarSqrt(d); if (d <= tol) { return 1; } else { int temp = SkScalarCeil(SkScalarSqrt(SkScalarDiv(d, tol))); int pow2 = GrNextPow2(temp); // Because of NaNs & INFs we can wind up with a degenerate temp // such that pow2 comes out negative. Also, our point generator // will always output at least one pt. if (pow2 < 1) { pow2 = 1; } return GrMin(pow2, MAX_POINTS_PER_CURVE); } } uint32_t GrPathUtils::generateCubicPoints(const GrPoint& p0, const GrPoint& p1, const GrPoint& p2, const GrPoint& p3, GrScalar tolSqd, GrPoint** points, uint32_t pointsLeft) { if (pointsLeft < 2 || (p1.distanceToLineSegmentBetweenSqd(p0, p3) < tolSqd && p2.distanceToLineSegmentBetweenSqd(p0, p3) < tolSqd)) { (*points)[0] = p3; *points += 1; return 1; } GrPoint q[] = { { GrScalarAve(p0.fX, p1.fX), GrScalarAve(p0.fY, p1.fY) }, { GrScalarAve(p1.fX, p2.fX), GrScalarAve(p1.fY, p2.fY) }, { GrScalarAve(p2.fX, p3.fX), GrScalarAve(p2.fY, p3.fY) } }; GrPoint r[] = { { GrScalarAve(q[0].fX, q[1].fX), GrScalarAve(q[0].fY, q[1].fY) }, { GrScalarAve(q[1].fX, q[2].fX), GrScalarAve(q[1].fY, q[2].fY) } }; GrPoint s = { GrScalarAve(r[0].fX, r[1].fX), GrScalarAve(r[0].fY, r[1].fY) }; pointsLeft >>= 1; uint32_t a = generateCubicPoints(p0, q[0], r[0], s, tolSqd, points, pointsLeft); uint32_t b = generateCubicPoints(s, r[1], q[2], p3, tolSqd, points, pointsLeft); return a + b; } int GrPathUtils::worstCasePointCount(const GrPath& path, int* subpaths, GrScalar tol) { if (tol < gMinCurveTol) { tol = gMinCurveTol; } GrAssert(tol > 0); int pointCount = 0; *subpaths = 1; bool first = true; SkPath::Iter iter(path, false); GrPathCmd cmd; GrPoint pts[4]; while ((cmd = (GrPathCmd)iter.next(pts)) != kEnd_PathCmd) { switch (cmd) { case kLine_PathCmd: pointCount += 1; break; case kQuadratic_PathCmd: pointCount += quadraticPointCount(pts, tol); break; case kCubic_PathCmd: pointCount += cubicPointCount(pts, tol); break; case kMove_PathCmd: pointCount += 1; if (!first) { ++(*subpaths); } break; default: break; } first = false; } return pointCount; } namespace { // The matrix computed for quadDesignSpaceToUVCoordsMatrix should never really // have perspective and we really want to avoid perspective matrix muls. // However, the first two entries of the perspective row may be really close to // 0 and the third may not be 1 due to a scale on the entire matrix. inline void fixup_matrix(GrMatrix* mat) { GR_STATIC_ASSERT(SK_SCALAR_IS_FLOAT); static const GrScalar gTOL = 1.f / 100.f; GrAssert(GrScalarAbs(mat->get(SkMatrix::kMPersp0)) < gTOL); GrAssert(GrScalarAbs(mat->get(SkMatrix::kMPersp1)) < gTOL); float m33 = mat->get(SkMatrix::kMPersp2); if (1.f != m33) { m33 = 1.f / m33; mat->setAll(m33 * mat->get(SkMatrix::kMScaleX), m33 * mat->get(SkMatrix::kMSkewX), m33 * mat->get(SkMatrix::kMTransX), m33 * mat->get(SkMatrix::kMSkewY), m33 * mat->get(SkMatrix::kMScaleY), m33 * mat->get(SkMatrix::kMTransY), 0.f, 0.f, 1.f); } else { mat->setPerspX(0); mat->setPerspY(0); } } } // Compute a matrix that goes from the 2d space coordinates to UV space where // u^2-v = 0 specifies the quad. void GrPathUtils::quadDesignSpaceToUVCoordsMatrix(const SkPoint qPts[3], GrMatrix* matrix) { // can't make this static, no cons :( SkMatrix UVpts; GR_STATIC_ASSERT(SK_SCALAR_IS_FLOAT); UVpts.setAll(0, 0.5f, 1.f, 0, 0, 1.f, 1.f, 1.f, 1.f); matrix->setAll(qPts[0].fX, qPts[1].fX, qPts[2].fX, qPts[0].fY, qPts[1].fY, qPts[2].fY, 1.f, 1.f, 1.f); matrix->invert(matrix); matrix->postConcat(UVpts); fixup_matrix(matrix); } namespace { void convert_noninflect_cubic_to_quads(const SkPoint p[4], SkScalar tolScale, SkTArray<SkPoint, true>* quads, int sublevel = 0) { SkVector ab = p[1]; ab -= p[0]; SkVector dc = p[2]; dc -= p[3]; static const SkScalar gLengthScale = 3 * SK_Scalar1 / 2; // base tolerance is 2 pixels in dev coords. const SkScalar distanceSqdTol = SkScalarMul(tolScale, 1 * SK_Scalar1); static const int kMaxSubdivs = 10; ab.scale(gLengthScale); dc.scale(gLengthScale); SkVector c0 = p[0]; c0 += ab; SkVector c1 = p[3]; c1 += dc; SkScalar dSqd = c0.distanceToSqd(c1); if (sublevel > kMaxSubdivs || dSqd <= distanceSqdTol) { SkPoint cAvg = c0; cAvg += c1; cAvg.scale(SK_ScalarHalf); SkPoint* pts = quads->push_back_n(3); pts[0] = p[0]; pts[1] = cAvg; pts[2] = p[3]; return; } else { SkPoint choppedPts[7]; SkChopCubicAtHalf(p, choppedPts); convert_noninflect_cubic_to_quads(choppedPts + 0, tolScale, quads, sublevel + 1); convert_noninflect_cubic_to_quads(choppedPts + 3, tolScale, quads, sublevel + 1); } } } void GrPathUtils::convertCubicToQuads(const GrPoint p[4], SkScalar tolScale, SkTArray<SkPoint, true>* quads) { SkPoint chopped[10]; int count = SkChopCubicAtInflections(p, chopped); for (int i = 0; i < count; ++i) { SkPoint* cubic = chopped + 3*i; convert_noninflect_cubic_to_quads(cubic, tolScale, quads); } } <commit_msg>Change static asserts of scalar type to runtime asserts (re r3040)<commit_after> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrPathUtils.h" #include "GrPoint.h" #include "SkGeometry.h" GrScalar GrPathUtils::scaleToleranceToSrc(GrScalar devTol, const GrMatrix& viewM, const GrRect& pathBounds) { // In order to tesselate the path we get a bound on how much the matrix can // stretch when mapping to screen coordinates. GrScalar stretch = viewM.getMaxStretch(); GrScalar srcTol = devTol; if (stretch < 0) { // take worst case mapRadius amoung four corners. // (less than perfect) for (int i = 0; i < 4; ++i) { GrMatrix mat; mat.setTranslate((i % 2) ? pathBounds.fLeft : pathBounds.fRight, (i < 2) ? pathBounds.fTop : pathBounds.fBottom); mat.postConcat(viewM); stretch = SkMaxScalar(stretch, mat.mapRadius(SK_Scalar1)); } } srcTol = GrScalarDiv(srcTol, stretch); return srcTol; } static const int MAX_POINTS_PER_CURVE = 1 << 10; static const GrScalar gMinCurveTol = GrFloatToScalar(0.0001f); uint32_t GrPathUtils::quadraticPointCount(const GrPoint points[], GrScalar tol) { if (tol < gMinCurveTol) { tol = gMinCurveTol; } GrAssert(tol > 0); GrScalar d = points[1].distanceToLineSegmentBetween(points[0], points[2]); if (d <= tol) { return 1; } else { // Each time we subdivide, d should be cut in 4. So we need to // subdivide x = log4(d/tol) times. x subdivisions creates 2^(x) // points. // 2^(log4(x)) = sqrt(x); int temp = SkScalarCeil(SkScalarSqrt(SkScalarDiv(d, tol))); int pow2 = GrNextPow2(temp); // Because of NaNs & INFs we can wind up with a degenerate temp // such that pow2 comes out negative. Also, our point generator // will always output at least one pt. if (pow2 < 1) { pow2 = 1; } return GrMin(pow2, MAX_POINTS_PER_CURVE); } } uint32_t GrPathUtils::generateQuadraticPoints(const GrPoint& p0, const GrPoint& p1, const GrPoint& p2, GrScalar tolSqd, GrPoint** points, uint32_t pointsLeft) { if (pointsLeft < 2 || (p1.distanceToLineSegmentBetweenSqd(p0, p2)) < tolSqd) { (*points)[0] = p2; *points += 1; return 1; } GrPoint q[] = { { GrScalarAve(p0.fX, p1.fX), GrScalarAve(p0.fY, p1.fY) }, { GrScalarAve(p1.fX, p2.fX), GrScalarAve(p1.fY, p2.fY) }, }; GrPoint r = { GrScalarAve(q[0].fX, q[1].fX), GrScalarAve(q[0].fY, q[1].fY) }; pointsLeft >>= 1; uint32_t a = generateQuadraticPoints(p0, q[0], r, tolSqd, points, pointsLeft); uint32_t b = generateQuadraticPoints(r, q[1], p2, tolSqd, points, pointsLeft); return a + b; } uint32_t GrPathUtils::cubicPointCount(const GrPoint points[], GrScalar tol) { if (tol < gMinCurveTol) { tol = gMinCurveTol; } GrAssert(tol > 0); GrScalar d = GrMax( points[1].distanceToLineSegmentBetweenSqd(points[0], points[3]), points[2].distanceToLineSegmentBetweenSqd(points[0], points[3])); d = SkScalarSqrt(d); if (d <= tol) { return 1; } else { int temp = SkScalarCeil(SkScalarSqrt(SkScalarDiv(d, tol))); int pow2 = GrNextPow2(temp); // Because of NaNs & INFs we can wind up with a degenerate temp // such that pow2 comes out negative. Also, our point generator // will always output at least one pt. if (pow2 < 1) { pow2 = 1; } return GrMin(pow2, MAX_POINTS_PER_CURVE); } } uint32_t GrPathUtils::generateCubicPoints(const GrPoint& p0, const GrPoint& p1, const GrPoint& p2, const GrPoint& p3, GrScalar tolSqd, GrPoint** points, uint32_t pointsLeft) { if (pointsLeft < 2 || (p1.distanceToLineSegmentBetweenSqd(p0, p3) < tolSqd && p2.distanceToLineSegmentBetweenSqd(p0, p3) < tolSqd)) { (*points)[0] = p3; *points += 1; return 1; } GrPoint q[] = { { GrScalarAve(p0.fX, p1.fX), GrScalarAve(p0.fY, p1.fY) }, { GrScalarAve(p1.fX, p2.fX), GrScalarAve(p1.fY, p2.fY) }, { GrScalarAve(p2.fX, p3.fX), GrScalarAve(p2.fY, p3.fY) } }; GrPoint r[] = { { GrScalarAve(q[0].fX, q[1].fX), GrScalarAve(q[0].fY, q[1].fY) }, { GrScalarAve(q[1].fX, q[2].fX), GrScalarAve(q[1].fY, q[2].fY) } }; GrPoint s = { GrScalarAve(r[0].fX, r[1].fX), GrScalarAve(r[0].fY, r[1].fY) }; pointsLeft >>= 1; uint32_t a = generateCubicPoints(p0, q[0], r[0], s, tolSqd, points, pointsLeft); uint32_t b = generateCubicPoints(s, r[1], q[2], p3, tolSqd, points, pointsLeft); return a + b; } int GrPathUtils::worstCasePointCount(const GrPath& path, int* subpaths, GrScalar tol) { if (tol < gMinCurveTol) { tol = gMinCurveTol; } GrAssert(tol > 0); int pointCount = 0; *subpaths = 1; bool first = true; SkPath::Iter iter(path, false); GrPathCmd cmd; GrPoint pts[4]; while ((cmd = (GrPathCmd)iter.next(pts)) != kEnd_PathCmd) { switch (cmd) { case kLine_PathCmd: pointCount += 1; break; case kQuadratic_PathCmd: pointCount += quadraticPointCount(pts, tol); break; case kCubic_PathCmd: pointCount += cubicPointCount(pts, tol); break; case kMove_PathCmd: pointCount += 1; if (!first) { ++(*subpaths); } break; default: break; } first = false; } return pointCount; } namespace { // The matrix computed for quadDesignSpaceToUVCoordsMatrix should never really // have perspective and we really want to avoid perspective matrix muls. // However, the first two entries of the perspective row may be really close to // 0 and the third may not be 1 due to a scale on the entire matrix. inline void fixup_matrix(GrMatrix* mat) { GrAssert(SK_SCALAR_IS_FLOAT); static const GrScalar gTOL = 1.f / 100.f; GrAssert(GrScalarAbs(mat->get(SkMatrix::kMPersp0)) < gTOL); GrAssert(GrScalarAbs(mat->get(SkMatrix::kMPersp1)) < gTOL); float m33 = mat->get(SkMatrix::kMPersp2); if (1.f != m33) { m33 = 1.f / m33; mat->setAll(m33 * mat->get(SkMatrix::kMScaleX), m33 * mat->get(SkMatrix::kMSkewX), m33 * mat->get(SkMatrix::kMTransX), m33 * mat->get(SkMatrix::kMSkewY), m33 * mat->get(SkMatrix::kMScaleY), m33 * mat->get(SkMatrix::kMTransY), 0.f, 0.f, 1.f); } else { mat->setPerspX(0); mat->setPerspY(0); } } } // Compute a matrix that goes from the 2d space coordinates to UV space where // u^2-v = 0 specifies the quad. void GrPathUtils::quadDesignSpaceToUVCoordsMatrix(const SkPoint qPts[3], GrMatrix* matrix) { // can't make this static, no cons :( SkMatrix UVpts; GrAssert(SK_SCALAR_IS_FLOAT); UVpts.setAll(0, 0.5f, 1.f, 0, 0, 1.f, 1.f, 1.f, 1.f); matrix->setAll(qPts[0].fX, qPts[1].fX, qPts[2].fX, qPts[0].fY, qPts[1].fY, qPts[2].fY, 1.f, 1.f, 1.f); matrix->invert(matrix); matrix->postConcat(UVpts); fixup_matrix(matrix); } namespace { void convert_noninflect_cubic_to_quads(const SkPoint p[4], SkScalar tolScale, SkTArray<SkPoint, true>* quads, int sublevel = 0) { SkVector ab = p[1]; ab -= p[0]; SkVector dc = p[2]; dc -= p[3]; static const SkScalar gLengthScale = 3 * SK_Scalar1 / 2; // base tolerance is 2 pixels in dev coords. const SkScalar distanceSqdTol = SkScalarMul(tolScale, 1 * SK_Scalar1); static const int kMaxSubdivs = 10; ab.scale(gLengthScale); dc.scale(gLengthScale); SkVector c0 = p[0]; c0 += ab; SkVector c1 = p[3]; c1 += dc; SkScalar dSqd = c0.distanceToSqd(c1); if (sublevel > kMaxSubdivs || dSqd <= distanceSqdTol) { SkPoint cAvg = c0; cAvg += c1; cAvg.scale(SK_ScalarHalf); SkPoint* pts = quads->push_back_n(3); pts[0] = p[0]; pts[1] = cAvg; pts[2] = p[3]; return; } else { SkPoint choppedPts[7]; SkChopCubicAtHalf(p, choppedPts); convert_noninflect_cubic_to_quads(choppedPts + 0, tolScale, quads, sublevel + 1); convert_noninflect_cubic_to_quads(choppedPts + 3, tolScale, quads, sublevel + 1); } } } void GrPathUtils::convertCubicToQuads(const GrPoint p[4], SkScalar tolScale, SkTArray<SkPoint, true>* quads) { SkPoint chopped[10]; int count = SkChopCubicAtInflections(p, chopped); for (int i = 0; i < count; ++i) { SkPoint* cubic = chopped + 3*i; convert_noninflect_cubic_to_quads(cubic, tolScale, quads); } } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <gmock/gmock.h> #include "./common/true_spec.h" #include "./common/false_spec.h" using namespace std; class ASpecification : public ::testing::Test { public: true_spec truthy; false_spec falsy; }; TEST_F(ASpecification, SupportsAndOperaion) { ASSERT_TRUE(truthy.And(truthy).is_satisfied_by(true)); ASSERT_FALSE(truthy.And(falsy).is_satisfied_by(true)); ASSERT_FALSE(falsy.And(truthy).is_satisfied_by(true)); ASSERT_FALSE(falsy.And(falsy).is_satisfied_by(true)); } TEST_F(ASpecification, SupportsOrOperation) { ASSERT_TRUE(truthy.Or(truthy).is_satisfied_by(true)); ASSERT_TRUE(truthy.Or(falsy).is_satisfied_by(true)); ASSERT_TRUE(falsy.Or(truthy).is_satisfied_by(true)); ASSERT_FALSE(falsy.Or(falsy).is_satisfied_by(true)); } TEST_F(ASpecification, SupportsNotOperation) { ASSERT_FALSE(truthy.Not().is_satisfied_by(true)); ASSERT_TRUE(falsy.Not().is_satisfied_by(true)); } TEST_F(ASpecification, CanBeChained) { ASSERT_TRUE(truthy.Or(falsy).And(truthy).is_satisfied_by(true)); ASSERT_FALSE(truthy.Or(falsy).And(truthy).Not().is_satisfied_by(true)); }<commit_msg>removed gmock dependency<commit_after>#include <gtest/gtest.h> #include "./common/true_spec.h" #include "./common/false_spec.h" using namespace std; class ASpecification : public ::testing::Test { public: true_spec truthy; false_spec falsy; }; TEST_F(ASpecification, SupportsAndOperaion) { ASSERT_TRUE(truthy.And(truthy).is_satisfied_by(true)); ASSERT_FALSE(truthy.And(falsy).is_satisfied_by(true)); ASSERT_FALSE(falsy.And(truthy).is_satisfied_by(true)); ASSERT_FALSE(falsy.And(falsy).is_satisfied_by(true)); } TEST_F(ASpecification, SupportsOrOperation) { ASSERT_TRUE(truthy.Or(truthy).is_satisfied_by(true)); ASSERT_TRUE(truthy.Or(falsy).is_satisfied_by(true)); ASSERT_TRUE(falsy.Or(truthy).is_satisfied_by(true)); ASSERT_FALSE(falsy.Or(falsy).is_satisfied_by(true)); } TEST_F(ASpecification, SupportsNotOperation) { ASSERT_FALSE(truthy.Not().is_satisfied_by(true)); ASSERT_TRUE(falsy.Not().is_satisfied_by(true)); } TEST_F(ASpecification, CanBeChained) { ASSERT_TRUE(truthy.Or(falsy).And(truthy).is_satisfied_by(true)); ASSERT_FALSE(truthy.Or(falsy).And(truthy).Not().is_satisfied_by(true)); }<|endoftext|>
<commit_before>#include <string.h> #include <iostream> #include <cassert> #include <stdlib.h> using namespace std; template <class T> class CachedValue { protected: int valueCount; T values[2]; public: CachedValue(T initialValue) { this->valueCount = 0; put(initialValue); } T& get() { if (valueCount > 1) { values[0] = values[1]; valueCount--; } return values[0]; } void put(T value) { if (valueCount > 1) { throw "CachedValue overflow"; } values[valueCount] = value; valueCount++; } }; template <class T> class SmartPointer { public: class ReferencedPointer { private: int references; private: T* ptr; public: ReferencedPointer() { ptr = NULL; references = 0; } public: ReferencedPointer(T* ptr) { references = 1; this->ptr = ptr; } public: void decref() { references--; if (references < 0) { throw "ReferencedPointer extra dereference"; } if (ptr && references == 0) { cout << "ReferencedPointer() free " << (long) ptr << endl; * (char *) ptr = 0; // mark as deleted free(ptr); } } public: void incref() { references++; } public: T* get() { return ptr; } public: int getReferences() { return references; } }; private: ReferencedPointer *pPointer; public: SmartPointer(T* ptr) { cout << "SmartPointer(" << (long) ptr << ")" << endl; this->pPointer = new ReferencedPointer(ptr); } public: SmartPointer() { cout << "SmartPointer(NULL)" << endl; this->pPointer = NULL; } public: SmartPointer(const SmartPointer &that) { this->pPointer = that.pPointer; this->pPointer->incref(); } public: ~SmartPointer() { if (pPointer) { pPointer->decref(); } } public: SmartPointer& operator=( const SmartPointer& that ) { if (pPointer) { pPointer->decref(); } this->pPointer = that.pPointer; this->pPointer->incref(); return *this; } public: int getReferences() { return pPointer ? pPointer->getReferences() : 0; } public: T* operator->() const { return pPointer ? pPointer->get() : NULL; } public: operator T*() const { return pPointer ? pPointer->get() : NULL; } }; class MockValue { private: int value; public: MockValue(int aValue) { cout << "MockValue(" << aValue << ")" << " " << (long) this << endl; value = aValue; } MockValue() { cout << "MockValue(0)" << " " << (long) this << endl; value = 0; } MockValue(const MockValue &that) { cout << "copy MockValue(" << that.value << ")" << " " << (long) this << endl; value = that.value; } ~MockValue() { cout << "~MockValue(" << value << ")" << " " << (long) this << endl; } MockValue& operator=( const MockValue& that ) { cout << "MockValue::operator=(" << that.value << ")" << " " << (long) this << endl; value = that.value; return *this; } int getValue() { cout << "MockValue.getValue() => " << value << " " << (long) this << endl; return value; } }; int testSmartPointer( ){ cout << "testSmartPointer() ------------------------" << endl; char *pOne = (char*)malloc(100); strcpy(pOne, "one"); cout << "pOne == " << (long) pOne << endl; char *pTwo = (char*)malloc(100); strcpy(pTwo, "two"); cout << "pTwo == " << (long) pTwo << endl; MockValue *pMock = new MockValue(123); cout << "pMock == " << (long) pMock << endl; { SmartPointer<char> zero; assert(NULL == (char*) zero); SmartPointer<char> one(pOne); assert(pOne == (char*)one); assert(*pOne == 'o'); assert(1 == one.getReferences()); assert(0 == strcmp("one", (char*)one)); assert(0 == strcmp("one", pOne)); SmartPointer<char> oneCopy(one); assert(0 == strcmp("one", (char*)oneCopy)); assert(2 == one.getReferences()); assert(2 == oneCopy.getReferences()); SmartPointer<char> two(pTwo); assert(0 == strcmp("two", (char*)two)); assert(0 != strcmp((char *) one, (char *) two)); one = two; assert(0 == strcmp((char *) one, (char *) two)); assert(2 == one.getReferences()); assert(1 == oneCopy.getReferences()); SmartPointer<MockValue> mock(pMock); assert(123 == mock->getValue()); } assert(0 != strcmp("one", pOne)); assert(0 != strcmp("two", pTwo)); cout << "testSmartPointer() PASSED" << endl; cout << endl; return 0; } typedef SmartPointer<char> CharPtr; int testCachedValue() { cout << "testCachedValue() ------------------------" << endl; { CachedValue<MockValue> bufInt(MockValue(1)); cout << "testCachedValue() get" << endl; assert(1 == bufInt.get().getValue()); assert(1 == bufInt.get().getValue()); cout << "testCachedValue() put" << endl; bufInt.put(MockValue(2)); assert(2 == bufInt.get().getValue()); bufInt.put(MockValue(3)); const char *caughtMsg = NULL; try { bufInt.put(MockValue(4)); } catch (const char * msg) { caughtMsg = msg; } assert(caughtMsg); CachedValue<string> bufString("one"); assert(0 == strcmp("one", bufString.get().c_str())); assert(0 == strcmp("one", bufString.get().c_str())); bufString.put("two"); assert(0 == strcmp("two", bufString.get().c_str())); char *one = (char *) malloc(100); strcpy(one, "one"); cout << "one " << (long) one << endl; char *two = (char *) malloc(200); cout << "two " << (long) two << endl; strcpy(two, "two"); { CharPtr spOne(one); CharPtr spTwo(two); CachedValue<CharPtr> bufAlloc(CharPtr()); SmartPointer<char> spX; assert(NULL == (char *)spX); spX = spOne; assert(one == (char *)spX); //spX = bufAlloc.get(); //assert(NULL == (char *)spX); // //bufAlloc.put(spOne); //assert(0 == strcmp("one", (char *) bufAlloc.get())); //assert(0 == strcmp("one", (char *) bufAlloc.get())); //bufAlloc.put(spTwo); //assert(0 == strcmp("two", (char *) bufAlloc.get())); } assert(0 != strcmp("one", one)); assert(0 != strcmp("two", two)); } cout << endl; cout << "testCachedValue() PASS" << endl; cout << endl; return 0; } int main(int argc, char *argv[]) { return testSmartPointer()==0 && testCachedValue()==0 ? 0 : -1; } <commit_msg>SmartPointer<commit_after>#include <string.h> #include <iostream> #include <cassert> #include <stdlib.h> #include <memory> using namespace std; template <class T> class CachedValue { protected: int valueCount; T emptyValue; T values[2]; public: CachedValue() { this->valueCount = 0; } T& get() { if (valueCount > 1) { values[0] = values[1]; values[1] = emptyValue; valueCount--; } return values[0]; } void put(T value) { if (valueCount > 1) { throw "CachedValue overflow"; } values[valueCount] = value; valueCount++; } int getValueCount() { return valueCount; } }; template <class T> class SmartPointer { public: class ReferencedPointer { private: int references; private: T* ptr; public: ReferencedPointer() { ptr = NULL; references = 0; } public: ReferencedPointer(T* ptr) { references = 1; this->ptr = ptr; } public: void decref() { references--; if (references < 0) { throw "ReferencedPointer extra dereference"; } if (ptr && references == 0) { cout << "ReferencedPointer() free " << (long) ptr << endl; * (char *) ptr = 0; // mark as deleted free(ptr); } } public: void incref() { references++; } public: T* get() { return ptr; } public: int getReferences() const { return references; } }; private: ReferencedPointer *pPointer; private: void decref() { if (pPointer) { pPointer->decref(); } } private: void incref() { if (pPointer) { pPointer->incref(); } } public: SmartPointer(T* ptr) { cout << "SmartPointer(" << (long) ptr << ")" << endl; this->pPointer = new ReferencedPointer(ptr); } public: SmartPointer() { cout << "SmartPointer(NULL)" << endl; this->pPointer = NULL; } public: SmartPointer(const SmartPointer &that) { this->pPointer = that.pPointer; this->incref(); } public: ~SmartPointer() { decref(); } public: SmartPointer& operator=( SmartPointer that ) { decref(); this->pPointer = that.pPointer; incref(); return *this; } public: int getReferences() { return pPointer ? pPointer->getReferences() : 0; } public: T& operator*() { throw "SmartPointer not implemented (1)"; } public: const T& operator*() const { throw "SmartPointer not implemented (2)"; } public: T* operator->() { return pPointer ? pPointer->get() : NULL; } public: const T* operator->() const { return pPointer ? pPointer->get() : NULL; } public: operator T*() const { return pPointer ? pPointer->get() : NULL; } }; template <class T> class MockValue { private: T value; public: MockValue(T aValue) { cout << "MockValue(" << aValue << ")" << " " << (long) this << endl; value = aValue; } MockValue() { cout << "MockValue(0)" << " " << (long) this << endl; value = 0; } MockValue(const MockValue &that) { cout << "copy MockValue(" << that.value << ")" << " " << (long) this << endl; value = that.value; } ~MockValue() { cout << "~MockValue(" << value << ")" << " " << (long) this << endl; } MockValue& operator=( const MockValue& that ) { cout << "MockValue::operator=(" << that.value << ")" << " " << (long) this << endl; value = that.value; return *this; } T getValue() { cout << "MockValue.getValue() => " << value << " " << (long) this << endl; return value; } }; //#define SMARTPOINTER shared_ptr #define SMARTPOINTER SmartPointer int testSmartPointer( ){ cout << "testSmartPointer() ------------------------" << endl; char *pOne = (char*)malloc(100); strcpy(pOne, "one"); cout << "pOne == " << (long) pOne << endl; char *pTwo = (char*)malloc(100); strcpy(pTwo, "two"); cout << "pTwo == " << (long) pTwo << endl; MockValue<int> *pMock = new MockValue<int>(123); cout << "pMock == " << (long) pMock << endl; { SMARTPOINTER<char> zero; assert(NULL == (char*) zero); SMARTPOINTER<char> one(pOne); assert(pOne == (char*)one); assert(*pOne == 'o'); assert(1 == one.getReferences()); assert(0 == strcmp("one", (char*)one)); assert(0 == strcmp("one", pOne)); SMARTPOINTER<char> oneCopy(one); assert(0 == strcmp("one", (char*)oneCopy)); assert(2 == one.getReferences()); assert(2 == oneCopy.getReferences()); SMARTPOINTER<char> two(pTwo); assert(0 == strcmp("two", (char*)two)); assert(0 != strcmp((char *) one, (char *) two)); one = two; assert(0 == strcmp((char *) one, (char *) two)); assert(2 == one.getReferences()); assert(1 == oneCopy.getReferences()); SMARTPOINTER<MockValue<int> > mock(pMock); assert(123 == mock->getValue()); } assert(0 != strcmp("one", pOne)); assert(0 != strcmp("two", pTwo)); cout << "testSmartPointer() PASSED" << endl; cout << endl; return 0; } typedef SmartPointer<char> CharPtr; int testCachedValue() { cout << "testCachedValue() ------------------------" << endl; { CachedValue<MockValue<int> > bufInt; bufInt.put(MockValue<int>(1)); cout << "testCachedValue() get" << endl; assert(1 == bufInt.get().getValue()); assert(1 == bufInt.get().getValue()); cout << "testCachedValue() put" << endl; bufInt.put(MockValue<int>(2)); assert(2 == bufInt.get().getValue()); bufInt.put(MockValue<int>(3)); const char *caughtMsg = NULL; try { bufInt.put(MockValue<int>(4)); } catch (const char * msg) { caughtMsg = msg; } assert(caughtMsg); CachedValue<string> bufString; bufString.put("one"); assert(0 == strcmp("one", bufString.get().c_str())); assert(0 == strcmp("one", bufString.get().c_str())); assert(1 == bufString.getValueCount()); bufString.put("two"); assert(0 == strcmp("two", bufString.get().c_str())); char *one = (char *) malloc(100); strcpy(one, "one"); cout << "one " << (long) one << endl; char *two = (char *) malloc(200); cout << "two " << (long) two << endl; strcpy(two, "two"); { CharPtr spOne(one); assert(1 == spOne.getReferences()); CharPtr spTwo(two); CachedValue<CharPtr> bufCharPtr; assert(0 == bufCharPtr.getValueCount()); assert(NULL == (char *)bufCharPtr.get()); assert(0 == bufCharPtr.get().getReferences()); bufCharPtr.put(spOne); assert(1 == bufCharPtr.getValueCount()); assert(one == (char *)bufCharPtr.get()); assert(2 == bufCharPtr.get().getReferences()); bufCharPtr.put(spTwo); assert(2 == bufCharPtr.getValueCount()); assert(two == (char *)bufCharPtr.get()); assert(1 == bufCharPtr.getValueCount()); assert(2 == bufCharPtr.get().getReferences()); } assert(0 != strcmp("one", one)); assert(0 != strcmp("two", two)); } cout << endl; cout << "testCachedValue() PASS" << endl; cout << endl; return 0; } int main(int argc, char *argv[]) { return testSmartPointer()==0 && testCachedValue()==0 ? 0 : -1; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: droptargetlistener.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: as $ $Date: 2002-07-05 08:00:05 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef __FRAMEWORK_CLASSES_DROPTARGETLISTENER_HXX_ #define __FRAMEWORK_CLASSES_DROPTARGETLISTENER_HXX_ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_GENERAL_H_ #include <general.h> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_DATATRANSFER_DND_XDROPTARGETELISTENER_HPP_ #include <com/sun/star/datatransfer/dnd/XDropTargetListener.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif //_________________________________________________________________________________________________________________ // includes of other projects //_________________________________________________________________________________________________________________ #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _SOT_EXCHANGE_HXX_ #include <sot/exchange.hxx> #endif namespace framework { class DropTargetListener : private ThreadHelpBase , public ::cppu::WeakImplHelper1< ::com::sun::star::datatransfer::dnd::XDropTargetListener > { //___________________________________________ // member private: /// uno service manager to create neccessary services css::uno::Reference< css::lang::XMultiServiceFactory > m_xFactory; /// weakreference to target frame (Don't use a hard reference. Owner can't delete us then!) css::uno::WeakReference< css::frame::XFrame > m_xTargetFrame; /// drag/drop info DataFlavorExVector* m_pFormats; //___________________________________________ // c++ interface public: DropTargetListener( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory , const css::uno::Reference< css::frame::XFrame >& xFrame ); ~DropTargetListener( ); //___________________________________________ // uno interface public: // XEventListener virtual void SAL_CALL disposing ( const css::lang::EventObject& Source ) throw(css::uno::RuntimeException); // XDropTargetListener virtual void SAL_CALL drop ( const css::datatransfer::dnd::DropTargetDropEvent& dtde ) throw(css::uno::RuntimeException); virtual void SAL_CALL dragEnter ( const css::datatransfer::dnd::DropTargetDragEnterEvent& dtdee ) throw(css::uno::RuntimeException); virtual void SAL_CALL dragExit ( const css::datatransfer::dnd::DropTargetEvent& dte ) throw(css::uno::RuntimeException); virtual void SAL_CALL dragOver ( const css::datatransfer::dnd::DropTargetDragEvent& dtde ) throw(css::uno::RuntimeException); virtual void SAL_CALL dropActionChanged( const css::datatransfer::dnd::DropTargetDragEvent& dtde ) throw(css::uno::RuntimeException); //___________________________________________ // internal helper private: void implts_BeginDrag ( const css::uno::Sequence< css::datatransfer::DataFlavor >& rSupportedDataFlavors ); void implts_EndDrag ( ); sal_Bool implts_IsDropFormatSupported( SotFormatStringId nFormat ); void implts_OpenFile ( const String& rFilePath ); }; // class DropTargetListener } // namespace framework #endif // __FRAMEWORK_CLASSES_DROPTARGETLISTENER_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.3.560); FILE MERGED 2005/09/05 13:04:15 rt 1.3.560.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: droptargetlistener.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 00:03:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef __FRAMEWORK_CLASSES_DROPTARGETLISTENER_HXX_ #define __FRAMEWORK_CLASSES_DROPTARGETLISTENER_HXX_ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_GENERAL_H_ #include <general.h> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_DATATRANSFER_DND_XDROPTARGETELISTENER_HPP_ #include <com/sun/star/datatransfer/dnd/XDropTargetListener.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif //_________________________________________________________________________________________________________________ // includes of other projects //_________________________________________________________________________________________________________________ #ifndef _CPPUHELPER_IMPLBASE1_HXX_ #include <cppuhelper/implbase1.hxx> #endif #ifndef _SOT_EXCHANGE_HXX_ #include <sot/exchange.hxx> #endif namespace framework { class DropTargetListener : private ThreadHelpBase , public ::cppu::WeakImplHelper1< ::com::sun::star::datatransfer::dnd::XDropTargetListener > { //___________________________________________ // member private: /// uno service manager to create neccessary services css::uno::Reference< css::lang::XMultiServiceFactory > m_xFactory; /// weakreference to target frame (Don't use a hard reference. Owner can't delete us then!) css::uno::WeakReference< css::frame::XFrame > m_xTargetFrame; /// drag/drop info DataFlavorExVector* m_pFormats; //___________________________________________ // c++ interface public: DropTargetListener( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory , const css::uno::Reference< css::frame::XFrame >& xFrame ); ~DropTargetListener( ); //___________________________________________ // uno interface public: // XEventListener virtual void SAL_CALL disposing ( const css::lang::EventObject& Source ) throw(css::uno::RuntimeException); // XDropTargetListener virtual void SAL_CALL drop ( const css::datatransfer::dnd::DropTargetDropEvent& dtde ) throw(css::uno::RuntimeException); virtual void SAL_CALL dragEnter ( const css::datatransfer::dnd::DropTargetDragEnterEvent& dtdee ) throw(css::uno::RuntimeException); virtual void SAL_CALL dragExit ( const css::datatransfer::dnd::DropTargetEvent& dte ) throw(css::uno::RuntimeException); virtual void SAL_CALL dragOver ( const css::datatransfer::dnd::DropTargetDragEvent& dtde ) throw(css::uno::RuntimeException); virtual void SAL_CALL dropActionChanged( const css::datatransfer::dnd::DropTargetDragEvent& dtde ) throw(css::uno::RuntimeException); //___________________________________________ // internal helper private: void implts_BeginDrag ( const css::uno::Sequence< css::datatransfer::DataFlavor >& rSupportedDataFlavors ); void implts_EndDrag ( ); sal_Bool implts_IsDropFormatSupported( SotFormatStringId nFormat ); void implts_OpenFile ( const String& rFilePath ); }; // class DropTargetListener } // namespace framework #endif // __FRAMEWORK_CLASSES_DROPTARGETLISTENER_HXX_ <|endoftext|>
<commit_before>#include <SDL.h> #include GLCXX_GL_INCLUDE #include <iostream> #include "glcxx.hpp" using namespace std; #define WIDTH 800 #define HEIGHT 600 shared_ptr<glcxx::Shader> vs; shared_ptr<glcxx::Shader> vs2; shared_ptr<glcxx::Shader> fs; shared_ptr<glcxx::Shader> fs2; shared_ptr<glcxx::Program> program; shared_ptr<glcxx::Program> program2; shared_ptr<glcxx::Buffer> buffer; shared_ptr<glcxx::Buffer> buffer2; shared_ptr<glcxx::Buffer> buffer3; bool init(void) { glClearColor (0.0, 0.0, 0.0, 0.0); try { vs = make_shared<glcxx::Shader>(); vs2 = make_shared<glcxx::Shader>(); fs = make_shared<glcxx::Shader>(); fs2 = make_shared<glcxx::Shader>(); program = make_shared<glcxx::Program>(); program2 = make_shared<glcxx::Program>(); buffer = make_shared<glcxx::Buffer>(); buffer2 = make_shared<glcxx::Buffer>(); buffer3 = make_shared<glcxx::Buffer>(); vs->create_from_file(GL_VERTEX_SHADER, "test/vert.glsl"); fs->create_from_file(GL_FRAGMENT_SHADER, "test/frag.glsl"); program->create(vs, fs, "position", 0); vs2->create_from_file(GL_VERTEX_SHADER, "test/vert2.glsl"); fs2->create_from_file(GL_FRAGMENT_SHADER, "test/frag2.glsl"); program2->create(vs2, fs2, "position", 0, "color", 1); GLfloat coords[] = { -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, }; buffer->create(GL_ARRAY_BUFFER, GL_STATIC_DRAW, &coords, sizeof(coords)); GLfloat coords2[] = { 0.2, 0.2, 0.9, 0.2, 0.9, 0.9, }; buffer2->create(GL_ARRAY_BUFFER, GL_STATIC_DRAW, &coords2, sizeof(coords2)); GLfloat colors[] = { 1.0, 0.1, 0.1, 1.0, 0.1, 1.0, 0.1, 1.0, 0.1, 0.1, 1.0, 1.0, }; buffer3->create(GL_ARRAY_BUFFER, GL_STATIC_DRAW, &colors, sizeof(colors)); } catch (glcxx::Error & e) { cerr << "glcxx error: " << e.what() << endl; return false; } return true; } void display(SDL_Window * window) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnableVertexAttribArray(0); buffer->bind(); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), NULL); program->use(); GLint uniform_location = program->get_uniform_location("color"); glUniform4f(uniform_location, 1.0, 0.6, 0.2, 1.0); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glEnableVertexAttribArray(1); buffer2->bind(); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), NULL); buffer3->bind(); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), NULL); program2->use(); glDrawArrays(GL_TRIANGLE_FAN, 0, 3); SDL_GL_SwapWindow(window); } int main(int argc, char *argv[]) { if (SDL_Init(SDL_INIT_VIDEO)) { printf("Failed to initialize SDL!\n"); return 1; } atexit(SDL_Quit); SDL_Window * window = SDL_CreateWindow(argv[0], SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_OPENGL); if (!window) { printf("Failed to create window!\n"); SDL_Quit(); return 2; } SDL_GLContext gl_context = SDL_GL_CreateContext(window); if (gl_context == NULL) { cerr << "Failed to create OpenGL context" << endl; return 1; } SDL_GL_MakeCurrent(window, gl_context); if (gl3wInit()) { cerr << "Failed to initialize gl3w!" << endl; return 1; } if (!gl3wIsSupported(3, 0)) { cerr << "OpenGL 3.0 is not supported!" << endl; return 1; } if (!init()) { return 1; } display(window); SDL_Event event; while (SDL_WaitEvent(&event)) { if (event.type == SDL_QUIT) break; else if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_ESCAPE) break; if (event.key.keysym.sym == SDLK_RETURN) display(window); } } return 0; } <commit_msg>test VAOs<commit_after>#include <SDL.h> #include GLCXX_GL_INCLUDE #include <iostream> #include "glcxx.hpp" using namespace std; #define WIDTH 800 #define HEIGHT 600 shared_ptr<glcxx::Array> array1; shared_ptr<glcxx::Array> array2; shared_ptr<glcxx::Shader> vs; shared_ptr<glcxx::Shader> vs2; shared_ptr<glcxx::Shader> fs; shared_ptr<glcxx::Shader> fs2; shared_ptr<glcxx::Program> program; shared_ptr<glcxx::Program> program2; shared_ptr<glcxx::Buffer> buffer; shared_ptr<glcxx::Buffer> buffer2; shared_ptr<glcxx::Buffer> buffer3; bool init(void) { glClearColor (0.0, 0.0, 0.0, 0.0); try { array1 = make_shared<glcxx::Array>(); array2 = make_shared<glcxx::Array>(); array1->create(); array2->create(); vs = make_shared<glcxx::Shader>(); vs2 = make_shared<glcxx::Shader>(); fs = make_shared<glcxx::Shader>(); fs2 = make_shared<glcxx::Shader>(); program = make_shared<glcxx::Program>(); program2 = make_shared<glcxx::Program>(); buffer = make_shared<glcxx::Buffer>(); buffer2 = make_shared<glcxx::Buffer>(); buffer3 = make_shared<glcxx::Buffer>(); vs->create_from_file(GL_VERTEX_SHADER, "test/vert.glsl"); fs->create_from_file(GL_FRAGMENT_SHADER, "test/frag.glsl"); program->create(vs, fs, "position", 0); vs2->create_from_file(GL_VERTEX_SHADER, "test/vert2.glsl"); fs2->create_from_file(GL_FRAGMENT_SHADER, "test/frag2.glsl"); program2->create(vs2, fs2, "position", 0, "color", 1); GLfloat coords[] = { -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, }; buffer->create(GL_ARRAY_BUFFER, GL_STATIC_DRAW, &coords, sizeof(coords)); GLfloat coords2[] = { 0.2, 0.2, 0.9, 0.2, 0.9, 0.9, }; buffer2->create(GL_ARRAY_BUFFER, GL_STATIC_DRAW, &coords2, sizeof(coords2)); GLfloat colors[] = { 1.0, 0.1, 0.1, 1.0, 0.1, 1.0, 0.1, 1.0, 0.1, 0.1, 1.0, 1.0, }; buffer3->create(GL_ARRAY_BUFFER, GL_STATIC_DRAW, &colors, sizeof(colors)); array1->bind(); glEnableVertexAttribArray(0); buffer->bind(); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), NULL); array2->bind(); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); buffer2->bind(); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), NULL); buffer3->bind(); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), NULL); } catch (glcxx::Error & e) { cerr << "glcxx error: " << e.what() << endl; return false; } return true; } void display(SDL_Window * window) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); array1->bind(); program->use(); GLint uniform_location = program->get_uniform_location("color"); glUniform4f(uniform_location, 1.0, 0.6, 0.2, 1.0); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); array2->bind(); program2->use(); glDrawArrays(GL_TRIANGLE_FAN, 0, 3); SDL_GL_SwapWindow(window); } int main(int argc, char *argv[]) { if (SDL_Init(SDL_INIT_VIDEO)) { printf("Failed to initialize SDL!\n"); return 1; } atexit(SDL_Quit); SDL_Window * window = SDL_CreateWindow(argv[0], SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_OPENGL); if (!window) { printf("Failed to create window!\n"); SDL_Quit(); return 2; } SDL_GLContext gl_context = SDL_GL_CreateContext(window); if (gl_context == NULL) { cerr << "Failed to create OpenGL context" << endl; return 1; } SDL_GL_MakeCurrent(window, gl_context); if (gl3wInit()) { cerr << "Failed to initialize gl3w!" << endl; return 1; } if (!gl3wIsSupported(3, 0)) { cerr << "OpenGL 3.0 is not supported!" << endl; return 1; } if (!init()) { return 1; } display(window); SDL_Event event; while (SDL_WaitEvent(&event)) { if (event.type == SDL_QUIT) break; else if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_ESCAPE) break; if (event.key.keysym.sym == SDLK_RETURN) display(window); } } return 0; } <|endoftext|>
<commit_before>#include <cstdio> #include <cstring> #include <algorithm> #include <vector> using namespace std; #define MAXN 100 #define MAXM 10000 struct edge{ int u,v,w; bool operator < (edge e) const{ return w < e.w; } }e[MAXM]; bool in_tree[MAXM]; // Union - Find int parent[MAXN + 1]; int Find(int x){ if(parent[x] == x) return x; parent[x] = Find(parent[x]); return parent[x]; } void Union(int x, int y){ x = Find(x); y = Find(y); parent[x] = y; } // dfs to find a path between two nodes in the MST vector<int> L[MAXN],path; bool visited[MAXN]; bool dfs(int u, int v){ path.push_back(u); if(u == v) return true; bool ret = false; if(!visited[u]){ visited[u] = true; for(int i = 0;i < L[u].size();++i){ int to = L[u][i]; if(dfs(to,v)){ ret = true; break; } } } if(!ret) path.pop_back(); return ret; } // dfs to mark edges in a subtree after erasing an edge int mark[MAXN]; void dfs2(int u, int v, int cur){ if(visited[cur]) return; visited[cur] = true; mark[cur] = u; for(int i = 0;i < L[cur].size();++i){ int to = L[cur][i]; if(to != u && to != v) dfs2(u,v,to); } } int main(){ int n = 0,m = 0; while(scanf("%d,%d,%d",&e[m].u,&e[m].v,&e[m].w) == 3){ n = max(n,max(e[m].u,e[m].v)); ++m; } // Find minimum spanning tree using Kruskal's algorithm for(int i = 1;i <= n;++i) parent[i] = i; sort(e,e + m); int total = 0; for(int i = 0;i < m;++i){ if(Find(e[i].u) != Find(e[i].v)){ Union(e[i].u,e[i].v); total += e[i].w; in_tree[i] = true; L[ e[i].u ].push_back(e[i].v); L[ e[i].v ].push_back(e[i].u); printf("%d - %d (%d)\n",e[i].u,e[i].v,e[i].w); }else in_tree[i] = false; } printf("Total weight = %d\n\n",total); // Find the path int T that connect two endpoint of an edge for(int i = 0;i < m;++i){ if(!in_tree[i]){ memset(visited,false,sizeof visited); path.clear(); dfs(e[i].u,e[i].v); printf("(%d, %d) : ",e[i].u,e[i].v); for(int j = 0;j < path.size();++j){ if(j > 0) printf(" -> "); printf("%d",path[j]); } printf("\n"); } } printf("\n"); // Find edges that can replace an edge in the MST for(int i = 0;i < m;++i){ if(in_tree[i]){ memset(visited,false,sizeof visited); dfs2(e[i].u,e[i].v,e[i].u); dfs2(e[i].v,e[i].u,e[i].v); printf("(%d, %d) :",e[i].u,e[i].v); int rep = -1; for(int j = 0;j < m;++j) if(j != i && ((mark[ e[j].u ] == e[i].u && mark[ e[j].v ] == e[i].v) || (mark[ e[j].v ] == e[i].u && mark[ e[j].u ] == e[i].v))){ printf(" (%d, %d)",e[j].u,e[j].v); if(rep == -1 || e[j].w < e[rep].w) rep = j; } printf(", replacement : (%d, %d)\n",e[rep].u,e[rep].v); /* //test for(int j = 1;j <= n;++j) parent[j] = j; for(int j = 0;j < m;++j){ if(j != i && Find(e[j].u) != Find(e[j].v)){ Union(e[j].u,e[j].v); if(!in_tree[j]) printf("(%d, %d)\n",e[j].u,e[j].v); } }*/ } } printf("\n"); return 0; }<commit_msg>Most vital edge<commit_after>#include <cstdio> #include <cstring> #include <algorithm> #include <vector> using namespace std; #define MAXN 100 #define MAXM 10000 struct edge{ int u,v,w; bool operator < (edge e) const{ return w < e.w; } }e[MAXM]; bool in_tree[MAXM]; // Union - Find int parent[MAXN + 1]; int Find(int x){ if(parent[x] == x) return x; parent[x] = Find(parent[x]); return parent[x]; } void Union(int x, int y){ x = Find(x); y = Find(y); parent[x] = y; } // dfs to find a path between two nodes in the MST vector<int> L[MAXN],path; bool visited[MAXN]; bool dfs(int u, int v){ path.push_back(u); if(u == v) return true; bool ret = false; if(!visited[u]){ visited[u] = true; for(int i = 0;i < L[u].size();++i){ int to = L[u][i]; if(dfs(to,v)){ ret = true; break; } } } if(!ret) path.pop_back(); return ret; } // dfs to mark edges in a subtree after erasing an edge int mark[MAXN]; void dfs2(int u, int v, int cur){ if(visited[cur]) return; visited[cur] = true; mark[cur] = u; for(int i = 0;i < L[cur].size();++i){ int to = L[cur][i]; if(to != u && to != v) dfs2(u,v,to); } } int main(){ int n = 0,m = 0; while(scanf("%d,%d,%d",&e[m].u,&e[m].v,&e[m].w) == 3){ n = max(n,max(e[m].u,e[m].v)); ++m; } // Find minimum spanning tree using Kruskal's algorithm for(int i = 1;i <= n;++i) parent[i] = i; sort(e,e + m); int total = 0; for(int i = 0;i < m;++i){ if(Find(e[i].u) != Find(e[i].v)){ Union(e[i].u,e[i].v); total += e[i].w; in_tree[i] = true; L[ e[i].u ].push_back(e[i].v); L[ e[i].v ].push_back(e[i].u); printf("%d - %d (%d)\n",e[i].u,e[i].v,e[i].w); }else in_tree[i] = false; } printf("Total weight = %d\n\n",total); // Find the path int T that connect two endpoint of an edge for(int i = 0;i < m;++i){ if(!in_tree[i]){ memset(visited,false,sizeof visited); path.clear(); dfs(e[i].u,e[i].v); printf("(%d, %d) : ",e[i].u,e[i].v); for(int j = 0;j < path.size();++j){ if(j > 0) printf(" -> "); printf("%d",path[j]); } printf("\n"); } } printf("\n"); // Find edges that can replace an edge in the MST int most_vital_edge = -1; int min_increase = -1; for(int i = 0;i < m;++i){ if(in_tree[i]){ memset(visited,false,sizeof visited); dfs2(e[i].u,e[i].v,e[i].u); dfs2(e[i].v,e[i].u,e[i].v); printf("(%d, %d) :",e[i].u,e[i].v); int rep = -1; for(int j = 0;j < m;++j) if(j != i && ((mark[ e[j].u ] == e[i].u && mark[ e[j].v ] == e[i].v) || (mark[ e[j].v ] == e[i].u && mark[ e[j].u ] == e[i].v))){ printf(" (%d, %d)",e[j].u,e[j].v); if(rep == -1 || e[j].w < e[rep].w) rep = j; } printf(", replacement : (%d, %d)\n",e[rep].u,e[rep].v); if(most_vital_edge == -1 || e[rep].w - e[i].w < min_increase){ min_increase = e[rep].w - e[i].w; most_vital_edge = i; } /* //test for(int j = 1;j <= n;++j) parent[j] = j; for(int j = 0;j < m;++j){ if(j != i && Find(e[j].u) != Find(e[j].v)){ Union(e[j].u,e[j].v); if(!in_tree[j]) printf("(%d, %d)\n",e[j].u,e[j].v); } }*/ } } printf("\n"); printf("Most vital edge = (%d, %d)\n",e[most_vital_edge].u,e[most_vital_edge].v); printf("Increase = %d\n",min_increase); return 0; }<|endoftext|>
<commit_before>/* This file is part of KAddressBook. Copyright (C) 2003 Helge Deller <deller@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public version 2 License as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * - ldifvcardthumbnail - * * kioslave which generates tumbnails for vCard and LDIF files. * The thumbnails are used e.g. by Konqueror or in the file selection * dialog. * */ #include <QDateTime> #include <QFile> #include <QPixmap> #include <QImage> #include <QPainter> #include <kdebug.h> #include <kglobal.h> #include <kglobalsettings.h> #include <klocale.h> #include <kabc/ldifconverter.h> #include <kabc/vcardconverter.h> #include <kstandarddirs.h> #include "ldifvcardcreator.h" extern "C" { ThumbCreator *new_creator() { KGlobal::locale()->insertCatalog( "kaddressbook" ); return new VCard_LDIFCreator; } } VCard_LDIFCreator::VCard_LDIFCreator() : mFont( 0 ) { } VCard_LDIFCreator::~VCard_LDIFCreator() { delete mFont; } bool VCard_LDIFCreator::readContents( const QString &path ) { // read file contents QFile file( path ); if ( !file.open( QIODevice::ReadOnly ) ) return false; QString info; text.truncate(0); // read the file QByteArray contents = file.readAll(); file.close(); // convert the file contents to a KABC::Addressee address KABC::Addressee::List addrList; KABC::Addressee addr; KABC::VCardConverter converter; addrList = converter.parseVCards( contents); if ( addrList.count() == 0 ) { KABC::AddresseeList l; // FIXME porting if ( !KABC::LDIFConverter::LDIFToAddressee( contents, l ) ) return false; // FIXME porting KABC::AddresseeList::ConstIterator it( l.constBegin() ); for ( ; it != l.constEnd(); ++ it ) { addrList.append( *it ); } } if ( addrList.count()>1 ) { // create an overview (list of all names) name = i18np("One contact found:", "%1 contacts found:", addrList.count()); int no, linenr; for (linenr=no=0; linenr<30 && no<addrList.count(); ++no) { addr = addrList[no]; info = addr.formattedName().simplified(); if (info.isEmpty()) info = addr.givenName() + ' ' + addr.familyName(); info = info.simplified(); if (info.isEmpty()) continue; text.append(info); text.append("\n"); ++linenr; } return true; } // create card for _one_ contact addr = addrList[ 0 ]; // prepare the text name = addr.formattedName().simplified(); if ( name.isEmpty() ) name = addr.givenName() + ' ' + addr.familyName(); name = name.simplified(); KABC::PhoneNumber::List pnList = addr.phoneNumbers(); QStringList phoneNumbers; for (int no=0; no<pnList.count(); ++no) { QString pn = pnList[no].number().simplified(); if (!pn.isEmpty() && !phoneNumbers.contains(pn)) phoneNumbers.append(pn); } if ( !phoneNumbers.isEmpty() ) text += phoneNumbers.join("\n") + '\n'; info = addr.organization().simplified(); if ( !info.isEmpty() ) text += info + '\n'; // get an address KABC::Address address = addr.address(KABC::Address::Work); if (address.isEmpty()) address = addr.address(KABC::Address::Home); if (address.isEmpty()) address = addr.address(KABC::Address::Pref); info = address.formattedAddress(); if ( !info.isEmpty() ) text += info + '\n'; return true; } QRect glyphCoords(int index, int fontWidth) { int itemsPerRow = fontWidth / 4; return QRect( (index % itemsPerRow) * 4, (index / itemsPerRow) * 7, 4, 7 ); } bool VCard_LDIFCreator::createImageSmall() { text = name + '\n' + text; if ( !mFont ) { QString pixmap = KStandardDirs::locate( "data", "konqueror/pics/thumbnailfont_7x4.png" ); if ( pixmap.isEmpty() ) { kWarning() <<"VCard_LDIFCreator: Font image \"thumbnailfont_7x4.png\" not found!"; return false; } mFont = new QPixmap( pixmap ); } QSize chSize(4, 7); // the size of one char int xOffset = chSize.width(); int yOffset = chSize.height(); // calculate a better border so that the text is centered int canvasWidth = pixmapSize.width() - 2 * xborder; int canvasHeight = pixmapSize.height() - 2 * yborder; int numCharsPerLine = (int) (canvasWidth / chSize.width()); int numLines = (int) (canvasHeight / chSize.height()); // render the information QRect rect; int rest = mPixmap.width() - (numCharsPerLine * chSize.width()); xborder = qMax( xborder, rest / 2 ); // center horizontally rest = mPixmap.height() - (numLines * chSize.height()); yborder = qMax( yborder, rest / 2 ); // center vertically // end centering int x = xborder, y = yborder; // where to paint the characters int posNewLine = mPixmap.width() - (chSize.width() + xborder); int posLastLine = mPixmap.height() - (chSize.height() + yborder); bool newLine = false; Q_ASSERT( posNewLine > 0 ); //const QPixmap *fontPixmap = &(mSplitter->pixmap()); for ( int i = 0; i < text.length(); i++ ) { if ( x > posNewLine || newLine ) { // start a new line? x = xborder; y += yOffset; if ( y > posLastLine ) // more text than space break; // after starting a new line, we also jump to the next // physical newline in the file if we don't come from one if ( !newLine ) { int pos = text.indexOf( '\n', i ); if ( pos > (int) i ) i = pos +1; } newLine = false; } // check for newlines in the text (unix,dos) QChar ch = text.at( i ); if ( ch == '\n' ) { newLine = true; continue; } else if ( ch == '\r' && text.at(i+1) == '\n' ) { newLine = true; i++; // skip the next character (\n) as well continue; } rect = glyphCoords( (unsigned char)ch.toLatin1(), mFont->width() ); /* FIXME porting if ( !rect.isEmpty() ) bitBlt( &mPixmap, QPoint(x,y), fontPixmap, rect, Qt::CopyROP ); */ x += xOffset; // next character } return true; } bool VCard_LDIFCreator::createImageBig() { QFont normalFont( KGlobalSettings::generalFont() ); QFont titleFont( normalFont ); titleFont.setBold(true); // titleFont.setUnderline(true); titleFont.setItalic(true); QPainter painter(&mPixmap); painter.setFont(titleFont); QFontMetrics fm(painter.fontMetrics()); // draw contact name painter.setClipRect(2, 2, pixmapSize.width()-4, pixmapSize.height()-4); QPoint p(5, fm.height()+2); painter.drawText(p, name); p.setY( 3*p.y()/2 ); // draw contact information painter.setFont(normalFont); fm = painter.fontMetrics(); const QStringList list( text.split('\n', QString::SkipEmptyParts) ); for ( QStringList::ConstIterator it = list.begin(); p.y()<=pixmapSize.height() && it != list.end(); ++it ) { p.setY( p.y() + fm.height() ); painter.drawText(p, *it); } return true; } bool VCard_LDIFCreator::create(const QString &path, int width, int height, QImage &img) { if ( !readContents(path) ) return false; // resize the image if necessary pixmapSize = QSize( width, height ); if (height * 3 > width * 4) pixmapSize.setHeight( width * 4 / 3 ); else pixmapSize.setWidth( height * 3 / 4 ); if ( pixmapSize != mPixmap.size() ) mPixmap = QPixmap( pixmapSize ); mPixmap.fill( QColor( 245, 245, 245 ) ); // light-grey background // one pixel for the rectangle, the rest. whitespace xborder = 1 + pixmapSize.width()/16; // minimum x-border yborder = 1 + pixmapSize.height()/16; // minimum y-border bool ok; if ( width >= 150 /*pixel*/ ) ok = createImageBig(); else ok = createImageSmall(); if (!ok) return false; img = mPixmap.toImage(); return true; } ThumbCreator::Flags VCard_LDIFCreator::flags() const { return (Flags)(DrawFrame | BlendIcon); } <commit_msg>Move thumbnailfont_7x4.png from libkonq (where it's not used) to the kio_thumbnail code (where it's used); spotted by Maksim.<commit_after>/* This file is part of KAddressBook. Copyright (C) 2003 Helge Deller <deller@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public version 2 License as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * - ldifvcardthumbnail - * * kioslave which generates tumbnails for vCard and LDIF files. * The thumbnails are used e.g. by Konqueror or in the file selection * dialog. * */ #include <QDateTime> #include <QFile> #include <QPixmap> #include <QImage> #include <QPainter> #include <kdebug.h> #include <kglobal.h> #include <kglobalsettings.h> #include <klocale.h> #include <kabc/ldifconverter.h> #include <kabc/vcardconverter.h> #include <kstandarddirs.h> #include "ldifvcardcreator.h" extern "C" { ThumbCreator *new_creator() { KGlobal::locale()->insertCatalog( "kaddressbook" ); return new VCard_LDIFCreator; } } VCard_LDIFCreator::VCard_LDIFCreator() : mFont( 0 ) { } VCard_LDIFCreator::~VCard_LDIFCreator() { delete mFont; } bool VCard_LDIFCreator::readContents( const QString &path ) { // read file contents QFile file( path ); if ( !file.open( QIODevice::ReadOnly ) ) return false; QString info; text.truncate(0); // read the file QByteArray contents = file.readAll(); file.close(); // convert the file contents to a KABC::Addressee address KABC::Addressee::List addrList; KABC::Addressee addr; KABC::VCardConverter converter; addrList = converter.parseVCards( contents); if ( addrList.count() == 0 ) { KABC::AddresseeList l; // FIXME porting if ( !KABC::LDIFConverter::LDIFToAddressee( contents, l ) ) return false; // FIXME porting KABC::AddresseeList::ConstIterator it( l.constBegin() ); for ( ; it != l.constEnd(); ++ it ) { addrList.append( *it ); } } if ( addrList.count()>1 ) { // create an overview (list of all names) name = i18np("One contact found:", "%1 contacts found:", addrList.count()); int no, linenr; for (linenr=no=0; linenr<30 && no<addrList.count(); ++no) { addr = addrList[no]; info = addr.formattedName().simplified(); if (info.isEmpty()) info = addr.givenName() + ' ' + addr.familyName(); info = info.simplified(); if (info.isEmpty()) continue; text.append(info); text.append("\n"); ++linenr; } return true; } // create card for _one_ contact addr = addrList[ 0 ]; // prepare the text name = addr.formattedName().simplified(); if ( name.isEmpty() ) name = addr.givenName() + ' ' + addr.familyName(); name = name.simplified(); KABC::PhoneNumber::List pnList = addr.phoneNumbers(); QStringList phoneNumbers; for (int no=0; no<pnList.count(); ++no) { QString pn = pnList[no].number().simplified(); if (!pn.isEmpty() && !phoneNumbers.contains(pn)) phoneNumbers.append(pn); } if ( !phoneNumbers.isEmpty() ) text += phoneNumbers.join("\n") + '\n'; info = addr.organization().simplified(); if ( !info.isEmpty() ) text += info + '\n'; // get an address KABC::Address address = addr.address(KABC::Address::Work); if (address.isEmpty()) address = addr.address(KABC::Address::Home); if (address.isEmpty()) address = addr.address(KABC::Address::Pref); info = address.formattedAddress(); if ( !info.isEmpty() ) text += info + '\n'; return true; } QRect glyphCoords(int index, int fontWidth) { int itemsPerRow = fontWidth / 4; return QRect( (index % itemsPerRow) * 4, (index / itemsPerRow) * 7, 4, 7 ); } bool VCard_LDIFCreator::createImageSmall() { text = name + '\n' + text; if ( !mFont ) { QString pixmap = KStandardDirs::locate( "data", "kio_thumbnail/pics/thumbnailfont_7x4.png" ); if ( pixmap.isEmpty() ) { kWarning() <<"VCard_LDIFCreator: Font image \"thumbnailfont_7x4.png\" not found!"; return false; } mFont = new QPixmap( pixmap ); } QSize chSize(4, 7); // the size of one char int xOffset = chSize.width(); int yOffset = chSize.height(); // calculate a better border so that the text is centered int canvasWidth = pixmapSize.width() - 2 * xborder; int canvasHeight = pixmapSize.height() - 2 * yborder; int numCharsPerLine = (int) (canvasWidth / chSize.width()); int numLines = (int) (canvasHeight / chSize.height()); // render the information QRect rect; int rest = mPixmap.width() - (numCharsPerLine * chSize.width()); xborder = qMax( xborder, rest / 2 ); // center horizontally rest = mPixmap.height() - (numLines * chSize.height()); yborder = qMax( yborder, rest / 2 ); // center vertically // end centering int x = xborder, y = yborder; // where to paint the characters int posNewLine = mPixmap.width() - (chSize.width() + xborder); int posLastLine = mPixmap.height() - (chSize.height() + yborder); bool newLine = false; Q_ASSERT( posNewLine > 0 ); //const QPixmap *fontPixmap = &(mSplitter->pixmap()); for ( int i = 0; i < text.length(); i++ ) { if ( x > posNewLine || newLine ) { // start a new line? x = xborder; y += yOffset; if ( y > posLastLine ) // more text than space break; // after starting a new line, we also jump to the next // physical newline in the file if we don't come from one if ( !newLine ) { int pos = text.indexOf( '\n', i ); if ( pos > (int) i ) i = pos +1; } newLine = false; } // check for newlines in the text (unix,dos) QChar ch = text.at( i ); if ( ch == '\n' ) { newLine = true; continue; } else if ( ch == '\r' && text.at(i+1) == '\n' ) { newLine = true; i++; // skip the next character (\n) as well continue; } rect = glyphCoords( (unsigned char)ch.toLatin1(), mFont->width() ); /* FIXME porting if ( !rect.isEmpty() ) bitBlt( &mPixmap, QPoint(x,y), fontPixmap, rect, Qt::CopyROP ); */ x += xOffset; // next character } return true; } bool VCard_LDIFCreator::createImageBig() { QFont normalFont( KGlobalSettings::generalFont() ); QFont titleFont( normalFont ); titleFont.setBold(true); // titleFont.setUnderline(true); titleFont.setItalic(true); QPainter painter(&mPixmap); painter.setFont(titleFont); QFontMetrics fm(painter.fontMetrics()); // draw contact name painter.setClipRect(2, 2, pixmapSize.width()-4, pixmapSize.height()-4); QPoint p(5, fm.height()+2); painter.drawText(p, name); p.setY( 3*p.y()/2 ); // draw contact information painter.setFont(normalFont); fm = painter.fontMetrics(); const QStringList list( text.split('\n', QString::SkipEmptyParts) ); for ( QStringList::ConstIterator it = list.begin(); p.y()<=pixmapSize.height() && it != list.end(); ++it ) { p.setY( p.y() + fm.height() ); painter.drawText(p, *it); } return true; } bool VCard_LDIFCreator::create(const QString &path, int width, int height, QImage &img) { if ( !readContents(path) ) return false; // resize the image if necessary pixmapSize = QSize( width, height ); if (height * 3 > width * 4) pixmapSize.setHeight( width * 4 / 3 ); else pixmapSize.setWidth( height * 3 / 4 ); if ( pixmapSize != mPixmap.size() ) mPixmap = QPixmap( pixmapSize ); mPixmap.fill( QColor( 245, 245, 245 ) ); // light-grey background // one pixel for the rectangle, the rest. whitespace xborder = 1 + pixmapSize.width()/16; // minimum x-border yborder = 1 + pixmapSize.height()/16; // minimum y-border bool ok; if ( width >= 150 /*pixel*/ ) ok = createImageBig(); else ok = createImageSmall(); if (!ok) return false; img = mPixmap.toImage(); return true; } ThumbCreator::Flags VCard_LDIFCreator::flags() const { return (Flags)(DrawFrame | BlendIcon); } <|endoftext|>
<commit_before>#include "stdafx.h" #include <assembly64.hpp> uint32_t* OnAMissionFlag; uint8_t* ScriptSpace; uint8_t* m_WideScreenOn; bool IsPlayerOnAMission() { return *OnAMissionFlag && (ScriptSpace[*OnAMissionFlag] == 1); } void Init() { CIniReader iniReader(""); static auto nIniSaveSlot = iniReader.ReadInteger("MAIN", "SaveSlot", 6) - 1; auto pattern = hook::pattern("8B 05 ? ? ? ? 85 C0 74 0E 4C 8D 05 ? ? ? ? 42 83 3C 00"); OnAMissionFlag = (uint32_t*)injector::ReadRelativeOffset(pattern.get_first(2), 4, true).as_int(); ScriptSpace = (uint8_t*)injector::ReadRelativeOffset(pattern.get_first(13), 4, true).as_int(); pattern = hook::pattern("80 3D ? ? ? ? ? 48 8D 1D ? ? ? ? 0F 94 05 ? ? ? ? 66 90"); m_WideScreenOn = (uint8_t*)injector::ReadRelativeOffset(pattern.get_first(2), 4, true).as_int(); pattern = hook::pattern("BA ? ? ? ? 48 89 5C 24 ? 48 8D 4C 24 ? 48 89 5C 24 ? E8 ? ? ? ? 8B 7C 24 58 83 C7 08"); static auto sub_140F7A567 = (void(__fastcall*)())(pattern.get_first(-6)); static uint8_t prologue_code[] = { 0x40, 0x53, 0x48, 0x83, 0xEC, 0x40 }; static uint8_t prologue_og_code[sizeof(prologue_code)] = {0}; injector::ReadMemoryRaw(sub_140F7A567, prologue_og_code, sizeof(prologue_og_code), true); static auto gxt_offset = pattern.get_first(64); static auto gxt_location = (char*)injector::ReadRelativeOffset(gxt_offset, 4, true).as_int(); DWORD out = 0; injector::UnprotectMemory(gxt_location, 7, out); static std::string_view gxt(gxt_location, 7); static auto FESZ_WR = std::string("FESZ_WR"); static auto USJ_ALL = std::string("USJ_ALL"); static auto gxt_ptr = const_cast<char*>(gxt.data()); pattern = hook::pattern("48 8D 15 ? ? ? ? E8 ? ? ? ? 48 85 C0 74 1E 41 B8 ? ? ? ? C7 44 24"); static auto ret_addr = (uintptr_t)pattern.get_first(0); static uint8_t ret_code[] = { 0x48, 0x83, 0xC4, 0x40, 0x5B, 0xC3 }; static uint8_t og_code[sizeof(ret_code)] = {0}; injector::ReadMemoryRaw(ret_addr, og_code, sizeof(og_code), true); pattern = hook::pattern("40 53 48 83 EC 20 45 33 C0 8B DA E8 ? ? ? ? 0F B6 D3 E8 ? ? ? ? 48 83 C4 20 5B E9"); static auto SaveToSlot = (void(__fastcall*)(int, int))(pattern.get_first(0)); pattern = hook::pattern("B9 ? ? ? ? E8 ? ? ? ? 0F B6 15 ? ? ? ? F3 0F 10 05 ? ? ? ? F3 0F 59 05 ? ? ? ? 48 8B 7C 24"); static auto DoGameSpecificStuffBeforeSaveTime = pattern.get_first(1); pattern = hook::pattern("E8 ? ? ? ? 4C 89 25 ? ? ? ? E8 ? ? ? ? EB 3C"); static auto sub_140FC7ED0 = (void(__fastcall*)())(injector::GetBranchDestination(pattern.get_first(0)).as_int()); struct IdleHook { void operator()(injector::reg_pack& regs) { sub_140FC7ED0(); static bool bF5LastState = false; bool bF5CurState = GetKeyState(VK_F5) & 0x8000; if (!bF5LastState && bF5CurState) { if (!IsPlayerOnAMission() && !*m_WideScreenOn) { injector::WriteMemory<uint32_t>(DoGameSpecificStuffBeforeSaveTime, 0, true); SaveToSlot(0x708, nIniSaveSlot); injector::WriteMemory<uint32_t>(DoGameSpecificStuffBeforeSaveTime, 360, true); injector::WriteMemoryRaw(sub_140F7A567, prologue_code, sizeof(prologue_code), true); injector::WriteMemoryRaw(ret_addr, ret_code, sizeof(ret_code), true); FESZ_WR.copy(gxt_ptr, gxt.length() + 1); sub_140F7A567(); USJ_ALL.copy(gxt_ptr, gxt.length() + 1); injector::WriteMemoryRaw(ret_addr, og_code, sizeof(og_code), true); injector::WriteMemoryRaw(sub_140F7A567, prologue_og_code, sizeof(prologue_og_code), true); } } bF5LastState = bF5CurState; } }; injector::MakeInline<IdleHook>(pattern.get_first(0)); } CEXP void InitializeASI() { std::call_once(CallbackHandler::flag, []() { CallbackHandler::RegisterCallback(Init, hook::pattern("E8 ? ? ? ? 4C 89 25 ? ? ? ? E8 ? ? ? ? EB 3C")); }); } BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved) { if (reason == DLL_PROCESS_ATTACH) { if (!IsUALPresent()) { InitializeASI(); } } return TRUE; } <commit_msg>sa de fix<commit_after>#include "stdafx.h" #include <assembly64.hpp> uint32_t* OnAMissionFlag; uint8_t* ScriptSpace; uint8_t* m_WideScreenOn; bool IsPlayerOnAMission() { return *OnAMissionFlag && (ScriptSpace[*OnAMissionFlag] == 1); } void Init() { CIniReader iniReader(""); static auto nIniSaveSlot = iniReader.ReadInteger("MAIN", "SaveSlot", 6) - 1; auto pattern = hook::pattern("8B 05 ? ? ? ? 85 C0 74 0E 4C 8D 05 ? ? ? ? 42 83 3C 00"); OnAMissionFlag = (uint32_t*)injector::ReadRelativeOffset(pattern.get_first(2), 4, true).as_int(); ScriptSpace = (uint8_t*)injector::ReadRelativeOffset(pattern.get_first(13), 4, true).as_int(); pattern = hook::pattern("80 3D ? ? ? ? ? 48 8D 1D ? ? ? ? 0F 94 05 ? ? ? ? 66 90"); m_WideScreenOn = (uint8_t*)injector::ReadRelativeOffset(pattern.get_first(2), 4, true).as_int(); pattern = hook::pattern("BA ? ? ? ? 48 89 5C 24 ? 48 8D 4C 24 ? 48 89 5C 24 ? E8 ? ? ? ? 8B 7C 24 58 83 C7 08"); static uint8_t prologue_code[] = { 0x40, 0x53, 0x48, 0x83, 0xEC, 0x40, 0x48, 0x31, 0xDB }; static auto sub_140F7A567 = (void(__fastcall*)())(pattern.get_first(-sizeof(prologue_code))); static uint8_t prologue_og_code[] = {0}; injector::ReadMemoryRaw(sub_140F7A567, prologue_og_code, sizeof(prologue_og_code), true); static auto gxt_offset = pattern.get_first(64); static auto gxt_location = (char*)injector::ReadRelativeOffset(gxt_offset, 4, true).as_int(); DWORD out = 0; injector::UnprotectMemory(gxt_location, 7, out); static std::string_view gxt(gxt_location, 7); static auto FESZ_WR = std::string("FESZ_WR"); static auto USJ_ALL = std::string("USJ_ALL"); static auto gxt_ptr = const_cast<char*>(gxt.data()); pattern = hook::pattern("48 8D 15 ? ? ? ? E8 ? ? ? ? 48 85 C0 74 1E 41 B8 ? ? ? ? C7 44 24"); static auto ret_addr = (uintptr_t)pattern.get_first(0); static uint8_t ret_code[] = { 0x48, 0x83, 0xC4, 0x40, 0x5B, 0xC3 }; static uint8_t og_code[sizeof(ret_code)] = {0}; injector::ReadMemoryRaw(ret_addr, og_code, sizeof(og_code), true); pattern = hook::pattern("40 53 48 83 EC 20 45 33 C0 8B DA E8 ? ? ? ? 0F B6 D3 E8 ? ? ? ? 48 83 C4 20 5B E9"); static auto SaveToSlot = (void(__fastcall*)(int, int))(pattern.get_first(0)); pattern = hook::pattern("B9 ? ? ? ? E8 ? ? ? ? 0F B6 15 ? ? ? ? F3 0F 10 05 ? ? ? ? F3 0F 59 05 ? ? ? ? 48 8B 7C 24"); static auto DoGameSpecificStuffBeforeSaveTime = pattern.get_first(1); pattern = hook::pattern("E8 ? ? ? ? 4C 89 25 ? ? ? ? E8 ? ? ? ? EB 3C"); static auto sub_140FC7ED0 = (void(__fastcall*)())(injector::GetBranchDestination(pattern.get_first(0)).as_int()); struct IdleHook { void operator()(injector::reg_pack& regs) { sub_140FC7ED0(); static bool bF5LastState = false; bool bF5CurState = GetKeyState(VK_F5) & 0x8000; if (!bF5LastState && bF5CurState) { if (!IsPlayerOnAMission() && !*m_WideScreenOn) { injector::WriteMemory<uint32_t>(DoGameSpecificStuffBeforeSaveTime, 0, true); SaveToSlot(0x708, nIniSaveSlot); injector::WriteMemory<uint32_t>(DoGameSpecificStuffBeforeSaveTime, 360, true); injector::WriteMemoryRaw(sub_140F7A567, prologue_code, sizeof(prologue_code), true); injector::WriteMemoryRaw(ret_addr, ret_code, sizeof(ret_code), true); FESZ_WR.copy(gxt_ptr, gxt.length() + 1); sub_140F7A567(); USJ_ALL.copy(gxt_ptr, gxt.length() + 1); injector::WriteMemoryRaw(ret_addr, og_code, sizeof(og_code), true); injector::WriteMemoryRaw(sub_140F7A567, prologue_og_code, sizeof(prologue_og_code), true); } } bF5LastState = bF5CurState; } }; injector::MakeInline<IdleHook>(pattern.get_first(0)); } CEXP void InitializeASI() { std::call_once(CallbackHandler::flag, []() { CallbackHandler::RegisterCallback(Init, hook::pattern("E8 ? ? ? ? 4C 89 25 ? ? ? ? E8 ? ? ? ? EB 3C")); }); } BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved) { if (reason == DLL_PROCESS_ATTACH) { if (!IsUALPresent()) { InitializeASI(); } } return TRUE; } <|endoftext|>
<commit_before>/* Copyright(c) Microsoft Open Technologies, Inc. All rights reserved. The MIT License(MIT) 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 "pch.h" #include "RemoteDevice.h" #include <ppltasks.h> using namespace Microsoft::Maker; using namespace Microsoft::Maker::RemoteWiring; //****************************************************************************** //* Constructors / Destructors //****************************************************************************** RemoteDevice::RemoteDevice( Serial::IStream ^serial_connection_ ) : _firmata( ref new Firmata::UwpFirmata ), _twoWire( nullptr ) { initialize(); _firmata->begin( serial_connection_ ); _firmata->startListening(); } RemoteDevice::RemoteDevice( Firmata::UwpFirmata ^firmata_ ) : _firmata( firmata_ ), _twoWire( nullptr ) { initialize(); } RemoteDevice::~RemoteDevice() { _firmata->finish(); } //****************************************************************************** //* Public Methods //****************************************************************************** uint16_t RemoteDevice::analogRead( uint8_t pin_ ) { uint16_t val = 0; if( pin_ < MAX_PINS ) { val = _analog_pins[ pin_ ]; } return val; } void RemoteDevice::analogWrite( uint8_t pin_, uint16_t value_ ) { if( _pin_mode[ pin_ ] != static_cast<uint8_t>( PinMode::PWM ) ) { if( _pin_mode[ pin_ ] == static_cast<uint8_t>( PinMode::OUTPUT ) ) { pinMode( pin_, PinMode::PWM ); _pin_mode[ pin_ ] = static_cast<uint8_t>( PinMode::PWM ); } else { return; } } _firmata->sendAnalog( pin_, value_ ); } PinState RemoteDevice::digitalRead( uint8_t pin_ ) { int port; uint8_t port_mask; getPinMap( pin_, &port, &port_mask ); return ( ( _digital_port[ port ] & port_mask ) > 0 ) ? static_cast<PinState>( 1 ) : static_cast<PinState>( 0 ); } void RemoteDevice::digitalWrite( uint8_t pin_, PinState state_ ) { int port; uint8_t port_mask; getPinMap( pin_, &port, &port_mask ); if( _pin_mode[ pin_ ] != static_cast<uint8_t>( PinMode::OUTPUT ) ) { if( _pin_mode[ pin_ ] == static_cast<uint8_t>( PinMode::PWM ) ) { pinMode( pin_, PinMode::OUTPUT ); } else { return; } } if( static_cast<uint8_t>( state_ ) ) { _digital_port[ port ] |= port_mask; } else { _digital_port[ port ] &= ~port_mask; } _firmata->sendDigitalPort( port, static_cast<uint16_t>( _digital_port[ port ] ) ); DigitalPinUpdatedEvent( pin_, state_ ); } PinMode RemoteDevice::getPinMode( uint8_t pin_ ) { return static_cast<PinMode>( _pin_mode[ pin_ ] ); } void RemoteDevice::pinMode( uint8_t pin_, PinMode mode_ ) { int port; uint8_t port_mask; getPinMap( pin_, &port, &port_mask ); _firmata->write( static_cast<uint8_t>( Firmata::Command::SET_PIN_MODE ) ); _firmata->write( pin_ ); _firmata->write( static_cast<uint8_t>( mode_ ) ); //lets subscribe to this port if we're setting it to input if( mode_ == PinMode::INPUT ) { _subscribed_ports[ port ] |= port_mask; _firmata->write( static_cast<uint8_t>( Firmata::Command::REPORT_DIGITAL_PIN ) | ( port & 0x0F ) ); _firmata->write( _subscribed_ports[ port ] ); } //if the selected mode is NOT input and we WERE subscribed to it, unsubscribe else if( _pin_mode[ pin_ ] == static_cast<uint8_t>( PinMode::INPUT ) ) { //make sure we aren't subscribed to this port _subscribed_ports[ port ] &= ~port_mask; _firmata->write( static_cast<uint8_t>( Firmata::Command::REPORT_DIGITAL_PIN ) | ( port & 0x0F ) ); _firmata->write( _subscribed_ports[ port ] ); } //finally, update the cached pin mode _pin_mode[ pin_ ] = static_cast<uint8_t>( mode_ ); } //****************************************************************************** //* Callbacks //****************************************************************************** void RemoteDevice::onDigitalReport( Firmata::CallbackEventArgs ^args ) { uint8_t port = args->getPort(); uint8_t port_val = static_cast<uint8_t>(args->getValue()); //output_state will only set bits which correspond to output pins that are HIGH uint8_t output_state = ~_subscribed_ports[ port ] & _digital_port[ port ]; port_val |= output_state; //determine which pins have changed uint8_t port_xor = port_val ^ _digital_port[ port ]; //throw a pin event for each pin that has changed uint8_t i = 0; while( port_xor > 0 ) { if( port_xor & 0x01 ) { DigitalPinUpdatedEvent( ( port * 8 ) + i, ( ( port_val >> i ) & 0x01 ) > 0 ? PinState::HIGH : PinState::LOW ); } port_xor >>= 1; ++i; } _digital_port[ port ] = port_val; } void RemoteDevice::onAnalogReport( Firmata::CallbackEventArgs ^args ) { uint8_t pin = args->getPort(); uint16_t val = args->getValue(); _analog_pins[ pin ] = val; AnalogPinUpdatedEvent( pin, val ); } void RemoteDevice::onSysexMessage( Firmata::SysexCallbackEventArgs ^argv ) { SysexMessageReceivedEvent( argv->getCommand(), argv->getSysexString() ); } void RemoteDevice::onStringMessage( Firmata::StringCallbackEventArgs ^argv ) { StringMessageReceivedEvent( argv->getString() ); } //****************************************************************************** //* Private Methods //****************************************************************************** void const RemoteDevice::initialize( void ) { _firmata->DigitalPortValueEvent += ref new Firmata::CallbackFunction( [ this ]( Firmata::UwpFirmata ^caller, Firmata::CallbackEventArgs^ args ) -> void { onDigitalReport( args ); } ); _firmata->AnalogValueEvent += ref new Firmata::CallbackFunction( [ this ]( Firmata::UwpFirmata ^caller, Firmata::CallbackEventArgs^ args ) -> void { onAnalogReport( args ); } ); _firmata->SysexEvent += ref new Firmata::SysexCallbackFunction( [ this ]( Firmata::UwpFirmata ^caller, Firmata::SysexCallbackEventArgs^ args ) -> void { onSysexMessage( args ); } ); _firmata->StringEvent += ref new Firmata::StringCallbackFunction( [ this ]( Firmata::UwpFirmata ^caller, Firmata::StringCallbackEventArgs^ args ) -> void { onStringMessage( args ); } ); //TODO: Initialize from Firmata, I have a good idea how to do this, JDF for( int i = 0; i < sizeof( _digital_port ); ++i ) { _digital_port[ i ] = 0; } for( int i = 0; i < sizeof( _subscribed_ports ); ++i ) { _subscribed_ports[ i ] = 0; } for( int i = 0; i < sizeof( _analog_pins ); ++i ) { _analog_pins[ i ] = 0; } for( int i = 0; i < sizeof( _pin_mode ); ++i ) { _pin_mode[ i ] = static_cast<uint8_t>( PinMode::OUTPUT ); } } void RemoteDevice::getPinMap( uint8_t pin, int *port, uint8_t *port_mask ) { if( port != nullptr ) { *port = ( pin / 8 ); } if( port_mask != nullptr ) { *port_mask = ( 1 << ( pin % 8 ) ); } }<commit_msg>Finished plumbing packet caching through RemoteWiring<commit_after>/* Copyright(c) Microsoft Open Technologies, Inc. All rights reserved. The MIT License(MIT) 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 "pch.h" #include "RemoteDevice.h" using namespace Concurrency; using namespace Microsoft::Maker; using namespace Microsoft::Maker::RemoteWiring; //****************************************************************************** //* Constructors / Destructors //****************************************************************************** RemoteDevice::RemoteDevice( Serial::IStream ^serial_connection_ ) : _firmata( ref new Firmata::UwpFirmata ), _twoWire( nullptr ) { initialize(); _firmata->begin( serial_connection_ ); _firmata->startListening(); } RemoteDevice::RemoteDevice( Firmata::UwpFirmata ^firmata_ ) : _firmata( firmata_ ), _twoWire( nullptr ) { initialize(); } RemoteDevice::~RemoteDevice() { _firmata->finish(); } //****************************************************************************** //* Public Methods //****************************************************************************** uint16_t RemoteDevice::analogRead( uint8_t pin_ ) { uint16_t val = -1; if (_pin_mode[pin_] != static_cast<uint8_t>(PinMode::ANALOG)) { if (_pin_mode[pin_] == static_cast<uint8_t>(PinMode::INPUT)) { pinMode(pin_, PinMode::ANALOG); _pin_mode[pin_] = static_cast<uint8_t>(PinMode::ANALOG); } else { return static_cast<uint16_t>(val); } } if( pin_ < MAX_PINS ) { val = _analog_pins[ pin_ ]; } return val; } void RemoteDevice::analogWrite( uint8_t pin_, uint16_t value_ ) { if( _pin_mode[ pin_ ] != static_cast<uint8_t>( PinMode::PWM ) ) { if( _pin_mode[ pin_ ] == static_cast<uint8_t>( PinMode::OUTPUT ) ) { pinMode( pin_, PinMode::PWM ); _pin_mode[ pin_ ] = static_cast<uint8_t>( PinMode::PWM ); } else { return; } } _firmata->sendAnalog( pin_, value_ ); } PinState RemoteDevice::digitalRead( uint8_t pin_ ) { int port; uint8_t port_mask; getPinMap( pin_, &port, &port_mask ); if (_pin_mode[pin_] != static_cast<uint8_t>(PinMode::INPUT)) { if (_pin_mode[pin_] == static_cast<uint8_t>(PinMode::ANALOG)) { pinMode(pin_, PinMode::INPUT); } else { return PinState::LOW; } } return static_cast<PinState>(_digital_port[port] & port_mask); } void RemoteDevice::digitalWrite( uint8_t pin_, PinState state_ ) { int port; uint8_t port_mask; getPinMap( pin_, &port, &port_mask ); if( _pin_mode[ pin_ ] != static_cast<uint8_t>( PinMode::OUTPUT ) ) { if( _pin_mode[ pin_ ] == static_cast<uint8_t>( PinMode::PWM ) ) { pinMode( pin_, PinMode::OUTPUT ); } else { return; } } if( static_cast<uint8_t>( state_ ) ) { _digital_port[ port ] |= port_mask; } else { _digital_port[ port ] &= ~port_mask; } _firmata->sendDigitalPort( port, static_cast<uint16_t>( _digital_port[ port ] ) ); } PinMode RemoteDevice::getPinMode( uint8_t pin_ ) { return static_cast<PinMode>( _pin_mode[ pin_ ] ); } void RemoteDevice::pinMode( uint8_t pin_, PinMode mode_ ) { int port; uint8_t port_mask; getPinMap( pin_, &port, &port_mask ); _firmata->write( static_cast<uint8_t>( Firmata::Command::SET_PIN_MODE ) ); _firmata->write( pin_ ); _firmata->write( static_cast<uint8_t>( mode_ ) ); //lets subscribe to this port if we're setting it to input if( mode_ == PinMode::INPUT ) { _subscribed_ports[ port ] |= port_mask; _firmata->write( static_cast<uint8_t>( Firmata::Command::REPORT_DIGITAL_PIN ) | ( port & 0x0F ) ); _firmata->write( _subscribed_ports[ port ] ); } //if the selected mode is NOT input and we WERE subscribed to it, unsubscribe else if( _pin_mode[ pin_ ] == static_cast<uint8_t>( PinMode::INPUT ) ) { //make sure we aren't subscribed to this port _subscribed_ports[ port ] &= ~port_mask; _firmata->write( static_cast<uint8_t>( Firmata::Command::REPORT_DIGITAL_PIN ) | ( port & 0x0F ) ); _firmata->write( _subscribed_ports[ port ] ); } _firmata->flush(); //finally, update the cached pin mode _pin_mode[ pin_ ] = static_cast<uint8_t>( mode_ ); } //****************************************************************************** //* Callbacks //****************************************************************************** void RemoteDevice::onDigitalReport( Firmata::CallbackEventArgs ^args ) { uint8_t port = args->getPort(); uint8_t port_val = static_cast<uint8_t>(args->getValue()); //output_state will only set bits which correspond to output pins that are HIGH uint8_t output_state = ~_subscribed_ports[ port ] & _digital_port[ port ]; port_val |= output_state; //determine which pins have changed uint8_t port_xor = port_val ^ _digital_port[ port ]; //throw a pin event for each pin that has changed uint8_t i = 0; while( port_xor > 0 ) { if( port_xor & 0x01 ) { DigitalPinUpdatedEvent( ( port * 8 ) + i, ( ( port_val >> i ) & 0x01 ) > 0 ? PinState::HIGH : PinState::LOW ); } port_xor >>= 1; ++i; } _digital_port[ port ] = port_val; } void RemoteDevice::onAnalogReport( Firmata::CallbackEventArgs ^args ) { uint8_t pin = args->getPort(); uint16_t val = args->getValue(); _analog_pins[ pin ] = val; AnalogPinUpdatedEvent( pin, val ); } void RemoteDevice::onSysexMessage( Firmata::SysexCallbackEventArgs ^argv ) { SysexMessageReceivedEvent( argv->getCommand(), argv->getSysexString() ); } void RemoteDevice::onStringMessage( Firmata::StringCallbackEventArgs ^argv ) { StringMessageReceivedEvent( argv->getString() ); } //****************************************************************************** //* Private Methods //****************************************************************************** void const RemoteDevice::initialize( void ) { _firmata->DigitalPortValueEvent += ref new Firmata::CallbackFunction( [ this ]( Firmata::UwpFirmata ^caller, Firmata::CallbackEventArgs^ args ) -> void { onDigitalReport( args ); } ); _firmata->AnalogValueEvent += ref new Firmata::CallbackFunction( [ this ]( Firmata::UwpFirmata ^caller, Firmata::CallbackEventArgs^ args ) -> void { onAnalogReport( args ); } ); _firmata->SysexEvent += ref new Firmata::SysexCallbackFunction( [ this ]( Firmata::UwpFirmata ^caller, Firmata::SysexCallbackEventArgs^ args ) -> void { onSysexMessage( args ); } ); _firmata->StringEvent += ref new Firmata::StringCallbackFunction( [ this ]( Firmata::UwpFirmata ^caller, Firmata::StringCallbackEventArgs^ args ) -> void { onStringMessage( args ); } ); //TODO: Initialize from Firmata, I have a good idea how to do this, JDF for( int i = 0; i < sizeof( _digital_port ); ++i ) { _digital_port[ i ] = 0; } for( int i = 0; i < sizeof( _subscribed_ports ); ++i ) { _subscribed_ports[ i ] = 0; } for( int i = 0; i < sizeof( _analog_pins ); ++i ) { _analog_pins[ i ] = 0; } for( int i = 0; i < sizeof( _pin_mode ); ++i ) { _pin_mode[ i ] = static_cast<uint8_t>( PinMode::OUTPUT ); } } void RemoteDevice::getPinMap( uint8_t pin, int *port, uint8_t *port_mask ) { if( port != nullptr ) { *port = ( pin / 8 ); } if( port_mask != nullptr ) { *port_mask = ( 1 << ( pin % 8 ) ); } }<|endoftext|>
<commit_before>#include <am/filemapper/detail/PersistImpl.h> NS_IZENELIB_AM_BEGIN PersistImpl::PersistImpl() { mappedData = 0; num_mapped_blocks=0; flags=0; } PersistImpl::~PersistImpl() { close(); } void PersistImpl::roundToPageSize(size_t &size) { const size_t mask = pageSize-1; if (size&mask) { size &= ~mask; size += pageSize; } } void PersistImpl::open(const char *filename, int uid, int f, size_t init_size) { flags = f; try { openFile(filename); mapBase(); if (!mappedData->created) { // First time creation initialize_map(); mappedData->uid = uid; if (init_size) addBlock(init_size); } else { // Already created if (uid != mappedData->uid) throw std::bad_alloc(); num_mapped_blocks = 0; mapBlocks(); } } catch (...) { // Could not open the file close(); mappedData = 0; // TODO: Done by close throw; } } void PersistImpl::close() { unmapAll(); closeFile(); } void PersistImpl::mapBase() { mappedData = static_cast<MappedData*>(map(0, sizeof(MappedData))); } void PersistImpl::mapBlocks() { int n = mappedData->num_mapped_blocks; for (int b=num_mapped_blocks; b<n; ++b) { MappedData::mapped_block &block = mappedData->blocks[b]; try{ map(block.file_offset, block.size, block.base); }catch (std::bad_alloc&) { void *base = map(block.file_offset, block.size, 0); block.base = base; } } num_mapped_blocks = n; } void PersistImpl::initialize_map() { new(mappedData) MappedData(); mappedData->auto_grow = (flags&auto_grow)!=0; mappedData->file_length = sizeof(MappedData); roundToPageSize(mappedData->file_length); } void PersistImpl::unmapAll() { if (mappedData) { for (int b=0; b<mappedData->num_mapped_blocks; ++b) { MappedData::mapped_block &block = mappedData->blocks[b]; unmap(block.base, block.size); } unmap(mappedData, sizeof(MappedData)); mappedData = 0; } num_mapped_blocks=0; } void *PersistImpl::malloc(size_t size) { if (!mappedData) return 0; // if(size==0) return mappedData->top; // A valid address? TODO lockMem(); int free_cell = object_cell(size); #if RECYCLE if (mappedData->free_space[free_cell]) { // We have a free cell of the desired size void *block = mappedData->free_space[free_cell]; mappedData->free_space[free_cell] = *(void**)block; #if CHECK_MEM ((int*)block)[-1] = size; #endif #if TRACE_ALLOCS std::cout << " +" << block << "(" << size << ")"; #endif unlockMem(); return block; } #endif #if CHECK_MEM *(int*)mappedData->top = size; mappedData->top += sizeof(int); #endif void *t = mappedData->top; if (mappedData->top + size > mappedData->end && mappedData->auto_grow) { // We have run out of mapped memory addBlock(size); t = mappedData->top; } if (mappedData->top + size > mappedData->end) { // We were unable to extend the mapped memory unlockMem(); return 0; // Failure } mappedData->top += size; #if TRACE_ALLOCS std::cout << " +" << t << "(" << size << ")"; #endif unlockMem(); return t; } void PersistImpl::free(void *block) { // TODO: Not implemented... } void PersistImpl::free(void* block, size_t size) { lockMem(); #if TRACE_ALLOCS std::cout << " -" << block << "(" << size << ")"; #endif if (size==0) return; // Do nothing if (block <mappedData || block >=mappedData->end) { // We have attempted to "free" data not allocated by this memory manager // This is a serious fault, but we carry on std::cout << "Block out of range!\n"; // This is a serious error! // This happens in basic_string... unlockMem(); return; } // This assertion no longer applies... // assert(block>=mappedData && block<mappedData->end); // This means that the address is not managed by this heap! #if CHECK_MEM assert(((int*)block)[-1] == size); ((int*)block)[-1] = 0; // This is now DEAD! #endif #if RECYCLE // Enable this to enable block to be reused int free_cell = object_cell(size); // free_cell is the cell number for blocks of size "size" // Add the free block to the linked list in free_space *(void**)block = mappedData->free_space[free_cell]; mappedData->free_space[free_cell] = block; #endif unlockMem(); } void *PersistImpl::root() const { if (!mappedData) return 0; // Failed #if CHECK_MEM // return (int*)mappedData->root + 1; return (int*)mappedData->blocks[0].base + 1; #endif return mappedData->blocks[0].base; // return mappedData->root; } bool PersistImpl::empty() const { if (!mappedData) return true; return mappedData->top == mappedData->bottom; } bool PersistImpl::usable() const { return mappedData != 0; } void PersistImpl::updateMappedBlocks() { if (num_mapped_blocks != mappedData->num_mapped_blocks) { mapBlocks(); } } void PersistImpl::addBlock(size_t size) { if (size < MappedData::block_size) size = MappedData::block_size; roundToPageSize(size); remapFile(mappedData->file_length + size); void *base = map(mappedData->file_length, size, 0); MappedData::mapped_block &block = mappedData->blocks[mappedData->num_mapped_blocks]; block.base = base; block.file_offset = mappedData->file_length; block.size = size; mappedData->file_length += size; mappedData->num_mapped_blocks++; num_mapped_blocks++; mappedData->top = (char*)base; mappedData->bottom = base; mappedData->end = (char*)base + size; } NS_IZENELIB_AM_END #ifdef WIN32 #include <am/filemapper/detail/win32/PersistImplBase.h> #else #include <am/filemapper/detail/posix/PersistImplBase.h> #endif <commit_msg>recover modifications for file mapper<commit_after>#include <am/filemapper/detail/PersistImpl.h> NS_IZENELIB_AM_BEGIN PersistImpl::PersistImpl() { mappedData = 0; num_mapped_blocks=0; flags=0; } PersistImpl::~PersistImpl() { close(); } void PersistImpl::roundToPageSize(size_t &size) { const size_t mask = pageSize-1; if (size&mask) { size &= ~mask; size += pageSize; } } void PersistImpl::open(const char *filename, int uid, int f, size_t init_size) { flags = f; try { openFile(filename); mapBase(); if (!mappedData->created) { // First time creation initialize_map(); mappedData->uid = uid; if (init_size) addBlock(init_size); } else { // Already created if (uid != mappedData->uid) throw std::bad_alloc(); num_mapped_blocks = 0; mapBlocks(); } } catch (...) { // Could not open the file close(); mappedData = 0; // TODO: Done by close throw; } } void PersistImpl::close() { unmapAll(); closeFile(); } void PersistImpl::mapBase() { mappedData = static_cast<MappedData*>(map(0, sizeof(MappedData))); } void PersistImpl::mapBlocks() { int n = mappedData->num_mapped_blocks; for (int b=num_mapped_blocks; b<n; ++b) { MappedData::mapped_block &block = mappedData->blocks[b]; map(block.file_offset, block.size, block.base); } num_mapped_blocks = n; } void PersistImpl::initialize_map() { new(mappedData) MappedData(); mappedData->auto_grow = (flags&auto_grow)!=0; mappedData->file_length = sizeof(MappedData); roundToPageSize(mappedData->file_length); } void PersistImpl::unmapAll() { if (mappedData) { for (int b=0; b<mappedData->num_mapped_blocks; ++b) { MappedData::mapped_block &block = mappedData->blocks[b]; unmap(block.base, block.size); } unmap(mappedData, sizeof(MappedData)); mappedData = 0; } num_mapped_blocks=0; } void *PersistImpl::malloc(size_t size) { if (!mappedData) return 0; // if(size==0) return mappedData->top; // A valid address? TODO lockMem(); int free_cell = object_cell(size); #if RECYCLE if (mappedData->free_space[free_cell]) { // We have a free cell of the desired size void *block = mappedData->free_space[free_cell]; mappedData->free_space[free_cell] = *(void**)block; #if CHECK_MEM ((int*)block)[-1] = size; #endif #if TRACE_ALLOCS std::cout << " +" << block << "(" << size << ")"; #endif unlockMem(); return block; } #endif #if CHECK_MEM *(int*)mappedData->top = size; mappedData->top += sizeof(int); #endif void *t = mappedData->top; if (mappedData->top + size > mappedData->end && mappedData->auto_grow) { // We have run out of mapped memory addBlock(size); t = mappedData->top; } if (mappedData->top + size > mappedData->end) { // We were unable to extend the mapped memory unlockMem(); return 0; // Failure } mappedData->top += size; #if TRACE_ALLOCS std::cout << " +" << t << "(" << size << ")"; #endif unlockMem(); return t; } void PersistImpl::free(void *block) { // TODO: Not implemented... } void PersistImpl::free(void* block, size_t size) { lockMem(); #if TRACE_ALLOCS std::cout << " -" << block << "(" << size << ")"; #endif if (size==0) return; // Do nothing if (block <mappedData || block >=mappedData->end) { // We have attempted to "free" data not allocated by this memory manager // This is a serious fault, but we carry on std::cout << "Block out of range!\n"; // This is a serious error! // This happens in basic_string... unlockMem(); return; } // This assertion no longer applies... // assert(block>=mappedData && block<mappedData->end); // This means that the address is not managed by this heap! #if CHECK_MEM assert(((int*)block)[-1] == size); ((int*)block)[-1] = 0; // This is now DEAD! #endif #if RECYCLE // Enable this to enable block to be reused int free_cell = object_cell(size); // free_cell is the cell number for blocks of size "size" // Add the free block to the linked list in free_space *(void**)block = mappedData->free_space[free_cell]; mappedData->free_space[free_cell] = block; #endif unlockMem(); } void *PersistImpl::root() const { if (!mappedData) return 0; // Failed #if CHECK_MEM // return (int*)mappedData->root + 1; return (int*)mappedData->blocks[0].base + 1; #endif return mappedData->blocks[0].base; // return mappedData->root; } bool PersistImpl::empty() const { if (!mappedData) return true; return mappedData->top == mappedData->bottom; } bool PersistImpl::usable() const { return mappedData != 0; } void PersistImpl::updateMappedBlocks() { if (num_mapped_blocks != mappedData->num_mapped_blocks) { mapBlocks(); } } void PersistImpl::addBlock(size_t size) { if (size < MappedData::block_size) size = MappedData::block_size; roundToPageSize(size); remapFile(mappedData->file_length + size); void *base = map(mappedData->file_length, size, 0); MappedData::mapped_block &block = mappedData->blocks[mappedData->num_mapped_blocks]; block.base = base; block.file_offset = mappedData->file_length; block.size = size; mappedData->file_length += size; mappedData->num_mapped_blocks++; num_mapped_blocks++; mappedData->top = (char*)base; mappedData->bottom = base; mappedData->end = (char*)base + size; } NS_IZENELIB_AM_END #ifdef WIN32 #include <am/filemapper/detail/win32/PersistImplBase.h> #else #include <am/filemapper/detail/posix/PersistImplBase.h> #endif <|endoftext|>
<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #include "autocomplete.h" #include "type/pt_data.h" namespace navitia { namespace autocomplete { void compute_score_poi(type::PT_Data&, georef::GeoRef &georef) { for (auto it = georef.fl_poi.word_quality_list.begin(); it != georef.fl_poi.word_quality_list.end(); ++it){ for (navitia::georef::Admin* admin : georef.pois[it->first]->admin_list){ if(admin->level == 8){ (it->second).score = georef.fl_admin.word_quality_list.at(admin->idx).score; } } } } void compute_score_way(type::PT_Data&, georef::GeoRef &georef) { for (auto it = georef.fl_way.word_quality_list.begin(); it != georef.fl_way.word_quality_list.end(); ++it){ for (navitia::georef::Admin* admin : georef.ways[it->first]->admin_list){ if (admin->level == 8){ //georef.fl_way.ac_list.at(it->first).score = georef.fl_admin.ac_list.at(admin->idx).score; (it->second).score = georef.fl_admin.word_quality_list.at(admin->idx).score; } } } } void compute_score_stop_point(type::PT_Data &pt_data, georef::GeoRef &georef) { //Récupérer le score de son admin du niveau 8 dans le autocomplete: georef.fl_admin for (auto it = pt_data.stop_point_autocomplete.word_quality_list.begin(); it != pt_data.stop_point_autocomplete.word_quality_list.end(); ++it){ for(navitia::georef::Admin* admin : pt_data.stop_points[it->first]->admin_list){ if (admin->level == 8){ (it->second).score = georef.fl_admin.word_quality_list.at(admin->idx).score; } } } } void compute_score_stop_area(type::PT_Data & pt_data){ //Calculate de maximum stop-point count; size_t max_score = 0; for (navitia::type::StopArea* sa : pt_data.stop_areas){ max_score = std::max(max_score, sa->stop_point_list.size()); } //Ajust the score of each stop_area from 0 to 100 using maximum score (max_score) if (max_score > 0){ for (auto & it : pt_data.stop_area_autocomplete.word_quality_list){ it.second.score = (pt_data.stop_areas[it.first]->stop_point_list.size() * 100)/max_score; } } } void compute_score_admin(type::PT_Data &pt_data, georef::GeoRef &georef) { int max_score = 0; //Pour chaque stop_point incrémenter le score de son admin de niveau 8 par 1. for (navitia::type::StopPoint* sp : pt_data.stop_points){ for (navitia::georef::Admin * admin : sp->admin_list){ if (admin->level == 8){ georef.fl_admin.word_quality_list.at(admin->idx).score++; } } } //Calculer le max_score des admins for (auto it = georef.fl_admin.word_quality_list.begin(); it != georef.fl_admin.word_quality_list.end(); ++it){ max_score = ((it->second).score > max_score)?(it->second).score:max_score; } //Ajuster le score de chaque admin an utilisant le max_score. for (auto it = georef.fl_admin.word_quality_list.begin(); it != georef.fl_admin.word_quality_list.end(); ++it){ (it->second).score = max_score == 0 ? 0 : ((it->second).score * 100)/max_score; } } void compute_score_line(type::PT_Data&, georef::GeoRef&) { } template<> void Autocomplete<type::idx_t>::compute_score(type::PT_Data &pt_data, georef::GeoRef &georef, const type::Type_e type) { switch(type){ case type::Type_e::StopArea: compute_score_stop_area(pt_data); break; case type::Type_e::StopPoint: compute_score_stop_point(pt_data, georef); break; case type::Type_e::Line: compute_score_line(pt_data, georef); break; case type::Type_e::Admin: compute_score_admin(pt_data, georef); break; case type::Type_e::Way: compute_score_way(pt_data, georef); break; case type::Type_e::POI: compute_score_poi(pt_data, georef); break; default: break; } } }} <commit_msg>autocomplete : comments modified<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #include "autocomplete.h" #include "type/pt_data.h" namespace navitia { namespace autocomplete { void compute_score_poi(type::PT_Data&, georef::GeoRef &georef) { for (auto it = georef.fl_poi.word_quality_list.begin(); it != georef.fl_poi.word_quality_list.end(); ++it){ for (navitia::georef::Admin* admin : georef.pois[it->first]->admin_list){ if(admin->level == 8){ (it->second).score = georef.fl_admin.word_quality_list.at(admin->idx).score; } } } } void compute_score_way(type::PT_Data&, georef::GeoRef &georef) { //The scocre of each admin(level 8) is attributed to all its ways for (auto it = georef.fl_way.word_quality_list.begin(); it != georef.fl_way.word_quality_list.end(); ++it){ for (navitia::georef::Admin* admin : georef.ways[it->first]->admin_list){ if (admin->level == 8){ (it->second).score = georef.fl_admin.word_quality_list.at(admin->idx).score; } } } } void compute_score_stop_point(type::PT_Data &pt_data, georef::GeoRef &georef) { //The scocre of each admin(level 8) is attributed to all its stop_points for (auto it = pt_data.stop_point_autocomplete.word_quality_list.begin(); it != pt_data.stop_point_autocomplete.word_quality_list.end(); ++it){ for(navitia::georef::Admin* admin : pt_data.stop_points[it->first]->admin_list){ if (admin->level == 8){ (it->second).score = georef.fl_admin.word_quality_list.at(admin->idx).score; } } } } void compute_score_stop_area(type::PT_Data & pt_data){ //Find the stop-point count in all stop_areas and keep the highest; size_t max_score = 0; for (navitia::type::StopArea* sa : pt_data.stop_areas){ max_score = std::max(max_score, sa->stop_point_list.size()); } //Ajust the score of each stop_area from 0 to 100 using maximum score (max_score) if (max_score > 0){ for (auto & it : pt_data.stop_area_autocomplete.word_quality_list){ it.second.score = (pt_data.stop_areas[it.first]->stop_point_list.size() * 100)/max_score; } } } void compute_score_admin(type::PT_Data &pt_data, georef::GeoRef &georef) { int max_score = 0; //For each stop_point increase the score of it's admin(level 8) by 1. for (navitia::type::StopPoint* sp : pt_data.stop_points){ for (navitia::georef::Admin * admin : sp->admin_list){ if (admin->level == 8){ georef.fl_admin.word_quality_list.at(admin->idx).score++; } } } //Calculate max_score of all admins for (auto it = georef.fl_admin.word_quality_list.begin(); it != georef.fl_admin.word_quality_list.end(); ++it){ max_score = ((it->second).score > max_score)?(it->second).score:max_score; } //Ajust the score of each admin using max_score. for (auto it = georef.fl_admin.word_quality_list.begin(); it != georef.fl_admin.word_quality_list.end(); ++it){ (it->second).score = max_score == 0 ? 0 : ((it->second).score * 100)/max_score; } } template<> void Autocomplete<type::idx_t>::compute_score(type::PT_Data &pt_data, georef::GeoRef &georef, const type::Type_e type) { switch(type){ case type::Type_e::StopArea: compute_score_stop_area(pt_data); break; case type::Type_e::StopPoint: compute_score_stop_point(pt_data, georef); break; case type::Type_e::Admin: compute_score_admin(pt_data, georef); break; case type::Type_e::Way: compute_score_way(pt_data, georef); break; case type::Type_e::POI: compute_score_poi(pt_data, georef); break; default: break; } } }} <|endoftext|>
<commit_before>#include <b1/session/shared_bytes.hpp> #include <boost/test/unit_test.hpp> using namespace eosio::session; BOOST_AUTO_TEST_SUITE(shared_bytes_tests) BOOST_AUTO_TEST_CASE(make_shared_bytes_test) { static constexpr auto* char_value = "hello world"; static const auto char_length = strlen(char_value) - 1; static constexpr auto int_value = int64_t{ 100000000 }; auto b1 = shared_bytes(char_value, char_length); BOOST_REQUIRE(memcmp(b1.data(), reinterpret_cast<const int8_t*>(char_value), char_length) == 0); BOOST_REQUIRE(b1.size() == char_length); auto b2 = shared_bytes(reinterpret_cast<const int8_t*>(char_value), char_length); BOOST_REQUIRE(memcmp(b1.data(), reinterpret_cast<const int8_t*>(char_value), char_length) == 0); BOOST_REQUIRE(b2.size() == char_length); auto b3 = shared_bytes(&int_value, 1); BOOST_REQUIRE(*(reinterpret_cast<const decltype(int_value)*>(b3.data())) == int_value); BOOST_REQUIRE(b3.size() == sizeof(decltype(int_value))); auto b4 = shared_bytes(char_value, char_length); BOOST_REQUIRE(memcmp(b4.data(), reinterpret_cast<const int8_t*>(char_value), char_length) == 0); BOOST_REQUIRE(b4.size() == char_length); auto invalid = shared_bytes(static_cast<int8_t*>(nullptr), 0); BOOST_REQUIRE(invalid.data() == nullptr); BOOST_REQUIRE(invalid.size() == 0); BOOST_REQUIRE(b1 == b2); BOOST_REQUIRE(b1 == b4); BOOST_REQUIRE(invalid == shared_bytes{}); BOOST_REQUIRE(b1 != b3); auto b5 = b1; BOOST_REQUIRE(memcmp(b5.data(), reinterpret_cast<const int8_t*>(char_value), char_length) == 0); BOOST_REQUIRE(b5.size() == char_length); BOOST_REQUIRE(b1 == b5); auto b6{ b1 }; BOOST_REQUIRE(memcmp(b6.data(), reinterpret_cast<const int8_t*>(char_value), char_length) == 0); BOOST_REQUIRE(b6.size() == char_length); BOOST_REQUIRE(b1 == b6); auto b7 = std::move(b1); BOOST_REQUIRE(memcmp(b7.data(), reinterpret_cast<const int8_t*>(char_value), char_length) == 0); BOOST_REQUIRE(b7.size() == char_length); auto b8{ std::move(b2) }; BOOST_REQUIRE(memcmp(b8.data(), reinterpret_cast<const int8_t*>(char_value), char_length) == 0); BOOST_REQUIRE(b8.size() == char_length); } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>Add unit test cases for next method of shared_bytes_tests.cpp<commit_after>#include <b1/session/shared_bytes.hpp> #include <boost/test/unit_test.hpp> using namespace eosio::session; BOOST_AUTO_TEST_SUITE(shared_bytes_tests) BOOST_AUTO_TEST_CASE(make_shared_bytes_test) { static constexpr auto* char_value = "hello world"; static const auto char_length = strlen(char_value) - 1; static constexpr auto int_value = int64_t{ 100000000 }; auto b1 = shared_bytes(char_value, char_length); BOOST_REQUIRE(memcmp(b1.data(), reinterpret_cast<const int8_t*>(char_value), char_length) == 0); BOOST_REQUIRE(b1.size() == char_length); auto b2 = shared_bytes(reinterpret_cast<const int8_t*>(char_value), char_length); BOOST_REQUIRE(memcmp(b1.data(), reinterpret_cast<const int8_t*>(char_value), char_length) == 0); BOOST_REQUIRE(b2.size() == char_length); auto b3 = shared_bytes(&int_value, 1); BOOST_REQUIRE(*(reinterpret_cast<const decltype(int_value)*>(b3.data())) == int_value); BOOST_REQUIRE(b3.size() == sizeof(decltype(int_value))); auto b4 = shared_bytes(char_value, char_length); BOOST_REQUIRE(memcmp(b4.data(), reinterpret_cast<const int8_t*>(char_value), char_length) == 0); BOOST_REQUIRE(b4.size() == char_length); auto invalid = shared_bytes(static_cast<int8_t*>(nullptr), 0); BOOST_REQUIRE(invalid.data() == nullptr); BOOST_REQUIRE(invalid.size() == 0); BOOST_REQUIRE(b1 == b2); BOOST_REQUIRE(b1 == b4); BOOST_REQUIRE(invalid == shared_bytes{}); BOOST_REQUIRE(b1 != b3); auto b5 = b1; BOOST_REQUIRE(memcmp(b5.data(), reinterpret_cast<const int8_t*>(char_value), char_length) == 0); BOOST_REQUIRE(b5.size() == char_length); BOOST_REQUIRE(b1 == b5); auto b6{ b1 }; BOOST_REQUIRE(memcmp(b6.data(), reinterpret_cast<const int8_t*>(char_value), char_length) == 0); BOOST_REQUIRE(b6.size() == char_length); BOOST_REQUIRE(b1 == b6); auto b7 = std::move(b1); BOOST_REQUIRE(memcmp(b7.data(), reinterpret_cast<const int8_t*>(char_value), char_length) == 0); BOOST_REQUIRE(b7.size() == char_length); auto b8{ std::move(b2) }; BOOST_REQUIRE(memcmp(b8.data(), reinterpret_cast<const int8_t*>(char_value), char_length) == 0); BOOST_REQUIRE(b8.size() == char_length); } BOOST_AUTO_TEST_CASE(next_test) { static constexpr auto* a_value = "a"; static constexpr auto* a_next_expected = "b"; auto a = shared_bytes(a_value, 1); BOOST_REQUIRE(memcmp(a.next().data(), reinterpret_cast<const int8_t*>(a_next_expected), 1) == 0); BOOST_REQUIRE(a.next().size() == 1); static constexpr auto* aa_value = "aa"; static constexpr auto* aa_next_expected = "ab"; auto aa = shared_bytes(aa_value, 2); BOOST_REQUIRE(memcmp(aa.next().data(), reinterpret_cast<const int8_t*>(aa_next_expected), 2) == 0); BOOST_REQUIRE(aa.next().size() == 2); static constexpr auto* empty_value = ""; auto empty = shared_bytes(empty_value, 0); BOOST_REQUIRE(empty.next().size() == 0); // next of a sequence of 0xFFs is empty char single_last_value[1] = {static_cast<char>(0xFF)}; auto single_last = shared_bytes(single_last_value, 1); BOOST_REQUIRE(single_last.next().size() == 0); char double_last_value[2] = {static_cast<char>(0xFF), static_cast<char>(0xFF)}; auto double_last = shared_bytes(double_last_value, 2); BOOST_REQUIRE(double_last.next().size() == 0); char mixed_last_value[2] = {static_cast<char>(0xFE), static_cast<char>(0xFF)}; char mixed_last_next_expected[1] = {static_cast<char>(0xFF)}; auto mixed_last = shared_bytes(mixed_last_value, 2); BOOST_REQUIRE(memcmp(mixed_last.next().data(), reinterpret_cast<const int8_t*>(mixed_last_next_expected), 1) == 0); BOOST_REQUIRE(mixed_last.next().size() == 1); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/runtime/browser/xwalk_browser_main_parts_android.h" #include <string> #include "base/android/path_utils.h" #include "base/base_paths_android.h" #include "base/files/file_path.h" #include "base/file_util.h" #include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "base/threading/sequenced_worker_pool.h" #include "cc/base/switches.h" #include "content/public/browser/android/compositor.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/cookie_store_factory.h" #include "content/public/common/content_switches.h" #include "content/public/common/result_codes.h" #include "grit/net_resources.h" #include "net/android/network_change_notifier_factory_android.h" #include "net/base/network_change_notifier.h" #include "net/base/net_module.h" #include "net/base/net_util.h" #include "net/cookies/cookie_monster.h" #include "net/cookies/cookie_store.h" #include "ui/base/layout.h" #include "ui/base/l10n/l10n_util_android.h" #include "ui/base/resource/resource_bundle.h" #include "xwalk/extensions/browser/xwalk_extension_service.h" #include "xwalk/extensions/common/xwalk_extension.h" #include "xwalk/extensions/common/xwalk_extension_switches.h" #include "xwalk/runtime/browser/android/cookie_manager.h" #include "xwalk/runtime/browser/runtime_context.h" #include "xwalk/runtime/browser/xwalk_runner.h" #include "xwalk/runtime/common/xwalk_runtime_features.h" #include "xwalk/runtime/common/xwalk_switches.h" namespace { base::StringPiece PlatformResourceProvider(int key) { if (key == IDR_DIR_HEADER_HTML) { base::StringPiece html_data = ui::ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_DIR_HEADER_HTML); return html_data; } return base::StringPiece(); } } // namespace namespace xwalk { using content::BrowserThread; using extensions::XWalkExtension; XWalkBrowserMainPartsAndroid::XWalkBrowserMainPartsAndroid( const content::MainFunctionParams& parameters) : XWalkBrowserMainParts(parameters) { } XWalkBrowserMainPartsAndroid::~XWalkBrowserMainPartsAndroid() { } void XWalkBrowserMainPartsAndroid::PreEarlyInitialization() { net::NetworkChangeNotifier::SetFactory( new net::NetworkChangeNotifierFactoryAndroid()); CommandLine::ForCurrentProcess()->AppendSwitch( cc::switches::kCompositeToMailbox); // Initialize the Compositor. content::Compositor::Initialize(); XWalkBrowserMainParts::PreEarlyInitialization(); } void XWalkBrowserMainPartsAndroid::PreMainMessageLoopStart() { CommandLine* command_line = CommandLine::ForCurrentProcess(); // Disable ExtensionProcess for Android. // External extensions will run in the BrowserProcess (in process mode). command_line->AppendSwitch(switches::kXWalkDisableExtensionProcess); // Only force to enable WebGL for Android for IA platforms because // we've tested the WebGL conformance test. For other platforms, just // follow up the behavior defined by Chromium upstream. #if defined(ARCH_CPU_X86) command_line->AppendSwitch(switches::kIgnoreGpuBlacklist); #endif #if defined(ENABLE_WEBRTC) // Disable HW encoding/decoding acceleration for WebRTC on Android. // FIXME: Remove these switches for Android when Android OS is removed from // GPU accelerated_video_decode blacklist or we stop ignoring the GPU // blacklist. command_line->AppendSwitch(switches::kDisableWebRtcHWDecoding); command_line->AppendSwitch(switches::kDisableWebRtcHWEncoding); #endif // For fullscreen video playback, the ContentVideoView is still buggy, so // we switch back to ContentVideoViewLegacy for temp. // TODO(shouqun): Remove this flag when ContentVideoView is ready. command_line->AppendSwitch( switches::kDisableOverlayFullscreenVideoSubtitle); command_line->AppendSwitch(switches::kEnableViewportMeta); XWalkBrowserMainParts::PreMainMessageLoopStart(); startup_url_ = GURL(); } void XWalkBrowserMainPartsAndroid::PostMainMessageLoopStart() { base::MessageLoopForUI::current()->Start(); } void XWalkBrowserMainPartsAndroid::PreMainMessageLoopRun() { net::NetModule::SetResourceProvider(PlatformResourceProvider); if (parameters_.ui_task) { parameters_.ui_task->Run(); delete parameters_.ui_task; run_default_message_loop_ = false; } xwalk_runner_->PreMainMessageLoopRun(); extension_service_ = xwalk_runner_->extension_service(); // Prepare the cookie store. base::FilePath user_data_dir; if (!PathService::Get(base::DIR_ANDROID_APP_DATA, &user_data_dir)) { NOTREACHED() << "Failed to get app data directory for Crosswalk"; } CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kXWalkProfileName)) user_data_dir = user_data_dir.Append( command_line->GetSwitchValuePath(switches::kXWalkProfileName)); base::FilePath cookie_store_path = user_data_dir.Append( FILE_PATH_LITERAL("Cookies")); scoped_refptr<base::SequencedTaskRunner> background_task_runner = BrowserThread::GetBlockingPool()->GetSequencedTaskRunner( BrowserThread::GetBlockingPool()->GetSequenceToken()); content::CookieStoreConfig cookie_config( cookie_store_path, content::CookieStoreConfig::RESTORED_SESSION_COOKIES, NULL, NULL); cookie_config.client_task_runner = BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO); cookie_config.background_task_runner = background_task_runner; cookie_store_ = content::CreateCookieStore(cookie_config); cookie_store_->GetCookieMonster()->SetPersistSessionCookies(true); SetCookieMonsterOnNetworkStackInit(cookie_store_->GetCookieMonster()); } void XWalkBrowserMainPartsAndroid::PostMainMessageLoopRun() { XWalkBrowserMainParts::PostMainMessageLoopRun(); base::MessageLoopForUI::current()->Start(); } void XWalkBrowserMainPartsAndroid::CreateInternalExtensionsForExtensionThread( content::RenderProcessHost* host, extensions::XWalkExtensionVector* extensions) { // On Android part, the ownership of each extension object will be transferred // to XWalkExtensionServer after this method is called. It is a rule enforced // by extension system that XWalkExtensionServer must own the extension // objects and extension instances. extensions::XWalkExtensionVector::const_iterator it = extensions_.begin(); for (; it != extensions_.end(); ++it) extensions->push_back(*it); } void XWalkBrowserMainPartsAndroid::RegisterExtension( scoped_ptr<XWalkExtension> extension) { // Since the creation of extension object is driven by Java side, and each // Java extension is backed by a native extension object. However, the Java // object may be destroyed by Android lifecycle management without destroying // the native side object. We keep the reference to native extension object // to make sure we can reuse the native object if Java extension is re-created // on resuming. extensions_.push_back(extension.release()); } XWalkExtension* XWalkBrowserMainPartsAndroid::LookupExtension( const std::string& name) { extensions::XWalkExtensionVector::const_iterator it = extensions_.begin(); for (; it != extensions_.end(); ++it) { XWalkExtension* extension = *it; if (name == extension->name()) return extension; } return NULL; } } // namespace xwalk <commit_msg>[Android] Increase the open files limit<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/runtime/browser/xwalk_browser_main_parts_android.h" #include <string> #include "base/android/path_utils.h" #include "base/base_paths_android.h" #include "base/files/file_path.h" #include "base/file_util.h" #include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "base/threading/sequenced_worker_pool.h" #include "cc/base/switches.h" #include "content/public/browser/android/compositor.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/cookie_store_factory.h" #include "content/public/common/content_switches.h" #include "content/public/common/result_codes.h" #include "grit/net_resources.h" #include "net/android/network_change_notifier_factory_android.h" #include "net/base/network_change_notifier.h" #include "net/base/net_module.h" #include "net/base/net_util.h" #include "net/cookies/cookie_monster.h" #include "net/cookies/cookie_store.h" #include "ui/base/layout.h" #include "ui/base/l10n/l10n_util_android.h" #include "ui/base/resource/resource_bundle.h" #include "xwalk/extensions/browser/xwalk_extension_service.h" #include "xwalk/extensions/common/xwalk_extension.h" #include "xwalk/extensions/common/xwalk_extension_switches.h" #include "xwalk/runtime/browser/android/cookie_manager.h" #include "xwalk/runtime/browser/runtime_context.h" #include "xwalk/runtime/browser/xwalk_runner.h" #include "xwalk/runtime/common/xwalk_runtime_features.h" #include "xwalk/runtime/common/xwalk_switches.h" namespace { base::StringPiece PlatformResourceProvider(int key) { if (key == IDR_DIR_HEADER_HTML) { base::StringPiece html_data = ui::ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_DIR_HEADER_HTML); return html_data; } return base::StringPiece(); } } // namespace namespace xwalk { using content::BrowserThread; using extensions::XWalkExtension; XWalkBrowserMainPartsAndroid::XWalkBrowserMainPartsAndroid( const content::MainFunctionParams& parameters) : XWalkBrowserMainParts(parameters) { } XWalkBrowserMainPartsAndroid::~XWalkBrowserMainPartsAndroid() { } void XWalkBrowserMainPartsAndroid::PreEarlyInitialization() { net::NetworkChangeNotifier::SetFactory( new net::NetworkChangeNotifierFactoryAndroid()); // As Crosswalk uses in-process mode, that's easier than Chromium // to reach the default limit(1024) of open files per process on // Android. So increase the limit to 4096 explicitly. base::SetFdLimit(4096); CommandLine::ForCurrentProcess()->AppendSwitch( cc::switches::kCompositeToMailbox); // Initialize the Compositor. content::Compositor::Initialize(); XWalkBrowserMainParts::PreEarlyInitialization(); } void XWalkBrowserMainPartsAndroid::PreMainMessageLoopStart() { CommandLine* command_line = CommandLine::ForCurrentProcess(); // Disable ExtensionProcess for Android. // External extensions will run in the BrowserProcess (in process mode). command_line->AppendSwitch(switches::kXWalkDisableExtensionProcess); // Only force to enable WebGL for Android for IA platforms because // we've tested the WebGL conformance test. For other platforms, just // follow up the behavior defined by Chromium upstream. #if defined(ARCH_CPU_X86) command_line->AppendSwitch(switches::kIgnoreGpuBlacklist); #endif #if defined(ENABLE_WEBRTC) // Disable HW encoding/decoding acceleration for WebRTC on Android. // FIXME: Remove these switches for Android when Android OS is removed from // GPU accelerated_video_decode blacklist or we stop ignoring the GPU // blacklist. command_line->AppendSwitch(switches::kDisableWebRtcHWDecoding); command_line->AppendSwitch(switches::kDisableWebRtcHWEncoding); #endif // For fullscreen video playback, the ContentVideoView is still buggy, so // we switch back to ContentVideoViewLegacy for temp. // TODO(shouqun): Remove this flag when ContentVideoView is ready. command_line->AppendSwitch( switches::kDisableOverlayFullscreenVideoSubtitle); command_line->AppendSwitch(switches::kEnableViewportMeta); XWalkBrowserMainParts::PreMainMessageLoopStart(); startup_url_ = GURL(); } void XWalkBrowserMainPartsAndroid::PostMainMessageLoopStart() { base::MessageLoopForUI::current()->Start(); } void XWalkBrowserMainPartsAndroid::PreMainMessageLoopRun() { net::NetModule::SetResourceProvider(PlatformResourceProvider); if (parameters_.ui_task) { parameters_.ui_task->Run(); delete parameters_.ui_task; run_default_message_loop_ = false; } xwalk_runner_->PreMainMessageLoopRun(); extension_service_ = xwalk_runner_->extension_service(); // Prepare the cookie store. base::FilePath user_data_dir; if (!PathService::Get(base::DIR_ANDROID_APP_DATA, &user_data_dir)) { NOTREACHED() << "Failed to get app data directory for Crosswalk"; } CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kXWalkProfileName)) user_data_dir = user_data_dir.Append( command_line->GetSwitchValuePath(switches::kXWalkProfileName)); base::FilePath cookie_store_path = user_data_dir.Append( FILE_PATH_LITERAL("Cookies")); scoped_refptr<base::SequencedTaskRunner> background_task_runner = BrowserThread::GetBlockingPool()->GetSequencedTaskRunner( BrowserThread::GetBlockingPool()->GetSequenceToken()); content::CookieStoreConfig cookie_config( cookie_store_path, content::CookieStoreConfig::RESTORED_SESSION_COOKIES, NULL, NULL); cookie_config.client_task_runner = BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO); cookie_config.background_task_runner = background_task_runner; cookie_store_ = content::CreateCookieStore(cookie_config); cookie_store_->GetCookieMonster()->SetPersistSessionCookies(true); SetCookieMonsterOnNetworkStackInit(cookie_store_->GetCookieMonster()); } void XWalkBrowserMainPartsAndroid::PostMainMessageLoopRun() { XWalkBrowserMainParts::PostMainMessageLoopRun(); base::MessageLoopForUI::current()->Start(); } void XWalkBrowserMainPartsAndroid::CreateInternalExtensionsForExtensionThread( content::RenderProcessHost* host, extensions::XWalkExtensionVector* extensions) { // On Android part, the ownership of each extension object will be transferred // to XWalkExtensionServer after this method is called. It is a rule enforced // by extension system that XWalkExtensionServer must own the extension // objects and extension instances. extensions::XWalkExtensionVector::const_iterator it = extensions_.begin(); for (; it != extensions_.end(); ++it) extensions->push_back(*it); } void XWalkBrowserMainPartsAndroid::RegisterExtension( scoped_ptr<XWalkExtension> extension) { // Since the creation of extension object is driven by Java side, and each // Java extension is backed by a native extension object. However, the Java // object may be destroyed by Android lifecycle management without destroying // the native side object. We keep the reference to native extension object // to make sure we can reuse the native object if Java extension is re-created // on resuming. extensions_.push_back(extension.release()); } XWalkExtension* XWalkBrowserMainPartsAndroid::LookupExtension( const std::string& name) { extensions::XWalkExtensionVector::const_iterator it = extensions_.begin(); for (; it != extensions_.end(); ++it) { XWalkExtension* extension = *it; if (name == extension->name()) return extension; } return NULL; } } // namespace xwalk <|endoftext|>
<commit_before>#pragma once #include <cstdint> #include <array> #include <memory> #include <vector> #include <algorithm> #ifdef __EMSCRIPTEN__ #include "SDL2/SDL.h" #else #include "SDL.h" #endif #include "vm/utils.hpp" #include "vm/context.hpp" namespace yagbe { class sdl2_renderer { public: sdl2_renderer(const ipoint &size, int scale = 4) : _w(size.x), _h(size.y) { if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) throw std::runtime_error("SDL_Init"); _window.reset(SDL_CreateWindow("YAGBE", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _w * scale, _h * scale, SDL_WINDOW_SHOWN)); if (!_window) throw std::runtime_error("SDL_CreateWindow"); _renderer.reset(SDL_CreateRenderer(_window.get(), -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)); if (!_renderer) throw std::runtime_error("SDL_CreateRenderer"); _texture.reset(SDL_CreateTexture(_renderer.get(), SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING, _w, _h)); if (!_texture) throw std::runtime_error("SDL_CreateTexture"); #ifdef _DEBUG open_audio(); #endif } ~sdl2_renderer() { #ifdef _DEBUG SDL_CloseAudioDevice(_audio); #endif SDL_Quit(); } void initialize(yagbe::context &ctx) { ctx.gpu.onFrameReady = [&](auto& frame) { accept_image(frame); }; #ifdef _DEBUG ctx.apu.configure(_audioSpec.freq, _audioSpec.samples / 4); ctx.apu.onSamplesReady = [&](auto&& samples) { accept_samples(std::move(samples)); }; #endif } bool frame_drawn() { return _frame_drawn; } void next_frame() { _frame_drawn = false; } bool step() { handle_events(); return _running; } void accept_image(const std::vector<uint8_t>& image) { if (image.size() != _w * _h * channels) throw std::runtime_error("accept_image wrong size"); accept_raw_image(image.data()); } void accept_image(const std::vector<uint32_t>& image) { if (image.size() != _w * _h) throw std::runtime_error("accept_image wrong size"); accept_raw_image((uint8_t*)image.data()); } void accept_image(const std::vector<color>& image) { if (image.size() != _w * _h) throw std::runtime_error("accept_image wrong size"); accept_raw_image((uint8_t*)image.data()); } void accept_samples(const std::vector<float>&& samples) { SDL_QueueAudio(_audio, samples.data(), (Uint32)samples.size() * sizeof(float)); } bool running() { return _running; } struct key_info { bool shift = false; }; std::function<void(SDL_Keycode, bool, const key_info&)> onKeyChanged; protected: void audio_callback(float* buff, int len) { int channels = 2; for (int i = 0; i < len; i += channels) { auto& outLeft = buff[i]; auto& outRight = buff[i + 1]; auto sine = [=](double freq) { static double secondsFromStart = 0; secondsFromStart += _audioStep; return (float)sin(secondsFromStart * freq * M_PI * 2.0); }; auto square = [=](double freq) { static double len = 1.0 / freq / 2.0; static double acc = 0.0; static double v = 0.25; acc += _audioStep; if (acc > len) { acc = 0.0; v = -v; }; return v; }; auto silence = [=]() { return 0.0; }; //square 1000 outLeft = outRight = (float)silence(); } } void open_audio() { SDL_AudioSpec want; SDL_memset(&_audioSpec, 0, sizeof(_audioSpec)); SDL_memset(&want, 0, sizeof(want)); /* or SDL_zero(want) */ want.freq = 48000; want.format = AUDIO_F32; want.channels = 2; want.samples = 4096; want.userdata = this; want.callback = nullptr; /* [](void* userdata, Uint8* stream, int len) { ((sdl2_renderer*)userdata)->audio_callback((float*)stream, len/sizeof(float)); };*/ _audio = SDL_OpenAudioDevice(NULL, 0, &want, &_audioSpec, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE); if (_audio == 0) { SDL_Log("Failed to open audio: %s", SDL_GetError()); } else { _audioStep = 1.0 / (double)_audioSpec.freq; SDL_PauseAudioDevice(_audio, 0); /* start audio playing. */ } } void accept_raw_image(const uint8_t *input) { _frame_drawn = true; auto texture = _texture.get(); uint8_t *pixels; int pitch; if (SDL_LockTexture(texture, nullptr, &(void*&)pixels, &pitch) != 0) throw std::runtime_error("SDL_LockTexture"); auto it = input; for (auto y = 0; y < _h; y++) { std::copy(it, it + _w*channels, pixels); it += _w*channels; pixels += pitch; } SDL_UnlockTexture(texture); auto ren = _renderer.get(); SDL_RenderCopy(ren, _texture.get(), NULL, NULL); SDL_RenderPresent(ren); } void handle_events() { SDL_Event e; while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) _running = false; if (e.type == SDL_KEYDOWN || e.type == SDL_KEYUP) { auto key_code = e.key.keysym.sym; key_info info; info.shift = (e.key.keysym.mod & KMOD_SHIFT) != 0; if (onKeyChanged) onKeyChanged(key_code, e.type == SDL_KEYDOWN, info); return; } } } int _w, _h; bool _frame_drawn = false; const static int channels = 4; std::unique_ptr<SDL_Window, void(*)(SDL_Window*)> _window = { nullptr, SDL_DestroyWindow }; std::unique_ptr<SDL_Renderer, void(*)(SDL_Renderer*)> _renderer = { nullptr, SDL_DestroyRenderer }; std::unique_ptr<SDL_Texture, void(*)(SDL_Texture*)> _texture = { nullptr, SDL_DestroyTexture }; SDL_AudioDeviceID _audio = 0; SDL_AudioSpec _audioSpec = {}; double _audioStep = 0.0f; bool _running = true; }; };<commit_msg>Enable audio in release.<commit_after>#pragma once #include <cstdint> #include <array> #include <memory> #include <vector> #include <algorithm> #ifdef __EMSCRIPTEN__ #include "SDL2/SDL.h" #else #include "SDL.h" #endif #include "vm/utils.hpp" #include "vm/context.hpp" namespace yagbe { class sdl2_renderer { public: sdl2_renderer(const ipoint &size, int scale = 4) : _w(size.x), _h(size.y) { if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) throw std::runtime_error("SDL_Init"); _window.reset(SDL_CreateWindow("YAGBE", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, _w * scale, _h * scale, SDL_WINDOW_SHOWN)); if (!_window) throw std::runtime_error("SDL_CreateWindow"); _renderer.reset(SDL_CreateRenderer(_window.get(), -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)); if (!_renderer) throw std::runtime_error("SDL_CreateRenderer"); _texture.reset(SDL_CreateTexture(_renderer.get(), SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING, _w, _h)); if (!_texture) throw std::runtime_error("SDL_CreateTexture"); open_audio(); } ~sdl2_renderer() { SDL_CloseAudioDevice(_audio); SDL_Quit(); } void initialize(yagbe::context &ctx) { ctx.gpu.onFrameReady = [&](auto& frame) { accept_image(frame); }; ctx.apu.configure(_audioSpec.freq, _audioSpec.samples / 4); ctx.apu.onSamplesReady = [&](auto&& samples) { accept_samples(std::move(samples)); }; } bool frame_drawn() { return _frame_drawn; } void next_frame() { _frame_drawn = false; } bool step() { handle_events(); return _running; } void accept_image(const std::vector<uint8_t>& image) { if (image.size() != _w * _h * channels) throw std::runtime_error("accept_image wrong size"); accept_raw_image(image.data()); } void accept_image(const std::vector<uint32_t>& image) { if (image.size() != _w * _h) throw std::runtime_error("accept_image wrong size"); accept_raw_image((uint8_t*)image.data()); } void accept_image(const std::vector<color>& image) { if (image.size() != _w * _h) throw std::runtime_error("accept_image wrong size"); accept_raw_image((uint8_t*)image.data()); } void accept_samples(const std::vector<float>&& samples) { SDL_QueueAudio(_audio, samples.data(), (Uint32)samples.size() * sizeof(float)); } bool running() { return _running; } struct key_info { bool shift = false; }; std::function<void(SDL_Keycode, bool, const key_info&)> onKeyChanged; protected: void audio_callback(float* buff, int len) { int channels = 2; for (int i = 0; i < len; i += channels) { auto& outLeft = buff[i]; auto& outRight = buff[i + 1]; auto sine = [=](double freq) { static double secondsFromStart = 0; secondsFromStart += _audioStep; return (float)sin(secondsFromStart * freq * M_PI * 2.0); }; auto square = [=](double freq) { static double len = 1.0 / freq / 2.0; static double acc = 0.0; static double v = 0.25; acc += _audioStep; if (acc > len) { acc = 0.0; v = -v; }; return v; }; auto silence = [=]() { return 0.0; }; //square 1000 outLeft = outRight = (float)silence(); } } void open_audio() { SDL_AudioSpec want; SDL_memset(&_audioSpec, 0, sizeof(_audioSpec)); SDL_memset(&want, 0, sizeof(want)); /* or SDL_zero(want) */ want.freq = 48000; want.format = AUDIO_F32; want.channels = 2; want.samples = 4096; want.userdata = this; want.callback = nullptr; _audio = SDL_OpenAudioDevice(NULL, 0, &want, &_audioSpec, SDL_AUDIO_ALLOW_FREQUENCY_CHANGE); if (_audio == 0) { SDL_Log("Failed to open audio: %s", SDL_GetError()); } else { _audioStep = 1.0 / (double)_audioSpec.freq; SDL_PauseAudioDevice(_audio, 0); /* start audio playing. */ } } void accept_raw_image(const uint8_t *input) { _frame_drawn = true; auto texture = _texture.get(); uint8_t *pixels; int pitch; if (SDL_LockTexture(texture, nullptr, &(void*&)pixels, &pitch) != 0) throw std::runtime_error("SDL_LockTexture"); auto it = input; for (auto y = 0; y < _h; y++) { std::copy(it, it + _w*channels, pixels); it += _w*channels; pixels += pitch; } SDL_UnlockTexture(texture); auto ren = _renderer.get(); SDL_RenderCopy(ren, _texture.get(), NULL, NULL); SDL_RenderPresent(ren); } void handle_events() { SDL_Event e; while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) _running = false; if (e.type == SDL_KEYDOWN || e.type == SDL_KEYUP) { auto key_code = e.key.keysym.sym; key_info info; info.shift = (e.key.keysym.mod & KMOD_SHIFT) != 0; if (onKeyChanged) onKeyChanged(key_code, e.type == SDL_KEYDOWN, info); return; } } } int _w, _h; bool _frame_drawn = false; const static int channels = 4; std::unique_ptr<SDL_Window, void(*)(SDL_Window*)> _window = { nullptr, SDL_DestroyWindow }; std::unique_ptr<SDL_Renderer, void(*)(SDL_Renderer*)> _renderer = { nullptr, SDL_DestroyRenderer }; std::unique_ptr<SDL_Texture, void(*)(SDL_Texture*)> _texture = { nullptr, SDL_DestroyTexture }; SDL_AudioDeviceID _audio = 0; SDL_AudioSpec _audioSpec = {}; double _audioStep = 0.0f; bool _running = true; }; };<|endoftext|>
<commit_before>//===--- PthreadLockChecker.cpp - Check for locking problems ---*- C++ -*--===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This defines PthreadLockChecker, a simple lock -> unlock checker. // Also handles XNU locks, which behave similarly enough to share code. // //===----------------------------------------------------------------------===// #include "ClangSACheckers.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" #include "llvm/ADT/ImmutableList.h" using namespace clang; using namespace ento; namespace { class PthreadLockChecker : public Checker< check::PostStmt<CallExpr> > { mutable OwningPtr<BugType> BT_doublelock; mutable OwningPtr<BugType> BT_lor; enum LockingSemantics { NotApplicable = 0, PthreadSemantics, XNUSemantics }; public: void checkPostStmt(const CallExpr *CE, CheckerContext &C) const; void AcquireLock(CheckerContext &C, const CallExpr *CE, SVal lock, bool isTryLock, enum LockingSemantics semantics) const; void ReleaseLock(CheckerContext &C, const CallExpr *CE, SVal lock) const; }; } // end anonymous namespace // GDM Entry for tracking lock state. REGISTER_LIST_WITH_PROGRAMSTATE(LockSet, const MemRegion *) void PthreadLockChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const { ProgramStateRef state = C.getState(); const LocationContext *LCtx = C.getLocationContext(); StringRef FName = C.getCalleeName(CE); if (FName.empty()) return; if (CE->getNumArgs() != 1) return; if (FName == "pthread_mutex_lock" || FName == "pthread_rwlock_rdlock" || FName == "pthread_rwlock_wrlock") AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx), false, PthreadSemantics); else if (FName == "lck_mtx_lock" || FName == "lck_rw_lock_exclusive" || FName == "lck_rw_lock_shared") AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx), false, XNUSemantics); else if (FName == "pthread_mutex_trylock" || FName == "pthread_rwlock_tryrdlock" || FName == "pthread_rwlock_tryrwlock") AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx), true, PthreadSemantics); else if (FName == "lck_mtx_try_lock" || FName == "lck_rw_try_lock_exclusive" || FName == "lck_rw_try_lock_shared") AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx), true, XNUSemantics); else if (FName == "pthread_mutex_unlock" || FName == "pthread_rwlock_unlock" || FName == "lck_mtx_unlock" || FName == "lck_rw_done") ReleaseLock(C, CE, state->getSVal(CE->getArg(0), LCtx)); } void PthreadLockChecker::AcquireLock(CheckerContext &C, const CallExpr *CE, SVal lock, bool isTryLock, enum LockingSemantics semantics) const { const MemRegion *lockR = lock.getAsRegion(); if (!lockR) return; ProgramStateRef state = C.getState(); SVal X = state->getSVal(CE, C.getLocationContext()); if (X.isUnknownOrUndef()) return; DefinedSVal retVal = X.castAs<DefinedSVal>(); if (state->contains<LockSet>(lockR)) { if (!BT_doublelock) BT_doublelock.reset(new BugType("Double locking", "Lock checker")); ExplodedNode *N = C.generateSink(); if (!N) return; BugReport *report = new BugReport(*BT_doublelock, "This lock has already " "been acquired", N); report->addRange(CE->getArg(0)->getSourceRange()); C.emitReport(report); return; } ProgramStateRef lockSucc = state; if (isTryLock) { // Bifurcate the state, and allow a mode where the lock acquisition fails. ProgramStateRef lockFail; switch (semantics) { case PthreadSemantics: llvm::tie(lockFail, lockSucc) = state->assume(retVal); break; case XNUSemantics: llvm::tie(lockSucc, lockFail) = state->assume(retVal); break; default: llvm_unreachable("Unknown tryLock locking semantics"); } assert(lockFail && lockSucc); C.addTransition(lockFail); } else if (semantics == PthreadSemantics) { // Assume that the return value was 0. lockSucc = state->assume(retVal, false); assert(lockSucc); } else { // XNU locking semantics return void on non-try locks assert((semantics == XNUSemantics) && "Unknown locking semantics"); lockSucc = state; } // Record that the lock was acquired. lockSucc = lockSucc->add<LockSet>(lockR); C.addTransition(lockSucc); } void PthreadLockChecker::ReleaseLock(CheckerContext &C, const CallExpr *CE, SVal lock) const { const MemRegion *lockR = lock.getAsRegion(); if (!lockR) return; ProgramStateRef state = C.getState(); LockSetTy LS = state->get<LockSet>(); // FIXME: Better analysis requires IPA for wrappers. // FIXME: check for double unlocks if (LS.isEmpty()) return; const MemRegion *firstLockR = LS.getHead(); if (firstLockR != lockR) { if (!BT_lor) BT_lor.reset(new BugType("Lock order reversal", "Lock checker")); ExplodedNode *N = C.generateSink(); if (!N) return; BugReport *report = new BugReport(*BT_lor, "This was not the most " "recently acquired lock. " "Possible lock order " "reversal", N); report->addRange(CE->getArg(0)->getSourceRange()); C.emitReport(report); return; } // Record that the lock was released. state = state->set<LockSet>(LS.getTail()); C.addTransition(state); } void ento::registerPthreadLockChecker(CheckerManager &mgr) { mgr.registerChecker<PthreadLockChecker>(); } <commit_msg>[analyzer] Fix incorrect spelling of 'pthread_rwlock_trywrlock'. Patch by Jean Baptiste Noblot.<commit_after>//===--- PthreadLockChecker.cpp - Check for locking problems ---*- C++ -*--===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This defines PthreadLockChecker, a simple lock -> unlock checker. // Also handles XNU locks, which behave similarly enough to share code. // //===----------------------------------------------------------------------===// #include "ClangSACheckers.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/CheckerManager.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h" #include "llvm/ADT/ImmutableList.h" using namespace clang; using namespace ento; namespace { class PthreadLockChecker : public Checker< check::PostStmt<CallExpr> > { mutable OwningPtr<BugType> BT_doublelock; mutable OwningPtr<BugType> BT_lor; enum LockingSemantics { NotApplicable = 0, PthreadSemantics, XNUSemantics }; public: void checkPostStmt(const CallExpr *CE, CheckerContext &C) const; void AcquireLock(CheckerContext &C, const CallExpr *CE, SVal lock, bool isTryLock, enum LockingSemantics semantics) const; void ReleaseLock(CheckerContext &C, const CallExpr *CE, SVal lock) const; }; } // end anonymous namespace // GDM Entry for tracking lock state. REGISTER_LIST_WITH_PROGRAMSTATE(LockSet, const MemRegion *) void PthreadLockChecker::checkPostStmt(const CallExpr *CE, CheckerContext &C) const { ProgramStateRef state = C.getState(); const LocationContext *LCtx = C.getLocationContext(); StringRef FName = C.getCalleeName(CE); if (FName.empty()) return; if (CE->getNumArgs() != 1) return; if (FName == "pthread_mutex_lock" || FName == "pthread_rwlock_rdlock" || FName == "pthread_rwlock_wrlock") AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx), false, PthreadSemantics); else if (FName == "lck_mtx_lock" || FName == "lck_rw_lock_exclusive" || FName == "lck_rw_lock_shared") AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx), false, XNUSemantics); else if (FName == "pthread_mutex_trylock" || FName == "pthread_rwlock_tryrdlock" || FName == "pthread_rwlock_trywrlock") AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx), true, PthreadSemantics); else if (FName == "lck_mtx_try_lock" || FName == "lck_rw_try_lock_exclusive" || FName == "lck_rw_try_lock_shared") AcquireLock(C, CE, state->getSVal(CE->getArg(0), LCtx), true, XNUSemantics); else if (FName == "pthread_mutex_unlock" || FName == "pthread_rwlock_unlock" || FName == "lck_mtx_unlock" || FName == "lck_rw_done") ReleaseLock(C, CE, state->getSVal(CE->getArg(0), LCtx)); } void PthreadLockChecker::AcquireLock(CheckerContext &C, const CallExpr *CE, SVal lock, bool isTryLock, enum LockingSemantics semantics) const { const MemRegion *lockR = lock.getAsRegion(); if (!lockR) return; ProgramStateRef state = C.getState(); SVal X = state->getSVal(CE, C.getLocationContext()); if (X.isUnknownOrUndef()) return; DefinedSVal retVal = X.castAs<DefinedSVal>(); if (state->contains<LockSet>(lockR)) { if (!BT_doublelock) BT_doublelock.reset(new BugType("Double locking", "Lock checker")); ExplodedNode *N = C.generateSink(); if (!N) return; BugReport *report = new BugReport(*BT_doublelock, "This lock has already " "been acquired", N); report->addRange(CE->getArg(0)->getSourceRange()); C.emitReport(report); return; } ProgramStateRef lockSucc = state; if (isTryLock) { // Bifurcate the state, and allow a mode where the lock acquisition fails. ProgramStateRef lockFail; switch (semantics) { case PthreadSemantics: llvm::tie(lockFail, lockSucc) = state->assume(retVal); break; case XNUSemantics: llvm::tie(lockSucc, lockFail) = state->assume(retVal); break; default: llvm_unreachable("Unknown tryLock locking semantics"); } assert(lockFail && lockSucc); C.addTransition(lockFail); } else if (semantics == PthreadSemantics) { // Assume that the return value was 0. lockSucc = state->assume(retVal, false); assert(lockSucc); } else { // XNU locking semantics return void on non-try locks assert((semantics == XNUSemantics) && "Unknown locking semantics"); lockSucc = state; } // Record that the lock was acquired. lockSucc = lockSucc->add<LockSet>(lockR); C.addTransition(lockSucc); } void PthreadLockChecker::ReleaseLock(CheckerContext &C, const CallExpr *CE, SVal lock) const { const MemRegion *lockR = lock.getAsRegion(); if (!lockR) return; ProgramStateRef state = C.getState(); LockSetTy LS = state->get<LockSet>(); // FIXME: Better analysis requires IPA for wrappers. // FIXME: check for double unlocks if (LS.isEmpty()) return; const MemRegion *firstLockR = LS.getHead(); if (firstLockR != lockR) { if (!BT_lor) BT_lor.reset(new BugType("Lock order reversal", "Lock checker")); ExplodedNode *N = C.generateSink(); if (!N) return; BugReport *report = new BugReport(*BT_lor, "This was not the most " "recently acquired lock. " "Possible lock order " "reversal", N); report->addRange(CE->getArg(0)->getSourceRange()); C.emitReport(report); return; } // Record that the lock was released. state = state->set<LockSet>(LS.getTail()); C.addTransition(state); } void ento::registerPthreadLockChecker(CheckerManager &mgr) { mgr.registerChecker<PthreadLockChecker>(); } <|endoftext|>