text
stringlengths
54
60.6k
<commit_before>// zlib #include <zlib.h> // std #include <stdexcept> namespace mapnik { namespace vector_tile_impl { // decodes both zlib and gzip // http://stackoverflow.com/a/1838702/2333354 void zlib_decompress(const char * data, std::size_t size, std::string & output) { z_stream inflate_s; inflate_s.zalloc = Z_NULL; inflate_s.zfree = Z_NULL; inflate_s.opaque = Z_NULL; inflate_s.avail_in = 0; inflate_s.next_in = Z_NULL; inflateInit2(&inflate_s, 32 + 15); inflate_s.next_in = (Bytef *)data; inflate_s.avail_in = size; size_t length = 0; do { output.resize(length + 2 * size); inflate_s.avail_out = 2 * size; inflate_s.next_out = (Bytef *)(output.data() + length); int ret = inflate(&inflate_s, Z_FINISH); if (ret != Z_STREAM_END && ret != Z_OK && ret != Z_BUF_ERROR) { inflateEnd(&inflate_s); throw std::runtime_error(inflate_s.msg); } length += (2 * size - inflate_s.avail_out); } while (inflate_s.avail_out == 0); inflateEnd(&inflate_s); output.resize(length); } void zlib_decompress(std::string const& input, std::string & output) { zlib_decompress(input.data(),input.size(),output); } void zlib_compress(const char * data, std::size_t size, std::string & output, bool gzip, int level, int strategy) { z_stream deflate_s; deflate_s.zalloc = Z_NULL; deflate_s.zfree = Z_NULL; deflate_s.opaque = Z_NULL; deflate_s.avail_in = 0; deflate_s.next_in = Z_NULL; int windowsBits = 15; if (gzip) { windowsBits = windowsBits | 16; } if (deflateInit2(&deflate_s, level, Z_DEFLATED, windowsBits, 8, strategy) != Z_OK) { deflateEnd(&deflate_s); throw std::runtime_error("deflate init failed"); } deflate_s.next_in = (Bytef *)data; deflate_s.avail_in = size; size_t length = 0; do { size_t increase = size / 2 + 1024; output.resize(length + increase); deflate_s.avail_out = increase; deflate_s.next_out = (Bytef *)(output.data() + length); // From http://www.zlib.net/zlib_how.html // "deflate() has a return value that can indicate errors, yet we do not check it here. // Why not? Well, it turns out that deflate() can do no wrong here." // Basically only possible error is from deflateInit not working properly deflate(&deflate_s, Z_FINISH); length += (increase - deflate_s.avail_out); } while (deflate_s.avail_out == 0); deflateEnd(&deflate_s); output.resize(length); } void zlib_compress(std::string const& input, std::string & output, bool gzip, int level, int strategy) { zlib_compress(input.data(),input.size(),output,gzip,level,strategy); } } // end ns vector_tile_impl } // end ns mapnik <commit_msg>Remove possible invalidated memory situation<commit_after>// zlib #include <zlib.h> // std #include <stdexcept> namespace mapnik { namespace vector_tile_impl { // decodes both zlib and gzip // http://stackoverflow.com/a/1838702/2333354 void zlib_decompress(const char * data, std::size_t size, std::string & output) { z_stream inflate_s; inflate_s.zalloc = Z_NULL; inflate_s.zfree = Z_NULL; inflate_s.opaque = Z_NULL; inflate_s.avail_in = 0; inflate_s.next_in = Z_NULL; inflateInit2(&inflate_s, 32 + 15); inflate_s.next_in = (Bytef *)data; inflate_s.avail_in = size; size_t length = 0; do { output.resize(length + 2 * size); inflate_s.avail_out = 2 * size; inflate_s.next_out = (Bytef *)(output.data() + length); int ret = inflate(&inflate_s, Z_FINISH); if (ret != Z_STREAM_END && ret != Z_OK && ret != Z_BUF_ERROR) { std::string error_msg = inflate_s.msg; inflateEnd(&inflate_s); throw std::runtime_error(error_msg); } length += (2 * size - inflate_s.avail_out); } while (inflate_s.avail_out == 0); inflateEnd(&inflate_s); output.resize(length); } void zlib_decompress(std::string const& input, std::string & output) { zlib_decompress(input.data(),input.size(),output); } void zlib_compress(const char * data, std::size_t size, std::string & output, bool gzip, int level, int strategy) { z_stream deflate_s; deflate_s.zalloc = Z_NULL; deflate_s.zfree = Z_NULL; deflate_s.opaque = Z_NULL; deflate_s.avail_in = 0; deflate_s.next_in = Z_NULL; int windowsBits = 15; if (gzip) { windowsBits = windowsBits | 16; } if (deflateInit2(&deflate_s, level, Z_DEFLATED, windowsBits, 8, strategy) != Z_OK) { deflateEnd(&deflate_s); throw std::runtime_error("deflate init failed"); } deflate_s.next_in = (Bytef *)data; deflate_s.avail_in = size; size_t length = 0; do { size_t increase = size / 2 + 1024; output.resize(length + increase); deflate_s.avail_out = increase; deflate_s.next_out = (Bytef *)(output.data() + length); // From http://www.zlib.net/zlib_how.html // "deflate() has a return value that can indicate errors, yet we do not check it here. // Why not? Well, it turns out that deflate() can do no wrong here." // Basically only possible error is from deflateInit not working properly deflate(&deflate_s, Z_FINISH); length += (increase - deflate_s.avail_out); } while (deflate_s.avail_out == 0); deflateEnd(&deflate_s); output.resize(length); } void zlib_compress(std::string const& input, std::string & output, bool gzip, int level, int strategy) { zlib_compress(input.data(),input.size(),output,gzip,level,strategy); } } // end ns vector_tile_impl } // end ns mapnik <|endoftext|>
<commit_before>// Copyright Daniel Wallin, Arvid Norberg 2007. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/extensions.hpp> #include <libtorrent/entry.hpp> #include <libtorrent/peer_request.hpp> #include <libtorrent/peer_connection.hpp> #include <libtorrent/extensions/ut_pex.hpp> #include <libtorrent/extensions/metadata_transfer.hpp> #include <boost/python.hpp> #include "gil.hpp" using namespace boost::python; using namespace libtorrent; namespace { struct torrent_plugin_wrap : torrent_plugin, wrapper<torrent_plugin> { boost::shared_ptr<peer_plugin> new_connection(peer_connection* p) { lock_gil lock; if (override f = this->get_override("new_connection")) return f(ptr(p)); return torrent_plugin::new_connection(p); } boost::shared_ptr<peer_plugin> default_new_connection(peer_connection* p) { return this->torrent_plugin::new_connection(p); } void on_piece_pass(int index) { lock_gil lock; if (override f = this->get_override("on_piece_pass")) f(index); else torrent_plugin::on_piece_pass(index); } void default_on_piece_pass(int index) { this->torrent_plugin::on_piece_pass(index); } void on_piece_failed(int index) { lock_gil lock; if (override f = this->get_override("on_piece_failed")) f(index); else torrent_plugin::on_piece_failed(index); } void default_on_piece_failed(int index) { return this->torrent_plugin::on_piece_failed(index); } void tick() { lock_gil lock; if (override f = this->get_override("tick")) f(); else torrent_plugin::tick(); } void default_tick() { return this->torrent_plugin::tick(); } bool on_pause() { lock_gil lock; if (override f = this->get_override("on_pause")) return f(); return torrent_plugin::on_pause(); } bool default_on_pause() { return this->torrent_plugin::on_pause(); } bool on_resume() { lock_gil lock; if (override f = this->get_override("on_resume")) return f(); return torrent_plugin::on_resume(); } bool default_on_resume() { return this->torrent_plugin::on_resume(); } }; } // namespace unnamed boost::shared_ptr<torrent_plugin> create_metadata_plugin_wrapper(torrent* t) { return create_metadata_plugin(t, NULL); } boost::shared_ptr<torrent_plugin> create_ut_pex_plugin_wrapper(torrent* t) { return create_ut_pex_plugin(t, NULL); } void bind_extensions() { class_< torrent_plugin_wrap, boost::shared_ptr<torrent_plugin_wrap>, boost::noncopyable >("torrent_plugin") .def( "new_connection" , &torrent_plugin::new_connection, &torrent_plugin_wrap::default_new_connection ) .def( "on_piece_pass" , &torrent_plugin::on_piece_pass, &torrent_plugin_wrap::default_on_piece_pass ) .def( "on_piece_failed" , &torrent_plugin::on_piece_failed, &torrent_plugin_wrap::default_on_piece_failed ) .def( "tick" , &torrent_plugin::tick, &torrent_plugin_wrap::default_tick ) .def( "on_pause" , &torrent_plugin::on_pause, &torrent_plugin_wrap::default_on_pause ) .def( "on_resume" , &torrent_plugin::on_resume, &torrent_plugin_wrap::default_on_resume ); // TODO move to it's own file class_<peer_connection, boost::noncopyable>("peer_connection", no_init); class_<torrent_plugin, boost::shared_ptr<torrent_plugin> >("torrent_plugin", no_init); def("create_ut_pex_plugin", create_ut_pex_plugin_wrapper); def("create_metadata_plugin", create_metadata_plugin_wrapper); } <commit_msg>Add create_ut_metadata_plugin() to bindings<commit_after>// Copyright Daniel Wallin, Arvid Norberg 2007. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/extensions.hpp> #include <libtorrent/entry.hpp> #include <libtorrent/peer_request.hpp> #include <libtorrent/peer_connection.hpp> #include <libtorrent/extensions/ut_pex.hpp> #include <libtorrent/extensions/metadata_transfer.hpp> #include <libtorrent/extensions/ut_metadata.hpp> #include <boost/python.hpp> #include "gil.hpp" using namespace boost::python; using namespace libtorrent; namespace { struct torrent_plugin_wrap : torrent_plugin, wrapper<torrent_plugin> { boost::shared_ptr<peer_plugin> new_connection(peer_connection* p) { lock_gil lock; if (override f = this->get_override("new_connection")) return f(ptr(p)); return torrent_plugin::new_connection(p); } boost::shared_ptr<peer_plugin> default_new_connection(peer_connection* p) { return this->torrent_plugin::new_connection(p); } void on_piece_pass(int index) { lock_gil lock; if (override f = this->get_override("on_piece_pass")) f(index); else torrent_plugin::on_piece_pass(index); } void default_on_piece_pass(int index) { this->torrent_plugin::on_piece_pass(index); } void on_piece_failed(int index) { lock_gil lock; if (override f = this->get_override("on_piece_failed")) f(index); else torrent_plugin::on_piece_failed(index); } void default_on_piece_failed(int index) { return this->torrent_plugin::on_piece_failed(index); } void tick() { lock_gil lock; if (override f = this->get_override("tick")) f(); else torrent_plugin::tick(); } void default_tick() { return this->torrent_plugin::tick(); } bool on_pause() { lock_gil lock; if (override f = this->get_override("on_pause")) return f(); return torrent_plugin::on_pause(); } bool default_on_pause() { return this->torrent_plugin::on_pause(); } bool on_resume() { lock_gil lock; if (override f = this->get_override("on_resume")) return f(); return torrent_plugin::on_resume(); } bool default_on_resume() { return this->torrent_plugin::on_resume(); } }; } // namespace unnamed boost::shared_ptr<torrent_plugin> create_metadata_plugin_wrapper(torrent* t) { return create_metadata_plugin(t, NULL); } boost::shared_ptr<torrent_plugin> create_ut_metadata_plugin_wrapper(torrent *t) { return create_ut_metadata_plugin(t, NULL); } boost::shared_ptr<torrent_plugin> create_ut_pex_plugin_wrapper(torrent* t) { return create_ut_pex_plugin(t, NULL); } void bind_extensions() { class_< torrent_plugin_wrap, boost::shared_ptr<torrent_plugin_wrap>, boost::noncopyable >("torrent_plugin") .def( "new_connection" , &torrent_plugin::new_connection, &torrent_plugin_wrap::default_new_connection ) .def( "on_piece_pass" , &torrent_plugin::on_piece_pass, &torrent_plugin_wrap::default_on_piece_pass ) .def( "on_piece_failed" , &torrent_plugin::on_piece_failed, &torrent_plugin_wrap::default_on_piece_failed ) .def( "tick" , &torrent_plugin::tick, &torrent_plugin_wrap::default_tick ) .def( "on_pause" , &torrent_plugin::on_pause, &torrent_plugin_wrap::default_on_pause ) .def( "on_resume" , &torrent_plugin::on_resume, &torrent_plugin_wrap::default_on_resume ); // TODO move to it's own file class_<peer_connection, boost::noncopyable>("peer_connection", no_init); class_<torrent_plugin, boost::shared_ptr<torrent_plugin> >("torrent_plugin", no_init); def("create_ut_pex_plugin", create_ut_pex_plugin_wrapper); def("create_metadata_plugin", create_metadata_plugin_wrapper); def("create_ut_metadata_plugin", create_ut_metadata_plugin_wrapper); } <|endoftext|>
<commit_before>/* * This is the main cpp file for cPlusPlusPlusLib * cPPPLib - A library of functions that should be in the C++ Standard Library * (C) - Charles Machalow - MIT License */ #ifndef cPPPLib_CPP #define cPPPLib_CPP #include "cPPPLib.h" /// <summary> /// Splits the original_str into a std::vector by delimiter /// </summary> /// <param name="original_str">The original_str.</param> /// <param name="delim">The delimiter.</param> /// <returns></returns> std::vector<std::string> StringFunctions::splitIntoVector(const std::string &original_str, const std::string &delim) { std::string working_str = original_str; std::vector<std::string> ret_vec; while (!working_str.empty()) { unsigned int loc = working_str.find(delim); // found in string if (loc != std::string::npos) { ret_vec.push_back(working_str.substr(0, loc)); working_str = working_str.substr(loc + 1); } else { ret_vec.push_back(working_str); break; } } return ret_vec; } /// <summary> /// Splits the original_str into a std::vector by whitespace. /// </summary> /// <param name="original_str">The original_str.</param> /// <returns></returns> std::vector<std::string> StringFunctions::splitIntoVectorByWhitespace(const std::string &original_str) { std::string working_str = original_str; std::vector<std::string> ret_vec; while (!working_str.empty()) { unsigned int loc = working_str.find(" "); // found in string if (loc != std::string::npos) { if (working_str.substr(0, loc) != "") { ret_vec.push_back(working_str.substr(0, loc)); } working_str = working_str.substr(loc + 1); } else { if (working_str != "") { ret_vec.push_back(working_str); } break; } } return ret_vec; } int main() { std::cout << "cPlusPlusPlusLib Version " << cPPPLib_H::cPPPLib_V << std::endl << "(C) - Charles Machalow - MIT License" << std::endl; std::string t = "a"; std::vector<std::string> tmp = StringFunctions::splitIntoVectorByWhitespace(" "); system("PAUSE"); return 1; } #endif cPPPLib_CPP<commit_msg>Add returns documentation to existing functions.<commit_after>/* * This is the main cpp file for cPlusPlusPlusLib * cPPPLib - A library of functions that should be in the C++ Standard Library * (C) - Charles Machalow - MIT License */ #ifndef cPPPLib_CPP #define cPPPLib_CPP #include "cPPPLib.h" /// <summary> /// Splits the original_str into a std::vector by delimiter /// </summary> /// <param name="original_str">The original_str.</param> /// <param name="delim">The delimiter.</param> /// <returns>std::vector<string> where each item is a string that has been delimited</returns> std::vector<std::string> StringFunctions::splitIntoVector(const std::string &original_str, const std::string &delim) { std::string working_str = original_str; std::vector<std::string> ret_vec; while (!working_str.empty()) { unsigned int loc = working_str.find(delim); // found in string if (loc != std::string::npos) { ret_vec.push_back(working_str.substr(0, loc)); working_str = working_str.substr(loc + 1); } else { ret_vec.push_back(working_str); break; } } return ret_vec; } /// <summary> /// Splits the original_str into a std::vector by whitespace. /// </summary> /// <param name="original_str">The original_str.</param> /// <returns>std::vector<string> where each item is a string that has been delimited by whitespace</returns> std::vector<std::string> StringFunctions::splitIntoVectorByWhitespace(const std::string &original_str) { std::string working_str = original_str; std::vector<std::string> ret_vec; while (!working_str.empty()) { unsigned int loc = working_str.find(" "); // found in string if (loc != std::string::npos) { if (working_str.substr(0, loc) != "") { ret_vec.push_back(working_str.substr(0, loc)); } working_str = working_str.substr(loc + 1); } else { if (working_str != "") { ret_vec.push_back(working_str); } break; } } return ret_vec; } int main() { std::cout << "cPlusPlusPlusLib Version " << cPPPLib_H::cPPPLib_V << std::endl << "(C) - Charles Machalow - MIT License" << std::endl; std::string t = "a"; std::vector<std::string> tmp = StringFunctions::splitIntoVectorByWhitespace(" "); system("PAUSE"); return 1; } #endif cPPPLib_CPP<|endoftext|>
<commit_before>#include "modules/temperature.hpp" #include "drawtypes/label.hpp" #include "drawtypes/ramp.hpp" #include "utils/file.hpp" #include "utils/math.hpp" #include <cmath> #include "modules/meta/base.inl" POLYBAR_NS namespace modules { template class module<temperature_module>; temperature_module::temperature_module(const bar_settings& bar, string name_) : timer_module<temperature_module>(bar, move(name_)) { m_zone = m_conf.get(name(), "thermal-zone", 0); m_path = m_conf.get(name(), "hwmon-path", ""s); m_tempwarn = m_conf.get(name(), "warn-temperature", 80); m_interval = m_conf.get<decltype(m_interval)>(name(), "interval", 1s); m_units = m_conf.get(name(), "units", m_units); if (m_path.empty()) { m_path = string_util::replace(PATH_TEMPERATURE_INFO, "%zone%", to_string(m_zone)); } if (!file_util::exists(m_path)) { throw module_error("The file '" + m_path + "' does not exist"); } m_formatter->add(DEFAULT_FORMAT, TAG_LABEL, {TAG_LABEL, TAG_RAMP}); m_formatter->add(FORMAT_WARN, TAG_LABEL_WARN, {TAG_LABEL_WARN, TAG_RAMP}); if (m_formatter->has(TAG_LABEL)) { m_label[temp_state::NORMAL] = load_optional_label(m_conf, name(), TAG_LABEL, "%temperature-c%"); } if (m_formatter->has(TAG_LABEL_WARN)) { m_label[temp_state::WARN] = load_optional_label(m_conf, name(), TAG_LABEL_WARN, "%temperature-c%"); } if (m_formatter->has(TAG_RAMP)) { m_ramp = load_ramp(m_conf, name(), TAG_RAMP); } // Deprecation warning for the %temperature% token if((m_label[temp_state::NORMAL] && m_label[temp_state::NORMAL]->has_token("%temperature%")) || ((m_label[temp_state::WARN] && m_label[temp_state::WARN]->has_token("%temperature%")))) { m_log.warn("%s: The token `%%temperature%%` is deprecated, use `%%temperature-c%%` instead.", name()); } } bool temperature_module::update() { m_temp = std::strtol(file_util::contents(m_path).c_str(), nullptr, 10) / 1000.0f + 0.5f; int m_temp_f = floor(((1.8 * m_temp) + 32) + 0.5); m_perc = math_util::cap(math_util::percentage(m_temp, 0, m_tempwarn), 0, 100); string temp_c_string = to_string(m_temp); string temp_f_string = to_string(m_temp_f); // Add units if `units = true` in config if(m_units) { temp_c_string += "°C"; temp_f_string += "°F"; } const auto replace_tokens = [&](label_t& label) { label->reset_tokens(); label->replace_token("%temperature-f%", temp_f_string); label->replace_token("%temperature-c%", temp_c_string); // DEPRECATED: Will be removed in later release label->replace_token("%temperature%", temp_c_string); }; if (m_label[temp_state::NORMAL]) { replace_tokens(m_label[temp_state::NORMAL]); } if (m_label[temp_state::WARN]) { replace_tokens(m_label[temp_state::WARN]); } return true; } string temperature_module::get_format() const { if (m_temp > m_tempwarn) { return FORMAT_WARN; } else { return DEFAULT_FORMAT; } } bool temperature_module::build(builder* builder, const string& tag) const { if (tag == TAG_LABEL) { builder->node(m_label.at(temp_state::NORMAL)); } else if (tag == TAG_LABEL_WARN) { builder->node(m_label.at(temp_state::WARN)); } else if (tag == TAG_RAMP) { builder->node(m_ramp->get_by_percentage(m_perc)); } else { return false; } return true; } } POLYBAR_NS_END <commit_msg>refactor(temperature): Do not use 'm_' prefix with local variable<commit_after>#include "modules/temperature.hpp" #include "drawtypes/label.hpp" #include "drawtypes/ramp.hpp" #include "utils/file.hpp" #include "utils/math.hpp" #include <cmath> #include "modules/meta/base.inl" POLYBAR_NS namespace modules { template class module<temperature_module>; temperature_module::temperature_module(const bar_settings& bar, string name_) : timer_module<temperature_module>(bar, move(name_)) { m_zone = m_conf.get(name(), "thermal-zone", 0); m_path = m_conf.get(name(), "hwmon-path", ""s); m_tempwarn = m_conf.get(name(), "warn-temperature", 80); m_interval = m_conf.get<decltype(m_interval)>(name(), "interval", 1s); m_units = m_conf.get(name(), "units", m_units); if (m_path.empty()) { m_path = string_util::replace(PATH_TEMPERATURE_INFO, "%zone%", to_string(m_zone)); } if (!file_util::exists(m_path)) { throw module_error("The file '" + m_path + "' does not exist"); } m_formatter->add(DEFAULT_FORMAT, TAG_LABEL, {TAG_LABEL, TAG_RAMP}); m_formatter->add(FORMAT_WARN, TAG_LABEL_WARN, {TAG_LABEL_WARN, TAG_RAMP}); if (m_formatter->has(TAG_LABEL)) { m_label[temp_state::NORMAL] = load_optional_label(m_conf, name(), TAG_LABEL, "%temperature-c%"); } if (m_formatter->has(TAG_LABEL_WARN)) { m_label[temp_state::WARN] = load_optional_label(m_conf, name(), TAG_LABEL_WARN, "%temperature-c%"); } if (m_formatter->has(TAG_RAMP)) { m_ramp = load_ramp(m_conf, name(), TAG_RAMP); } // Deprecation warning for the %temperature% token if((m_label[temp_state::NORMAL] && m_label[temp_state::NORMAL]->has_token("%temperature%")) || ((m_label[temp_state::WARN] && m_label[temp_state::WARN]->has_token("%temperature%")))) { m_log.warn("%s: The token `%%temperature%%` is deprecated, use `%%temperature-c%%` instead.", name()); } } bool temperature_module::update() { m_temp = std::strtol(file_util::contents(m_path).c_str(), nullptr, 10) / 1000.0f + 0.5f; int temp_f = floor(((1.8 * m_temp) + 32) + 0.5); m_perc = math_util::cap(math_util::percentage(m_temp, 0, m_tempwarn), 0, 100); string temp_c_string = to_string(m_temp); string temp_f_string = to_string(temp_f); // Add units if `units = true` in config if(m_units) { temp_c_string += "°C"; temp_f_string += "°F"; } const auto replace_tokens = [&](label_t& label) { label->reset_tokens(); label->replace_token("%temperature-f%", temp_f_string); label->replace_token("%temperature-c%", temp_c_string); // DEPRECATED: Will be removed in later release label->replace_token("%temperature%", temp_c_string); }; if (m_label[temp_state::NORMAL]) { replace_tokens(m_label[temp_state::NORMAL]); } if (m_label[temp_state::WARN]) { replace_tokens(m_label[temp_state::WARN]); } return true; } string temperature_module::get_format() const { if (m_temp > m_tempwarn) { return FORMAT_WARN; } else { return DEFAULT_FORMAT; } } bool temperature_module::build(builder* builder, const string& tag) const { if (tag == TAG_LABEL) { builder->node(m_label.at(temp_state::NORMAL)); } else if (tag == TAG_LABEL_WARN) { builder->node(m_label.at(temp_state::WARN)); } else if (tag == TAG_RAMP) { builder->node(m_ramp->get_by_percentage(m_perc)); } else { return false; } return true; } } POLYBAR_NS_END <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: imagemgr.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: kz $ $Date: 2005-01-21 12:49:41 $ * * 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 "sal/config.h" #include "imagemgr.hxx" #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_ #include <com/sun/star/frame/XController.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_UI_XIMAGEMANAGER_HPP_ #include <drafts/com/sun/star/ui/XImageManager.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_ #include <drafts/com/sun/star/frame/XModuleManager.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_UI_XMODULEUICONFIGURATIONMANAGERSUPPLIER_HPP_ #include <drafts/com/sun/star/ui/XModuleUIConfigurationManagerSupplier.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_UI_IMAGETYPE_HPP_ #include <drafts/com/sun/star/ui/ImageType.hpp> #endif #ifndef _DRAFTS_COM_SUN_STAR_UI_XUICONFIGURATIONMANAGERSUPPLIER_HPP_ #include <drafts/com/sun/star/ui/XUIConfigurationManagerSupplier.hpp> #endif #include <tools/urlobj.hxx> #include <svtools/imagemgr.hxx> #include <comphelper/processfactory.hxx> #include <rtl/ustring.hxx> #ifndef _RTL_LOGFILE_HXX_ #include <rtl/logfile.hxx> #endif #include "imgmgr.hxx" #include "app.hxx" #include "unoctitm.hxx" #include "dispatch.hxx" #include "msg.hxx" #include "msgpool.hxx" #include "viewfrm.hxx" #include "module.hxx" #include "objsh.hxx" #include "docfac.hxx" using namespace ::com::sun::star::uno; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; using namespace ::drafts::com::sun::star::ui; using namespace ::drafts::com::sun::star::frame; typedef std::hash_map< ::rtl::OUString, WeakReference< XImageManager >, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > ModuleIdToImagegMgr; static WeakReference< XModuleManager > m_xModuleManager; static WeakReference< XModuleUIConfigurationManagerSupplier > m_xModuleCfgMgrSupplier; static WeakReference< XURLTransformer > m_xURLTransformer; static ModuleIdToImagegMgr m_aModuleIdToImageMgrMap; Image SAL_CALL GetImage( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& aURL, BOOL bBig, BOOL bHiContrast ) { // TODO/LATeR: shouldn't this become a method at SfxViewFrame?! That would save the UnoTunnel if ( !rFrame.is() ) return Image(); INetURLObject aObj( aURL ); INetProtocol nProtocol = aObj.GetProtocol(); Reference < XController > xController; Reference < XModel > xModel; if ( rFrame.is() ) xController = rFrame->getController(); if ( xController.is() ) xModel = xController->getModel(); rtl::OUString aCommandURL( aURL ); if ( nProtocol == INET_PROT_SLOT ) { /* // Support old way to retrieve image via slot URL Reference< XURLTransformer > xURLTransformer = m_xURLTransformer; if ( !xURLTransformer.is() ) { xURLTransformer = Reference< XURLTransformer >( ::comphelper::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer" )), UNO_QUERY ); m_xURLTransformer = xURLTransformer; } URL aTargetURL; aTargetURL.Complete = aURL; xURLTransformer->parseStrict( aTargetURL ); USHORT nId = ( USHORT ) aTargetURL.Path.toInt32();*/ USHORT nId = ( USHORT ) String(aURL).Copy(5).ToInt32(); const SfxSlot* pSlot = 0; if ( xModel.is() ) { Reference < XUnoTunnel > xObj( xModel, UNO_QUERY ); Sequence < sal_Int8 > aSeq( SvGlobalName( SFX_GLOBAL_CLASSID ).GetByteSequence() ); sal_Int64 nHandle = xObj.is() ? xObj->getSomething( aSeq ) : 0; if ( nHandle ) { SfxObjectShell* pDoc = (SfxObjectShell*) (sal_Int32*) nHandle; SfxModule* pModule = pDoc->GetFactory().GetModule(); pSlot = pModule->GetSlotPool()->GetSlot( nId ); } } else pSlot = SFX_APP()->GetSlotPool().GetSlot( nId ); if ( pSlot ) { aCommandURL = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:" )); aCommandURL += rtl::OUString::createFromAscii( pSlot->GetUnoName() ); } else aCommandURL = rtl::OUString(); } Reference< XImageManager > xDocImgMgr; if ( xModel.is() ) { Reference< XUIConfigurationManagerSupplier > xSupplier( xModel, UNO_QUERY ); if ( xSupplier.is() ) { Reference< XUIConfigurationManager > xDocUICfgMgr( xSupplier->getUIConfigurationManager(), UNO_QUERY ); xDocImgMgr = Reference< XImageManager >( xDocUICfgMgr->getImageManager(), UNO_QUERY ); } } sal_Int16 nImageType( ::drafts::com::sun::star::ui::ImageType::COLOR_NORMAL| ::drafts::com::sun::star::ui::ImageType::SIZE_DEFAULT ); if ( bBig ) nImageType |= ::drafts::com::sun::star::ui::ImageType::SIZE_LARGE; if ( bHiContrast ) nImageType |= ::drafts::com::sun::star::ui::ImageType::COLOR_HIGHCONTRAST; if ( xDocImgMgr.is() ) { Sequence< Reference< ::com::sun::star::graphic::XGraphic > > aGraphicSeq; Sequence< rtl::OUString > aImageCmdSeq( 1 ); aImageCmdSeq[0] = aCommandURL; try { aGraphicSeq = xDocImgMgr->getImages( nImageType, aImageCmdSeq ); Reference< ::com::sun::star::graphic::XGraphic > xGraphic = aGraphicSeq[0]; Image aImage( xGraphic ); if ( !!aImage ) return aImage; } catch ( Exception& ) { } } Reference< XModuleManager > xModuleManager = m_xModuleManager; if ( !xModuleManager.is() ) { xModuleManager = Reference< XModuleManager >( ::comphelper::getProcessServiceFactory()->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "drafts.com.sun.star.frame.ModuleManager" ))), UNO_QUERY ); m_xModuleManager = xModuleManager; } try { if ( aCommandURL.getLength() > 0 ) { Reference< XImageManager > xModuleImageManager; rtl::OUString aModuleId = xModuleManager->identify( rFrame ); ModuleIdToImagegMgr::iterator pIter = m_aModuleIdToImageMgrMap.find( aModuleId ); if ( pIter != m_aModuleIdToImageMgrMap.end() ) xModuleImageManager = pIter->second; else { Reference< XModuleUIConfigurationManagerSupplier > xModuleCfgMgrSupplier = m_xModuleCfgMgrSupplier; if ( !xModuleCfgMgrSupplier.is() ) { xModuleCfgMgrSupplier = Reference< XModuleUIConfigurationManagerSupplier >( ::comphelper::getProcessServiceFactory()->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "drafts.com.sun.star.ui.ModuleUIConfigurationManagerSupplier" ))), UNO_QUERY ); m_xModuleCfgMgrSupplier = xModuleCfgMgrSupplier; } Reference< XUIConfigurationManager > xUICfgMgr = xModuleCfgMgrSupplier->getUIConfigurationManager( aModuleId ); xModuleImageManager = Reference< XImageManager >( xUICfgMgr->getImageManager(), UNO_QUERY ); m_aModuleIdToImageMgrMap.insert( ModuleIdToImagegMgr::value_type( aModuleId, xModuleImageManager )); } sal_Int16 nImageType( ::drafts::com::sun::star::ui::ImageType::COLOR_NORMAL| ::drafts::com::sun::star::ui::ImageType::SIZE_DEFAULT ); if ( bBig ) nImageType |= ::drafts::com::sun::star::ui::ImageType::SIZE_LARGE; if ( bHiContrast ) nImageType |= ::drafts::com::sun::star::ui::ImageType::COLOR_HIGHCONTRAST; Sequence< Reference< ::com::sun::star::graphic::XGraphic > > aGraphicSeq; Sequence< rtl::OUString > aImageCmdSeq( 1 ); aImageCmdSeq[0] = aCommandURL; aGraphicSeq = xModuleImageManager->getImages( nImageType, aImageCmdSeq ); Reference< ::com::sun::star::graphic::XGraphic > xGraphic = aGraphicSeq[0]; Image aImage( xGraphic ); if ( !!aImage ) return aImage; else if ( nProtocol != INET_PROT_UNO && nProtocol != INET_PROT_SLOT ) return SvFileInformationManager::GetImageNoDefault( aObj, bBig, bHiContrast ); } } catch ( Exception& ) { } return Image(); } <commit_msg>INTEGRATION: CWS removedrafts (1.12.46); FILE MERGED 2005/02/17 14:02:11 cd 1.12.46.1: #i42557# Move UNOIDL types from drafts to com<commit_after>/************************************************************************* * * $RCSfile: imagemgr.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: kz $ $Date: 2005-03-01 19:57:56 $ * * 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 "sal/config.h" #include "imagemgr.hxx" #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_ #include <com/sun/star/frame/XController.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_UI_XIMAGEMANAGER_HPP_ #include <com/sun/star/ui/XImageManager.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODULEMANAGER_HPP_ #include <com/sun/star/frame/XModuleManager.hpp> #endif #ifndef _COM_SUN_STAR_UI_XMODULEUICONFIGURATIONMANAGERSUPPLIER_HPP_ #include <com/sun/star/ui/XModuleUIConfigurationManagerSupplier.hpp> #endif #ifndef _COM_SUN_STAR_UI_IMAGETYPE_HPP_ #include <com/sun/star/ui/ImageType.hpp> #endif #ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONMANAGERSUPPLIER_HPP_ #include <com/sun/star/ui/XUIConfigurationManagerSupplier.hpp> #endif #include <tools/urlobj.hxx> #include <svtools/imagemgr.hxx> #include <comphelper/processfactory.hxx> #include <rtl/ustring.hxx> #ifndef _RTL_LOGFILE_HXX_ #include <rtl/logfile.hxx> #endif #include "imgmgr.hxx" #include "app.hxx" #include "unoctitm.hxx" #include "dispatch.hxx" #include "msg.hxx" #include "msgpool.hxx" #include "viewfrm.hxx" #include "module.hxx" #include "objsh.hxx" #include "docfac.hxx" using namespace ::com::sun::star::uno; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::util; using namespace ::com::sun::star::ui; using namespace ::com::sun::star::frame; typedef std::hash_map< ::rtl::OUString, WeakReference< XImageManager >, ::rtl::OUStringHash, ::std::equal_to< ::rtl::OUString > > ModuleIdToImagegMgr; static WeakReference< XModuleManager > m_xModuleManager; static WeakReference< XModuleUIConfigurationManagerSupplier > m_xModuleCfgMgrSupplier; static WeakReference< XURLTransformer > m_xURLTransformer; static ModuleIdToImagegMgr m_aModuleIdToImageMgrMap; Image SAL_CALL GetImage( ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, const ::rtl::OUString& aURL, BOOL bBig, BOOL bHiContrast ) { // TODO/LATeR: shouldn't this become a method at SfxViewFrame?! That would save the UnoTunnel if ( !rFrame.is() ) return Image(); INetURLObject aObj( aURL ); INetProtocol nProtocol = aObj.GetProtocol(); Reference < XController > xController; Reference < XModel > xModel; if ( rFrame.is() ) xController = rFrame->getController(); if ( xController.is() ) xModel = xController->getModel(); rtl::OUString aCommandURL( aURL ); if ( nProtocol == INET_PROT_SLOT ) { /* // Support old way to retrieve image via slot URL Reference< XURLTransformer > xURLTransformer = m_xURLTransformer; if ( !xURLTransformer.is() ) { xURLTransformer = Reference< XURLTransformer >( ::comphelper::getProcessServiceFactory()->createInstance( rtl::OUString::createFromAscii("com.sun.star.util.URLTransformer" )), UNO_QUERY ); m_xURLTransformer = xURLTransformer; } URL aTargetURL; aTargetURL.Complete = aURL; xURLTransformer->parseStrict( aTargetURL ); USHORT nId = ( USHORT ) aTargetURL.Path.toInt32();*/ USHORT nId = ( USHORT ) String(aURL).Copy(5).ToInt32(); const SfxSlot* pSlot = 0; if ( xModel.is() ) { Reference < XUnoTunnel > xObj( xModel, UNO_QUERY ); Sequence < sal_Int8 > aSeq( SvGlobalName( SFX_GLOBAL_CLASSID ).GetByteSequence() ); sal_Int64 nHandle = xObj.is() ? xObj->getSomething( aSeq ) : 0; if ( nHandle ) { SfxObjectShell* pDoc = (SfxObjectShell*) (sal_Int32*) nHandle; SfxModule* pModule = pDoc->GetFactory().GetModule(); pSlot = pModule->GetSlotPool()->GetSlot( nId ); } } else pSlot = SFX_APP()->GetSlotPool().GetSlot( nId ); if ( pSlot ) { aCommandURL = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:" )); aCommandURL += rtl::OUString::createFromAscii( pSlot->GetUnoName() ); } else aCommandURL = rtl::OUString(); } Reference< XImageManager > xDocImgMgr; if ( xModel.is() ) { Reference< XUIConfigurationManagerSupplier > xSupplier( xModel, UNO_QUERY ); if ( xSupplier.is() ) { Reference< XUIConfigurationManager > xDocUICfgMgr( xSupplier->getUIConfigurationManager(), UNO_QUERY ); xDocImgMgr = Reference< XImageManager >( xDocUICfgMgr->getImageManager(), UNO_QUERY ); } } sal_Int16 nImageType( ::com::sun::star::ui::ImageType::COLOR_NORMAL| ::com::sun::star::ui::ImageType::SIZE_DEFAULT ); if ( bBig ) nImageType |= ::com::sun::star::ui::ImageType::SIZE_LARGE; if ( bHiContrast ) nImageType |= ::com::sun::star::ui::ImageType::COLOR_HIGHCONTRAST; if ( xDocImgMgr.is() ) { Sequence< Reference< ::com::sun::star::graphic::XGraphic > > aGraphicSeq; Sequence< rtl::OUString > aImageCmdSeq( 1 ); aImageCmdSeq[0] = aCommandURL; try { aGraphicSeq = xDocImgMgr->getImages( nImageType, aImageCmdSeq ); Reference< ::com::sun::star::graphic::XGraphic > xGraphic = aGraphicSeq[0]; Image aImage( xGraphic ); if ( !!aImage ) return aImage; } catch ( Exception& ) { } } Reference< XModuleManager > xModuleManager = m_xModuleManager; if ( !xModuleManager.is() ) { xModuleManager = Reference< XModuleManager >( ::comphelper::getProcessServiceFactory()->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.frame.ModuleManager" ))), UNO_QUERY ); m_xModuleManager = xModuleManager; } try { if ( aCommandURL.getLength() > 0 ) { Reference< XImageManager > xModuleImageManager; rtl::OUString aModuleId = xModuleManager->identify( rFrame ); ModuleIdToImagegMgr::iterator pIter = m_aModuleIdToImageMgrMap.find( aModuleId ); if ( pIter != m_aModuleIdToImageMgrMap.end() ) xModuleImageManager = pIter->second; else { Reference< XModuleUIConfigurationManagerSupplier > xModuleCfgMgrSupplier = m_xModuleCfgMgrSupplier; if ( !xModuleCfgMgrSupplier.is() ) { xModuleCfgMgrSupplier = Reference< XModuleUIConfigurationManagerSupplier >( ::comphelper::getProcessServiceFactory()->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.ui.ModuleUIConfigurationManagerSupplier" ))), UNO_QUERY ); m_xModuleCfgMgrSupplier = xModuleCfgMgrSupplier; } Reference< XUIConfigurationManager > xUICfgMgr = xModuleCfgMgrSupplier->getUIConfigurationManager( aModuleId ); xModuleImageManager = Reference< XImageManager >( xUICfgMgr->getImageManager(), UNO_QUERY ); m_aModuleIdToImageMgrMap.insert( ModuleIdToImagegMgr::value_type( aModuleId, xModuleImageManager )); } sal_Int16 nImageType( ::com::sun::star::ui::ImageType::COLOR_NORMAL| ::com::sun::star::ui::ImageType::SIZE_DEFAULT ); if ( bBig ) nImageType |= ::com::sun::star::ui::ImageType::SIZE_LARGE; if ( bHiContrast ) nImageType |= ::com::sun::star::ui::ImageType::COLOR_HIGHCONTRAST; Sequence< Reference< ::com::sun::star::graphic::XGraphic > > aGraphicSeq; Sequence< rtl::OUString > aImageCmdSeq( 1 ); aImageCmdSeq[0] = aCommandURL; aGraphicSeq = xModuleImageManager->getImages( nImageType, aImageCmdSeq ); Reference< ::com::sun::star::graphic::XGraphic > xGraphic = aGraphicSeq[0]; Image aImage( xGraphic ); if ( !!aImage ) return aImage; else if ( nProtocol != INET_PROT_UNO && nProtocol != INET_PROT_SLOT ) return SvFileInformationManager::GetImageNoDefault( aObj, bBig, bHiContrast ); } } catch ( Exception& ) { } return Image(); } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011-2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include "Warnings.hpp" #include "Options.hpp" #include "mtac/WarningsEngine.hpp" #include "mtac/Program.hpp" using namespace eddic; void mtac::collect_warnings(mtac::Program& program, std::shared_ptr<Configuration> configuration){ if(configuration->option_defined("warning-unused")){ for(auto& function : program.functions){ if(program.call_graph.node(function.definition())->in_edges.size() == 0){ warn("Unused function: " + function.get_name()); } } } } <commit_msg>No unused warning for main<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011-2013. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include "Warnings.hpp" #include "Options.hpp" #include "mtac/WarningsEngine.hpp" #include "mtac/Program.hpp" using namespace eddic; void mtac::collect_warnings(mtac::Program& program, std::shared_ptr<Configuration> configuration){ if(configuration->option_defined("warning-unused")){ for(auto& function : program.functions){ if(program.call_graph.node(function.definition())->in_edges.size() == 0 && !function.is_main()){ warn("Unused function: " + function.get_name()); } } } } <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 - 2022 by Apex.AI Inc. 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. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_HOOFS_CXX_UNIQUE_PTR_INL #define IOX_HOOFS_CXX_UNIQUE_PTR_INL #include "iceoryx_hoofs/cxx/unique_ptr.hpp" namespace iox { namespace cxx { template <typename T> inline unique_ptr<T>::unique_ptr(T* const object, const function<void(T*)>& deleter) noexcept : m_ptr(object) , m_deleter(std::move(deleter)) { Ensures(object != nullptr); } template <typename T> inline unique_ptr<T>& unique_ptr<T>::operator=(unique_ptr&& rhs) noexcept { if (this != &rhs) { destroy(); m_ptr = rhs.m_ptr; m_deleter = rhs.m_deleter; rhs.m_ptr = nullptr; } return *this; } template <typename T> inline unique_ptr<T>::unique_ptr(unique_ptr&& rhs) noexcept : m_ptr{rhs.m_ptr} , m_deleter{rhs.m_deleter} { rhs.m_ptr = nullptr; } template <typename T> inline unique_ptr<T>::~unique_ptr() noexcept { destroy(); } template <typename T> inline T* unique_ptr<T>::operator->() noexcept { cxx::Expects(m_ptr != nullptr); return get(); } template <typename T> inline const T* unique_ptr<T>::operator->() const noexcept { // Avoid code duplication // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return const_cast<unique_ptr<T>*>(this)->operator->(); } template <typename T> inline T* unique_ptr<T>::get() noexcept { return m_ptr; } template <typename T> inline const T* unique_ptr<T>::get() const noexcept { // AXIVION Next Construct AutosarC++19_03-A5.2.3 : Avoid code duplication // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return const_cast<unique_ptr<T>*>(this)->get(); } template <typename T> inline T* unique_ptr<T>::release(unique_ptr&& ptrToBeReleased) noexcept { auto ptr = ptrToBeReleased.m_ptr; ptrToBeReleased.m_ptr = nullptr; return ptr; } template <typename T> inline void unique_ptr<T>::reset(T* const ptr) noexcept { Ensures(ptr != nullptr); destroy(); m_ptr = ptr; } template <typename T> inline void unique_ptr<T>::destroy() noexcept { if (m_ptr) { m_deleter(m_ptr); } m_ptr = nullptr; } template <typename T> inline void unique_ptr<T>::swap(unique_ptr<T>& other) noexcept { std::swap(m_ptr, other.m_ptr); std::swap(m_deleter, other.m_deleter); } template <typename T, typename U> inline bool operator==(const unique_ptr<T>& lhs, const unique_ptr<U>& rhs) noexcept { return lhs.get() == rhs.get(); } template <typename T, typename U> inline bool operator!=(const unique_ptr<T>& lhs, const unique_ptr<U>& rhs) noexcept { return !(lhs == rhs); } } // namespace cxx } // namespace iox #endif // IOX_HOOFS_CXX_UNIQUE_PTR_INL <commit_msg>iox-#1104 Add std::move in move operation<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 - 2022 by Apex.AI Inc. 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. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_HOOFS_CXX_UNIQUE_PTR_INL #define IOX_HOOFS_CXX_UNIQUE_PTR_INL #include "iceoryx_hoofs/cxx/unique_ptr.hpp" namespace iox { namespace cxx { template <typename T> inline unique_ptr<T>::unique_ptr(T* const object, const function<void(T*)>& deleter) noexcept : m_ptr(object) , m_deleter(std::move(deleter)) { Ensures(object != nullptr); } template <typename T> inline unique_ptr<T>& unique_ptr<T>::operator=(unique_ptr&& rhs) noexcept { if (this != &rhs) { destroy(); m_ptr = rhs.m_ptr; m_deleter = std::move(rhs.m_deleter); rhs.m_ptr = nullptr; } return *this; } template <typename T> inline unique_ptr<T>::unique_ptr(unique_ptr&& rhs) noexcept : m_ptr{rhs.m_ptr} , m_deleter{rhs.m_deleter} { rhs.m_ptr = nullptr; } template <typename T> inline unique_ptr<T>::~unique_ptr() noexcept { destroy(); } template <typename T> inline T* unique_ptr<T>::operator->() noexcept { cxx::Expects(m_ptr != nullptr); return get(); } template <typename T> inline const T* unique_ptr<T>::operator->() const noexcept { // Avoid code duplication // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return const_cast<unique_ptr<T>*>(this)->operator->(); } template <typename T> inline T* unique_ptr<T>::get() noexcept { return m_ptr; } template <typename T> inline const T* unique_ptr<T>::get() const noexcept { // AXIVION Next Construct AutosarC++19_03-A5.2.3 : Avoid code duplication // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return const_cast<unique_ptr<T>*>(this)->get(); } template <typename T> inline T* unique_ptr<T>::release(unique_ptr&& ptrToBeReleased) noexcept { auto ptr = ptrToBeReleased.m_ptr; ptrToBeReleased.m_ptr = nullptr; return ptr; } template <typename T> inline void unique_ptr<T>::reset(T* const ptr) noexcept { Ensures(ptr != nullptr); destroy(); m_ptr = ptr; } template <typename T> inline void unique_ptr<T>::destroy() noexcept { if (m_ptr) { m_deleter(m_ptr); } m_ptr = nullptr; } template <typename T> inline void unique_ptr<T>::swap(unique_ptr<T>& other) noexcept { std::swap(m_ptr, other.m_ptr); std::swap(m_deleter, other.m_deleter); } template <typename T, typename U> inline bool operator==(const unique_ptr<T>& lhs, const unique_ptr<U>& rhs) noexcept { return lhs.get() == rhs.get(); } template <typename T, typename U> inline bool operator!=(const unique_ptr<T>& lhs, const unique_ptr<U>& rhs) noexcept { return !(lhs == rhs); } } // namespace cxx } // namespace iox #endif // IOX_HOOFS_CXX_UNIQUE_PTR_INL <|endoftext|>
<commit_before>/* * File: property.cc * Author: ruehle * * Created on November 13, 2008, 5:54 PM */ #include <libxml/parser.h> #include <iostream> #include "property.h" #include <stdexcept> #include "tokenizer.h" Property &Property::get(const string &key) { Tokenizer tok(key, "."); Tokenizer::iterator n; n = tok.begin(); map<string, Property*>::iterator iter; iter = _map.find(*n); if(iter == _map.end()) throw runtime_error("property not found: " + key); Property *p(((*iter).second)); ++n; try { for(; n!=tok.end(); ++n) p = &p->get(*n); } catch(string err) { // catch here to get full key in exception throw runtime_error("property not found: " + key); } return *p; } std::list<Property *> Property::Select(const string &filter) { Tokenizer tok(filter, "."); std::list<Property *> selection; if(tok.begin()==tok.end()) return selection; selection.push_back(this); for (Tokenizer::iterator n = tok.begin(); n != tok.end(); ++n) { std::list<Property *> childs; for (std::list<Property *>::iterator p = selection.begin(); p != selection.end(); ++p) { for (list<Property>::iterator iter = (*p)->_properties.begin(); iter != (*p)->_properties.end(); ++iter) { if (wildcmp((*n).c_str(), (*iter).name().c_str())) { childs.push_back(&(*iter)); } } } selection = childs; } return selection; } void Property::PrintNode(std::ostream &out, const string &prefix, Property &p) { map<string, Property*>::iterator iter; if((p._value != "") || p.HasChilds()) out << prefix << " = " << p._value << endl; for(iter = p._map.begin(); iter!=p._map.end(); ++iter) { if(prefix=="") PrintNode(out, prefix + (*iter).first, *(*iter).second); else PrintNode(out, prefix + "." + (*iter).first, *(*iter).second); } } static void parse_node(Property &p, xmlDocPtr doc, xmlNodePtr cur) { xmlChar *key; key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1); string value(""); if(key) value = (const char *)key; // \todo test if unique Property &np = p.add((const char *)cur->name, value); xmlFree(key); for(xmlNodePtr node = cur->xmlChildrenNode; node != NULL; node = node->next) { if (node->type == XML_ELEMENT_NODE) parse_node(np, doc, node); } } bool load_property_from_xml(Property &p, string filename) { xmlDocPtr doc; xmlNodePtr node; xmlChar *key; doc = xmlParseFile(filename.c_str()); if(doc == NULL) throw std::ios_base::failure("Error on open xml bead map: " + filename); node = xmlDocGetRootElement(doc); if(node == NULL) { xmlFreeDoc(doc); throw std::invalid_argument("Error, empty xml document: " + filename); } //if(xmlStrcmp(node->name, (const xmlChar *)"cg_molecule")) { // xmlFreeDoc(doc); // throw std::invalid_argument("Error, in xml file: " + filename); //} // parse xml tree parse_node(p, doc, node); // free the document xmlFreeDoc(doc); xmlCleanupParser(); } std::ostream &operator<<(std::ostream &out, Property& p) { Property::PrintNode(out, "", p); return out; } <commit_msg>better property get<commit_after>/* * File: property.cc * Author: ruehle * * Created on November 13, 2008, 5:54 PM */ #include <libxml/parser.h> #include <iostream> #include "property.h" #include <stdexcept> #include "tokenizer.h" Property &Property::get(const string &key) { Tokenizer tok(key, "."); Tokenizer::iterator n; n = tok.begin(); if(n==tok.end()) return *this; Property *p; map<string, Property*>::iterator iter; if(*n=="") { p = this; } else { iter = _map.find(*n); if(iter == _map.end()) throw runtime_error("property not found: " + key); p = (((*iter).second)); } ++n; try { for(; n!=tok.end(); ++n) { p = &p->get(*n); cout << "tok <" << *n << ">" << endl; } } catch(string err) { // catch here to get full key in exception throw runtime_error("property not found: " + key); } return *p; } std::list<Property *> Property::Select(const string &filter) { Tokenizer tok(filter, "."); std::list<Property *> selection; if(tok.begin()==tok.end()) return selection; selection.push_back(this); for (Tokenizer::iterator n = tok.begin(); n != tok.end(); ++n) { std::list<Property *> childs; for (std::list<Property *>::iterator p = selection.begin(); p != selection.end(); ++p) { for (list<Property>::iterator iter = (*p)->_properties.begin(); iter != (*p)->_properties.end(); ++iter) { if (wildcmp((*n).c_str(), (*iter).name().c_str())) { childs.push_back(&(*iter)); } } } selection = childs; } return selection; } void Property::PrintNode(std::ostream &out, const string &prefix, Property &p) { map<string, Property*>::iterator iter; if((p._value != "") || p.HasChilds()) out << prefix << " = " << p._value << endl; for(iter = p._map.begin(); iter!=p._map.end(); ++iter) { if(prefix=="") PrintNode(out, prefix + (*iter).first, *(*iter).second); else PrintNode(out, prefix + "." + (*iter).first, *(*iter).second); } } static void parse_node(Property &p, xmlDocPtr doc, xmlNodePtr cur) { xmlChar *key; key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1); string value(""); if(key) value = (const char *)key; // \todo test if unique Property &np = p.add((const char *)cur->name, value); xmlFree(key); for(xmlNodePtr node = cur->xmlChildrenNode; node != NULL; node = node->next) { if (node->type == XML_ELEMENT_NODE) parse_node(np, doc, node); } } bool load_property_from_xml(Property &p, string filename) { xmlDocPtr doc; xmlNodePtr node; xmlChar *key; doc = xmlParseFile(filename.c_str()); if(doc == NULL) throw std::ios_base::failure("Error on open xml bead map: " + filename); node = xmlDocGetRootElement(doc); if(node == NULL) { xmlFreeDoc(doc); throw std::invalid_argument("Error, empty xml document: " + filename); } //if(xmlStrcmp(node->name, (const xmlChar *)"cg_molecule")) { // xmlFreeDoc(doc); // throw std::invalid_argument("Error, in xml file: " + filename); //} // parse xml tree parse_node(p, doc, node); // free the document xmlFreeDoc(doc); xmlCleanupParser(); } std::ostream &operator<<(std::ostream &out, Property& p) { Property::PrintNode(out, "", p); return out; } <|endoftext|>
<commit_before>/****************************************************************************/ /* Copyright 2005-2008, Francis Russell */ /* */ /* 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 DESOLIN_ITL_BLAS_INTERFACE_HPP #define DESOLIN_ITL_BLAS_INTERFACE_HPP #include <cassert> #include <complex> #include <itl/itl_tags.h> #include <itl/number_traits.h> namespace itl { using desolin::blas_wrappers::BLASVector; using desolin::blas_wrappers::BLASGeneralMatrix; //: The vector type used inside of the ITL routines for work space template <typename Vec> struct itl_traits { // TODO: Work out what this does before allowing it to be defined. //typedef referencing_object_tag vector_category; typedef typename Vec::value_type value_type; typedef typename Vec::size_type size_type; }; template <class Vec> struct Scaled { typedef typename Vec::value_type T; inline Scaled(const Vec& v, const T& alpha) : _alpha(alpha), _v(v) { } inline T alpha() const { return _alpha; } inline const Vec& vec() const { return _v; } inline int nrows() const { return _v.nrows(); } protected: T _alpha; const Vec _v; }; // Getting the scaling factor for scaled and unscaled vectors template<typename Vec> inline typename Vec::value_type scale_factor(const Vec& v) { return static_cast<typename Vec::value_type>(1.0); } template<typename Vec> inline typename Vec::value_type scale_factor(const Scaled<Vec>& s) { return s.alpha(); } // Getting the data for scaled and unscaled vectors template<typename Vec> inline typename Vec::value_type* get_data(Vec& v) { return v.data(); } template<typename Vec> inline const typename Vec::value_type* get_data(const Vec& v) { return v.data(); } template<typename Vec> inline const typename Vec::value_type* get_data(const Scaled<Vec>& s) { return s.vec().data(); } // ITL interface implementation inline void copy(const BLASVector<double>& a, BLASVector<double>& b) { cblas_dcopy(a.nrows(), a.data(), 1, b.data(), 1); } inline void copy(const Scaled< BLASVector<double> >& a, BLASVector<double>& b) { cblas_dcopy(a.nrows(), a.vec().data(), 1, b.data(), 1); cblas_dscal(b.nrows(), a.alpha(), b.data(), 1); } inline double dot(const BLASVector<double>& a, const BLASVector<double>& b) { return cblas_ddot(a.nrows(), a.data(), 1, b.data(), 1); } inline double dot_conj(const BLASVector<double>& a, const BLASVector<double>& b) { return cblas_ddot(a.nrows(), a.data(), 1, b.data(), 1); } inline double two_norm(const BLASVector<double>& v) { return cblas_dnrm2(v.nrows(), v.data(), 1); } template<typename VecX> inline void add(const VecX& x, BLASVector<double>& y) { cblas_daxpy(x.nrows(), scale_factor(x), get_data(x), 1, y.data(), 1); } template<typename VecX, typename VecY> inline void add(const VecX& x, const VecY& y, BLASVector<double>& z) { itl::copy(x, z); itl::add(y, z); } template<typename VecX, typename VecY, typename VecZ> inline void add(const VecX& x, const VecY& y, const VecZ& z, BLASVector<double>& r) { itl::copy(x, r); itl::add(y, r); itl::add(z, r); } template<typename VecX> inline void mult(const BLASGeneralMatrix<double>& A, const VecX& x, BLASVector<double>& y) { cblas_dgemv(CblasRowMajor, CblasNoTrans, A.nrows(), A.ncols(), scale_factor(x), A.data(), A.ncols(), get_data(x), 1, 0.0, y.data(), 1); } template<typename VecX, typename VecY> inline void mult(const BLASGeneralMatrix<double>& A, const VecX& x, const VecY& y, BLASVector<double>& z) { cblas_dcopy(y.nrows(), y.data(), 1, z.data(), 1); cblas_dgemv(CblasRowMajor, CblasNoTrans, A.nrows(), A.ncols(), scale_factor(x), A.data(), A.ncols(), get_data(x), 1, scale_factor(y), z.data(), 1); } template <class VecX> inline void trans_mult(const BLASGeneralMatrix<double>& A, const VecX& x, BLASVector<double>& y) { cblas_dgemv(CblasRowMajor, CblasTrans, A.nrows(), A.ncols(), scale_factor(x), A.data(), A.ncols(), get_data(x), 1, 0.0, y.data(), 1); } inline void scale(BLASVector<double>& s, const itl_traits< BLASVector<double> >::value_type& alpha) { cblas_dscal(s.nrows(), alpha, s.data(), 1); } inline Scaled< BLASVector<double> > scaled(const BLASVector<double>& s, const itl_traits< BLASVector<double> >::value_type& alpha) { return Scaled< BLASVector<double> >(s, alpha); } template<typename T> inline typename BLASVector<T>::size_type size(const BLASVector<T>& x) { return x.nrows(); } // Only define this when semantics are understood /* template <class Vector> inline void resize(Vector& x, const int sz) { x.resize(sz); } */ } #endif <commit_msg>propagate from branch 'uk.co.unchartedbackwaters.desolin.sparse' (head 9138ea68b7b129b15340f2c1d7fc4cea6aea59e9) to branch 'uk.co.unchartedbackwaters.desolin' (head 9cae03e2742bca5d2863a6a21f61e57c3d5317b7)<commit_after>/****************************************************************************/ /* Copyright 2005-2008, Francis Russell */ /* */ /* 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 DESOLIN_ITL_BLAS_INTERFACE_HPP #define DESOLIN_ITL_BLAS_INTERFACE_HPP #include <cassert> #include <complex> #include <itl/itl_tags.h> #include <itl/number_traits.h> namespace itl { using desolin::blas_wrappers::BLASVector; using desolin::blas_wrappers::BLASGeneralMatrix; //: The vector type used inside of the ITL routines for work space template <typename Vec> struct itl_traits { // TODO: Work out what this does before allowing it to be defined. //typedef referencing_object_tag vector_category; typedef typename Vec::value_type value_type; typedef typename Vec::size_type size_type; }; template <class Vec> struct Scaled { typedef typename Vec::value_type T; inline Scaled(const Vec& v, const T& alpha) : _alpha(alpha), _v(v) { } inline T alpha() const { return _alpha; } inline const Vec& vec() const { return _v; } inline int nrows() const { return _v.nrows(); } protected: T _alpha; const Vec _v; }; // Getting the scaling factor for scaled and unscaled vectors template<typename Vec> inline typename Vec::value_type scale_factor(const Vec& v) { return static_cast<typename Vec::value_type>(1.0); } template<typename Vec> inline typename Vec::value_type scale_factor(const Scaled<Vec>& s) { return s.alpha(); } // Getting the data for scaled and unscaled vectors template<typename Vec> inline typename Vec::value_type* get_data(Vec& v) { return v.data(); } template<typename Vec> inline const typename Vec::value_type* get_data(const Vec& v) { return v.data(); } template<typename Vec> inline const typename Vec::value_type* get_data(const Scaled<Vec>& s) { return s.vec().data(); } // ITL interface implementation inline void copy(const BLASVector<double>& a, BLASVector<double>& b) { cblas_dcopy(a.nrows(), a.data(), 1, b.data(), 1); } inline void copy(const Scaled< BLASVector<double> >& a, BLASVector<double>& b) { cblas_dcopy(a.nrows(), a.vec().data(), 1, b.data(), 1); cblas_dscal(b.nrows(), a.alpha(), b.data(), 1); } inline double dot(const BLASVector<double>& a, const BLASVector<double>& b) { return cblas_ddot(a.nrows(), a.data(), 1, b.data(), 1); } inline double dot_conj(const BLASVector<double>& a, const BLASVector<double>& b) { return cblas_ddot(a.nrows(), a.data(), 1, b.data(), 1); } inline double two_norm(const BLASVector<double>& v) { return cblas_dnrm2(v.nrows(), v.data(), 1); } template<typename VecX> inline void add(const VecX& x, BLASVector<double>& y) { cblas_daxpy(x.nrows(), scale_factor(x), get_data(x), 1, y.data(), 1); } template<typename VecX, typename VecY> inline void add(const VecX& x, const VecY& y, BLASVector<double>& z) { itl::copy(x, z); itl::add(y, z); } template<typename VecX, typename VecY, typename VecZ> inline void add(const VecX& x, const VecY& y, const VecZ& z, BLASVector<double>& r) { itl::copy(x, r); itl::add(y, r); itl::add(z, r); } template<typename VecX> inline void mult(const BLASGeneralMatrix<double>& A, const VecX& x, BLASVector<double>& y) { cblas_dgemv(CblasRowMajor, CblasNoTrans, A.nrows(), A.ncols(), scale_factor(x), A.data(), A.ncols(), get_data(x), 1, 0.0, y.data(), 1); } template<typename VecX, typename VecY> inline void mult(const BLASGeneralMatrix<double>& A, const VecX& x, const VecY& y, BLASVector<double>& z) { cblas_dcopy(y.nrows(), get_data(y), 1, z.data(), 1); cblas_dgemv(CblasRowMajor, CblasNoTrans, A.nrows(), A.ncols(), scale_factor(x), A.data(), A.ncols(), get_data(x), 1, scale_factor(y), z.data(), 1); } template <class VecX> inline void trans_mult(const BLASGeneralMatrix<double>& A, const VecX& x, BLASVector<double>& y) { cblas_dgemv(CblasRowMajor, CblasTrans, A.nrows(), A.ncols(), scale_factor(x), A.data(), A.ncols(), get_data(x), 1, 0.0, y.data(), 1); } inline void scale(BLASVector<double>& s, const itl_traits< BLASVector<double> >::value_type& alpha) { cblas_dscal(s.nrows(), alpha, s.data(), 1); } inline Scaled< BLASVector<double> > scaled(const BLASVector<double>& s, const itl_traits< BLASVector<double> >::value_type& alpha) { return Scaled< BLASVector<double> >(s, alpha); } template<typename T> inline typename BLASVector<T>::size_type size(const BLASVector<T>& x) { return x.nrows(); } // Only define this when semantics are understood /* template <class Vector> inline void resize(Vector& x, const int sz) { x.resize(sz); } */ } #endif <|endoftext|>
<commit_before>/*! \file PerspectiveSensor.cpp * \author Jared Hoberock * \brief Implementation of PerspectiveSensor class. */ #include "PerspectiveSensor.h" PerspectiveSensor ::PerspectiveSensor(void) { ; } // end PerspectiveSensor::PerspectiveSensor() PerspectiveSensor ::PerspectiveSensor(const Spectrum &response, const float aspect, const Point &origin, const Vector3 &right, const Vector3 &up) :mAspectRatio(aspect), mInverseWindowSurfaceArea(1.0f/(2.0f*2.0f*aspect)), mWindowOrigin(origin), mRight(right), mUp(up), mResponse(response) { ; } // end PerspectiveSensor::PerspectiveSensor() void PerspectiveSensor ::set(const float aspect, const Point &origin) { mAspectRatio = aspect; mWindowOrigin = origin; mInverseWindowSurfaceArea = (1.0f/(2.0f*2.0f*mAspectRatio)); } // end PerspectiveSensor::set() Spectrum PerspectiveSensor ::sample(const DifferentialGeometry &dg, const float u0, const float u1, const float u2, Vector3 &ws, float &pdf, bool &delta) const { delta = false; Point q; sampleWindow(u0,u1, mRight, mUp, dg.getNormal(), q, pdf); ws = q - dg.getPoint(); float d2 = ws.norm2(); ws /= sqrt(d2); // compute surface area pdf to solid angle pdf pdf *= d2; // this removes the vignetting effect, but is it correct? pdf *= dg.getNormal().dot(ws); //// divide the response by the dot product to remove the vignette effect //return mResponse / dg.getNormal().dot(ws); return mResponse; } // end PerspectiveSensor::sample() void PerspectiveSensor ::invert(const Vector &w, const DifferentialGeometry &dg, float &u0, float &u1) const { // a ray from the dg in direction w intersects the window at // time t // remember that the normal points in the -look direction float t = -dg.getNormal().dot(mWindowOrigin - dg.getPoint()) / -dg.getNormal().dot(w); // compute q the intersection with the ray and the plane Point q = dg.getPoint() + t * w; // this is the inverse operation of sampleFilmPlane(): // get the film plane coordinates of q q -= mWindowOrigin; q *= 0.5f; u0 = q.dot(mRight) / mAspectRatio; u1 = q.dot(mUp); } // end PerspectiveSensor::invert() void PerspectiveSensor ::sampleWindow(const float u, const float v, const Vector3 &xAxis, const Vector3 &yAxis, const Vector3 &zAxis, Point &p, float &pdf) const { p = mWindowOrigin; p += 2.0f * mAspectRatio * u * xAxis; p += 2.0f * v * yAxis; pdf = mInverseWindowSurfaceArea; } // end PerspectiveSensor::sampleWindow() float PerspectiveSensor ::evaluatePdf(const Vector3 &ws, const DifferentialGeometry &dg) const { // intersect a ray through dg in direction ws with the sensor window // remember that the normal points in the -look direction float t = -dg.getNormal().dot(mWindowOrigin - dg.getPoint()) / -dg.getNormal().dot(ws); // compute q the intersection with the ray and the window Point q = dg.getPoint() + t * ws; Point coords = q - mWindowOrigin; coords *= 0.5f; float u = coords.dot(mRight) / mAspectRatio; float v = coords.dot(mUp); // if the ray does not pass through the window, // then there is zero probability of having generated it if(u < 0.0f || u >= 1.0f) return 0.0f; if(v < 0.0f || v >= 1.0f) return 0.0f; // compute solid angle pdf Vector3 wi = q - dg.getPoint(); float pdf = wi.norm2(); pdf *= mInverseWindowSurfaceArea; // this removes the vignetting effect, but is it correct? pdf *= dg.getNormal().absDot(ws); return pdf; } // end PerspectiveSensor::evaluatePdf() Spectrum PerspectiveSensor ::evaluate(const Vector &ws, const DifferentialGeometry &dg) const { // evaluate the pdf at ws, and if it is not zero, return mResponse // divide by dot product to remove the vignetting effect //return evaluatePdf(ws, dg) > 0 ? (mResponse / dg.getNormal().absDot(ws)) : Spectrum::black(); return evaluatePdf(ws, dg) > 0 ? (mResponse) : Spectrum::black(); } // end PerspectiveSensor::evaluate() Vector PerspectiveSensor ::getRight(void) const { return mRight; } // end PerspectiveSensor::getRight() Vector PerspectiveSensor ::getUp(void) const { return mUp; } // end PerspectiveSensor::getUp() <commit_msg>Fix a bug where if a ray is coming from "behind" the sensor, it still has non-zero response.<commit_after>/*! \file PerspectiveSensor.cpp * \author Jared Hoberock * \brief Implementation of PerspectiveSensor class. */ #include "PerspectiveSensor.h" PerspectiveSensor ::PerspectiveSensor(void) { ; } // end PerspectiveSensor::PerspectiveSensor() PerspectiveSensor ::PerspectiveSensor(const Spectrum &response, const float aspect, const Point &origin, const Vector3 &right, const Vector3 &up) :mAspectRatio(aspect), mInverseWindowSurfaceArea(1.0f/(2.0f*2.0f*aspect)), mWindowOrigin(origin), mRight(right), mUp(up), mResponse(response) { ; } // end PerspectiveSensor::PerspectiveSensor() void PerspectiveSensor ::set(const float aspect, const Point &origin) { mAspectRatio = aspect; mWindowOrigin = origin; mInverseWindowSurfaceArea = (1.0f/(2.0f*2.0f*mAspectRatio)); } // end PerspectiveSensor::set() Spectrum PerspectiveSensor ::sample(const DifferentialGeometry &dg, const float u0, const float u1, const float u2, Vector3 &ws, float &pdf, bool &delta) const { delta = false; Point q; sampleWindow(u0,u1, mRight, mUp, dg.getNormal(), q, pdf); ws = q - dg.getPoint(); float d2 = ws.norm2(); ws /= sqrt(d2); // compute surface area pdf to solid angle pdf pdf *= d2; // this removes the vignetting effect, but is it correct? pdf *= dg.getNormal().dot(ws); //// divide the response by the dot product to remove the vignette effect //return mResponse / dg.getNormal().dot(ws); return mResponse; } // end PerspectiveSensor::sample() void PerspectiveSensor ::invert(const Vector &w, const DifferentialGeometry &dg, float &u0, float &u1) const { // a ray from the dg in direction w intersects the window at // time t // remember that the normal points in the -look direction float t = -dg.getNormal().dot(mWindowOrigin - dg.getPoint()) / -dg.getNormal().dot(w); // compute q the intersection with the ray and the plane Point q = dg.getPoint() + t * w; // this is the inverse operation of sampleFilmPlane(): // get the film plane coordinates of q q -= mWindowOrigin; q *= 0.5f; u0 = q.dot(mRight) / mAspectRatio; u1 = q.dot(mUp); } // end PerspectiveSensor::invert() void PerspectiveSensor ::sampleWindow(const float u, const float v, const Vector3 &xAxis, const Vector3 &yAxis, const Vector3 &zAxis, Point &p, float &pdf) const { p = mWindowOrigin; p += 2.0f * mAspectRatio * u * xAxis; p += 2.0f * v * yAxis; pdf = mInverseWindowSurfaceArea; } // end PerspectiveSensor::sampleWindow() float PerspectiveSensor ::evaluatePdf(const Vector3 &ws, const DifferentialGeometry &dg) const { // intersect a ray through dg in direction ws with the sensor window // remember that the normal points in the -look direction float t = -dg.getNormal().dot(mWindowOrigin - dg.getPoint()) / -dg.getNormal().dot(ws); // if t is negative, then ws came from 'behind the camera', // and there is zero pdf of generating such directions if(t < 0) return 0; // compute q the intersection with the ray and the window Point q = dg.getPoint() + t * ws; Point coords = q - mWindowOrigin; coords *= 0.5f; float u = coords.dot(mRight) / mAspectRatio; float v = coords.dot(mUp); // if the ray does not pass through the window, // then there is zero probability of having generated it if(u < 0.0f || u >= 1.0f) return 0.0f; if(v < 0.0f || v >= 1.0f) return 0.0f; // compute solid angle pdf Vector3 wi = q - dg.getPoint(); float pdf = wi.norm2(); pdf *= mInverseWindowSurfaceArea; // this removes the vignetting effect, but is it correct? pdf *= dg.getNormal().absDot(ws); return pdf; } // end PerspectiveSensor::evaluatePdf() Spectrum PerspectiveSensor ::evaluate(const Vector &ws, const DifferentialGeometry &dg) const { // evaluate the pdf at ws, and if it is not zero, return mResponse // divide by dot product to remove the vignetting effect //return evaluatePdf(ws, dg) > 0 ? (mResponse / dg.getNormal().absDot(ws)) : Spectrum::black(); Spectrum result = evaluatePdf(ws, dg) > 0 ? (mResponse) : Spectrum::black(); return result; } // end PerspectiveSensor::evaluate() Vector PerspectiveSensor ::getRight(void) const { return mRight; } // end PerspectiveSensor::getRight() Vector PerspectiveSensor ::getUp(void) const { return mUp; } // end PerspectiveSensor::getUp() <|endoftext|>
<commit_before>#pragma once // adapt_integer_and_posit.hpp: adapter functions to convert integer<size> type and posit<nbits,es> types // // Copyright (C) 2017-2020 Stillwater Supercomputing, Inc. // // This file is part of the UNIVERSAL project, which is released under an MIT Open Source license. #include <iostream> // include this adapter before the src/tgt types that you want to connect // if included, set the compilation flag that will enable the operator=(const TargetType&) in the SourceType. #ifndef ADAPTER_POSIT_AND_INTEGER #define ADAPTER_POSIT_AND_INTEGER 1 #else #define ADAPTER_POSIT_AND_INTEGER 0 #endif // ADAPTER_POSIT_AND_INTEGER namespace sw { namespace unum { // forward references template<size_t nbits> class bitblock; template<size_t nbits> class value; template<size_t nbits, size_t es> class posit; template<size_t nbits, size_t es> int scale(const posit<nbits, es>&); template<size_t nbits, size_t es, size_t fbits> bitblock<fbits+1> significant(const posit<nbits, es>&); template<size_t nbits, typename BlockType> class integer; /* Why is the convert function not part of the Integer or Posit types? It would tightly couple the types, which we want to avoid. If we want to productize these convertions we would need a new layer in the module design that sits above the Universal types. TODO */ // convert a Posit to an Integer template<size_t nbits, size_t es, size_t ibits, typename BlockType> inline void convert_p2i(const sw::unum::posit<nbits, es>& p, sw::unum::integer<ibits, BlockType>& v) { // get the scale of the posit value int scale = sw::unum::scale(p); if (scale < 0) { v = 0; return; } if (scale == 0) { v = 1; } else { // gather all the fraction bits // sw::unum::bitblock<p.fhbits> significant = sw::unum::significant<p.nbits, p.es, p.fbits>(p); sw::unum::bitblock<Posit::fhbits> significant = sw::unum::significant<Posit::nbits, Posit::es, Posit::fbits>(p); // the radix point is at fbits, to make an integer out of this // we shift that radix point fbits to the right. // that is equivalent to a scale of 2^fbits v.clear(); int msb = (v.nbits < p.fbits + 1) ? v.nbits : p.fbits + 1; for (int i = msb-1; i >= 0; --i) { v.set(i, significant[i]); } int shift = scale - p.fbits; // if scale > fbits we need to shift left v <<= shift; if (p.isneg()) { v.flip(); v += 1; } } } ///////////////////////////////////////////////////////////////////////// // convert an Integer to a Posit template<size_t ibits, typename BlockType, size_t nbits, size_t es> inline void convert_i2p(const sw::unum::integer<ibits, BlockType>& w, sw::unum::posit<nbits, es>& p) { using namespace std; using namespace sw::unum; bool sign = w < 0; bool isZero = w == 0; bool isInf = false; bool isNan = false; long _scale = scale(w); integer<ibits, BlockType> w2 = sign ? twos_complement(w) : w; int msb = findMsb(w2); bitblock<nbits> fraction_without_hidden_bit; int fbit = nbits - 1; for (int i = msb - 1; i >= 0; --i) { fraction_without_hidden_bit.set(fbit, w2.at(i)); --fbit; } value<nbits> v; v.set(sign, _scale, fraction_without_hidden_bit, isZero, isInf, isNan); p = v; } } // namespace unum } // namespace sw <commit_msg>compilation fixes for gcc<commit_after>#pragma once // adapt_integer_and_posit.hpp: adapter functions to convert integer<size> type and posit<nbits,es> types // // Copyright (C) 2017-2020 Stillwater Supercomputing, Inc. // // This file is part of the UNIVERSAL project, which is released under an MIT Open Source license. #include <iostream> // include this adapter before the src/tgt types that you want to connect // if included, set the compilation flag that will enable the operator=(const TargetType&) in the SourceType. #ifndef ADAPTER_POSIT_AND_INTEGER #define ADAPTER_POSIT_AND_INTEGER 1 #else #define ADAPTER_POSIT_AND_INTEGER 0 #endif // ADAPTER_POSIT_AND_INTEGER namespace sw { namespace unum { // forward references template<size_t nbits> class bitblock; template<size_t nbits> class value; template<size_t nbits, size_t es> class posit; template<size_t nbits, size_t es> int scale(const posit<nbits, es>&); template<size_t nbits, size_t es, size_t fbits> bitblock<fbits+1> significant(const posit<nbits, es>&); template<size_t nbits, typename BlockType> class integer; /* Why is the convert function not part of the Integer or Posit types? It would tightly couple the types, which we want to avoid. If we want to productize these convertions we would need a new layer in the module design that sits above the Universal types. TODO */ // convert a Posit to an Integer template<size_t nbits, size_t es, size_t ibits, typename BlockType> inline void convert_p2i(const sw::unum::posit<nbits, es>& p, sw::unum::integer<ibits, BlockType>& v) { // get the scale of the posit value int scale = sw::unum::scale(p); if (scale < 0) { v = 0; return; } if (scale == 0) { v = 1; } else { // gather all the fraction bits // sw::unum::bitblock<p.fhbits> significant = sw::unum::significant<p.nbits, p.es, p.fbits>(p); sw::unum::bitblock<sw::unum::posit<nbits, es>::fhbits> significant = sw::unum::significant<nbits, es, sw::unum::posit<nbits, es>::fbits>(p); // the radix point is at fbits, to make an integer out of this // we shift that radix point fbits to the right. // that is equivalent to a scale of 2^fbits v.clear(); int msb = (v.nbits < p.fbits + 1) ? v.nbits : p.fbits + 1; for (int i = msb-1; i >= 0; --i) { v.set(i, significant[i]); } int shift = scale - p.fbits; // if scale > fbits we need to shift left v <<= shift; if (p.isneg()) { v.flip(); v += 1; } } } ///////////////////////////////////////////////////////////////////////// // convert an Integer to a Posit template<size_t ibits, typename BlockType, size_t nbits, size_t es> inline void convert_i2p(const sw::unum::integer<ibits, BlockType>& w, sw::unum::posit<nbits, es>& p) { using namespace std; using namespace sw::unum; bool sign = w < 0; bool isZero = w == 0; bool isInf = false; bool isNan = false; long _scale = scale(w); integer<ibits, BlockType> w2 = sign ? twos_complement(w) : w; int msb = findMsb(w2); bitblock<nbits> fraction_without_hidden_bit; int fbit = nbits - 1; for (int i = msb - 1; i >= 0; --i) { fraction_without_hidden_bit.set(fbit, w2.at(i)); --fbit; } value<nbits> v; v.set(sign, _scale, fraction_without_hidden_bit, isZero, isInf, isNan); p = v; } } // namespace unum } // namespace sw <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: sbintern.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2004-03-17 13:34:46 $ * * 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 _SB_INTERN_HXX #define _SB_INTERN_HXX #include <svtools/sbxfac.hxx> #ifndef _UNOTOOLS_TRANSLITERATIONWRAPPER_HXX #include <unotools/transliterationwrapper.hxx> #endif #include "sb.hxx" class ::utl::TransliterationWrapper; class SbUnoFactory; class SbTypeFactory; class SbOLEFactory; class SbiInstance; class SbModule; class SbiFactory : public SbxFactory { public: virtual SbxBase* Create( UINT16 nSbxId, UINT32 = SBXCR_SBX ); virtual SbxObject* CreateObject( const String& ); }; // Stack fuer die im Fehlerfall abgebaute SbiRuntime Kette class SbErrorStackEntry { public: SbErrorStackEntry(SbMethodRef aM, xub_StrLen nL, xub_StrLen nC1, xub_StrLen nC2) : aMethod(aM), nLine(nL), nCol1(nC1), nCol2(nC2) {} SbMethodRef aMethod; xub_StrLen nLine; xub_StrLen nCol1, nCol2; }; SV_DECL_PTRARR_DEL(SbErrorStack, SbErrorStackEntry*, 1, 1) struct SbiGlobals { SbiInstance* pInst; // alle aktiven Runtime-Instanzen SbiFactory* pSbFac; // StarBASIC-Factory SbUnoFactory* pUnoFac; // Factory fuer Uno-Structs bei DIM AS NEW SbTypeFactory* pTypeFac; // Factory for user defined types SbOLEFactory* pOLEFac; // Factory for OLE types SbModule* pMod; // aktuell aktives Modul SbModule* pCompMod; // aktuell compiliertes Modul short nInst; // Anzahl BASICs Link aErrHdl; // globaler Error-Handler Link aBreakHdl; // globaler Break-Handler SbError nCode; // aktueller Fehlercode xub_StrLen nLine; // aktuelle Zeile xub_StrLen nCol1,nCol2; // aktuelle Spalten (von,bis) BOOL bCompiler; // Flag fuer Compiler-Error BOOL bGlobalInitErr; // Beim GlobalInit trat ein Compiler-Fehler auf BOOL bRunInit; // TRUE, wenn RunInit vom Basic aktiv ist String aErrMsg; // Puffer fuer GetErrorText() SbLanguageMode eLanguageMode; // Flag fuer Visual-Basic-Script-Modus SbErrorStack* pErrStack; // Stack fuer die im Fehlerfall abgebaute SbiRuntime Kette ::utl::TransliterationWrapper* pTransliterationWrapper; // For StrComp BOOL bBlockCompilerError; SbiGlobals(); ~SbiGlobals(); }; // Utility-Makros und -Routinen SbiGlobals* GetSbData(); #define pINST GetSbData()->pInst #define pMOD GetSbData()->pMod #define pCMOD GetSbData()->pCompMod #define pSBFAC GetSbData()->pSbFac #define pUNOFAC GetSbData()->pUnoFac #define pTYPEFAC GetSbData()->pTypeFac #define pOLEFAC GetSbData()->pOLEFac #endif <commit_msg>INTEGRATION: CWS ab11clonepp4 (1.5.62); FILE MERGED 2004/10/15 08:39:08 ab 1.5.62.1: #118083# #118084# Class support PP4 -> SO 8<commit_after>/************************************************************************* * * $RCSfile: sbintern.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: pjunck $ $Date: 2004-11-02 11:56:34 $ * * 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 _SB_INTERN_HXX #define _SB_INTERN_HXX #include <svtools/sbxfac.hxx> #ifndef _UNOTOOLS_TRANSLITERATIONWRAPPER_HXX #include <unotools/transliterationwrapper.hxx> #endif #include "sb.hxx" class ::utl::TransliterationWrapper; class SbUnoFactory; class SbTypeFactory; class SbOLEFactory; class SbiInstance; class SbModule; class SbiFactory : public SbxFactory { public: virtual SbxBase* Create( UINT16 nSbxId, UINT32 = SBXCR_SBX ); virtual SbxObject* CreateObject( const String& ); }; // #115824: Factory class to create class objects (type command) // Implementation: sb.cxx class SbClassFactory : public SbxFactory { SbxObjectRef xClassModules; public: SbClassFactory( void ); void AddClassModule( SbModule* pClassModule ); void RemoveClassModule( SbModule* pClassModule ); virtual SbxBase* Create( UINT16 nSbxId, UINT32 = SBXCR_SBX ); virtual SbxObject* CreateObject( const String& ); }; // Stack fuer die im Fehlerfall abgebaute SbiRuntime Kette class SbErrorStackEntry { public: SbErrorStackEntry(SbMethodRef aM, xub_StrLen nL, xub_StrLen nC1, xub_StrLen nC2) : aMethod(aM), nLine(nL), nCol1(nC1), nCol2(nC2) {} SbMethodRef aMethod; xub_StrLen nLine; xub_StrLen nCol1, nCol2; }; SV_DECL_PTRARR_DEL(SbErrorStack, SbErrorStackEntry*, 1, 1) struct SbiGlobals { SbiInstance* pInst; // alle aktiven Runtime-Instanzen SbiFactory* pSbFac; // StarBASIC-Factory SbUnoFactory* pUnoFac; // Factory fuer Uno-Structs bei DIM AS NEW SbTypeFactory* pTypeFac; // Factory for user defined types SbClassFactory* pClassFac; // Factory for user defined classes (based on class modules) SbOLEFactory* pOLEFac; // Factory for OLE types SbModule* pMod; // aktuell aktives Modul SbModule* pCompMod; // aktuell compiliertes Modul short nInst; // Anzahl BASICs Link aErrHdl; // globaler Error-Handler Link aBreakHdl; // globaler Break-Handler SbError nCode; // aktueller Fehlercode xub_StrLen nLine; // aktuelle Zeile xub_StrLen nCol1,nCol2; // aktuelle Spalten (von,bis) BOOL bCompiler; // Flag fuer Compiler-Error BOOL bGlobalInitErr; // Beim GlobalInit trat ein Compiler-Fehler auf BOOL bRunInit; // TRUE, wenn RunInit vom Basic aktiv ist String aErrMsg; // Puffer fuer GetErrorText() SbLanguageMode eLanguageMode; // Flag fuer Visual-Basic-Script-Modus SbErrorStack* pErrStack; // Stack fuer die im Fehlerfall abgebaute SbiRuntime Kette ::utl::TransliterationWrapper* pTransliterationWrapper; // For StrComp BOOL bBlockCompilerError; SbiGlobals(); ~SbiGlobals(); }; // Utility-Makros und -Routinen SbiGlobals* GetSbData(); #define pINST GetSbData()->pInst #define pMOD GetSbData()->pMod #define pCMOD GetSbData()->pCompMod #define pSBFAC GetSbData()->pSbFac #define pUNOFAC GetSbData()->pUnoFac #define pTYPEFAC GetSbData()->pTypeFac #define pCLASSFAC GetSbData()->pClassFac #define pOLEFAC GetSbData()->pOLEFac #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: graphicproperties.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: hr $ $Date: 2007-06-27 18:52:23 $ * * 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_svx.hxx" #ifndef _SDR_PROPERTIES_GRAPHICPROPERTIES_HXX #include <svx/sdr/properties/graphicproperties.hxx> #endif #ifndef _SFXITEMSET_HXX #include <svtools/itemset.hxx> #endif #ifndef _SFXSTYLE_HXX #include <svtools/style.hxx> #endif #ifndef _SVDDEF_HXX #include <svx/svddef.hxx> #endif #ifndef _EEITEM_HXX #include <svx/eeitem.hxx> #endif #ifndef _SVDOGRAF_HXX #include <svx/svdograf.hxx> #endif #ifndef _SDGCPITM_HXX #include <svx/sdgcpitm.hxx> #endif ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace properties { // create a new itemset SfxItemSet& GraphicProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool) { return *(new SfxItemSet(rPool, // range from SdrAttrObj SDRATTR_START, SDRATTR_SHADOW_LAST, SDRATTR_MISC_FIRST, SDRATTR_MISC_LAST, SDRATTR_TEXTDIRECTION, SDRATTR_TEXTDIRECTION, // range from SdrGrafObj SDRATTR_GRAF_FIRST, SDRATTR_GRAF_LAST, // range from SdrTextObj EE_ITEMS_START, EE_ITEMS_END, // end 0, 0)); } GraphicProperties::GraphicProperties(SdrObject& rObj) : RectangleProperties(rObj) { } GraphicProperties::GraphicProperties(const GraphicProperties& rProps, SdrObject& rObj) : RectangleProperties(rProps, rObj) { } GraphicProperties::~GraphicProperties() { } BaseProperties& GraphicProperties::Clone(SdrObject& rObj) const { return *(new GraphicProperties(*this, rObj)); } void GraphicProperties::ItemSetChanged(const SfxItemSet& rSet) { SdrGrafObj& rObj = (SdrGrafObj&)GetSdrObject(); // local changes rObj.SetXPolyDirty(); // #i29367# Update GraphicAttr, too. This was formerly // triggered by SdrGrafObj::SFX_NOTIFY, which is no longer // called nowadays. BTW: strictly speaking, the whole // ImpSetAttrToGrafInfo/ImpSetGrafInfoToAttr stuff could // be dumped, when SdrGrafObj::aGrafInfo is removed and // always created on the fly for repaint. rObj.ImpSetAttrToGrafInfo(); // call parent RectangleProperties::ItemSetChanged(rSet); } void GraphicProperties::SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr) { SdrGrafObj& rObj = (SdrGrafObj&)GetSdrObject(); // local changes rObj.SetXPolyDirty(); // call parent RectangleProperties::SetStyleSheet(pNewStyleSheet, bDontRemoveHardAttr); // local changes rObj.ImpSetAttrToGrafInfo(); } void GraphicProperties::ForceDefaultAttributes() { // call parent RectangleProperties::ForceDefaultAttributes(); // force ItemSet GetObjectItemSet(); mpItemSet->Put( SdrGrafLuminanceItem( 0 ) ); mpItemSet->Put( SdrGrafContrastItem( 0 ) ); mpItemSet->Put( SdrGrafRedItem( 0 ) ); mpItemSet->Put( SdrGrafGreenItem( 0 ) ); mpItemSet->Put( SdrGrafBlueItem( 0 ) ); mpItemSet->Put( SdrGrafGamma100Item( 100 ) ); mpItemSet->Put( SdrGrafTransparenceItem( 0 ) ); mpItemSet->Put( SdrGrafInvertItem( FALSE ) ); mpItemSet->Put( SdrGrafModeItem( GRAPHICDRAWMODE_STANDARD ) ); mpItemSet->Put( SdrGrafCropItem( 0, 0, 0, 0 ) ); // #i25616# mpItemSet->Put( XFillStyleItem(XFILL_NONE) ); mpItemSet->Put( XLineStyleItem(XLINE_NONE) ); } } // end of namespace properties } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <commit_msg>INTEGRATION: CWS changefileheader (1.11.368); FILE MERGED 2008/04/01 15:51:32 thb 1.11.368.3: #i85898# Stripping all external header guards 2008/04/01 12:49:43 thb 1.11.368.2: #i85898# Stripping all external header guards 2008/03/31 14:23:15 rt 1.11.368.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: graphicproperties.cxx,v $ * $Revision: 1.12 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <svx/sdr/properties/graphicproperties.hxx> #include <svtools/itemset.hxx> #include <svtools/style.hxx> #include <svx/svddef.hxx> #include <svx/eeitem.hxx> #include <svx/svdograf.hxx> #include <svx/sdgcpitm.hxx> ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace properties { // create a new itemset SfxItemSet& GraphicProperties::CreateObjectSpecificItemSet(SfxItemPool& rPool) { return *(new SfxItemSet(rPool, // range from SdrAttrObj SDRATTR_START, SDRATTR_SHADOW_LAST, SDRATTR_MISC_FIRST, SDRATTR_MISC_LAST, SDRATTR_TEXTDIRECTION, SDRATTR_TEXTDIRECTION, // range from SdrGrafObj SDRATTR_GRAF_FIRST, SDRATTR_GRAF_LAST, // range from SdrTextObj EE_ITEMS_START, EE_ITEMS_END, // end 0, 0)); } GraphicProperties::GraphicProperties(SdrObject& rObj) : RectangleProperties(rObj) { } GraphicProperties::GraphicProperties(const GraphicProperties& rProps, SdrObject& rObj) : RectangleProperties(rProps, rObj) { } GraphicProperties::~GraphicProperties() { } BaseProperties& GraphicProperties::Clone(SdrObject& rObj) const { return *(new GraphicProperties(*this, rObj)); } void GraphicProperties::ItemSetChanged(const SfxItemSet& rSet) { SdrGrafObj& rObj = (SdrGrafObj&)GetSdrObject(); // local changes rObj.SetXPolyDirty(); // #i29367# Update GraphicAttr, too. This was formerly // triggered by SdrGrafObj::SFX_NOTIFY, which is no longer // called nowadays. BTW: strictly speaking, the whole // ImpSetAttrToGrafInfo/ImpSetGrafInfoToAttr stuff could // be dumped, when SdrGrafObj::aGrafInfo is removed and // always created on the fly for repaint. rObj.ImpSetAttrToGrafInfo(); // call parent RectangleProperties::ItemSetChanged(rSet); } void GraphicProperties::SetStyleSheet(SfxStyleSheet* pNewStyleSheet, sal_Bool bDontRemoveHardAttr) { SdrGrafObj& rObj = (SdrGrafObj&)GetSdrObject(); // local changes rObj.SetXPolyDirty(); // call parent RectangleProperties::SetStyleSheet(pNewStyleSheet, bDontRemoveHardAttr); // local changes rObj.ImpSetAttrToGrafInfo(); } void GraphicProperties::ForceDefaultAttributes() { // call parent RectangleProperties::ForceDefaultAttributes(); // force ItemSet GetObjectItemSet(); mpItemSet->Put( SdrGrafLuminanceItem( 0 ) ); mpItemSet->Put( SdrGrafContrastItem( 0 ) ); mpItemSet->Put( SdrGrafRedItem( 0 ) ); mpItemSet->Put( SdrGrafGreenItem( 0 ) ); mpItemSet->Put( SdrGrafBlueItem( 0 ) ); mpItemSet->Put( SdrGrafGamma100Item( 100 ) ); mpItemSet->Put( SdrGrafTransparenceItem( 0 ) ); mpItemSet->Put( SdrGrafInvertItem( FALSE ) ); mpItemSet->Put( SdrGrafModeItem( GRAPHICDRAWMODE_STANDARD ) ); mpItemSet->Put( SdrGrafCropItem( 0, 0, 0, 0 ) ); // #i25616# mpItemSet->Put( XFillStyleItem(XFILL_NONE) ); mpItemSet->Put( XLineStyleItem(XLINE_NONE) ); } } // end of namespace properties } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Manasij Mukherjee <[email protected]> // author: Vassil Vassilev <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Path.h" #include "clang/Sema/Sema.h" #include "clang/Basic/Diagnostic.h" #include "clang/AST/AST.h" #include "clang/AST/ASTContext.h" // for operator new[](unsigned long, ASTCtx..) #include "clang/AST/RecursiveASTVisitor.h" #include "clang/AST/DeclVisitor.h" #include "clang/Lex/Preprocessor.h" #include "clang/Frontend/CompilerInstance.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/AutoloadCallback.h" #include "cling/Interpreter/Transaction.h" using namespace clang; namespace cling { void AutoloadCallback::report(clang::SourceLocation l, llvm::StringRef name, llvm::StringRef header) { Sema& sema= m_Interpreter->getSema(); unsigned id = sema.getDiagnostics().getCustomDiagID (DiagnosticsEngine::Level::Warning, "Note: '%0' can be found in %1"); /* unsigned idn //TODO: To be enabled after we have a way to get the full path = sema.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Level::Note, "Type : %0 , Full Path: %1")*/; sema.Diags.Report(l, id) << name << header; } bool AutoloadCallback::LookupObject (TagDecl *t) { if (t->hasAttr<AnnotateAttr>()) report(t->getLocation(),t->getNameAsString(),t->getAttr<AnnotateAttr>()->getAnnotation()); return false; } class AutoloadingVisitor: public RecursiveASTVisitor<AutoloadingVisitor> { private: bool m_IsStoringState; AutoloadCallback::FwdDeclsMap* m_Map; clang::Preprocessor* m_PP; private: void InsertIntoAutoloadingState (Decl* decl, std::string annotation) { assert(annotation != "" && "Empty annotation!"); assert(m_PP); const FileEntry* FE = 0; SourceLocation fileNameLoc; bool isAngled = false; const DirectoryLookup* LookupFrom = 0; const DirectoryLookup* CurDir = 0; FE = m_PP->LookupFile(fileNameLoc, annotation, isAngled, LookupFrom, CurDir, /*SearchPath*/0, /*RelativePath*/ 0, /*suggestedModule*/0, /*SkipCache*/false, /*OpenFile*/ false, /*CacheFail*/ false); assert(FE && "Must have a valid FileEntry"); if (m_Map->find(FE) == m_Map->end()) (*m_Map)[FE] = std::vector<Decl*>(); (*m_Map)[FE].push_back(decl); } public: AutoloadingVisitor() : m_IsStoringState(false), m_Map(0) {} void RemoveDefaultArgsOf(Decl* D) { //D = D->getMostRecentDecl(); TraverseDecl(D); //while ((D = D->getPreviousDecl())) // TraverseDecl(D); } void TrackDefaultArgStateOf(Decl* D, AutoloadCallback::FwdDeclsMap& map, Preprocessor& PP) { m_IsStoringState = true; m_Map = &map; m_PP = &PP; TraverseDecl(D); m_PP = 0; m_Map = 0; m_IsStoringState = false; } bool shouldVisitTemplateInstantiations() { return true; } bool VisitDecl(Decl* D) { if (!m_IsStoringState) return true; if (!D->hasAttr<AnnotateAttr>()) return true; AnnotateAttr* attr = D->getAttr<AnnotateAttr>(); if (!attr) return true; switch (D->getKind()) { default: InsertIntoAutoloadingState(D, attr->getAnnotation()); break; case Decl::Enum: // EnumDecls have extra information 2 chars after the filename used // for extra fixups. EnumDecl* ED = cast<EnumDecl>(D); if (ED->isFixed()) { StringRef str = ED->getAttr<AnnotateAttr>()->getAnnotation(); char ch = str.back(); // str.drop_back(2); ED->getAttr<AnnotateAttr>()->setAnnotation(ED->getASTContext(), str); struct EnumDeclDerived: public EnumDecl { static void setFixed(EnumDecl* ED, bool value = true) { ((EnumDeclDerived*)ED)->IsFixed = value; } }; if (ch != '1') EnumDeclDerived::setFixed(ED, false); } InsertIntoAutoloadingState(D, attr->getAnnotation().drop_back(2)); break; } return true; } bool VisitCXXRecordDecl(CXXRecordDecl* D) { if (!D->hasAttr<AnnotateAttr>()) return true; VisitDecl(D); if (ClassTemplateDecl* TmplD = D->getDescribedClassTemplate()) return VisitTemplateDecl(TmplD); return true; } bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl* D) { VisitDecl(D); if (m_IsStoringState) return true; if (D->hasDefaultArgument()) D->removeDefaultArgument(); return true; } bool VisitTemplateDecl(TemplateDecl* D) { if (D->getTemplatedDecl() && !D->getTemplatedDecl()->hasAttr<AnnotateAttr>()) return true; VisitDecl(D); for(auto P: D->getTemplateParameters()->asArray()) TraverseDecl(P); return true; } bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl* D) { VisitDecl(D); if (m_IsStoringState) return true; if (D->hasDefaultArgument()) D->removeDefaultArgument(); return true; } bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl* D) { VisitDecl(D); if (m_IsStoringState) return true; if (D->hasDefaultArgument()) D->removeDefaultArgument(); return true; } bool VisitParmVarDecl(ParmVarDecl* D) { VisitDecl(D); if (m_IsStoringState) return true; if (D->hasDefaultArg()) D->setDefaultArg(nullptr); return true; } }; void AutoloadCallback::InclusionDirective(clang::SourceLocation HashLoc, const clang::Token &IncludeTok, llvm::StringRef FileName, bool IsAngled, clang::CharSourceRange FilenameRange, const clang::FileEntry *File, llvm::StringRef SearchPath, llvm::StringRef RelativePath, const clang::Module *Imported) { // If File is 0 this means that the #included file doesn't exist. if (!File) return; auto found = m_Map.find(File); if (found == m_Map.end()) return; // nothing to do, file not referred in any annotation AutoloadingVisitor defaultArgsCleaner; for (auto D : found->second) { defaultArgsCleaner.RemoveDefaultArgsOf(D); } // Don't need to keep track of cleaned up decls from file. m_Map.erase(found); } AutoloadCallback::~AutoloadCallback() { } void AutoloadCallback::TransactionCommitted(const Transaction &T) { if (T.decls_begin() == T.decls_end()) return; if (T.decls_begin()->m_DGR.isNull()) return; if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin())) if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) { AutoloadingVisitor defaultArgsStateCollector; Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor(); for (Transaction::const_iterator I = T.decls_begin(), E = T.decls_end(); I != E; ++I) { Transaction::DelayCallInfo DCI = *I; // if (DCI.m_Call != Transaction::kCCIHandleTopLevelDecl) // continue; if (DCI.m_DGR.isNull()) continue; if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin())) if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) { for (Transaction::const_iterator I = T.decls_begin(), E = T.decls_end(); I != E; ++I) { Transaction::DelayCallInfo DCI = *I; for (DeclGroupRef::iterator J = DCI.m_DGR.begin(), JE = DCI.m_DGR.end(); J != JE; ++J) { defaultArgsStateCollector.TrackDefaultArgStateOf(*J, m_Map, PP); } } } } } } } //end namespace cling <commit_msg>Disable default cling-autoload callback (diag) for now.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Manasij Mukherjee <[email protected]> // author: Vassil Vassilev <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Path.h" #include "clang/Sema/Sema.h" #include "clang/Basic/Diagnostic.h" #include "clang/AST/AST.h" #include "clang/AST/ASTContext.h" // for operator new[](unsigned long, ASTCtx..) #include "clang/AST/RecursiveASTVisitor.h" #include "clang/AST/DeclVisitor.h" #include "clang/Lex/Preprocessor.h" #include "clang/Frontend/CompilerInstance.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/AutoloadCallback.h" #include "cling/Interpreter/Transaction.h" using namespace clang; namespace cling { void AutoloadCallback::report(clang::SourceLocation l, llvm::StringRef name, llvm::StringRef header) { Sema& sema= m_Interpreter->getSema(); unsigned id = sema.getDiagnostics().getCustomDiagID (DiagnosticsEngine::Level::Warning, "Note: '%0' can be found in %1"); /* unsigned idn //TODO: To be enabled after we have a way to get the full path = sema.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Level::Note, "Type : %0 , Full Path: %1")*/; sema.Diags.Report(l, id) << name << header; } bool AutoloadCallback::LookupObject (TagDecl *t) { #if 0 if (t->hasAttr<AnnotateAttr>()) report(t->getLocation(),t->getNameAsString(),t->getAttr<AnnotateAttr>()->getAnnotation()); #endif return false; } class AutoloadingVisitor: public RecursiveASTVisitor<AutoloadingVisitor> { private: bool m_IsStoringState; AutoloadCallback::FwdDeclsMap* m_Map; clang::Preprocessor* m_PP; private: void InsertIntoAutoloadingState (Decl* decl, std::string annotation) { assert(annotation != "" && "Empty annotation!"); assert(m_PP); const FileEntry* FE = 0; SourceLocation fileNameLoc; bool isAngled = false; const DirectoryLookup* LookupFrom = 0; const DirectoryLookup* CurDir = 0; FE = m_PP->LookupFile(fileNameLoc, annotation, isAngled, LookupFrom, CurDir, /*SearchPath*/0, /*RelativePath*/ 0, /*suggestedModule*/0, /*SkipCache*/false, /*OpenFile*/ false, /*CacheFail*/ false); assert(FE && "Must have a valid FileEntry"); if (m_Map->find(FE) == m_Map->end()) (*m_Map)[FE] = std::vector<Decl*>(); (*m_Map)[FE].push_back(decl); } public: AutoloadingVisitor() : m_IsStoringState(false), m_Map(0) {} void RemoveDefaultArgsOf(Decl* D) { //D = D->getMostRecentDecl(); TraverseDecl(D); //while ((D = D->getPreviousDecl())) // TraverseDecl(D); } void TrackDefaultArgStateOf(Decl* D, AutoloadCallback::FwdDeclsMap& map, Preprocessor& PP) { m_IsStoringState = true; m_Map = &map; m_PP = &PP; TraverseDecl(D); m_PP = 0; m_Map = 0; m_IsStoringState = false; } bool shouldVisitTemplateInstantiations() { return true; } bool VisitDecl(Decl* D) { if (!m_IsStoringState) return true; if (!D->hasAttr<AnnotateAttr>()) return true; AnnotateAttr* attr = D->getAttr<AnnotateAttr>(); if (!attr) return true; switch (D->getKind()) { default: InsertIntoAutoloadingState(D, attr->getAnnotation()); break; case Decl::Enum: // EnumDecls have extra information 2 chars after the filename used // for extra fixups. EnumDecl* ED = cast<EnumDecl>(D); if (ED->isFixed()) { StringRef str = ED->getAttr<AnnotateAttr>()->getAnnotation(); char ch = str.back(); // str.drop_back(2); ED->getAttr<AnnotateAttr>()->setAnnotation(ED->getASTContext(), str); struct EnumDeclDerived: public EnumDecl { static void setFixed(EnumDecl* ED, bool value = true) { ((EnumDeclDerived*)ED)->IsFixed = value; } }; if (ch != '1') EnumDeclDerived::setFixed(ED, false); } InsertIntoAutoloadingState(D, attr->getAnnotation().drop_back(2)); break; } return true; } bool VisitCXXRecordDecl(CXXRecordDecl* D) { if (!D->hasAttr<AnnotateAttr>()) return true; VisitDecl(D); if (ClassTemplateDecl* TmplD = D->getDescribedClassTemplate()) return VisitTemplateDecl(TmplD); return true; } bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl* D) { VisitDecl(D); if (m_IsStoringState) return true; if (D->hasDefaultArgument()) D->removeDefaultArgument(); return true; } bool VisitTemplateDecl(TemplateDecl* D) { if (D->getTemplatedDecl() && !D->getTemplatedDecl()->hasAttr<AnnotateAttr>()) return true; VisitDecl(D); for(auto P: D->getTemplateParameters()->asArray()) TraverseDecl(P); return true; } bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl* D) { VisitDecl(D); if (m_IsStoringState) return true; if (D->hasDefaultArgument()) D->removeDefaultArgument(); return true; } bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl* D) { VisitDecl(D); if (m_IsStoringState) return true; if (D->hasDefaultArgument()) D->removeDefaultArgument(); return true; } bool VisitParmVarDecl(ParmVarDecl* D) { VisitDecl(D); if (m_IsStoringState) return true; if (D->hasDefaultArg()) D->setDefaultArg(nullptr); return true; } }; void AutoloadCallback::InclusionDirective(clang::SourceLocation HashLoc, const clang::Token &IncludeTok, llvm::StringRef FileName, bool IsAngled, clang::CharSourceRange FilenameRange, const clang::FileEntry *File, llvm::StringRef SearchPath, llvm::StringRef RelativePath, const clang::Module *Imported) { // If File is 0 this means that the #included file doesn't exist. if (!File) return; auto found = m_Map.find(File); if (found == m_Map.end()) return; // nothing to do, file not referred in any annotation AutoloadingVisitor defaultArgsCleaner; for (auto D : found->second) { defaultArgsCleaner.RemoveDefaultArgsOf(D); } // Don't need to keep track of cleaned up decls from file. m_Map.erase(found); } AutoloadCallback::~AutoloadCallback() { } void AutoloadCallback::TransactionCommitted(const Transaction &T) { if (T.decls_begin() == T.decls_end()) return; if (T.decls_begin()->m_DGR.isNull()) return; if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin())) if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) { AutoloadingVisitor defaultArgsStateCollector; Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor(); for (Transaction::const_iterator I = T.decls_begin(), E = T.decls_end(); I != E; ++I) { Transaction::DelayCallInfo DCI = *I; // if (DCI.m_Call != Transaction::kCCIHandleTopLevelDecl) // continue; if (DCI.m_DGR.isNull()) continue; if (const NamedDecl* ND = dyn_cast<NamedDecl>(*T.decls_begin()->m_DGR.begin())) if (ND->getIdentifier() && ND->getName().equals("__Cling_Autoloading_Map")) { for (Transaction::const_iterator I = T.decls_begin(), E = T.decls_end(); I != E; ++I) { Transaction::DelayCallInfo DCI = *I; for (DeclGroupRef::iterator J = DCI.m_DGR.begin(), JE = DCI.m_DGR.end(); J != JE; ++J) { defaultArgsStateCollector.TrackDefaultArgStateOf(*J, m_Map, PP); } } } } } } } //end namespace cling <|endoftext|>
<commit_before>#include "HardFloat.hpp" #include <xmmintrin.h> #include <cassert> // Debug checks // checks performed via softfloat #if defined(_DEBUG) && 0 #include "../deps/softfloat/softfloat.hpp" #define CHECKED_IMPL_BEGIN(x, q) \ { \ SoftFloat::Float theirs = q(SoftFloat::Float(x.f)); \ HardFloat ours = ([x]() mutable #define CHECKED_IMPL_BEGIN2(a, b, q) \ { \ SoftFloat::Float theirs = q(SoftFloat::Float(a.f), SoftFloat::Float(b.f)); \ HardFloat ours = ([a, b]() mutable #define CHECKED_IMPL_BEGIN_OP2(a, b, op) \ { \ SoftFloat::Float theirs = SoftFloat::Float(a.f) op SoftFloat::Float(b.f); \ HardFloat ours = ([a, b]() mutable #define CHECKED_IMPL_END() \ )(); \ assert(theirs.getInternalUint32() == ours.getInternalUint32()); \ return ours; \ } #define CHECKED_IMPL_BEGIN_OP0(op) \ { \ op theirs = (op)SoftFloat::Float(f); \ op ours = ([=]() #define CHECKED_IMPL_END_OP0() \ )(); \ assert(theirs == ours); \ return ours; \ } #define CHECKED_IMPL_BEGIN_OP2_BOOL(a, b, op) \ { \ bool theirs = SoftFloat::Float(a.f) op SoftFloat::Float(b.f); \ bool ours = ([a, b]() mutable #else #define CHECKED_IMPL_BEGIN(x, f) #define CHECKED_IMPL_BEGIN2(a, b, f) #define CHECKED_IMPL_BEGIN_OP2(a, b, op) #define CHECKED_IMPL_END() #define CHECKED_IMPL_BEGIN_OP0(op) #define CHECKED_IMPL_END_OP0() #define CHECKED_IMPL_BEGIN_OP2_BOOL(a, b, op) #endif BEGIN_INANITY_MATH const HardFloat HardFloat::pi = HardFloat::fromUint32Const(0x40490fdb); const HardFloat HardFloat::pi2 = HardFloat::fromUint32Const(0x40c90fdb); const HardFloat HardFloat::pi_2 = HardFloat::fromUint32Const(0x3fc90fdb); HardFloat::HardFloat() : f(0) {} HardFloat::HardFloat(int32_t n) { _mm_store_ss(&f, _mm_cvt_si2ss(_mm_setzero_ps(), (int)n)); } HardFloat::HardFloat(uint32_t n) { _mm_store_ss(&f, _mm_cvt_si2ss(_mm_setzero_ps(), (int)n)); } HardFloat::HardFloat(float n) : f(n) {} HardFloat HardFloat::operator-() const { float q = f; *(uint32_t*)&q ^= 0x80000000U; return HardFloat(q); } HardFloat operator+(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2(a, b, +) { return HardFloat(_mm_cvtss_f32(_mm_add_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)))); } CHECKED_IMPL_END() HardFloat operator-(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2(a, b, -) { return HardFloat(_mm_cvtss_f32(_mm_sub_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)))); } CHECKED_IMPL_END() HardFloat operator*(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2(a, b, *) { return HardFloat(_mm_cvtss_f32(_mm_mul_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)))); } CHECKED_IMPL_END() HardFloat operator/(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2(a, b, /) { return HardFloat(_mm_cvtss_f32(_mm_div_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)))); } CHECKED_IMPL_END() HardFloat fmod(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN2(a, b, fmod) { __m128 p = _mm_set_ss(a.f); __m128 q = _mm_set_ss(b.f); return HardFloat(_mm_cvtss_f32(_mm_sub_ss(p, _mm_mul_ss(_mm_cvt_si2ss(p, _mm_cvtt_ss2si(_mm_div_ss(p, q))), q)))); } CHECKED_IMPL_END() HardFloat& HardFloat::operator+=(HardFloat b) { _mm_store_ss(&f, _mm_add_ss(_mm_set_ss(f), _mm_set_ss(b.f))); return *this; } HardFloat& HardFloat::operator-=(HardFloat b) { _mm_store_ss(&f, _mm_sub_ss(_mm_set_ss(f), _mm_set_ss(b.f))); return *this; } HardFloat& HardFloat::operator*=(HardFloat b) { _mm_store_ss(&f, _mm_mul_ss(_mm_set_ss(f), _mm_set_ss(b.f))); return *this; } HardFloat& HardFloat::operator/=(HardFloat b) { _mm_store_ss(&f, _mm_div_ss(_mm_set_ss(f), _mm_set_ss(b.f))); return *this; } bool operator==(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2_BOOL(a, b, ==) { return (bool)_mm_comieq_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)); } CHECKED_IMPL_END_OP0() bool operator!=(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2_BOOL(a, b, !=) { return (bool)_mm_comineq_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)); } CHECKED_IMPL_END_OP0() bool operator<(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2_BOOL(a, b, <) { return (bool)_mm_comilt_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)); } CHECKED_IMPL_END_OP0() bool operator<=(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2_BOOL(a, b, <=) { return (bool)_mm_comile_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)); } CHECKED_IMPL_END_OP0() bool operator>(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2_BOOL(a, b, >) { return (bool)_mm_comigt_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)); } CHECKED_IMPL_END_OP0() bool operator>=(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2_BOOL(a, b, >=) { return (bool)_mm_comige_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)); } CHECKED_IMPL_END_OP0() HardFloat abs(HardFloat a) CHECKED_IMPL_BEGIN(a, abs) { float f = a.f; *(uint32_t*)&f &= 0x7FFFFFFFU; return HardFloat(f); } CHECKED_IMPL_END() HardFloat floor(HardFloat a) CHECKED_IMPL_BEGIN(a, floor) { __m128 p = _mm_set_ss(a.f); __m128 t = _mm_cvtepi32_ps(_mm_cvttps_epi32(p)); return HardFloat(_mm_cvtss_f32(_mm_sub_ps(t, _mm_and_ps(_mm_cmplt_ps(p, t), _mm_set_ss(1.0f))))); } CHECKED_IMPL_END() HardFloat ceil(HardFloat a) CHECKED_IMPL_BEGIN(a, ceil) { __m128 p = _mm_set_ss(a.f); __m128 t = _mm_cvtepi32_ps(_mm_cvttps_epi32(p)); return HardFloat(_mm_cvtss_f32(_mm_add_ps(t, _mm_and_ps(_mm_cmpgt_ps(p, t), _mm_set_ss(1.0f))))); } CHECKED_IMPL_END() HardFloat trunc(HardFloat a) CHECKED_IMPL_BEGIN(a, trunc) { return HardFloat(_mm_cvtss_f32(_mm_cvtepi32_ps(_mm_cvttps_epi32(_mm_set_ss(a.f))))); } CHECKED_IMPL_END() HardFloat sqrt(HardFloat a) CHECKED_IMPL_BEGIN(a, sqrt) { return HardFloat(_mm_cvtss_f32(_mm_sqrt_ss(_mm_set_ss(a.f)))); } CHECKED_IMPL_END() HardFloat sin(HardFloat a) CHECKED_IMPL_BEGIN(a, sin) { // handle negative values if(a < HardFloat()) return -sin(-a); // reduce to range [0, pi] HardFloat n; if(a > HardFloat::pi) { n = trunc(a / HardFloat::pi); a -= n * HardFloat::pi; } // reduce to range [0, pi/2] if(a > HardFloat::pi_2) a = HardFloat::pi - a; static const HardFloat k1 = HardFloat::fromUint32Const(0x3f7ff052), // 0.99976073735983227f k3 = HardFloat::fromUint32Const(0xbe29c7cc), // -0.16580121984779175f k5 = HardFloat::fromUint32Const(0x3bf7d14a); // 0.00756279111686865f HardFloat a2 = a * a, a3 = a2 * a, a5 = a3 * a2; a = a * k1 + a3 * k3 + a5 * k5; return ((int)n % 2 == 0) ? a : -a; } CHECKED_IMPL_END() HardFloat cos(HardFloat a) CHECKED_IMPL_BEGIN(a, cos) { return sin(a + HardFloat::pi_2); } CHECKED_IMPL_END() HardFloat atan(HardFloat a) CHECKED_IMPL_BEGIN(a, atan) { // handle negative values if(a < HardFloat()) return -atan(-a); if(a > HardFloat(1.0f)) return HardFloat::pi_2 - atan(HardFloat(1.0f) / a); static const HardFloat k1 = HardFloat::fromUint32Const(0x3f7ff50e), // 0.9998329769337240f k3 = HardFloat::fromUint32Const(0xbea75d21), // -0.3268824051434949f k5 = HardFloat::fromUint32Const(0x3e22d89e), // 0.1590294514698240f k7 = HardFloat::fromUint32Const(0xbd407012); // -0.0469818803609288f HardFloat a2 = a * a, a4 = a2 * a2, a6 = a4 * a2; return a * (k1 + a2 * k3 + a4 * k5 + a6 * k7); } CHECKED_IMPL_END() HardFloat atan2(HardFloat y, HardFloat x) CHECKED_IMPL_BEGIN2(y, x, atan2) { bool xs = x >= HardFloat(); if(y == HardFloat()) return xs ? HardFloat() : HardFloat::pi; bool ys = y >= HardFloat(); if(x == HardFloat()) return ys ? HardFloat::pi_2 : (-HardFloat::pi_2); HardFloat a = atan(y / x); return (xs == ys) ? (xs ? a : (a - HardFloat::pi)) : (xs ? a : (a + HardFloat::pi)); } CHECKED_IMPL_END() HardFloat::operator int32_t() const CHECKED_IMPL_BEGIN_OP0(int32_t) { return (int32_t)_mm_cvtt_ss2si(_mm_set_ss(f)); } CHECKED_IMPL_END_OP0() HardFloat::operator uint32_t() const CHECKED_IMPL_BEGIN_OP0(uint32_t) { return (uint32_t)_mm_cvtt_ss2si(_mm_set_ss(f)); } CHECKED_IMPL_END_OP0() HardFloat::operator float() const CHECKED_IMPL_BEGIN_OP0(float) { return f; } CHECKED_IMPL_END_OP0() uint32_t HardFloat::getInternalUint32() const { return *(uint32_t*)&f; } HardFloat HardFloat::fromUint32Const(uint32_t a) { HardFloat f; *(uint32_t*)&f.f = a; return f; } END_INANITY_MATH namespace std { Inanity::Math::HardFloat numeric_limits<Inanity::Math::HardFloat>::min() { return Inanity::Math::HardFloat(numeric_limits<float>::min()); } Inanity::Math::HardFloat numeric_limits<Inanity::Math::HardFloat>::lowest() { return Inanity::Math::HardFloat(numeric_limits<float>::lowest()); } Inanity::Math::HardFloat numeric_limits<Inanity::Math::HardFloat>::max() { return Inanity::Math::HardFloat(numeric_limits<float>::max()); } } <commit_msg>fix warnings in msvc<commit_after>#include "HardFloat.hpp" #include <xmmintrin.h> #include <cassert> // Debug checks // checks performed via softfloat #if defined(_DEBUG) && 0 #include "../deps/softfloat/softfloat.hpp" #define CHECKED_IMPL_BEGIN(x, q) \ { \ SoftFloat::Float theirs = q(SoftFloat::Float(x.f)); \ HardFloat ours = ([x]() mutable #define CHECKED_IMPL_BEGIN2(a, b, q) \ { \ SoftFloat::Float theirs = q(SoftFloat::Float(a.f), SoftFloat::Float(b.f)); \ HardFloat ours = ([a, b]() mutable #define CHECKED_IMPL_BEGIN_OP2(a, b, op) \ { \ SoftFloat::Float theirs = SoftFloat::Float(a.f) op SoftFloat::Float(b.f); \ HardFloat ours = ([a, b]() mutable #define CHECKED_IMPL_END() \ )(); \ assert(theirs.getInternalUint32() == ours.getInternalUint32()); \ return ours; \ } #define CHECKED_IMPL_BEGIN_OP0(op) \ { \ op theirs = (op)SoftFloat::Float(f); \ op ours = ([=]() #define CHECKED_IMPL_END_OP0() \ )(); \ assert(theirs == ours); \ return ours; \ } #define CHECKED_IMPL_BEGIN_OP2_BOOL(a, b, op) \ { \ bool theirs = SoftFloat::Float(a.f) op SoftFloat::Float(b.f); \ bool ours = ([a, b]() mutable #else #define CHECKED_IMPL_BEGIN(x, f) #define CHECKED_IMPL_BEGIN2(a, b, f) #define CHECKED_IMPL_BEGIN_OP2(a, b, op) #define CHECKED_IMPL_END() #define CHECKED_IMPL_BEGIN_OP0(op) #define CHECKED_IMPL_END_OP0() #define CHECKED_IMPL_BEGIN_OP2_BOOL(a, b, op) #endif BEGIN_INANITY_MATH const HardFloat HardFloat::pi = HardFloat::fromUint32Const(0x40490fdb); const HardFloat HardFloat::pi2 = HardFloat::fromUint32Const(0x40c90fdb); const HardFloat HardFloat::pi_2 = HardFloat::fromUint32Const(0x3fc90fdb); HardFloat::HardFloat() : f(0) {} HardFloat::HardFloat(int32_t n) { _mm_store_ss(&f, _mm_cvt_si2ss(_mm_setzero_ps(), (int)n)); } HardFloat::HardFloat(uint32_t n) { _mm_store_ss(&f, _mm_cvt_si2ss(_mm_setzero_ps(), (int)n)); } HardFloat::HardFloat(float n) : f(n) {} HardFloat HardFloat::operator-() const { float q = f; *(uint32_t*)&q ^= 0x80000000U; return HardFloat(q); } HardFloat operator+(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2(a, b, +) { return HardFloat(_mm_cvtss_f32(_mm_add_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)))); } CHECKED_IMPL_END() HardFloat operator-(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2(a, b, -) { return HardFloat(_mm_cvtss_f32(_mm_sub_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)))); } CHECKED_IMPL_END() HardFloat operator*(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2(a, b, *) { return HardFloat(_mm_cvtss_f32(_mm_mul_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)))); } CHECKED_IMPL_END() HardFloat operator/(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2(a, b, /) { return HardFloat(_mm_cvtss_f32(_mm_div_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)))); } CHECKED_IMPL_END() HardFloat fmod(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN2(a, b, fmod) { __m128 p = _mm_set_ss(a.f); __m128 q = _mm_set_ss(b.f); return HardFloat(_mm_cvtss_f32(_mm_sub_ss(p, _mm_mul_ss(_mm_cvt_si2ss(p, _mm_cvtt_ss2si(_mm_div_ss(p, q))), q)))); } CHECKED_IMPL_END() HardFloat& HardFloat::operator+=(HardFloat b) { _mm_store_ss(&f, _mm_add_ss(_mm_set_ss(f), _mm_set_ss(b.f))); return *this; } HardFloat& HardFloat::operator-=(HardFloat b) { _mm_store_ss(&f, _mm_sub_ss(_mm_set_ss(f), _mm_set_ss(b.f))); return *this; } HardFloat& HardFloat::operator*=(HardFloat b) { _mm_store_ss(&f, _mm_mul_ss(_mm_set_ss(f), _mm_set_ss(b.f))); return *this; } HardFloat& HardFloat::operator/=(HardFloat b) { _mm_store_ss(&f, _mm_div_ss(_mm_set_ss(f), _mm_set_ss(b.f))); return *this; } bool operator==(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2_BOOL(a, b, ==) { return !!_mm_comieq_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)); } CHECKED_IMPL_END_OP0() bool operator!=(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2_BOOL(a, b, !=) { return !!_mm_comineq_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)); } CHECKED_IMPL_END_OP0() bool operator<(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2_BOOL(a, b, <) { return !!_mm_comilt_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)); } CHECKED_IMPL_END_OP0() bool operator<=(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2_BOOL(a, b, <=) { return !!_mm_comile_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)); } CHECKED_IMPL_END_OP0() bool operator>(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2_BOOL(a, b, >) { return !!_mm_comigt_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)); } CHECKED_IMPL_END_OP0() bool operator>=(HardFloat a, HardFloat b) CHECKED_IMPL_BEGIN_OP2_BOOL(a, b, >=) { return !!_mm_comige_ss(_mm_set_ss(a.f), _mm_set_ss(b.f)); } CHECKED_IMPL_END_OP0() HardFloat abs(HardFloat a) CHECKED_IMPL_BEGIN(a, abs) { float f = a.f; *(uint32_t*)&f &= 0x7FFFFFFFU; return HardFloat(f); } CHECKED_IMPL_END() HardFloat floor(HardFloat a) CHECKED_IMPL_BEGIN(a, floor) { __m128 p = _mm_set_ss(a.f); __m128 t = _mm_cvtepi32_ps(_mm_cvttps_epi32(p)); return HardFloat(_mm_cvtss_f32(_mm_sub_ps(t, _mm_and_ps(_mm_cmplt_ps(p, t), _mm_set_ss(1.0f))))); } CHECKED_IMPL_END() HardFloat ceil(HardFloat a) CHECKED_IMPL_BEGIN(a, ceil) { __m128 p = _mm_set_ss(a.f); __m128 t = _mm_cvtepi32_ps(_mm_cvttps_epi32(p)); return HardFloat(_mm_cvtss_f32(_mm_add_ps(t, _mm_and_ps(_mm_cmpgt_ps(p, t), _mm_set_ss(1.0f))))); } CHECKED_IMPL_END() HardFloat trunc(HardFloat a) CHECKED_IMPL_BEGIN(a, trunc) { return HardFloat(_mm_cvtss_f32(_mm_cvtepi32_ps(_mm_cvttps_epi32(_mm_set_ss(a.f))))); } CHECKED_IMPL_END() HardFloat sqrt(HardFloat a) CHECKED_IMPL_BEGIN(a, sqrt) { return HardFloat(_mm_cvtss_f32(_mm_sqrt_ss(_mm_set_ss(a.f)))); } CHECKED_IMPL_END() HardFloat sin(HardFloat a) CHECKED_IMPL_BEGIN(a, sin) { // handle negative values if(a < HardFloat()) return -sin(-a); // reduce to range [0, pi] HardFloat n; if(a > HardFloat::pi) { n = trunc(a / HardFloat::pi); a -= n * HardFloat::pi; } // reduce to range [0, pi/2] if(a > HardFloat::pi_2) a = HardFloat::pi - a; static const HardFloat k1 = HardFloat::fromUint32Const(0x3f7ff052), // 0.99976073735983227f k3 = HardFloat::fromUint32Const(0xbe29c7cc), // -0.16580121984779175f k5 = HardFloat::fromUint32Const(0x3bf7d14a); // 0.00756279111686865f HardFloat a2 = a * a, a3 = a2 * a, a5 = a3 * a2; a = a * k1 + a3 * k3 + a5 * k5; return ((int)n % 2 == 0) ? a : -a; } CHECKED_IMPL_END() HardFloat cos(HardFloat a) CHECKED_IMPL_BEGIN(a, cos) { return sin(a + HardFloat::pi_2); } CHECKED_IMPL_END() HardFloat atan(HardFloat a) CHECKED_IMPL_BEGIN(a, atan) { // handle negative values if(a < HardFloat()) return -atan(-a); if(a > HardFloat(1.0f)) return HardFloat::pi_2 - atan(HardFloat(1.0f) / a); static const HardFloat k1 = HardFloat::fromUint32Const(0x3f7ff50e), // 0.9998329769337240f k3 = HardFloat::fromUint32Const(0xbea75d21), // -0.3268824051434949f k5 = HardFloat::fromUint32Const(0x3e22d89e), // 0.1590294514698240f k7 = HardFloat::fromUint32Const(0xbd407012); // -0.0469818803609288f HardFloat a2 = a * a, a4 = a2 * a2, a6 = a4 * a2; return a * (k1 + a2 * k3 + a4 * k5 + a6 * k7); } CHECKED_IMPL_END() HardFloat atan2(HardFloat y, HardFloat x) CHECKED_IMPL_BEGIN2(y, x, atan2) { bool xs = x >= HardFloat(); if(y == HardFloat()) return xs ? HardFloat() : HardFloat::pi; bool ys = y >= HardFloat(); if(x == HardFloat()) return ys ? HardFloat::pi_2 : (-HardFloat::pi_2); HardFloat a = atan(y / x); return (xs == ys) ? (xs ? a : (a - HardFloat::pi)) : (xs ? a : (a + HardFloat::pi)); } CHECKED_IMPL_END() HardFloat::operator int32_t() const CHECKED_IMPL_BEGIN_OP0(int32_t) { return (int32_t)_mm_cvtt_ss2si(_mm_set_ss(f)); } CHECKED_IMPL_END_OP0() HardFloat::operator uint32_t() const CHECKED_IMPL_BEGIN_OP0(uint32_t) { return (uint32_t)_mm_cvtt_ss2si(_mm_set_ss(f)); } CHECKED_IMPL_END_OP0() HardFloat::operator float() const CHECKED_IMPL_BEGIN_OP0(float) { return f; } CHECKED_IMPL_END_OP0() uint32_t HardFloat::getInternalUint32() const { return *(uint32_t*)&f; } HardFloat HardFloat::fromUint32Const(uint32_t a) { HardFloat f; *(uint32_t*)&f.f = a; return f; } END_INANITY_MATH namespace std { Inanity::Math::HardFloat numeric_limits<Inanity::Math::HardFloat>::min() { return Inanity::Math::HardFloat(numeric_limits<float>::min()); } Inanity::Math::HardFloat numeric_limits<Inanity::Math::HardFloat>::lowest() { return Inanity::Math::HardFloat(numeric_limits<float>::lowest()); } Inanity::Math::HardFloat numeric_limits<Inanity::Math::HardFloat>::max() { return Inanity::Math::HardFloat(numeric_limits<float>::max()); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: bastype3.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-07 20:01:01 $ * * 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 _BASTYPE3_HXX #define _BASTYPE3_HXX #ifndef _SVHEADER_HXX #include <svheader.hxx> #endif #include <svtools/svmedit.hxx> #include <iderid.hxx> class EditorWindow; #ifndef NO_SPECIALEDIT class ExtendedEdit : public Edit { private: Accelerator aAcc; Link aAccHdl; Link aGotFocusHdl; Link aLoseFocusHdl; protected: DECL_LINK( EditAccHdl, Accelerator * ); DECL_LINK( ImplGetFocusHdl, Control* ); DECL_LINK( ImplLoseFocusHdl, Control* ); public: ExtendedEdit( Window* pParent, IDEResId nRes ); void SetAccHdl( const Link& rLink ) { aAccHdl = rLink; } void SetLoseFocusHdl( const Link& rLink ) { aLoseFocusHdl = rLink; } void SetGotFocusHdl( const Link& rLink ) { aGotFocusHdl = rLink; } Accelerator& GetAccelerator() { return aAcc; } }; class ExtendedMultiLineEdit : public MultiLineEdit { private: Accelerator aAcc; Link aAccHdl; protected: DECL_LINK( EditAccHdl, Accelerator * ); DECL_LINK( ImplGetFocusHdl, Control* ); DECL_LINK( ImplLoseFocusHdl, Control* ); public: ExtendedMultiLineEdit( Window* pParent, IDEResId nRes ); void SetAccHdl( const Link& rLink ) { aAccHdl = rLink; } Accelerator& GetAccelerator() { return aAcc; } }; #endif //NO_SPECIALEDIT #endif // _BASTYPE3_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.3.244); FILE MERGED 2008/04/01 10:47:45 thb 1.3.244.2: #i85898# Stripping all external header guards 2008/03/28 16:04:43 rt 1.3.244.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: bastype3.hxx,v $ * $Revision: 1.4 $ * * 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 _BASTYPE3_HXX #define _BASTYPE3_HXX #include <svheader.hxx> #include <svtools/svmedit.hxx> #include <iderid.hxx> class EditorWindow; #ifndef NO_SPECIALEDIT class ExtendedEdit : public Edit { private: Accelerator aAcc; Link aAccHdl; Link aGotFocusHdl; Link aLoseFocusHdl; protected: DECL_LINK( EditAccHdl, Accelerator * ); DECL_LINK( ImplGetFocusHdl, Control* ); DECL_LINK( ImplLoseFocusHdl, Control* ); public: ExtendedEdit( Window* pParent, IDEResId nRes ); void SetAccHdl( const Link& rLink ) { aAccHdl = rLink; } void SetLoseFocusHdl( const Link& rLink ) { aLoseFocusHdl = rLink; } void SetGotFocusHdl( const Link& rLink ) { aGotFocusHdl = rLink; } Accelerator& GetAccelerator() { return aAcc; } }; class ExtendedMultiLineEdit : public MultiLineEdit { private: Accelerator aAcc; Link aAccHdl; protected: DECL_LINK( EditAccHdl, Accelerator * ); DECL_LINK( ImplGetFocusHdl, Control* ); DECL_LINK( ImplLoseFocusHdl, Control* ); public: ExtendedMultiLineEdit( Window* pParent, IDEResId nRes ); void SetAccHdl( const Link& rLink ) { aAccHdl = rLink; } Accelerator& GetAccelerator() { return aAcc; } }; #endif //NO_SPECIALEDIT #endif // _BASTYPE3_HXX <|endoftext|>
<commit_before>/************************************************************************* * * 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: iderdll2.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 _IDERDLL2_HXX #define _IDERDLL2_HXX class StarBASIC; class SvxSearchItem; class Accelerator; #include <tools/string.hxx> #include <tools/gen.hxx> #include <tools/link.hxx> #include <bastypes.hxx> #include <bastype2.hxx> #define INVPOSITION 0x7fff class BasicIDEData { private: Accelerator* pAccelerator; SvxSearchItem* pSearchItem; LibInfos aLibInfos; BasicEntryDescriptor m_aLastEntryDesc; Point aObjCatPos; Size aObjCatSize; String aAddLibPath; String aAddLibFilter; USHORT nBasicDialogCount; BOOL OLD_bRelMacroRecording; BOOL bChoosingMacro; BOOL bShellInCriticalSection; void InitAccelerator(); protected: DECL_LINK( GlobalBasicBreakHdl, StarBASIC * ); public: BasicIDEData(); ~BasicIDEData(); LibInfos& GetLibInfos() { return aLibInfos; } BasicEntryDescriptor& GetLastEntryDescriptor() { return m_aLastEntryDesc; } void SetLastEntryDescriptor( BasicEntryDescriptor& rDesc ) { m_aLastEntryDesc = rDesc; } BOOL& ChoosingMacro() { return bChoosingMacro; } BOOL& ShellInCriticalSection() { return bShellInCriticalSection; } USHORT GetBasicDialogCount() const { return nBasicDialogCount; } void IncBasicDialogCount() { nBasicDialogCount++; } void DecBasicDialogCount() { nBasicDialogCount--; } SvxSearchItem& GetSearchItem() const; void SetSearchItem( const SvxSearchItem& rItem ); void SetObjectCatalogPos( const Point& rPnt ) { aObjCatPos = rPnt; } const Point& GetObjectCatalogPos() const { return aObjCatPos; } void SetObjectCatalogSize( const Size& rSize ) { aObjCatSize = rSize; } const Size& GetObjectCatalogSize() const { return aObjCatSize; } const String& GetAddLibPath() const { return aAddLibPath; } void SetAddLibPath( const String& rPath ) { aAddLibPath = rPath; } const String& GetAddLibFilter() const { return aAddLibFilter; } void SetAddLibFilter( const String& rFilter ) { aAddLibFilter = rFilter; } Accelerator* GetAccelerator() { if ( !pAccelerator ) InitAccelerator(); return pAccelerator; } DECL_LINK( ExecuteMacroEvent, void * ); }; #endif //_IDERDLL2_HXX <commit_msg>INTEGRATION: CWS ab53 (1.5.10); FILE MERGED 2008/06/06 13:13:17 ab 1.5.10.1: #i89523# Removed unused code<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: iderdll2.hxx,v $ * $Revision: 1.6 $ * * 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 _IDERDLL2_HXX #define _IDERDLL2_HXX class StarBASIC; class SvxSearchItem; class Accelerator; #include <tools/string.hxx> #include <tools/gen.hxx> #include <tools/link.hxx> #include <bastypes.hxx> #include <bastype2.hxx> #define INVPOSITION 0x7fff class BasicIDEData { private: Accelerator* pAccelerator; SvxSearchItem* pSearchItem; LibInfos aLibInfos; BasicEntryDescriptor m_aLastEntryDesc; Point aObjCatPos; Size aObjCatSize; String aAddLibPath; String aAddLibFilter; USHORT nBasicDialogCount; BOOL OLD_bRelMacroRecording; BOOL bChoosingMacro; BOOL bShellInCriticalSection; protected: DECL_LINK( GlobalBasicBreakHdl, StarBASIC * ); public: BasicIDEData(); ~BasicIDEData(); LibInfos& GetLibInfos() { return aLibInfos; } BasicEntryDescriptor& GetLastEntryDescriptor() { return m_aLastEntryDesc; } void SetLastEntryDescriptor( BasicEntryDescriptor& rDesc ) { m_aLastEntryDesc = rDesc; } BOOL& ChoosingMacro() { return bChoosingMacro; } BOOL& ShellInCriticalSection() { return bShellInCriticalSection; } USHORT GetBasicDialogCount() const { return nBasicDialogCount; } void IncBasicDialogCount() { nBasicDialogCount++; } void DecBasicDialogCount() { nBasicDialogCount--; } SvxSearchItem& GetSearchItem() const; void SetSearchItem( const SvxSearchItem& rItem ); void SetObjectCatalogPos( const Point& rPnt ) { aObjCatPos = rPnt; } const Point& GetObjectCatalogPos() const { return aObjCatPos; } void SetObjectCatalogSize( const Size& rSize ) { aObjCatSize = rSize; } const Size& GetObjectCatalogSize() const { return aObjCatSize; } const String& GetAddLibPath() const { return aAddLibPath; } void SetAddLibPath( const String& rPath ) { aAddLibPath = rPath; } const String& GetAddLibFilter() const { return aAddLibFilter; } void SetAddLibFilter( const String& rFilter ) { aAddLibFilter = rFilter; } DECL_LINK( ExecuteMacroEvent, void * ); }; #endif //_IDERDLL2_HXX <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/tab_contents/render_view_host_delegate_helper.h" #include "base/command_line.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/background_contents_service.h" #include "chrome/browser/character_encoding.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/render_widget_fullscreen_host.h" #include "chrome/browser/renderer_host/render_widget_host.h" #include "chrome/browser/renderer_host/render_widget_host_view.h" #include "chrome/browser/renderer_host/site_instance.h" #include "chrome/browser/tab_contents/background_contents.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view.h" #include "chrome/browser/user_style_sheet_watcher.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_service.h" #include "chrome/common/pref_names.h" BackgroundContents* RenderViewHostDelegateViewHelper::MaybeCreateBackgroundContents( int route_id, Profile* profile, SiteInstance* site, GURL opener_url, const string16& frame_name) { ExtensionsService* extensions_service = profile->GetExtensionsService(); if (!opener_url.is_valid() || frame_name.empty() || !extensions_service || !extensions_service->is_ready()) return NULL; Extension* extension = extensions_service->GetExtensionByURL(opener_url); if (!extension) extension = extensions_service->GetExtensionByWebExtent(opener_url); if (!extension || !extension->HasApiPermission(Extension::kBackgroundPermission)) return NULL; // Only allow a single background contents per app. if (!profile->GetBackgroundContentsService() || profile->GetBackgroundContentsService()->GetAppBackgroundContents( ASCIIToUTF16(extension->id()))) return NULL; // Ensure that we're trying to open this from the extension's process. ExtensionProcessManager* process_manager = profile->GetExtensionProcessManager(); if (!site->GetProcess() || !process_manager || site->GetProcess() != process_manager->GetExtensionProcess(opener_url)) return NULL; // Passed all the checks, so this should be created as a BackgroundContents. BackgroundContents* contents = new BackgroundContents( site, route_id, profile->GetBackgroundContentsService()); string16 appid = ASCIIToUTF16(extension->id()); BackgroundContentsOpenedDetails details = { contents, frame_name, appid }; NotificationService::current()->Notify( NotificationType::BACKGROUND_CONTENTS_OPENED, Source<Profile>(profile), Details<BackgroundContentsOpenedDetails>(&details)); return contents; } TabContents* RenderViewHostDelegateViewHelper::CreateNewWindow( int route_id, Profile* profile, SiteInstance* site, DOMUITypeID domui_type, RenderViewHostDelegate* opener, WindowContainerType window_container_type, const string16& frame_name) { if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) { BackgroundContents* contents = MaybeCreateBackgroundContents( route_id, profile, site, opener->GetURL(), frame_name); if (contents) { pending_contents_[route_id] = contents->render_view_host(); return NULL; } } // Create the new web contents. This will automatically create the new // TabContentsView. In the future, we may want to create the view separately. TabContents* new_contents = new TabContents(profile, site, route_id, opener->GetAsTabContents()); new_contents->set_opener_dom_ui_type(domui_type); TabContentsView* new_view = new_contents->view(); // TODO(brettw) it seems bogus that we have to call this function on the // newly created object and give it one of its own member variables. new_view->CreateViewForWidget(new_contents->render_view_host()); // Save the created window associated with the route so we can show it later. pending_contents_[route_id] = new_contents->render_view_host(); return new_contents; } RenderWidgetHostView* RenderViewHostDelegateViewHelper::CreateNewWidget( int route_id, WebKit::WebPopupType popup_type, RenderProcessHost* process) { RenderWidgetHost* widget_host = new RenderWidgetHost(process, route_id); RenderWidgetHostView* widget_view = RenderWidgetHostView::CreateViewForWidget(widget_host); // Popups should not get activated. widget_view->set_popup_type(popup_type); // Save the created widget associated with the route so we can show it later. pending_widget_views_[route_id] = widget_view; return widget_view; } RenderWidgetHostView* RenderViewHostDelegateViewHelper::CreateNewFullscreenWidget( int route_id, WebKit::WebPopupType popup_type, RenderProcessHost* process) { RenderWidgetFullscreenHost* fullscreen_widget_host = new RenderWidgetFullscreenHost(process, route_id); RenderWidgetHostView* widget_view = RenderWidgetHostView::CreateViewForWidget(fullscreen_widget_host); widget_view->set_popup_type(popup_type); pending_widget_views_[route_id] = widget_view; return widget_view; } TabContents* RenderViewHostDelegateViewHelper::GetCreatedWindow(int route_id) { PendingContents::iterator iter = pending_contents_.find(route_id); if (iter == pending_contents_.end()) { DCHECK(false); return NULL; } RenderViewHost* new_rvh = iter->second; pending_contents_.erase(route_id); // The renderer crashed or it is a TabContents and has no view. if (!new_rvh->process()->HasConnection() || (new_rvh->delegate()->GetAsTabContents() && !new_rvh->view())) return NULL; // TODO(brettw) this seems bogus to reach into here and initialize the host. new_rvh->Init(); return new_rvh->delegate()->GetAsTabContents(); } RenderWidgetHostView* RenderViewHostDelegateViewHelper::GetCreatedWidget( int route_id) { PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id); if (iter == pending_widget_views_.end()) { DCHECK(false); return NULL; } RenderWidgetHostView* widget_host_view = iter->second; pending_widget_views_.erase(route_id); RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost(); if (!widget_host->process()->HasConnection()) { // The view has gone away or the renderer crashed. Nothing to do. return NULL; } return widget_host_view; } void RenderViewHostDelegateViewHelper::RenderWidgetHostDestroyed( RenderWidgetHost* host) { for (PendingWidgetViews::iterator i = pending_widget_views_.begin(); i != pending_widget_views_.end(); ++i) { if (host->view() == i->second) { pending_widget_views_.erase(i); return; } } } // static WebPreferences RenderViewHostDelegateHelper::GetWebkitPrefs( Profile* profile, bool is_dom_ui) { PrefService* prefs = profile->GetPrefs(); WebPreferences web_prefs; web_prefs.fixed_font_family = UTF8ToWide(prefs->GetString(prefs::kWebKitFixedFontFamily)); web_prefs.serif_font_family = UTF8ToWide(prefs->GetString(prefs::kWebKitSerifFontFamily)); web_prefs.sans_serif_font_family = UTF8ToWide(prefs->GetString(prefs::kWebKitSansSerifFontFamily)); if (prefs->GetBoolean(prefs::kWebKitStandardFontIsSerif)) web_prefs.standard_font_family = web_prefs.serif_font_family; else web_prefs.standard_font_family = web_prefs.sans_serif_font_family; web_prefs.cursive_font_family = UTF8ToWide(prefs->GetString(prefs::kWebKitCursiveFontFamily)); web_prefs.fantasy_font_family = UTF8ToWide(prefs->GetString(prefs::kWebKitFantasyFontFamily)); web_prefs.default_font_size = prefs->GetInteger(prefs::kWebKitDefaultFontSize); web_prefs.default_fixed_font_size = prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize); web_prefs.minimum_font_size = prefs->GetInteger(prefs::kWebKitMinimumFontSize); web_prefs.minimum_logical_font_size = prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize); web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset); web_prefs.javascript_can_open_windows_automatically = prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically); web_prefs.dom_paste_enabled = prefs->GetBoolean(prefs::kWebKitDomPasteEnabled); web_prefs.shrinks_standalone_images_to_fit = prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit); const DictionaryValue* inspector_settings = prefs->GetDictionary(prefs::kWebKitInspectorSettings); if (inspector_settings) { for (DictionaryValue::key_iterator iter(inspector_settings->begin_keys()); iter != inspector_settings->end_keys(); ++iter) { std::string value; if (inspector_settings->GetStringWithoutPathExpansion(*iter, &value)) web_prefs.inspector_settings.push_back( std::make_pair(*iter, value)); } } web_prefs.tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks); { // Command line switches are used for preferences with no user interface. const CommandLine& command_line = *CommandLine::ForCurrentProcess(); web_prefs.developer_extras_enabled = !command_line.HasSwitch(switches::kDisableDevTools); web_prefs.javascript_enabled = !command_line.HasSwitch(switches::kDisableJavaScript) && prefs->GetBoolean(prefs::kWebKitJavascriptEnabled); web_prefs.web_security_enabled = !command_line.HasSwitch(switches::kDisableWebSecurity) && prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled); web_prefs.plugins_enabled = !command_line.HasSwitch(switches::kDisablePlugins) && prefs->GetBoolean(prefs::kWebKitPluginsEnabled); web_prefs.java_enabled = !command_line.HasSwitch(switches::kDisableJava) && prefs->GetBoolean(prefs::kWebKitJavaEnabled); web_prefs.loads_images_automatically = prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically); web_prefs.uses_page_cache = command_line.HasSwitch(switches::kEnableFastback); web_prefs.remote_fonts_enabled = !command_line.HasSwitch(switches::kDisableRemoteFonts); web_prefs.xss_auditor_enabled = command_line.HasSwitch(switches::kEnableXSSAuditor); web_prefs.application_cache_enabled = !command_line.HasSwitch(switches::kDisableApplicationCache); web_prefs.local_storage_enabled = !command_line.HasSwitch(switches::kDisableLocalStorage); web_prefs.databases_enabled = !command_line.HasSwitch(switches::kDisableDatabases); web_prefs.experimental_webgl_enabled = !command_line.HasSwitch(switches::kDisableExperimentalWebGL); web_prefs.site_specific_quirks_enabled = !command_line.HasSwitch(switches::kDisableSiteSpecificQuirks); web_prefs.allow_file_access_from_file_urls = command_line.HasSwitch(switches::kAllowFileAccessFromFiles); web_prefs.show_composited_layer_borders = command_line.HasSwitch(switches::kShowCompositedLayerBorders); web_prefs.accelerated_compositing_enabled = !command_line.HasSwitch(switches::kDisableAcceleratedCompositing); web_prefs.accelerated_2d_canvas_enabled = !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas); web_prefs.memory_info_enabled = command_line.HasSwitch(switches::kEnableMemoryInfo); // The user stylesheet watcher may not exist in a testing profile. if (profile->GetUserStyleSheetWatcher()) { web_prefs.user_style_sheet_enabled = true; web_prefs.user_style_sheet_location = profile->GetUserStyleSheetWatcher()->user_style_sheet(); } else { web_prefs.user_style_sheet_enabled = false; } } web_prefs.uses_universal_detector = prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector); web_prefs.text_areas_are_resizable = prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable); // Make sure we will set the default_encoding with canonical encoding name. web_prefs.default_encoding = CharacterEncoding::GetCanonicalEncodingNameByAliasName( web_prefs.default_encoding); if (web_prefs.default_encoding.empty()) { prefs->ClearPref(prefs::kDefaultCharset); web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset); } DCHECK(!web_prefs.default_encoding.empty()); if (is_dom_ui) { web_prefs.loads_images_automatically = true; web_prefs.javascript_enabled = true; } return web_prefs; } <commit_msg>Force accelerated canvas 2d to always be off on Mac<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/tab_contents/render_view_host_delegate_helper.h" #include "base/command_line.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/background_contents_service.h" #include "chrome/browser/character_encoding.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/render_widget_fullscreen_host.h" #include "chrome/browser/renderer_host/render_widget_host.h" #include "chrome/browser/renderer_host/render_widget_host_view.h" #include "chrome/browser/renderer_host/site_instance.h" #include "chrome/browser/tab_contents/background_contents.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view.h" #include "chrome/browser/user_style_sheet_watcher.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_service.h" #include "chrome/common/pref_names.h" BackgroundContents* RenderViewHostDelegateViewHelper::MaybeCreateBackgroundContents( int route_id, Profile* profile, SiteInstance* site, GURL opener_url, const string16& frame_name) { ExtensionsService* extensions_service = profile->GetExtensionsService(); if (!opener_url.is_valid() || frame_name.empty() || !extensions_service || !extensions_service->is_ready()) return NULL; Extension* extension = extensions_service->GetExtensionByURL(opener_url); if (!extension) extension = extensions_service->GetExtensionByWebExtent(opener_url); if (!extension || !extension->HasApiPermission(Extension::kBackgroundPermission)) return NULL; // Only allow a single background contents per app. if (!profile->GetBackgroundContentsService() || profile->GetBackgroundContentsService()->GetAppBackgroundContents( ASCIIToUTF16(extension->id()))) return NULL; // Ensure that we're trying to open this from the extension's process. ExtensionProcessManager* process_manager = profile->GetExtensionProcessManager(); if (!site->GetProcess() || !process_manager || site->GetProcess() != process_manager->GetExtensionProcess(opener_url)) return NULL; // Passed all the checks, so this should be created as a BackgroundContents. BackgroundContents* contents = new BackgroundContents( site, route_id, profile->GetBackgroundContentsService()); string16 appid = ASCIIToUTF16(extension->id()); BackgroundContentsOpenedDetails details = { contents, frame_name, appid }; NotificationService::current()->Notify( NotificationType::BACKGROUND_CONTENTS_OPENED, Source<Profile>(profile), Details<BackgroundContentsOpenedDetails>(&details)); return contents; } TabContents* RenderViewHostDelegateViewHelper::CreateNewWindow( int route_id, Profile* profile, SiteInstance* site, DOMUITypeID domui_type, RenderViewHostDelegate* opener, WindowContainerType window_container_type, const string16& frame_name) { if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) { BackgroundContents* contents = MaybeCreateBackgroundContents( route_id, profile, site, opener->GetURL(), frame_name); if (contents) { pending_contents_[route_id] = contents->render_view_host(); return NULL; } } // Create the new web contents. This will automatically create the new // TabContentsView. In the future, we may want to create the view separately. TabContents* new_contents = new TabContents(profile, site, route_id, opener->GetAsTabContents()); new_contents->set_opener_dom_ui_type(domui_type); TabContentsView* new_view = new_contents->view(); // TODO(brettw) it seems bogus that we have to call this function on the // newly created object and give it one of its own member variables. new_view->CreateViewForWidget(new_contents->render_view_host()); // Save the created window associated with the route so we can show it later. pending_contents_[route_id] = new_contents->render_view_host(); return new_contents; } RenderWidgetHostView* RenderViewHostDelegateViewHelper::CreateNewWidget( int route_id, WebKit::WebPopupType popup_type, RenderProcessHost* process) { RenderWidgetHost* widget_host = new RenderWidgetHost(process, route_id); RenderWidgetHostView* widget_view = RenderWidgetHostView::CreateViewForWidget(widget_host); // Popups should not get activated. widget_view->set_popup_type(popup_type); // Save the created widget associated with the route so we can show it later. pending_widget_views_[route_id] = widget_view; return widget_view; } RenderWidgetHostView* RenderViewHostDelegateViewHelper::CreateNewFullscreenWidget( int route_id, WebKit::WebPopupType popup_type, RenderProcessHost* process) { RenderWidgetFullscreenHost* fullscreen_widget_host = new RenderWidgetFullscreenHost(process, route_id); RenderWidgetHostView* widget_view = RenderWidgetHostView::CreateViewForWidget(fullscreen_widget_host); widget_view->set_popup_type(popup_type); pending_widget_views_[route_id] = widget_view; return widget_view; } TabContents* RenderViewHostDelegateViewHelper::GetCreatedWindow(int route_id) { PendingContents::iterator iter = pending_contents_.find(route_id); if (iter == pending_contents_.end()) { DCHECK(false); return NULL; } RenderViewHost* new_rvh = iter->second; pending_contents_.erase(route_id); // The renderer crashed or it is a TabContents and has no view. if (!new_rvh->process()->HasConnection() || (new_rvh->delegate()->GetAsTabContents() && !new_rvh->view())) return NULL; // TODO(brettw) this seems bogus to reach into here and initialize the host. new_rvh->Init(); return new_rvh->delegate()->GetAsTabContents(); } RenderWidgetHostView* RenderViewHostDelegateViewHelper::GetCreatedWidget( int route_id) { PendingWidgetViews::iterator iter = pending_widget_views_.find(route_id); if (iter == pending_widget_views_.end()) { DCHECK(false); return NULL; } RenderWidgetHostView* widget_host_view = iter->second; pending_widget_views_.erase(route_id); RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost(); if (!widget_host->process()->HasConnection()) { // The view has gone away or the renderer crashed. Nothing to do. return NULL; } return widget_host_view; } void RenderViewHostDelegateViewHelper::RenderWidgetHostDestroyed( RenderWidgetHost* host) { for (PendingWidgetViews::iterator i = pending_widget_views_.begin(); i != pending_widget_views_.end(); ++i) { if (host->view() == i->second) { pending_widget_views_.erase(i); return; } } } // static WebPreferences RenderViewHostDelegateHelper::GetWebkitPrefs( Profile* profile, bool is_dom_ui) { PrefService* prefs = profile->GetPrefs(); WebPreferences web_prefs; web_prefs.fixed_font_family = UTF8ToWide(prefs->GetString(prefs::kWebKitFixedFontFamily)); web_prefs.serif_font_family = UTF8ToWide(prefs->GetString(prefs::kWebKitSerifFontFamily)); web_prefs.sans_serif_font_family = UTF8ToWide(prefs->GetString(prefs::kWebKitSansSerifFontFamily)); if (prefs->GetBoolean(prefs::kWebKitStandardFontIsSerif)) web_prefs.standard_font_family = web_prefs.serif_font_family; else web_prefs.standard_font_family = web_prefs.sans_serif_font_family; web_prefs.cursive_font_family = UTF8ToWide(prefs->GetString(prefs::kWebKitCursiveFontFamily)); web_prefs.fantasy_font_family = UTF8ToWide(prefs->GetString(prefs::kWebKitFantasyFontFamily)); web_prefs.default_font_size = prefs->GetInteger(prefs::kWebKitDefaultFontSize); web_prefs.default_fixed_font_size = prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize); web_prefs.minimum_font_size = prefs->GetInteger(prefs::kWebKitMinimumFontSize); web_prefs.minimum_logical_font_size = prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize); web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset); web_prefs.javascript_can_open_windows_automatically = prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically); web_prefs.dom_paste_enabled = prefs->GetBoolean(prefs::kWebKitDomPasteEnabled); web_prefs.shrinks_standalone_images_to_fit = prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit); const DictionaryValue* inspector_settings = prefs->GetDictionary(prefs::kWebKitInspectorSettings); if (inspector_settings) { for (DictionaryValue::key_iterator iter(inspector_settings->begin_keys()); iter != inspector_settings->end_keys(); ++iter) { std::string value; if (inspector_settings->GetStringWithoutPathExpansion(*iter, &value)) web_prefs.inspector_settings.push_back( std::make_pair(*iter, value)); } } web_prefs.tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks); { // Command line switches are used for preferences with no user interface. const CommandLine& command_line = *CommandLine::ForCurrentProcess(); web_prefs.developer_extras_enabled = !command_line.HasSwitch(switches::kDisableDevTools); web_prefs.javascript_enabled = !command_line.HasSwitch(switches::kDisableJavaScript) && prefs->GetBoolean(prefs::kWebKitJavascriptEnabled); web_prefs.web_security_enabled = !command_line.HasSwitch(switches::kDisableWebSecurity) && prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled); web_prefs.plugins_enabled = !command_line.HasSwitch(switches::kDisablePlugins) && prefs->GetBoolean(prefs::kWebKitPluginsEnabled); web_prefs.java_enabled = !command_line.HasSwitch(switches::kDisableJava) && prefs->GetBoolean(prefs::kWebKitJavaEnabled); web_prefs.loads_images_automatically = prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically); web_prefs.uses_page_cache = command_line.HasSwitch(switches::kEnableFastback); web_prefs.remote_fonts_enabled = !command_line.HasSwitch(switches::kDisableRemoteFonts); web_prefs.xss_auditor_enabled = command_line.HasSwitch(switches::kEnableXSSAuditor); web_prefs.application_cache_enabled = !command_line.HasSwitch(switches::kDisableApplicationCache); web_prefs.local_storage_enabled = !command_line.HasSwitch(switches::kDisableLocalStorage); web_prefs.databases_enabled = !command_line.HasSwitch(switches::kDisableDatabases); web_prefs.experimental_webgl_enabled = !command_line.HasSwitch(switches::kDisableExperimentalWebGL); web_prefs.site_specific_quirks_enabled = !command_line.HasSwitch(switches::kDisableSiteSpecificQuirks); web_prefs.allow_file_access_from_file_urls = command_line.HasSwitch(switches::kAllowFileAccessFromFiles); web_prefs.show_composited_layer_borders = command_line.HasSwitch(switches::kShowCompositedLayerBorders); web_prefs.accelerated_compositing_enabled = !command_line.HasSwitch(switches::kDisableAcceleratedCompositing); // Force this flag off for mac for now. crbug.com/54197 #if defined(OS_MACOSX) web_prefs.accelerated_2d_canvas_enabled = false; #else web_prefs.accelerated_2d_canvas_enabled = !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas); #endif web_prefs.memory_info_enabled = command_line.HasSwitch(switches::kEnableMemoryInfo); // The user stylesheet watcher may not exist in a testing profile. if (profile->GetUserStyleSheetWatcher()) { web_prefs.user_style_sheet_enabled = true; web_prefs.user_style_sheet_location = profile->GetUserStyleSheetWatcher()->user_style_sheet(); } else { web_prefs.user_style_sheet_enabled = false; } } web_prefs.uses_universal_detector = prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector); web_prefs.text_areas_are_resizable = prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable); // Make sure we will set the default_encoding with canonical encoding name. web_prefs.default_encoding = CharacterEncoding::GetCanonicalEncodingNameByAliasName( web_prefs.default_encoding); if (web_prefs.default_encoding.empty()) { prefs->ClearPref(prefs::kDefaultCharset); web_prefs.default_encoding = prefs->GetString(prefs::kDefaultCharset); } DCHECK(!web_prefs.default_encoding.empty()); if (is_dom_ui) { web_prefs.loads_images_automatically = true; web_prefs.javascript_enabled = true; } return web_prefs; } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/tab_contents/tab_contents_view_views.h" #include "base/string_util.h" #include "build/build_config.h" #include "chrome/browser/download/download_shelf.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/render_view_host_factory.h" #include "chrome/browser/renderer_host/render_widget_host_view_views.h" #include "chrome/browser/tab_contents/interstitial_page.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_delegate.h" #include "chrome/browser/views/sad_tab_view.h" #include "chrome/browser/views/tab_contents/render_view_context_menu_views.h" #include "gfx/canvas_skia_paint.h" #include "gfx/point.h" #include "gfx/rect.h" #include "gfx/size.h" #include "views/controls/native/native_view_host.h" #include "views/fill_layout.h" #include "views/focus/focus_manager.h" #include "views/focus/view_storage.h" #include "views/screen.h" #include "views/widget/widget.h" using WebKit::WebDragOperation; using WebKit::WebDragOperationsMask; using WebKit::WebInputEvent; // static TabContentsView* TabContentsView::Create(TabContents* tab_contents) { return new TabContentsViewViews(tab_contents); } TabContentsViewViews::TabContentsViewViews(TabContents* tab_contents) : TabContentsView(tab_contents), sad_tab_(NULL), ignore_next_char_event_(false) { last_focused_view_storage_id_ = views::ViewStorage::GetSharedInstance()->CreateStorageID(); SetLayoutManager(new views::FillLayout()); } TabContentsViewViews::~TabContentsViewViews() { // Make sure to remove any stored view we may still have in the ViewStorage. // // It is possible the view went away before us, so we only do this if the // view is registered. views::ViewStorage* view_storage = views::ViewStorage::GetSharedInstance(); if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL) view_storage->RemoveView(last_focused_view_storage_id_); } void TabContentsViewViews::AttachConstrainedWindow( ConstrainedWindowGtk* constrained_window) { // TODO(anicolao): reimplement all dialogs as DOMUI NOTIMPLEMENTED(); } void TabContentsViewViews::RemoveConstrainedWindow( ConstrainedWindowGtk* constrained_window) { // TODO(anicolao): reimplement all dialogs as DOMUI NOTIMPLEMENTED(); } void TabContentsViewViews::CreateView(const gfx::Size& initial_size) { SetBounds(gfx::Rect(bounds().origin(), initial_size)); } RenderWidgetHostView* TabContentsViewViews::CreateViewForWidget( RenderWidgetHost* render_widget_host) { if (render_widget_host->view()) { // During testing, the view will already be set up in most cases to the // test view, so we don't want to clobber it with a real one. To verify that // this actually is happening (and somebody isn't accidentally creating the // view twice), we check for the RVH Factory, which will be set when we're // making special ones (which go along with the special views). DCHECK(RenderViewHostFactory::has_factory()); return render_widget_host->view(); } // If we were showing sad tab, remove it now. if (sad_tab_ != NULL) { RemoveChildView(sad_tab_); AddChildView(new views::View()); sad_tab_ = NULL; } RenderWidgetHostViewViews* view = new RenderWidgetHostViewViews(render_widget_host); AddChildView(view); view->Show(); view->InitAsChild(); // TODO(anicolao): implement drag'n'drop hooks if needed return view; } gfx::NativeView TabContentsViewViews::GetNativeView() const { return GetWidget()->GetNativeView(); } gfx::NativeView TabContentsViewViews::GetContentNativeView() const { RenderWidgetHostView* rwhv = tab_contents()->GetRenderWidgetHostView(); if (!rwhv) return NULL; return rwhv->GetNativeView(); } gfx::NativeWindow TabContentsViewViews::GetTopLevelNativeWindow() const { GtkWidget* window = gtk_widget_get_ancestor(GetNativeView(), GTK_TYPE_WINDOW); return window ? GTK_WINDOW(window) : NULL; } void TabContentsViewViews::GetContainerBounds(gfx::Rect* out) const { *out = bounds(); } void TabContentsViewViews::StartDragging(const WebDropData& drop_data, WebDragOperationsMask ops, const SkBitmap& image, const gfx::Point& image_offset) { // TODO(anicolao): implement dragging } void TabContentsViewViews::SetPageTitle(const std::wstring& title) { // TODO(anicolao): figure out if there's anything useful to do here } void TabContentsViewViews::OnTabCrashed() { } void TabContentsViewViews::SizeContents(const gfx::Size& size) { WasSized(size); // We need to send this immediately. RenderWidgetHostView* rwhv = tab_contents()->GetRenderWidgetHostView(); if (rwhv) rwhv->SetSize(size); } void TabContentsViewViews::Focus() { if (tab_contents()->interstitial_page()) { tab_contents()->interstitial_page()->Focus(); return; } if (tab_contents()->is_crashed() && sad_tab_ != NULL) { sad_tab_->RequestFocus(); return; } RenderWidgetHostView* rwhv = tab_contents()->GetRenderWidgetHostView(); gtk_widget_grab_focus(rwhv ? rwhv->GetNativeView() : GetNativeView()); } void TabContentsViewViews::SetInitialFocus() { if (tab_contents()->FocusLocationBarByDefault()) tab_contents()->SetFocusToLocationBar(false); else Focus(); } void TabContentsViewViews::StoreFocus() { views::ViewStorage* view_storage = views::ViewStorage::GetSharedInstance(); if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL) view_storage->RemoveView(last_focused_view_storage_id_); views::FocusManager* focus_manager = views::FocusManager::GetFocusManagerForNativeView(GetNativeView()); if (focus_manager) { // |focus_manager| can be NULL if the tab has been detached but still // exists. views::View* focused_view = focus_manager->GetFocusedView(); if (focused_view) view_storage->StoreView(last_focused_view_storage_id_, focused_view); } } void TabContentsViewViews::RestoreFocus() { views::ViewStorage* view_storage = views::ViewStorage::GetSharedInstance(); views::View* last_focused_view = view_storage->RetrieveView(last_focused_view_storage_id_); if (!last_focused_view) { SetInitialFocus(); } else { views::FocusManager* focus_manager = views::FocusManager::GetFocusManagerForNativeView(GetNativeView()); // If you hit this DCHECK, please report it to Jay (jcampan). DCHECK(focus_manager != NULL) << "No focus manager when restoring focus."; if (last_focused_view->IsFocusableInRootView() && focus_manager && focus_manager->ContainsView(last_focused_view)) { last_focused_view->RequestFocus(); } else { // The focused view may not belong to the same window hierarchy (e.g. // if the location bar was focused and the tab is dragged out), or it may // no longer be focusable (e.g. if the location bar was focused and then // we switched to fullscreen mode). In that case we default to the // default focus. SetInitialFocus(); } view_storage->RemoveView(last_focused_view_storage_id_); } } void TabContentsViewViews::DidChangeBounds(const gfx::Rect& previous, const gfx::Rect& current) { if (IsVisibleInRootView()) WasSized(gfx::Size(current.width(), current.height())); } void TabContentsViewViews::Paint(gfx::Canvas* canvas) { } void TabContentsViewViews::UpdateDragCursor(WebDragOperation operation) { NOTIMPLEMENTED(); // It's not even clear a drag cursor will make sense for touch. // TODO(anicolao): implement dragging } void TabContentsViewViews::GotFocus() { if (tab_contents()->delegate()) tab_contents()->delegate()->TabContentsFocused(tab_contents()); } void TabContentsViewViews::TakeFocus(bool reverse) { if (tab_contents()->delegate() && !tab_contents()->delegate()->TakeFocus(reverse)) { views::FocusManager* focus_manager = views::FocusManager::GetFocusManagerForNativeView(GetNativeView()); // We may not have a focus manager if the tab has been switched before this // message arrived. if (focus_manager) focus_manager->AdvanceFocus(reverse); } } void TabContentsViewViews::VisibilityChanged(views::View *, bool is_visible) { if (is_visible) { WasShown(); } else { WasHidden(); } } void TabContentsViewViews::ShowContextMenu(const ContextMenuParams& params) { // Allow delegates to handle the context menu operation first. if (tab_contents()->delegate()->HandleContextMenu(params)) return; context_menu_.reset(new RenderViewContextMenuViews(tab_contents(), params)); context_menu_->Init(); gfx::Point screen_point(params.x, params.y); RenderWidgetHostViewViews* rwhv = static_cast<RenderWidgetHostViewViews*> (tab_contents()->GetRenderWidgetHostView()); if (rwhv) { views::View::ConvertPointToScreen(rwhv, &screen_point); } // Enable recursive tasks on the message loop so we can get updates while // the context menu is being displayed. bool old_state = MessageLoop::current()->NestableTasksAllowed(); MessageLoop::current()->SetNestableTasksAllowed(true); context_menu_->RunMenuAt(screen_point.x(), screen_point.y()); MessageLoop::current()->SetNestableTasksAllowed(old_state); } void TabContentsViewViews::ShowPopupMenu(const gfx::Rect& bounds, int item_height, double item_font_size, int selected_item, const std::vector<WebMenuItem>& items, bool right_aligned) { // External popup menus are only used on Mac. NOTREACHED(); } void TabContentsViewViews::WasHidden() { tab_contents()->HideContents(); } void TabContentsViewViews::WasShown() { tab_contents()->ShowContents(); } void TabContentsViewViews::WasSized(const gfx::Size& size) { // We have to check that the RenderWidgetHostView is the proper size. // It can be wrong in cases where the renderer has died and the host // view needed to be recreated. bool needs_resize = size != size_; if (needs_resize) { size_ = size; if (tab_contents()->interstitial_page()) tab_contents()->interstitial_page()->SetSize(size); } RenderWidgetHostView* rwhv = tab_contents()->GetRenderWidgetHostView(); if (rwhv && rwhv->GetViewBounds().size() != size) rwhv->SetSize(size); if (needs_resize) SetFloatingPosition(size); } void TabContentsViewViews::SetFloatingPosition(const gfx::Size& size) { // TODO(anicolao): rework this once we have DOMUI views for dialogs SetBounds(x(), y(), size.width(), size.height()); } <commit_msg>Compile fix for touchui.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/tab_contents/tab_contents_view_views.h" #include "base/string_util.h" #include "build/build_config.h" #include "chrome/browser/download/download_shelf.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/render_view_host_factory.h" #include "chrome/browser/renderer_host/render_widget_host_view_views.h" #include "chrome/browser/tab_contents/interstitial_page.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_delegate.h" #include "chrome/browser/views/sad_tab_view.h" #include "chrome/browser/views/tab_contents/render_view_context_menu_views.h" #include "gfx/canvas_skia_paint.h" #include "gfx/point.h" #include "gfx/rect.h" #include "gfx/size.h" #include "views/controls/native/native_view_host.h" #include "views/fill_layout.h" #include "views/focus/focus_manager.h" #include "views/focus/view_storage.h" #include "views/screen.h" #include "views/widget/widget.h" using WebKit::WebDragOperation; using WebKit::WebDragOperationsMask; using WebKit::WebInputEvent; // static TabContentsView* TabContentsView::Create(TabContents* tab_contents) { return new TabContentsViewViews(tab_contents); } TabContentsViewViews::TabContentsViewViews(TabContents* tab_contents) : TabContentsView(tab_contents), sad_tab_(NULL), ignore_next_char_event_(false) { last_focused_view_storage_id_ = views::ViewStorage::GetInstance()->CreateStorageID(); SetLayoutManager(new views::FillLayout()); } TabContentsViewViews::~TabContentsViewViews() { // Make sure to remove any stored view we may still have in the ViewStorage. // // It is possible the view went away before us, so we only do this if the // view is registered. views::ViewStorage* view_storage = views::ViewStorage::GetInstance(); if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL) view_storage->RemoveView(last_focused_view_storage_id_); } void TabContentsViewViews::AttachConstrainedWindow( ConstrainedWindowGtk* constrained_window) { // TODO(anicolao): reimplement all dialogs as DOMUI NOTIMPLEMENTED(); } void TabContentsViewViews::RemoveConstrainedWindow( ConstrainedWindowGtk* constrained_window) { // TODO(anicolao): reimplement all dialogs as DOMUI NOTIMPLEMENTED(); } void TabContentsViewViews::CreateView(const gfx::Size& initial_size) { SetBounds(gfx::Rect(bounds().origin(), initial_size)); } RenderWidgetHostView* TabContentsViewViews::CreateViewForWidget( RenderWidgetHost* render_widget_host) { if (render_widget_host->view()) { // During testing, the view will already be set up in most cases to the // test view, so we don't want to clobber it with a real one. To verify that // this actually is happening (and somebody isn't accidentally creating the // view twice), we check for the RVH Factory, which will be set when we're // making special ones (which go along with the special views). DCHECK(RenderViewHostFactory::has_factory()); return render_widget_host->view(); } // If we were showing sad tab, remove it now. if (sad_tab_ != NULL) { RemoveChildView(sad_tab_); AddChildView(new views::View()); sad_tab_ = NULL; } RenderWidgetHostViewViews* view = new RenderWidgetHostViewViews(render_widget_host); AddChildView(view); view->Show(); view->InitAsChild(); // TODO(anicolao): implement drag'n'drop hooks if needed return view; } gfx::NativeView TabContentsViewViews::GetNativeView() const { return GetWidget()->GetNativeView(); } gfx::NativeView TabContentsViewViews::GetContentNativeView() const { RenderWidgetHostView* rwhv = tab_contents()->GetRenderWidgetHostView(); if (!rwhv) return NULL; return rwhv->GetNativeView(); } gfx::NativeWindow TabContentsViewViews::GetTopLevelNativeWindow() const { GtkWidget* window = gtk_widget_get_ancestor(GetNativeView(), GTK_TYPE_WINDOW); return window ? GTK_WINDOW(window) : NULL; } void TabContentsViewViews::GetContainerBounds(gfx::Rect* out) const { *out = bounds(); } void TabContentsViewViews::StartDragging(const WebDropData& drop_data, WebDragOperationsMask ops, const SkBitmap& image, const gfx::Point& image_offset) { // TODO(anicolao): implement dragging } void TabContentsViewViews::SetPageTitle(const std::wstring& title) { // TODO(anicolao): figure out if there's anything useful to do here } void TabContentsViewViews::OnTabCrashed() { } void TabContentsViewViews::SizeContents(const gfx::Size& size) { WasSized(size); // We need to send this immediately. RenderWidgetHostView* rwhv = tab_contents()->GetRenderWidgetHostView(); if (rwhv) rwhv->SetSize(size); } void TabContentsViewViews::Focus() { if (tab_contents()->interstitial_page()) { tab_contents()->interstitial_page()->Focus(); return; } if (tab_contents()->is_crashed() && sad_tab_ != NULL) { sad_tab_->RequestFocus(); return; } RenderWidgetHostView* rwhv = tab_contents()->GetRenderWidgetHostView(); gtk_widget_grab_focus(rwhv ? rwhv->GetNativeView() : GetNativeView()); } void TabContentsViewViews::SetInitialFocus() { if (tab_contents()->FocusLocationBarByDefault()) tab_contents()->SetFocusToLocationBar(false); else Focus(); } void TabContentsViewViews::StoreFocus() { views::ViewStorage* view_storage = views::ViewStorage::GetInstance(); if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL) view_storage->RemoveView(last_focused_view_storage_id_); views::FocusManager* focus_manager = views::FocusManager::GetFocusManagerForNativeView(GetNativeView()); if (focus_manager) { // |focus_manager| can be NULL if the tab has been detached but still // exists. views::View* focused_view = focus_manager->GetFocusedView(); if (focused_view) view_storage->StoreView(last_focused_view_storage_id_, focused_view); } } void TabContentsViewViews::RestoreFocus() { views::ViewStorage* view_storage = views::ViewStorage::GetInstance(); views::View* last_focused_view = view_storage->RetrieveView(last_focused_view_storage_id_); if (!last_focused_view) { SetInitialFocus(); } else { views::FocusManager* focus_manager = views::FocusManager::GetFocusManagerForNativeView(GetNativeView()); // If you hit this DCHECK, please report it to Jay (jcampan). DCHECK(focus_manager != NULL) << "No focus manager when restoring focus."; if (last_focused_view->IsFocusableInRootView() && focus_manager && focus_manager->ContainsView(last_focused_view)) { last_focused_view->RequestFocus(); } else { // The focused view may not belong to the same window hierarchy (e.g. // if the location bar was focused and the tab is dragged out), or it may // no longer be focusable (e.g. if the location bar was focused and then // we switched to fullscreen mode). In that case we default to the // default focus. SetInitialFocus(); } view_storage->RemoveView(last_focused_view_storage_id_); } } void TabContentsViewViews::DidChangeBounds(const gfx::Rect& previous, const gfx::Rect& current) { if (IsVisibleInRootView()) WasSized(gfx::Size(current.width(), current.height())); } void TabContentsViewViews::Paint(gfx::Canvas* canvas) { } void TabContentsViewViews::UpdateDragCursor(WebDragOperation operation) { NOTIMPLEMENTED(); // It's not even clear a drag cursor will make sense for touch. // TODO(anicolao): implement dragging } void TabContentsViewViews::GotFocus() { if (tab_contents()->delegate()) tab_contents()->delegate()->TabContentsFocused(tab_contents()); } void TabContentsViewViews::TakeFocus(bool reverse) { if (tab_contents()->delegate() && !tab_contents()->delegate()->TakeFocus(reverse)) { views::FocusManager* focus_manager = views::FocusManager::GetFocusManagerForNativeView(GetNativeView()); // We may not have a focus manager if the tab has been switched before this // message arrived. if (focus_manager) focus_manager->AdvanceFocus(reverse); } } void TabContentsViewViews::VisibilityChanged(views::View *, bool is_visible) { if (is_visible) { WasShown(); } else { WasHidden(); } } void TabContentsViewViews::ShowContextMenu(const ContextMenuParams& params) { // Allow delegates to handle the context menu operation first. if (tab_contents()->delegate()->HandleContextMenu(params)) return; context_menu_.reset(new RenderViewContextMenuViews(tab_contents(), params)); context_menu_->Init(); gfx::Point screen_point(params.x, params.y); RenderWidgetHostViewViews* rwhv = static_cast<RenderWidgetHostViewViews*> (tab_contents()->GetRenderWidgetHostView()); if (rwhv) { views::View::ConvertPointToScreen(rwhv, &screen_point); } // Enable recursive tasks on the message loop so we can get updates while // the context menu is being displayed. bool old_state = MessageLoop::current()->NestableTasksAllowed(); MessageLoop::current()->SetNestableTasksAllowed(true); context_menu_->RunMenuAt(screen_point.x(), screen_point.y()); MessageLoop::current()->SetNestableTasksAllowed(old_state); } void TabContentsViewViews::ShowPopupMenu(const gfx::Rect& bounds, int item_height, double item_font_size, int selected_item, const std::vector<WebMenuItem>& items, bool right_aligned) { // External popup menus are only used on Mac. NOTREACHED(); } void TabContentsViewViews::WasHidden() { tab_contents()->HideContents(); } void TabContentsViewViews::WasShown() { tab_contents()->ShowContents(); } void TabContentsViewViews::WasSized(const gfx::Size& size) { // We have to check that the RenderWidgetHostView is the proper size. // It can be wrong in cases where the renderer has died and the host // view needed to be recreated. bool needs_resize = size != size_; if (needs_resize) { size_ = size; if (tab_contents()->interstitial_page()) tab_contents()->interstitial_page()->SetSize(size); } RenderWidgetHostView* rwhv = tab_contents()->GetRenderWidgetHostView(); if (rwhv && rwhv->GetViewBounds().size() != size) rwhv->SetSize(size); if (needs_resize) SetFloatingPosition(size); } void TabContentsViewViews::SetFloatingPosition(const gfx::Size& size) { // TODO(anicolao): rework this once we have DOMUI views for dialogs SetBounds(x(), y(), size.width(), size.height()); } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2010-2011, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECore/CompoundData.h" #include "IECore/CompoundParameter.h" #include "IECore/MessageHandler.h" #include "Convert.h" #include "ToHoudiniAttribConverter.h" #include "ToHoudiniGeometryConverter.h" #include "ToHoudiniStringAttribConverter.h" using namespace IECore; using namespace IECoreHoudini; IE_CORE_DEFINERUNTIMETYPED( ToHoudiniGeometryConverter ); ToHoudiniGeometryConverter::ToHoudiniGeometryConverter( const VisibleRenderable *renderable, const std::string &description ) : ToHoudiniConverter( description, VisibleRenderableTypeId ) { srcParameter()->setValue( (VisibleRenderable *)renderable ); } ToHoudiniGeometryConverter::~ToHoudiniGeometryConverter() { } bool ToHoudiniGeometryConverter::convert( GU_DetailHandle handle ) const { ConstCompoundObjectPtr operands = parameters()->getTypedValidatedValue<CompoundObject>(); GU_DetailHandleAutoWriteLock writeHandle( handle ); GU_Detail *geo = writeHandle.getGdp(); if ( !geo ) { return false; } const VisibleRenderable *renderable = IECore::runTimeCast<const VisibleRenderable>( srcParameter()->getValidatedValue() ); if ( !renderable ) { return false; } return doConversion( renderable, geo ); } GA_Range ToHoudiniGeometryConverter::appendPoints( GA_Detail *geo, const IECore::V3fVectorData *positions ) const { if ( !positions ) { return GA_Range(); } const std::vector<Imath::V3f> &pos = positions->readable(); GA_OffsetList offsets; offsets.reserve( pos.size() ); for ( size_t i=0; i < pos.size(); i++ ) { GA_Offset offset = geo->appendPoint(); geo->setPos3( offset, IECore::convert<UT_Vector3>( pos[i] ) ); offsets.append( offset ); } return GA_Range( geo->getPointMap(), offsets ); } void ToHoudiniGeometryConverter::transferAttribs( const Primitive *primitive, GU_Detail *geo, const GA_Range &newPoints, const GA_Range &newPrims, PrimitiveVariable::Interpolation vertexInterpolation, PrimitiveVariable::Interpolation primitiveInterpolation, PrimitiveVariable::Interpolation pointInterpolation, PrimitiveVariable::Interpolation detailInterpolation ) const { GA_OffsetList offsets; if ( newPrims.isValid() ) { const GA_PrimitiveList &primitives = geo->getPrimitiveList(); for ( GA_Iterator it=newPrims.begin(); !it.atEnd(); ++it ) { const GA_Primitive *prim = primitives.get( it.getOffset() ); size_t numPrimVerts = prim->getVertexCount(); for ( size_t v=0; v < numPrimVerts; v++ ) { if ( prim->getTypeId() == GEO_PRIMPOLY ) { offsets.append( prim->getVertexOffset( numPrimVerts - 1 - v ) ); } else { offsets.append( prim->getVertexOffset( v ) ); } } } } GA_Range vertRange( geo->getVertexMap(), offsets ); // P should already have been added as points std::vector<std::string> variablesToIgnore; variablesToIgnore.push_back( "P" ); // match all the string variables to each associated indices variable /// \todo: replace all this logic with IECore::IndexedData once it exists... PrimitiveVariableMap stringsToIndices; for ( PrimitiveVariableMap::const_iterator it=primitive->variables.begin() ; it != primitive->variables.end(); it++ ) { if ( !primitive->isPrimitiveVariableValid( it->second ) ) { IECore::msg( IECore::MessageHandler::Warning, "ToHoudiniGeometryConverter", "PrimitiveVariable " + it->first + " is invilad. Ignoring." ); variablesToIgnore.push_back( it->first ); continue; } ToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( it->second.data ); if ( !converter ) { continue; } if ( it->second.data->isInstanceOf( StringVectorDataTypeId ) ) { std::string indicesVariableName = it->first + "Indices"; PrimitiveVariableMap::const_iterator indices = primitive->variables.find( indicesVariableName ); if ( indices != primitive->variables.end() && indices->second.data->isInstanceOf( IntVectorDataTypeId ) && primitive->isPrimitiveVariableValid( indices->second ) ) { stringsToIndices[it->first] = indices->second; variablesToIgnore.push_back( indicesVariableName ); } } } // add the primitive variables to the various GEO_AttribDicts based on interpolation type for ( PrimitiveVariableMap::const_iterator it=primitive->variables.begin() ; it != primitive->variables.end(); it++ ) { if ( find( variablesToIgnore.begin(), variablesToIgnore.end(), it->first ) != variablesToIgnore.end() ) { continue; } ToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( it->second.data ); if ( !converter ) { continue; } PrimitiveVariable::Interpolation interpolation = it->second.interpolation; if ( converter->isInstanceOf( (IECore::TypeId)ToHoudiniStringVectorAttribConverterTypeId ) ) { PrimitiveVariableMap::const_iterator indices = stringsToIndices.find( it->first ); if ( indices != stringsToIndices.end() ) { ToHoudiniStringVectorAttribConverter *stringVectorConverter = IECore::runTimeCast<ToHoudiniStringVectorAttribConverter>( converter ); stringVectorConverter->indicesParameter()->setValidatedValue( indices->second.data ); interpolation = indices->second.interpolation; } } if ( interpolation == detailInterpolation ) { // add detail attribs converter->convert( it->first, geo ); } else if ( interpolation == pointInterpolation ) { // add point attribs converter->convert( it->first, geo, newPoints ); } else if ( interpolation == primitiveInterpolation ) { // add primitive attribs converter->convert( it->first, geo, newPrims ); } else if ( interpolation == vertexInterpolation ) { // add vertex attribs converter->convert( it->first, geo, vertRange ); } } } ///////////////////////////////////////////////////////////////////////////////// // Factory ///////////////////////////////////////////////////////////////////////////////// ToHoudiniGeometryConverterPtr ToHoudiniGeometryConverter::create( const VisibleRenderable *renderable ) { const TypesToFnsMap *m = typesToFns(); TypesToFnsMap::const_iterator it = m->find( Types( renderable->typeId() ) ); if( it!=m->end() ) { return it->second( renderable ); } return 0; } void ToHoudiniGeometryConverter::registerConverter( IECore::TypeId fromType, CreatorFn creator ) { TypesToFnsMap *m = typesToFns(); m->insert( TypesToFnsMap::value_type( Types( fromType ), creator ) ); } ToHoudiniGeometryConverter::TypesToFnsMap *ToHoudiniGeometryConverter::typesToFns() { static TypesToFnsMap *m = new TypesToFnsMap; return m; } ///////////////////////////////////////////////////////////////////////////////// // Implementation of nested Types class ///////////////////////////////////////////////////////////////////////////////// ToHoudiniGeometryConverter::Types::Types( IECore::TypeId from ) : fromType( from ) { } bool ToHoudiniGeometryConverter::Types::operator < ( const Types &other ) const { return fromType < other.fromType; } <commit_msg>fixing typo<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2010-2011, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "IECore/CompoundData.h" #include "IECore/CompoundParameter.h" #include "IECore/MessageHandler.h" #include "Convert.h" #include "ToHoudiniAttribConverter.h" #include "ToHoudiniGeometryConverter.h" #include "ToHoudiniStringAttribConverter.h" using namespace IECore; using namespace IECoreHoudini; IE_CORE_DEFINERUNTIMETYPED( ToHoudiniGeometryConverter ); ToHoudiniGeometryConverter::ToHoudiniGeometryConverter( const VisibleRenderable *renderable, const std::string &description ) : ToHoudiniConverter( description, VisibleRenderableTypeId ) { srcParameter()->setValue( (VisibleRenderable *)renderable ); } ToHoudiniGeometryConverter::~ToHoudiniGeometryConverter() { } bool ToHoudiniGeometryConverter::convert( GU_DetailHandle handle ) const { ConstCompoundObjectPtr operands = parameters()->getTypedValidatedValue<CompoundObject>(); GU_DetailHandleAutoWriteLock writeHandle( handle ); GU_Detail *geo = writeHandle.getGdp(); if ( !geo ) { return false; } const VisibleRenderable *renderable = IECore::runTimeCast<const VisibleRenderable>( srcParameter()->getValidatedValue() ); if ( !renderable ) { return false; } return doConversion( renderable, geo ); } GA_Range ToHoudiniGeometryConverter::appendPoints( GA_Detail *geo, const IECore::V3fVectorData *positions ) const { if ( !positions ) { return GA_Range(); } const std::vector<Imath::V3f> &pos = positions->readable(); GA_OffsetList offsets; offsets.reserve( pos.size() ); for ( size_t i=0; i < pos.size(); i++ ) { GA_Offset offset = geo->appendPoint(); geo->setPos3( offset, IECore::convert<UT_Vector3>( pos[i] ) ); offsets.append( offset ); } return GA_Range( geo->getPointMap(), offsets ); } void ToHoudiniGeometryConverter::transferAttribs( const Primitive *primitive, GU_Detail *geo, const GA_Range &newPoints, const GA_Range &newPrims, PrimitiveVariable::Interpolation vertexInterpolation, PrimitiveVariable::Interpolation primitiveInterpolation, PrimitiveVariable::Interpolation pointInterpolation, PrimitiveVariable::Interpolation detailInterpolation ) const { GA_OffsetList offsets; if ( newPrims.isValid() ) { const GA_PrimitiveList &primitives = geo->getPrimitiveList(); for ( GA_Iterator it=newPrims.begin(); !it.atEnd(); ++it ) { const GA_Primitive *prim = primitives.get( it.getOffset() ); size_t numPrimVerts = prim->getVertexCount(); for ( size_t v=0; v < numPrimVerts; v++ ) { if ( prim->getTypeId() == GEO_PRIMPOLY ) { offsets.append( prim->getVertexOffset( numPrimVerts - 1 - v ) ); } else { offsets.append( prim->getVertexOffset( v ) ); } } } } GA_Range vertRange( geo->getVertexMap(), offsets ); // P should already have been added as points std::vector<std::string> variablesToIgnore; variablesToIgnore.push_back( "P" ); // match all the string variables to each associated indices variable /// \todo: replace all this logic with IECore::IndexedData once it exists... PrimitiveVariableMap stringsToIndices; for ( PrimitiveVariableMap::const_iterator it=primitive->variables.begin() ; it != primitive->variables.end(); it++ ) { if ( !primitive->isPrimitiveVariableValid( it->second ) ) { IECore::msg( IECore::MessageHandler::Warning, "ToHoudiniGeometryConverter", "PrimitiveVariable " + it->first + " is invalid. Ignoring." ); variablesToIgnore.push_back( it->first ); continue; } ToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( it->second.data ); if ( !converter ) { continue; } if ( it->second.data->isInstanceOf( StringVectorDataTypeId ) ) { std::string indicesVariableName = it->first + "Indices"; PrimitiveVariableMap::const_iterator indices = primitive->variables.find( indicesVariableName ); if ( indices != primitive->variables.end() && indices->second.data->isInstanceOf( IntVectorDataTypeId ) && primitive->isPrimitiveVariableValid( indices->second ) ) { stringsToIndices[it->first] = indices->second; variablesToIgnore.push_back( indicesVariableName ); } } } // add the primitive variables to the various GEO_AttribDicts based on interpolation type for ( PrimitiveVariableMap::const_iterator it=primitive->variables.begin() ; it != primitive->variables.end(); it++ ) { if ( find( variablesToIgnore.begin(), variablesToIgnore.end(), it->first ) != variablesToIgnore.end() ) { continue; } ToHoudiniAttribConverterPtr converter = ToHoudiniAttribConverter::create( it->second.data ); if ( !converter ) { continue; } PrimitiveVariable::Interpolation interpolation = it->second.interpolation; if ( converter->isInstanceOf( (IECore::TypeId)ToHoudiniStringVectorAttribConverterTypeId ) ) { PrimitiveVariableMap::const_iterator indices = stringsToIndices.find( it->first ); if ( indices != stringsToIndices.end() ) { ToHoudiniStringVectorAttribConverter *stringVectorConverter = IECore::runTimeCast<ToHoudiniStringVectorAttribConverter>( converter ); stringVectorConverter->indicesParameter()->setValidatedValue( indices->second.data ); interpolation = indices->second.interpolation; } } if ( interpolation == detailInterpolation ) { // add detail attribs converter->convert( it->first, geo ); } else if ( interpolation == pointInterpolation ) { // add point attribs converter->convert( it->first, geo, newPoints ); } else if ( interpolation == primitiveInterpolation ) { // add primitive attribs converter->convert( it->first, geo, newPrims ); } else if ( interpolation == vertexInterpolation ) { // add vertex attribs converter->convert( it->first, geo, vertRange ); } } } ///////////////////////////////////////////////////////////////////////////////// // Factory ///////////////////////////////////////////////////////////////////////////////// ToHoudiniGeometryConverterPtr ToHoudiniGeometryConverter::create( const VisibleRenderable *renderable ) { const TypesToFnsMap *m = typesToFns(); TypesToFnsMap::const_iterator it = m->find( Types( renderable->typeId() ) ); if( it!=m->end() ) { return it->second( renderable ); } return 0; } void ToHoudiniGeometryConverter::registerConverter( IECore::TypeId fromType, CreatorFn creator ) { TypesToFnsMap *m = typesToFns(); m->insert( TypesToFnsMap::value_type( Types( fromType ), creator ) ); } ToHoudiniGeometryConverter::TypesToFnsMap *ToHoudiniGeometryConverter::typesToFns() { static TypesToFnsMap *m = new TypesToFnsMap; return m; } ///////////////////////////////////////////////////////////////////////////////// // Implementation of nested Types class ///////////////////////////////////////////////////////////////////////////////// ToHoudiniGeometryConverter::Types::Types( IECore::TypeId from ) : fromType( from ) { } bool ToHoudiniGeometryConverter::Types::operator < ( const Types &other ) const { return fromType < other.fromType; } <|endoftext|>
<commit_before>/* * DepthSense SDK for Python and SimpleCV * ----------------------------------------------------------------------------- * file: depthsense.cxx * author: Abdi Dahir * modified: May 9 2014 * vim: set fenc=utf-8:ts=4:sw=4:expandtab: * * DepthSense hooks happen here. Initializes camera and buffers. * ----------------------------------------------------------------------------- */ // MS completly untested #ifdef _MSC_VER #include <windows.h> #endif // C includes #include <stdio.h> #ifndef _MSC_VER #include <stdint.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/mman.h> #include <pthread.h> #include <unistd.h> #endif #include <stdlib.h> #include <string.h> // C++ includes #include <vector> #include <exception> #include <iostream> #include <fstream> // DepthSense SDK includes #include <DepthSense.hxx> // Application includes #include "initdepthsense.h" using namespace DepthSense; using namespace std; // depth sense node inits static Context g_context; static DepthNode g_dnode; static ColorNode g_cnode; static AudioNode g_anode; static bool g_bDeviceFound = false; // unecassary frame counters static uint32_t g_aFrames = 0; static uint32_t g_cFrames = 0; static uint32_t g_dFrames = 0; // shared mem int16_t *depthMap; int16_t *depthFullMap; int16_t *vertexMap; int16_t *vertexFullMap; uint8_t *colourMap; uint8_t *colourFullMap; float *uvMap; float *uvFullMap; float *vertexFMap; float *vertexFFullMap; float *accelMap; float *accelFullMap; // proc mem int16_t * depthCMap; uint8_t * depthColouredMap; // thread for running processing loop #ifndef _MSC_VER pthread_t looper; #else HANDLE looper; #endif // can't write atomic op but i can atleast do a swap static void uptrSwap (uint8_t **pa, uint8_t **pb){ uint8_t *temp = *pa; *pa = *pb; *pb = temp; } static void fptrSwap (float **pa, float **pb){ float *temp = *pa; *pa = *pb; *pb = temp; } static void iptrSwap (int16_t **pa, int16_t **pb){ int16_t *temp = *pa; *pa = *pb; *pb = temp; } /*----------------------------------------------------------------------------*/ // New audio sample event handler static void onNewAudioSample(AudioNode node, AudioNode::NewSampleReceivedData data) { //printf("A#%u: %d\n",g_aFrames,data.audioData.size()); g_aFrames++; } /*----------------------------------------------------------------------------*/ // New color sample event handler static void onNewColorSample(ColorNode node, ColorNode::NewSampleReceivedData data) { //printf("C#%u: %d\n",g_cFrames,data.colorMap.size()); memcpy(colourMap, data.colorMap, 3*cshmsz); uptrSwap(&colourMap, &colourFullMap); g_cFrames++; } /*----------------------------------------------------------------------------*/ // New depth sample event handler static void onNewDepthSample(DepthNode node, DepthNode::NewSampleReceivedData data) { // Depth memcpy(depthMap, data.depthMap, dshmsz); iptrSwap(&depthMap, &depthFullMap); // Verticies Vertex vertex; FPVertex fvertex; for(int i=0; i < dH; i++) { for(int j=0; j < dW; j++) { vertex = data.vertices[i*dW + j]; fvertex = data.verticesFloatingPoint[i*dW + j]; vertexMap[i*dW*3 + j*3 + 0] = vertex.x; vertexMap[i*dW*3 + j*3 + 1] = vertex.y; vertexMap[i*dW*3 + j*3 + 2] = vertex.z; vertexFMap[i*dW*3 + j*3 + 0] = fvertex.x; vertexFMap[i*dW*3 + j*3 + 1] = fvertex.y; vertexFMap[i*dW*3 + j*3 + 2] = fvertex.z; //cout << vertex.x << vertex.y << vertex.z << endl; //cout << fvertex.x << fvertex.y << fvertex.z << endl; } } iptrSwap(&vertexMap, &vertexFullMap); fptrSwap(&vertexFMap, &vertexFFullMap); // uv UV uv; for(int i=0; i < dH; i++) { for(int j=0; j < dW; j++) { uv = data.uvMap[i*dW + j]; uvMap[i*dW*2 + j*2 + 0] = uv.u; uvMap[i*dW*2 + j*2 + 1] = uv.v; //cout << uv.u << uv.v << endl; } } fptrSwap(&uvMap, &uvFullMap); // Acceleration accelMap[0] = data.acceleration.x; accelMap[1] = data.acceleration.y; accelMap[2] = data.acceleration.z; fptrSwap(&accelMap, &accelFullMap); g_dFrames++; } /*----------------------------------------------------------------------------*/ static void configureAudioNode() { g_anode.newSampleReceivedEvent().connect(&onNewAudioSample); AudioNode::Configuration config = g_anode.getConfiguration(); config.sampleRate = 44100; try { g_context.requestControl(g_anode,0); g_anode.setConfiguration(config); g_anode.setInputMixerLevel(0.5f); } catch (ArgumentException& e) { printf("Argument Exception: %s\n",e.what()); } catch (UnauthorizedAccessException& e) { printf("Unauthorized Access Exception: %s\n",e.what()); } catch (ConfigurationException& e) { printf("Configuration Exception: %s\n",e.what()); } catch (StreamingException& e) { printf("Streaming Exception: %s\n",e.what()); } catch (TimeoutException&) { printf("TimeoutException\n"); } } /*----------------------------------------------------------------------------*/ static void configureDepthNode() { g_dnode.newSampleReceivedEvent().connect(&onNewDepthSample); DepthNode::Configuration config = g_dnode.getConfiguration(); config.frameFormat = FRAME_FORMAT_QVGA; config.framerate = 30; config.mode = DepthNode::CAMERA_MODE_CLOSE_MODE; config.saturation = true; try { g_context.requestControl(g_dnode,0); g_dnode.setConfidenceThreshold(100); g_dnode.setEnableDepthMap(true); g_dnode.setEnableVertices(true); g_dnode.setEnableVerticesFloatingPoint(true); g_dnode.setEnableAccelerometer(true); g_dnode.setEnableUvMap(true); g_dnode.setConfiguration(config); } catch (ArgumentException& e) { printf("Argument Exception: %s\n",e.what()); } catch (UnauthorizedAccessException& e) { printf("Unauthorized Access Exception: %s\n",e.what()); } catch (IOException& e) { printf("IO Exception: %s\n",e.what()); } catch (InvalidOperationException& e) { printf("Invalid Operation Exception: %s\n",e.what()); } catch (ConfigurationException& e) { printf("Configuration Exception: %s\n",e.what()); } catch (StreamingException& e) { printf("Streaming Exception: %s\n",e.what()); } catch (TimeoutException&) { printf("TimeoutException\n"); } } /*----------------------------------------------------------------------------*/ static void configureColorNode() { // connect new color sample handler g_cnode.newSampleReceivedEvent().connect(&onNewColorSample); ColorNode::Configuration config = g_cnode.getConfiguration(); config.frameFormat = FRAME_FORMAT_VGA; config.compression = COMPRESSION_TYPE_MJPEG; config.powerLineFrequency = POWER_LINE_FREQUENCY_50HZ; config.framerate = 30; g_cnode.setEnableColorMap(true); try { g_context.requestControl(g_cnode,0); g_cnode.setConfiguration(config); g_cnode.setBrightness(0); g_cnode.setContrast(5); g_cnode.setSaturation(5); g_cnode.setHue(0); g_cnode.setGamma(3); g_cnode.setWhiteBalance(4650); g_cnode.setSharpness(5); g_cnode.setWhiteBalanceAuto(true); } catch (ArgumentException& e) { printf("Argument Exception: %s\n",e.what()); } catch (UnauthorizedAccessException& e) { printf("Unauthorized Access Exception: %s\n",e.what()); } catch (IOException& e) { printf("IO Exception: %s\n",e.what()); } catch (InvalidOperationException& e) { printf("Invalid Operation Exception: %s\n",e.what()); } catch (ConfigurationException& e) { printf("Configuration Exception: %s\n",e.what()); } catch (StreamingException& e) { printf("Streaming Exception: %s\n",e.what()); } catch (TimeoutException&) { printf("TimeoutException\n"); } } /*----------------------------------------------------------------------------*/ static void configureNode(Node node) { if ((node.is<DepthNode>())&&(!g_dnode.isSet())) { g_dnode = node.as<DepthNode>(); configureDepthNode(); g_context.registerNode(node); } if ((node.is<ColorNode>())&&(!g_cnode.isSet())) { g_cnode = node.as<ColorNode>(); configureColorNode(); g_context.registerNode(node); } if ((node.is<AudioNode>())&&(!g_anode.isSet())) { g_anode = node.as<AudioNode>(); configureAudioNode(); // Audio seems to take up bandwith on usb3.0 devices ... we'll make this a param //g_context.registerNode(node); } } /*----------------------------------------------------------------------------*/ static void onNodeConnected(Device device, Device::NodeAddedData data) { configureNode(data.node); } /*----------------------------------------------------------------------------*/ static void onNodeDisconnected(Device device, Device::NodeRemovedData data) { if (data.node.is<AudioNode>() && (data.node.as<AudioNode>() == g_anode)) g_anode.unset(); if (data.node.is<ColorNode>() && (data.node.as<ColorNode>() == g_cnode)) g_cnode.unset(); if (data.node.is<DepthNode>() && (data.node.as<DepthNode>() == g_dnode)) g_dnode.unset(); printf("Node disconnected\n"); } /*----------------------------------------------------------------------------*/ static void onDeviceConnected(Context context, Context::DeviceAddedData data) { if (!g_bDeviceFound) { data.device.nodeAddedEvent().connect(&onNodeConnected); data.device.nodeRemovedEvent().connect(&onNodeDisconnected); g_bDeviceFound = true; } } /*----------------------------------------------------------------------------*/ static void onDeviceDisconnected(Context context, Context::DeviceRemovedData data) { g_bDeviceFound = false; printf("Device disconnected\n"); } static void * initblock(int sz) { void * block; if ((block = malloc(sz)) == NULL) { perror("malloc: cannot alloc mem;"); exit(1); } return block; } void killds() { cout << "DEPTHSENSE SHUTDOWN IN PROGRESS ..." << endl; g_context.quit(); #ifndef _MSC_VER pthread_join(looper, NULL); #else WaitForSingleObject(looper, NULL); CloseHandle(looper); #endif cout << "THREAD EXIT" << endl; free(depthMap); free(depthFullMap); free(colourMap); free(colourFullMap); free(vertexMap); free(vertexFullMap); free(vertexFMap); free(vertexFFullMap); free(uvMap); free(uvFullMap); free(depthCMap); free(depthColouredMap); cout << "DEPTHSENSE SHUTDOWN SUCCESSFUL" << endl; } #ifndef _MSC_VER void* loopfunc(void *arg) #else DWORD WINAPI loopfunc(void *arg) #endif { cout << "EVENT LOOP RUNNING" << endl; g_context.run(); cout << "EVENT LOOP FINISHED" << endl; return 0; } void initds() { // shared mem double buffers depthMap = (int16_t *) initblock(dshmsz); depthFullMap = (int16_t *) initblock(dshmsz); accelMap = (float *) initblock(3*sizeof(float)); accelFullMap = (float *) initblock(3*sizeof(float)); colourMap = (uint8_t *) initblock(cshmsz*3); colourFullMap = (uint8_t *) initblock(cshmsz*3); vertexMap = (int16_t *) initblock(vshmsz*3); vertexFullMap = (int16_t *) initblock(vshmsz*3); uvMap = (float *) initblock(ushmsz*2); uvFullMap = (float *) initblock(ushmsz*2); vertexFMap = (float *) initblock(ushmsz*3); vertexFFullMap = (float *) initblock(ushmsz*3); // mem buffer blocks depthCMap = (int16_t *) initblock(dshmsz); depthColouredMap = (uint8_t *) initblock(hshmsz*3); // prepare the context g_context = Context::createStandalone(); // TODO: Support multiple cameras ... standalone mode forces // a single session, can instead create a server once and join // to that server each time. Allow a list of devices //g_context = Context::create("localhost"); g_context.deviceAddedEvent().connect(&onDeviceConnected); g_context.deviceRemovedEvent().connect(&onDeviceDisconnected); // Get the list of currently connected devices vector<Device> da = g_context.getDevices(); // We are only interested in the first device if (da.size() >= 1) { g_bDeviceFound = true; da[0].nodeAddedEvent().connect(&onNodeConnected); da[0].nodeRemovedEvent().connect(&onNodeDisconnected); vector<Node> na = da[0].getNodes(); for (int n = 0; n < (int)na.size();n++) configureNode(na[n]); } g_context.startNodes(); // launch processing loop in a separate thread #ifndef _MSC_VER pthread_create(&looper, NULL, loopfunc, (void*)NULL); #else looper = CreateThread(NULL, 0, loopfunc, (void*)NULL, 0, NULL); #endif } <commit_msg>fix bug with depthsense context not being released<commit_after>/* * DepthSense SDK for Python and SimpleCV * ----------------------------------------------------------------------------- * file: depthsense.cxx * author: Abdi Dahir * modified: May 9 2014 * vim: set fenc=utf-8:ts=4:sw=4:expandtab: * * DepthSense hooks happen here. Initializes camera and buffers. * ----------------------------------------------------------------------------- */ // MS completly untested #ifdef _MSC_VER #include <windows.h> #endif // C includes #include <stdio.h> #ifndef _MSC_VER #include <stdint.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/mman.h> #include <pthread.h> #include <unistd.h> #endif #include <stdlib.h> #include <string.h> // C++ includes #include <vector> #include <exception> #include <iostream> #include <fstream> // DepthSense SDK includes #include <DepthSense.hxx> // Application includes #include "initdepthsense.h" using namespace DepthSense; using namespace std; // depth sense node inits static Context g_context; static DepthNode g_dnode; static ColorNode g_cnode; static AudioNode g_anode; static bool g_bDeviceFound = false; // unecassary frame counters static uint32_t g_aFrames = 0; static uint32_t g_cFrames = 0; static uint32_t g_dFrames = 0; // shared mem int16_t *depthMap; int16_t *depthFullMap; int16_t *vertexMap; int16_t *vertexFullMap; uint8_t *colourMap; uint8_t *colourFullMap; float *uvMap; float *uvFullMap; float *vertexFMap; float *vertexFFullMap; float *accelMap; float *accelFullMap; // proc mem int16_t * depthCMap; uint8_t * depthColouredMap; // thread for running processing loop #ifndef _MSC_VER pthread_t looper; #else HANDLE looper; #endif // can't write atomic op but i can atleast do a swap static void uptrSwap (uint8_t **pa, uint8_t **pb){ uint8_t *temp = *pa; *pa = *pb; *pb = temp; } static void fptrSwap (float **pa, float **pb){ float *temp = *pa; *pa = *pb; *pb = temp; } static void iptrSwap (int16_t **pa, int16_t **pb){ int16_t *temp = *pa; *pa = *pb; *pb = temp; } /*----------------------------------------------------------------------------*/ // New audio sample event handler static void onNewAudioSample(AudioNode node, AudioNode::NewSampleReceivedData data) { //printf("A#%u: %d\n",g_aFrames,data.audioData.size()); g_aFrames++; } /*----------------------------------------------------------------------------*/ // New color sample event handler static void onNewColorSample(ColorNode node, ColorNode::NewSampleReceivedData data) { //printf("C#%u: %d\n",g_cFrames,data.colorMap.size()); memcpy(colourMap, data.colorMap, 3*cshmsz); uptrSwap(&colourMap, &colourFullMap); g_cFrames++; } /*----------------------------------------------------------------------------*/ // New depth sample event handler static void onNewDepthSample(DepthNode node, DepthNode::NewSampleReceivedData data) { // Depth memcpy(depthMap, data.depthMap, dshmsz); iptrSwap(&depthMap, &depthFullMap); // Verticies Vertex vertex; FPVertex fvertex; for(int i=0; i < dH; i++) { for(int j=0; j < dW; j++) { vertex = data.vertices[i*dW + j]; fvertex = data.verticesFloatingPoint[i*dW + j]; vertexMap[i*dW*3 + j*3 + 0] = vertex.x; vertexMap[i*dW*3 + j*3 + 1] = vertex.y; vertexMap[i*dW*3 + j*3 + 2] = vertex.z; vertexFMap[i*dW*3 + j*3 + 0] = fvertex.x; vertexFMap[i*dW*3 + j*3 + 1] = fvertex.y; vertexFMap[i*dW*3 + j*3 + 2] = fvertex.z; //cout << vertex.x << vertex.y << vertex.z << endl; //cout << fvertex.x << fvertex.y << fvertex.z << endl; } } iptrSwap(&vertexMap, &vertexFullMap); fptrSwap(&vertexFMap, &vertexFFullMap); // uv UV uv; for(int i=0; i < dH; i++) { for(int j=0; j < dW; j++) { uv = data.uvMap[i*dW + j]; uvMap[i*dW*2 + j*2 + 0] = uv.u; uvMap[i*dW*2 + j*2 + 1] = uv.v; //cout << uv.u << uv.v << endl; } } fptrSwap(&uvMap, &uvFullMap); // Acceleration accelMap[0] = data.acceleration.x; accelMap[1] = data.acceleration.y; accelMap[2] = data.acceleration.z; fptrSwap(&accelMap, &accelFullMap); g_dFrames++; } /*----------------------------------------------------------------------------*/ static void configureAudioNode() { g_anode.newSampleReceivedEvent().connect(&onNewAudioSample); AudioNode::Configuration config = g_anode.getConfiguration(); config.sampleRate = 44100; try { g_context.requestControl(g_anode,0); g_anode.setConfiguration(config); g_anode.setInputMixerLevel(0.5f); } catch (ArgumentException& e) { printf("Argument Exception: %s\n",e.what()); } catch (UnauthorizedAccessException& e) { printf("Unauthorized Access Exception: %s\n",e.what()); } catch (ConfigurationException& e) { printf("Configuration Exception: %s\n",e.what()); } catch (StreamingException& e) { printf("Streaming Exception: %s\n",e.what()); } catch (TimeoutException&) { printf("TimeoutException\n"); } } /*----------------------------------------------------------------------------*/ static void configureDepthNode() { g_dnode.newSampleReceivedEvent().connect(&onNewDepthSample); DepthNode::Configuration config = g_dnode.getConfiguration(); config.frameFormat = FRAME_FORMAT_QVGA; config.framerate = 30; config.mode = DepthNode::CAMERA_MODE_CLOSE_MODE; config.saturation = true; try { g_context.requestControl(g_dnode,0); g_dnode.setConfidenceThreshold(100); g_dnode.setEnableDepthMap(true); g_dnode.setEnableVertices(true); g_dnode.setEnableVerticesFloatingPoint(true); g_dnode.setEnableAccelerometer(true); g_dnode.setEnableUvMap(true); g_dnode.setConfiguration(config); } catch (ArgumentException& e) { printf("Argument Exception: %s\n",e.what()); } catch (UnauthorizedAccessException& e) { printf("Unauthorized Access Exception: %s\n",e.what()); } catch (IOException& e) { printf("IO Exception: %s\n",e.what()); } catch (InvalidOperationException& e) { printf("Invalid Operation Exception: %s\n",e.what()); } catch (ConfigurationException& e) { printf("Configuration Exception: %s\n",e.what()); } catch (StreamingException& e) { printf("Streaming Exception: %s\n",e.what()); } catch (TimeoutException&) { printf("TimeoutException\n"); } } /*----------------------------------------------------------------------------*/ static void configureColorNode() { // connect new color sample handler g_cnode.newSampleReceivedEvent().connect(&onNewColorSample); ColorNode::Configuration config = g_cnode.getConfiguration(); config.frameFormat = FRAME_FORMAT_VGA; config.compression = COMPRESSION_TYPE_MJPEG; config.powerLineFrequency = POWER_LINE_FREQUENCY_50HZ; config.framerate = 30; g_cnode.setEnableColorMap(true); try { g_context.requestControl(g_cnode,0); g_cnode.setConfiguration(config); g_cnode.setBrightness(0); g_cnode.setContrast(5); g_cnode.setSaturation(5); g_cnode.setHue(0); g_cnode.setGamma(3); g_cnode.setWhiteBalance(4650); g_cnode.setSharpness(5); g_cnode.setWhiteBalanceAuto(true); } catch (ArgumentException& e) { printf("Argument Exception: %s\n",e.what()); } catch (UnauthorizedAccessException& e) { printf("Unauthorized Access Exception: %s\n",e.what()); } catch (IOException& e) { printf("IO Exception: %s\n",e.what()); } catch (InvalidOperationException& e) { printf("Invalid Operation Exception: %s\n",e.what()); } catch (ConfigurationException& e) { printf("Configuration Exception: %s\n",e.what()); } catch (StreamingException& e) { printf("Streaming Exception: %s\n",e.what()); } catch (TimeoutException&) { printf("TimeoutException\n"); } } /*----------------------------------------------------------------------------*/ static void configureNode(Node node) { if ((node.is<DepthNode>())&&(!g_dnode.isSet())) { g_dnode = node.as<DepthNode>(); configureDepthNode(); g_context.registerNode(node); } if ((node.is<ColorNode>())&&(!g_cnode.isSet())) { g_cnode = node.as<ColorNode>(); configureColorNode(); g_context.registerNode(node); } if ((node.is<AudioNode>())&&(!g_anode.isSet())) { g_anode = node.as<AudioNode>(); configureAudioNode(); // Audio seems to take up bandwith on usb3.0 devices ... we'll make this a param //g_context.registerNode(node); } } /*----------------------------------------------------------------------------*/ static void onNodeConnected(Device device, Device::NodeAddedData data) { configureNode(data.node); } /*----------------------------------------------------------------------------*/ static void onNodeDisconnected(Device device, Device::NodeRemovedData data) { if (data.node.is<AudioNode>() && (data.node.as<AudioNode>() == g_anode)) g_anode.unset(); if (data.node.is<ColorNode>() && (data.node.as<ColorNode>() == g_cnode)) g_cnode.unset(); if (data.node.is<DepthNode>() && (data.node.as<DepthNode>() == g_dnode)) g_dnode.unset(); printf("Node disconnected\n"); } /*----------------------------------------------------------------------------*/ static void onDeviceConnected(Context context, Context::DeviceAddedData data) { if (!g_bDeviceFound) { data.device.nodeAddedEvent().connect(&onNodeConnected); data.device.nodeRemovedEvent().connect(&onNodeDisconnected); g_bDeviceFound = true; } } /*----------------------------------------------------------------------------*/ static void onDeviceDisconnected(Context context, Context::DeviceRemovedData data) { g_bDeviceFound = false; printf("Device disconnected\n"); } static void * initblock(int sz) { void * block; if ((block = malloc(sz)) == NULL) { perror("malloc: cannot alloc mem;"); exit(1); } return block; } void killds() { cout << "DEPTHSENSE SHUTDOWN IN PROGRESS ..." << endl; g_context.quit(); #ifndef _MSC_VER pthread_join(looper, NULL); #else WaitForSingleObject(looper, NULL); CloseHandle(looper); #endif cout << "THREAD EXIT" << endl; g_context.stopNodes(); free(depthMap); free(depthFullMap); free(colourMap); free(colourFullMap); free(vertexMap); free(vertexFullMap); free(vertexFMap); free(vertexFFullMap); free(uvMap); free(uvFullMap); free(depthCMap); free(depthColouredMap); // prevents hang on exit on Windows by detaching // from the server properly g_context.unset(); cout << "DEPTHSENSE SHUTDOWN SUCCESSFUL" << endl; } #ifndef _MSC_VER void* loopfunc(void *arg) #else DWORD WINAPI loopfunc(void *arg) #endif { cout << "EVENT LOOP RUNNING" << endl; g_context.run(); cout << "EVENT LOOP FINISHED" << endl; return 0; } void initds() { // shared mem double buffers depthMap = (int16_t *) initblock(dshmsz); depthFullMap = (int16_t *) initblock(dshmsz); accelMap = (float *) initblock(3*sizeof(float)); accelFullMap = (float *) initblock(3*sizeof(float)); colourMap = (uint8_t *) initblock(cshmsz*3); colourFullMap = (uint8_t *) initblock(cshmsz*3); vertexMap = (int16_t *) initblock(vshmsz*3); vertexFullMap = (int16_t *) initblock(vshmsz*3); uvMap = (float *) initblock(ushmsz*2); uvFullMap = (float *) initblock(ushmsz*2); vertexFMap = (float *) initblock(ushmsz*3); vertexFFullMap = (float *) initblock(ushmsz*3); // mem buffer blocks depthCMap = (int16_t *) initblock(dshmsz); depthColouredMap = (uint8_t *) initblock(hshmsz*3); // prepare the context g_context = Context::createStandalone(); // TODO: Support multiple cameras ... standalone mode forces // a single session, can instead create a server once and join // to that server each time. Allow a list of devices //g_context = Context::create("localhost"); g_context.deviceAddedEvent().connect(&onDeviceConnected); g_context.deviceRemovedEvent().connect(&onDeviceDisconnected); // Get the list of currently connected devices vector<Device> da = g_context.getDevices(); // We are only interested in the first device if (da.size() >= 1) { g_bDeviceFound = true; da[0].nodeAddedEvent().connect(&onNodeConnected); da[0].nodeRemovedEvent().connect(&onNodeDisconnected); vector<Node> na = da[0].getNodes(); for (int n = 0; n < (int)na.size();n++) configureNode(na[n]); } g_context.startNodes(); // launch processing loop in a separate thread #ifndef _MSC_VER pthread_create(&looper, NULL, loopfunc, (void*)NULL); #else looper = CreateThread(NULL, 0, loopfunc, (void*)NULL, 0, NULL); #endif } <|endoftext|>
<commit_before>#include <tuple> #include <type_traits> #include <utility> #include <nek/utility/pointer_traits.hpp> #include <gtest/gtest.h> namespace { template <class T> class complete_smart_pointer_mock { private: T* ptr_ = nullptr; public: using element_type = T; using difference_type = char; complete_smart_pointer_mock() = default; explicit complete_smart_pointer_mock(T& p) : ptr_(&p) { } template <class U> struct rebind { using other = complete_smart_pointer_mock<U>; }; static complete_smart_pointer_mock pointer_to(T& p) { return complete_smart_pointer_mock(p); } friend bool operator==(complete_smart_pointer_mock const& l, complete_smart_pointer_mock const& r) { return l.ptr_ == r.ptr_; } }; template <class T> class simple_smart_pointer_mock { private: T* ptr_ = nullptr; public: simple_smart_pointer_mock() = default; simple_smart_pointer_mock(T* p) : ptr_(p) { } friend bool operator==(simple_smart_pointer_mock const& l, simple_smart_pointer_mock const& r) { return l.ptr_ == r.ptr_; } }; } template <class T> class pointer_traits_test : public ::testing::Test { protected: using ptr_t = typename std::tuple_element<0, T>::type; using elem_t = typename std::tuple_element<1, T>::type; using diff_t = typename std::tuple_element<2, T>::type; using pointer_t = typename std::tuple_element<3, T>::type; }; TYPED_TEST_CASE_P(pointer_traits_test); TYPED_TEST_P(pointer_traits_test, element_type) { using actual_t = typename nek::pointer_traits<ptr_t>::element_type; static_assert(std::is_same<actual_t, elem_t>::value, ""); } TYPED_TEST_P(pointer_traits_test, difference_type) { using actual_t = typename nek::pointer_traits<ptr_t>::difference_type; static_assert(std::is_same<actual_t, diff_t>::value, ""); } TYPED_TEST_P(pointer_traits_test, pointer) { using actual_t = typename nek::pointer_traits<ptr_t>::pointer; static_assert(std::is_same<actual_t, pointer_t>::value, ""); } TYPED_TEST_P(pointer_traits_test, rebind) { using actual_t = typename nek::pointer_traits<ptr_t>::template rebind<double>::other; using expect_t = typename std::tuple_element<4, TypeParam>::type; static_assert(std::is_same<actual_t, expect_t>::value, ""); } TEST(pointer_to_test, raw_type) { int val = 0; EXPECT_EQ(&val, nek::pointer_traits<int*>::pointer_to(val)); } TEST(pointer_to_test, complete_smart_ptr) { int val = 0; EXPECT_EQ(complete_smart_pointer_mock<int>(val), nek::pointer_traits<complete_smart_pointer_mock<int>>::pointer_to(val)); } TEST(pointer_to_test, simple_smart_pointer) { // when smart pointer does not provide a static member function pointer_to, // instantiation of this function must be a compile-time error. //int val = 0; //EXPECT_EQ(simple_smart_pointer_mock<int>(&val), nek::pointer_traits<simple_smart_pointer_mock<int>>::pointer_to(val)); } REGISTER_TYPED_TEST_CASE_P( pointer_traits_test, element_type, difference_type, pointer, rebind); using types = ::testing::Types< // <pointer_type, element_type, difference_type, pointer, rebind<double>::other, std::tuple<int*, int, std::ptrdiff_t, int*, double*>, std::tuple<complete_smart_pointer_mock<int>, int, char, complete_smart_pointer_mock<int>, complete_smart_pointer_mock<double>>, std::tuple<simple_smart_pointer_mock<int>, int, std::ptrdiff_t, simple_smart_pointer_mock<int>, simple_smart_pointer_mock<double>> >; INSTANTIATE_TYPED_TEST_CASE_P(parameterized, pointer_traits_test, types);<commit_msg>fix comment<commit_after>#include <tuple> #include <type_traits> #include <utility> #include <nek/utility/pointer_traits.hpp> #include <gtest/gtest.h> namespace { template <class T> class complete_smart_pointer_mock { private: T* ptr_ = nullptr; public: using element_type = T; using difference_type = char; complete_smart_pointer_mock() = default; explicit complete_smart_pointer_mock(T& p) : ptr_(&p) { } template <class U> struct rebind { using other = complete_smart_pointer_mock<U>; }; static complete_smart_pointer_mock pointer_to(T& p) { return complete_smart_pointer_mock(p); } friend bool operator==(complete_smart_pointer_mock const& l, complete_smart_pointer_mock const& r) { return l.ptr_ == r.ptr_; } }; template <class T> class simple_smart_pointer_mock { private: T* ptr_ = nullptr; public: simple_smart_pointer_mock() = default; simple_smart_pointer_mock(T* p) : ptr_(p) { } friend bool operator==(simple_smart_pointer_mock const& l, simple_smart_pointer_mock const& r) { return l.ptr_ == r.ptr_; } }; } template <class T> class pointer_traits_test : public ::testing::Test { protected: using ptr_t = typename std::tuple_element<0, T>::type; using elem_t = typename std::tuple_element<1, T>::type; using diff_t = typename std::tuple_element<2, T>::type; using pointer_t = typename std::tuple_element<3, T>::type; }; TYPED_TEST_CASE_P(pointer_traits_test); TYPED_TEST_P(pointer_traits_test, element_type) { using actual_t = typename nek::pointer_traits<ptr_t>::element_type; static_assert(std::is_same<actual_t, elem_t>::value, ""); } TYPED_TEST_P(pointer_traits_test, difference_type) { using actual_t = typename nek::pointer_traits<ptr_t>::difference_type; static_assert(std::is_same<actual_t, diff_t>::value, ""); } TYPED_TEST_P(pointer_traits_test, pointer) { using actual_t = typename nek::pointer_traits<ptr_t>::pointer; static_assert(std::is_same<actual_t, pointer_t>::value, ""); } TYPED_TEST_P(pointer_traits_test, rebind) { using actual_t = typename nek::pointer_traits<ptr_t>::template rebind<double>::other; using expect_t = typename std::tuple_element<4, TypeParam>::type; static_assert(std::is_same<actual_t, expect_t>::value, ""); } TEST(pointer_to_test, raw_type) { int val = 0; EXPECT_EQ(&val, nek::pointer_traits<int*>::pointer_to(val)); } TEST(pointer_to_test, complete_smart_ptr) { int val = 0; EXPECT_EQ(complete_smart_pointer_mock<int>(val), nek::pointer_traits<complete_smart_pointer_mock<int>>::pointer_to(val)); } TEST(pointer_to_test, simple_smart_pointer) { // if smart pointer does not provide a static member function pointer_to, // instantiation of this test must be a compile time error. //int val = 0; //EXPECT_EQ(simple_smart_pointer_mock<int>(&val), nek::pointer_traits<simple_smart_pointer_mock<int>>::pointer_to(val)); } REGISTER_TYPED_TEST_CASE_P( pointer_traits_test, element_type, difference_type, pointer, rebind); using types = ::testing::Types< // <pointer_type, element_type, difference_type, pointer, rebind<double>::other, std::tuple<int*, int, std::ptrdiff_t, int*, double*>, std::tuple<complete_smart_pointer_mock<int>, int, char, complete_smart_pointer_mock<int>, complete_smart_pointer_mock<double>>, std::tuple<simple_smart_pointer_mock<int>, int, std::ptrdiff_t, simple_smart_pointer_mock<int>, simple_smart_pointer_mock<double>> >; INSTANTIATE_TYPED_TEST_CASE_P(parameterized, pointer_traits_test, types);<|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gpu/gpu_plugin/gpu_plugin.h" #include "webkit/glue/plugins/nphostapi.h" namespace gpu_plugin { // Definitions of NPAPI plugin entry points. namespace { NPError NPP_New(NPMIMEType plugin_type, NPP instance, uint16 mode, int16 argc, char* argn[], char* argv[], NPSavedData* saved) { if (!instance) return NPERR_INVALID_INSTANCE_ERROR; return NPERR_NO_ERROR; } NPError NPP_Destroy(NPP instance, NPSavedData** saved) { if (!instance) return NPERR_INVALID_INSTANCE_ERROR; return NPERR_NO_ERROR; } NPError NPP_SetWindow(NPP instance, NPWindow* window) { return NPERR_NO_ERROR; } int16 NPP_HandleEvent(NPP instance, void* event) { return 0; } NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) { if (!instance) return NPERR_INVALID_INSTANCE_ERROR; switch (variable) { case NPPVpluginNeedsXEmbed: *static_cast<NPBool *>(value) = 1; return NPERR_NO_ERROR; default: return NPERR_INVALID_PARAM; } } NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) { return NPERR_NO_ERROR; } } NPError API_CALL NP_GetEntryPoints(NPPluginFuncs* funcs) { funcs->newp = NPP_New; funcs->destroy = NPP_Destroy; funcs->setwindow = NPP_SetWindow; funcs->event = NPP_HandleEvent; funcs->getvalue = NPP_GetValue; funcs->setvalue = NPP_SetValue; return NPERR_NO_ERROR; } #if defined(OS_LINUX) NPError API_CALL NP_Initialize(NPNetscapeFuncs *browser_funcs, NPPluginFuncs* plugin_funcs) { #else NPError API_CALL NP_Initialize(NPNetscapeFuncs *browser_funcs) { #endif if (!browser_funcs) return NPERR_INVALID_FUNCTABLE_ERROR; #if defined(OS_LINUX) NP_GetEntryPoints(plugin_funcs); #endif return NPERR_NO_ERROR; } NPError API_CALL NP_Shutdown() { return NPERR_NO_ERROR; } } // namespace gpu_plugin <commit_msg>Dummy whitespace change to force a build.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gpu/gpu_plugin/gpu_plugin.h" #include "webkit/glue/plugins/nphostapi.h" namespace gpu_plugin { // Definitions of NPAPI plugin entry points. namespace { NPError NPP_New(NPMIMEType plugin_type, NPP instance, uint16 mode, int16 argc, char* argn[], char* argv[], NPSavedData* saved) { if (!instance) return NPERR_INVALID_INSTANCE_ERROR; return NPERR_NO_ERROR; } NPError NPP_Destroy(NPP instance, NPSavedData** saved) { if (!instance) return NPERR_INVALID_INSTANCE_ERROR; return NPERR_NO_ERROR; } NPError NPP_SetWindow(NPP instance, NPWindow* window) { return NPERR_NO_ERROR; } int16 NPP_HandleEvent(NPP instance, void* event) { return 0; } NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) { if (!instance) return NPERR_INVALID_INSTANCE_ERROR; switch (variable) { case NPPVpluginNeedsXEmbed: *static_cast<NPBool *>(value) = 1; return NPERR_NO_ERROR; default: return NPERR_INVALID_PARAM; } } NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) { return NPERR_NO_ERROR; } } // namespace NPError API_CALL NP_GetEntryPoints(NPPluginFuncs* funcs) { funcs->newp = NPP_New; funcs->destroy = NPP_Destroy; funcs->setwindow = NPP_SetWindow; funcs->event = NPP_HandleEvent; funcs->getvalue = NPP_GetValue; funcs->setvalue = NPP_SetValue; return NPERR_NO_ERROR; } #if defined(OS_LINUX) NPError API_CALL NP_Initialize(NPNetscapeFuncs *browser_funcs, NPPluginFuncs* plugin_funcs) { #else NPError API_CALL NP_Initialize(NPNetscapeFuncs *browser_funcs) { #endif if (!browser_funcs) return NPERR_INVALID_FUNCTABLE_ERROR; #if defined(OS_LINUX) NP_GetEntryPoints(plugin_funcs); #endif return NPERR_NO_ERROR; } NPError API_CALL NP_Shutdown() { return NPERR_NO_ERROR; } } // namespace gpu_plugin <|endoftext|>
<commit_before>#include "BlinkSignal.h" BlinkSignal::BlinkSignal(uint8_t pin, unsigned long pulseWidth) { this->pin = pin; this->lowPulseWidth = pulseWidth; this->highPulseWidth = pulseWidth; pinMode(pin, OUTPUT); } void BlinkSignal::invertOutput(bool invert) { this->invert = invert; } void BlinkSignal::setOffPulseWidth(unsigned long pulseWidth) { this->lowPulseWidth = pulseWidth; } void BlinkSignal::setOnPulseCount(uint8_t count) { this->highPulseCount = count * 2 - 1; this->highPulseWidth = lowPulseWidth / highPulseCount ; this->countDown = this->highPulseCount; } void BlinkSignal::update(unsigned long millis) { if (millis >= nextMillis) { if (countDown > 0) { countDown--; nextMillis = millis + highPulseWidth; } else { countDown = highPulseCount; nextMillis = millis + lowPulseWidth; } currentState = currentState == HIGH ? LOW : HIGH; illuminate(); } } void BlinkSignal::illuminate() { // invert, since LED cathode is connected to GPIO pin uint8_t value = invert ? (currentState == HIGH ? LOW : HIGH): currentState; digitalWrite(pin, value); } <commit_msg>Fix the damn tabs!<commit_after>#include "BlinkSignal.h" BlinkSignal::BlinkSignal(uint8_t pin, unsigned long pulseWidth) { this->pin = pin; this->lowPulseWidth = pulseWidth; this->highPulseWidth = pulseWidth; pinMode(pin, OUTPUT); } void BlinkSignal::invertOutput(bool invert) { this->invert = invert; } void BlinkSignal::setOffPulseWidth(unsigned long pulseWidth) { this->lowPulseWidth = pulseWidth; } void BlinkSignal::setOnPulseCount(uint8_t count) { this->highPulseCount = count * 2 - 1; this->highPulseWidth = lowPulseWidth / highPulseCount ; this->countDown = this->highPulseCount; } void BlinkSignal::update(unsigned long millis) { if (millis >= nextMillis) { if (countDown > 0) { countDown--; nextMillis = millis + highPulseWidth; } else { countDown = highPulseCount; nextMillis = millis + lowPulseWidth; } currentState = currentState == HIGH ? LOW : HIGH; illuminate(); } } void BlinkSignal::illuminate() { // invert, since LED cathode is connected to GPIO pin uint8_t value = invert ? (currentState == HIGH ? LOW : HIGH): currentState; digitalWrite(pin, value); } <|endoftext|>
<commit_before>/*********************************************************************** filename: CEGUIOgreRenderer.cpp created: Tue Feb 17 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUIOgreRenderer.h" #include "CEGUIOgreGeometryBuffer.h" #include "CEGUIOgreTextureTarget.h" #include "CEGUIOgreTexture.h" #include "CEGUIOgreWindowTarget.h" #include "CEGUIRenderingRoot.h" #include "CEGUIExceptions.h" #include "CEGUISystem.h" #include "CEGUIOgreResourceProvider.h" #include "CEGUIOgreImageCodec.h" #include <OgreRoot.h> #include <OgreRenderSystem.h> #include <OgreRenderWindow.h> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// // Internal Ogre::FrameListener based class. This is how we noew hook into the // rendering process (as opposed to render queues previously) static class OgreGUIFrameListener : public Ogre::FrameListener { public: OgreGUIFrameListener(); void setCEGUIRenderEnabled(bool enabled); bool isCEGUIRenderEnabled() const; bool frameRenderingQueued(const Ogre::FrameEvent& evt); private: bool d_enabled; } S_frameListener; //----------------------------------------------------------------------------// String OgreRenderer::d_rendererID( "CEGUI::OgreRenderer - Official OGRE based 2nd generation renderer module."); //----------------------------------------------------------------------------// OgreRenderer& OgreRenderer::bootstrapSystem() { if (System::getSingletonPtr()) throw InvalidRequestException("OgreRenderer::bootstrapSystem: " "CEGUI::System object is already initialised."); OgreRenderer& renderer = create(); OgreResourceProvider& rp = createOgreResourceProvider(); OgreImageCodec& ic = createOgreImageCodec(); System::create(renderer, &rp, static_cast<XMLParser*>(0), &ic); return renderer; } //----------------------------------------------------------------------------// OgreRenderer& OgreRenderer::bootstrapSystem(Ogre::RenderTarget& target) { if (System::getSingletonPtr()) throw InvalidRequestException("OgreRenderer::bootstrapSystem: " "CEGUI::System object is already initialised."); OgreRenderer& renderer = OgreRenderer::create(target); OgreResourceProvider& rp = createOgreResourceProvider(); OgreImageCodec& ic = createOgreImageCodec(); System::create(renderer, &rp, static_cast<XMLParser*>(0), &ic); return renderer; } //----------------------------------------------------------------------------// void OgreRenderer::destroySystem() { System* sys; if (!(sys = System::getSingletonPtr())) throw InvalidRequestException("OgreRenderer::destroySystem: " "CEGUI::System object is not created or was already destroyed."); OgreRenderer* renderer = static_cast<OgreRenderer*>(sys->getRenderer()); OgreResourceProvider* rp = static_cast<OgreResourceProvider*>(sys->getResourceProvider()); OgreImageCodec* ic = &static_cast<OgreImageCodec&>(sys->getImageCodec()); System::destroy(); destroyOgreImageCodec(*ic); destroyOgreResourceProvider(*rp); destroy(*renderer); } //----------------------------------------------------------------------------// OgreRenderer& OgreRenderer::create() { return *new OgreRenderer; } //----------------------------------------------------------------------------// OgreRenderer& OgreRenderer::create(Ogre::RenderTarget& target) { return *new OgreRenderer(target); } //----------------------------------------------------------------------------// void OgreRenderer::destroy(OgreRenderer& renderer) { delete &renderer; } //----------------------------------------------------------------------------// OgreResourceProvider& OgreRenderer::createOgreResourceProvider() { return *new OgreResourceProvider; } //----------------------------------------------------------------------------// void OgreRenderer::destroyOgreResourceProvider(OgreResourceProvider& rp) { delete &rp; } //----------------------------------------------------------------------------// OgreImageCodec& OgreRenderer::createOgreImageCodec() { return *new OgreImageCodec; } //----------------------------------------------------------------------------// void OgreRenderer::destroyOgreImageCodec(OgreImageCodec& ic) { delete &ic; } //----------------------------------------------------------------------------// void OgreRenderer::setRenderingEnabled(const bool enabled) { S_frameListener.setCEGUIRenderEnabled(enabled); } //----------------------------------------------------------------------------// bool OgreRenderer::isRenderingEnabled() const { return S_frameListener.isCEGUIRenderEnabled(); } //----------------------------------------------------------------------------// RenderingRoot& OgreRenderer::getDefaultRenderingRoot() { return *d_defaultRoot; } //----------------------------------------------------------------------------// GeometryBuffer& OgreRenderer::createGeometryBuffer() { OgreGeometryBuffer* gb = new OgreGeometryBuffer(*d_renderSystem); d_geometryBuffers.push_back(gb); return *gb; } //----------------------------------------------------------------------------// void OgreRenderer::destroyGeometryBuffer(const GeometryBuffer& buffer) { GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(), d_geometryBuffers.end(), &buffer); if (d_geometryBuffers.end() != i) { d_geometryBuffers.erase(i); delete &buffer; } } //----------------------------------------------------------------------------// void OgreRenderer::destroyAllGeometryBuffers() { while (!d_geometryBuffers.empty()) destroyGeometryBuffer(**d_geometryBuffers.begin()); } //----------------------------------------------------------------------------// TextureTarget* OgreRenderer::createTextureTarget() { TextureTarget* tt = new OgreTextureTarget(*this, *d_renderSystem); d_textureTargets.push_back(tt); return tt; } //----------------------------------------------------------------------------// void OgreRenderer::destroyTextureTarget(TextureTarget* target) { TextureTargetList::iterator i = std::find(d_textureTargets.begin(), d_textureTargets.end(), target); if (d_textureTargets.end() != i) { d_textureTargets.erase(i); delete target; } } //----------------------------------------------------------------------------// void OgreRenderer::destroyAllTextureTargets() { while (!d_textureTargets.empty()) destroyTextureTarget(*d_textureTargets.begin()); } //----------------------------------------------------------------------------// Texture& OgreRenderer::createTexture() { OgreTexture* t = new OgreTexture; d_textures.push_back(t); return *t; } //----------------------------------------------------------------------------// Texture& OgreRenderer::createTexture(const String& filename, const String& resourceGroup) { OgreTexture* t = new OgreTexture(filename, resourceGroup); d_textures.push_back(t); return *t; } //----------------------------------------------------------------------------// Texture& OgreRenderer::createTexture(const Size& size) { OgreTexture* t = new OgreTexture(size); d_textures.push_back(t); return *t; } //----------------------------------------------------------------------------// Texture& OgreRenderer::createTexture(Ogre::TexturePtr& tex, bool take_ownership) { OgreTexture* t = new OgreTexture(tex, take_ownership); d_textures.push_back(t); return *t; } //----------------------------------------------------------------------------// void OgreRenderer::destroyTexture(Texture& texture) { TextureList::iterator i = std::find(d_textures.begin(), d_textures.end(), &texture); if (d_textures.end() != i) { d_textures.erase(i); delete &static_cast<OgreTexture&>(texture); } } //----------------------------------------------------------------------------// void OgreRenderer::destroyAllTextures() { while (!d_textures.empty()) destroyTexture(**d_textures.begin()); } //----------------------------------------------------------------------------// void OgreRenderer::beginRendering() { using namespace Ogre; // initialise render settings d_renderSystem->setLightingEnabled(false); d_renderSystem->_setDepthBufferParams(false, false); d_renderSystem->_setDepthBias(0, 0); d_renderSystem->_setCullingMode(CULL_NONE); d_renderSystem->_setFog(FOG_NONE); d_renderSystem->_setColourBufferWriteEnabled(true, true, true, true); d_renderSystem->unbindGpuProgram(GPT_FRAGMENT_PROGRAM); d_renderSystem->unbindGpuProgram(GPT_VERTEX_PROGRAM); d_renderSystem->setShadingType(SO_GOURAUD); d_renderSystem->_setPolygonMode(PM_SOLID); // enable alpha blending d_renderSystem->_setSceneBlending(SBF_SOURCE_ALPHA, SBF_ONE_MINUS_SOURCE_ALPHA); d_renderSystem->_beginFrame(); } //----------------------------------------------------------------------------// void OgreRenderer::endRendering() { d_renderSystem->_endFrame(); } //----------------------------------------------------------------------------// const Size& OgreRenderer::getDisplaySize() const { return d_displaySize; } //----------------------------------------------------------------------------// const Vector2& OgreRenderer::getDisplayDPI() const { return d_displayDPI; } //----------------------------------------------------------------------------// uint OgreRenderer::getMaxTextureSize() const { return d_maxTextureSize; } //----------------------------------------------------------------------------// const String& OgreRenderer::getIdentifierString() const { return d_rendererID; } //----------------------------------------------------------------------------// OgreRenderer::OgreRenderer() : d_displayDPI(96, 96), // TODO: should be set to correct value d_maxTextureSize(2048), d_ogreRoot(Ogre::Root::getSingletonPtr()) { checkOgreInitialised(); // get auto created window Ogre::RenderWindow* rwnd = d_ogreRoot->getAutoCreatedWindow(); if (!rwnd) throw RendererException("Ogre was not initialised to automatically " "create a window, you should therefore be " "explicitly specifying a Ogre::RenderTarget in " "the OgreRenderer::create function."); constructor_impl(*rwnd); } //----------------------------------------------------------------------------// OgreRenderer::OgreRenderer(Ogre::RenderTarget& target) : d_displayDPI(96, 96), // TODO: should be set to correct value d_maxTextureSize(2048), d_ogreRoot(Ogre::Root::getSingletonPtr()) { checkOgreInitialised(); constructor_impl(target); } //----------------------------------------------------------------------------// OgreRenderer::~OgreRenderer() { d_ogreRoot->removeFrameListener(&S_frameListener); destroyAllGeometryBuffers(); destroyAllTextureTargets(); destroyAllTextures(); delete d_defaultRoot; delete d_defaultTarget; } //----------------------------------------------------------------------------// void OgreRenderer::checkOgreInitialised() { if (!d_ogreRoot) throw RendererException("The Ogre::Root object has not been created. " "You must initialise Ogre first!"); if (!d_ogreRoot->isInitialised()) throw RendererException("Ogre has not been initialised. You must " "initialise Ogre first!"); } //----------------------------------------------------------------------------// void OgreRenderer::constructor_impl(Ogre::RenderTarget& target) { d_renderSystem = d_ogreRoot->getRenderSystem(); d_displaySize.d_width = target.getWidth(); d_displaySize.d_height = target.getHeight(); // create default target & rendering root (surface) that uses it d_defaultTarget = new OgreWindowTarget(*this, *d_renderSystem, target); d_defaultRoot = new RenderingRoot(*d_defaultTarget); // hook into the rendering process d_ogreRoot->addFrameListener(&S_frameListener); } //----------------------------------------------------------------------------// void OgreRenderer::setDisplaySize(const Size& sz) { if (sz != d_displaySize) { d_displaySize = sz; // FIXME: This is probably not the right thing to do in all cases. Rect area(d_defaultTarget->getArea()); area.setSize(sz); d_defaultTarget->setArea(area); } } //----------------------------------------------------------------------------// OgreGUIFrameListener::OgreGUIFrameListener() : d_enabled(true) { } //----------------------------------------------------------------------------// void OgreGUIFrameListener::setCEGUIRenderEnabled(bool enabled) { d_enabled = enabled; } //----------------------------------------------------------------------------// bool OgreGUIFrameListener::isCEGUIRenderEnabled() const { return d_enabled; } //----------------------------------------------------------------------------// bool OgreGUIFrameListener::frameRenderingQueued(const Ogre::FrameEvent&) { if (d_enabled) System::getSingleton().renderGUI(); return true; } } // End of CEGUI namespace section <commit_msg>FIX: Alpha blend issue for the Ogre renderer.<commit_after>/*********************************************************************** filename: CEGUIOgreRenderer.cpp created: Tue Feb 17 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUIOgreRenderer.h" #include "CEGUIOgreGeometryBuffer.h" #include "CEGUIOgreTextureTarget.h" #include "CEGUIOgreTexture.h" #include "CEGUIOgreWindowTarget.h" #include "CEGUIRenderingRoot.h" #include "CEGUIExceptions.h" #include "CEGUISystem.h" #include "CEGUIOgreResourceProvider.h" #include "CEGUIOgreImageCodec.h" #include <OgreRoot.h> #include <OgreRenderSystem.h> #include <OgreRenderWindow.h> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// // Internal Ogre::FrameListener based class. This is how we noew hook into the // rendering process (as opposed to render queues previously) static class OgreGUIFrameListener : public Ogre::FrameListener { public: OgreGUIFrameListener(); void setCEGUIRenderEnabled(bool enabled); bool isCEGUIRenderEnabled() const; bool frameRenderingQueued(const Ogre::FrameEvent& evt); private: bool d_enabled; } S_frameListener; //----------------------------------------------------------------------------// String OgreRenderer::d_rendererID( "CEGUI::OgreRenderer - Official OGRE based 2nd generation renderer module."); //----------------------------------------------------------------------------// OgreRenderer& OgreRenderer::bootstrapSystem() { if (System::getSingletonPtr()) throw InvalidRequestException("OgreRenderer::bootstrapSystem: " "CEGUI::System object is already initialised."); OgreRenderer& renderer = create(); OgreResourceProvider& rp = createOgreResourceProvider(); OgreImageCodec& ic = createOgreImageCodec(); System::create(renderer, &rp, static_cast<XMLParser*>(0), &ic); return renderer; } //----------------------------------------------------------------------------// OgreRenderer& OgreRenderer::bootstrapSystem(Ogre::RenderTarget& target) { if (System::getSingletonPtr()) throw InvalidRequestException("OgreRenderer::bootstrapSystem: " "CEGUI::System object is already initialised."); OgreRenderer& renderer = OgreRenderer::create(target); OgreResourceProvider& rp = createOgreResourceProvider(); OgreImageCodec& ic = createOgreImageCodec(); System::create(renderer, &rp, static_cast<XMLParser*>(0), &ic); return renderer; } //----------------------------------------------------------------------------// void OgreRenderer::destroySystem() { System* sys; if (!(sys = System::getSingletonPtr())) throw InvalidRequestException("OgreRenderer::destroySystem: " "CEGUI::System object is not created or was already destroyed."); OgreRenderer* renderer = static_cast<OgreRenderer*>(sys->getRenderer()); OgreResourceProvider* rp = static_cast<OgreResourceProvider*>(sys->getResourceProvider()); OgreImageCodec* ic = &static_cast<OgreImageCodec&>(sys->getImageCodec()); System::destroy(); destroyOgreImageCodec(*ic); destroyOgreResourceProvider(*rp); destroy(*renderer); } //----------------------------------------------------------------------------// OgreRenderer& OgreRenderer::create() { return *new OgreRenderer; } //----------------------------------------------------------------------------// OgreRenderer& OgreRenderer::create(Ogre::RenderTarget& target) { return *new OgreRenderer(target); } //----------------------------------------------------------------------------// void OgreRenderer::destroy(OgreRenderer& renderer) { delete &renderer; } //----------------------------------------------------------------------------// OgreResourceProvider& OgreRenderer::createOgreResourceProvider() { return *new OgreResourceProvider; } //----------------------------------------------------------------------------// void OgreRenderer::destroyOgreResourceProvider(OgreResourceProvider& rp) { delete &rp; } //----------------------------------------------------------------------------// OgreImageCodec& OgreRenderer::createOgreImageCodec() { return *new OgreImageCodec; } //----------------------------------------------------------------------------// void OgreRenderer::destroyOgreImageCodec(OgreImageCodec& ic) { delete &ic; } //----------------------------------------------------------------------------// void OgreRenderer::setRenderingEnabled(const bool enabled) { S_frameListener.setCEGUIRenderEnabled(enabled); } //----------------------------------------------------------------------------// bool OgreRenderer::isRenderingEnabled() const { return S_frameListener.isCEGUIRenderEnabled(); } //----------------------------------------------------------------------------// RenderingRoot& OgreRenderer::getDefaultRenderingRoot() { return *d_defaultRoot; } //----------------------------------------------------------------------------// GeometryBuffer& OgreRenderer::createGeometryBuffer() { OgreGeometryBuffer* gb = new OgreGeometryBuffer(*d_renderSystem); d_geometryBuffers.push_back(gb); return *gb; } //----------------------------------------------------------------------------// void OgreRenderer::destroyGeometryBuffer(const GeometryBuffer& buffer) { GeometryBufferList::iterator i = std::find(d_geometryBuffers.begin(), d_geometryBuffers.end(), &buffer); if (d_geometryBuffers.end() != i) { d_geometryBuffers.erase(i); delete &buffer; } } //----------------------------------------------------------------------------// void OgreRenderer::destroyAllGeometryBuffers() { while (!d_geometryBuffers.empty()) destroyGeometryBuffer(**d_geometryBuffers.begin()); } //----------------------------------------------------------------------------// TextureTarget* OgreRenderer::createTextureTarget() { TextureTarget* tt = new OgreTextureTarget(*this, *d_renderSystem); d_textureTargets.push_back(tt); return tt; } //----------------------------------------------------------------------------// void OgreRenderer::destroyTextureTarget(TextureTarget* target) { TextureTargetList::iterator i = std::find(d_textureTargets.begin(), d_textureTargets.end(), target); if (d_textureTargets.end() != i) { d_textureTargets.erase(i); delete target; } } //----------------------------------------------------------------------------// void OgreRenderer::destroyAllTextureTargets() { while (!d_textureTargets.empty()) destroyTextureTarget(*d_textureTargets.begin()); } //----------------------------------------------------------------------------// Texture& OgreRenderer::createTexture() { OgreTexture* t = new OgreTexture; d_textures.push_back(t); return *t; } //----------------------------------------------------------------------------// Texture& OgreRenderer::createTexture(const String& filename, const String& resourceGroup) { OgreTexture* t = new OgreTexture(filename, resourceGroup); d_textures.push_back(t); return *t; } //----------------------------------------------------------------------------// Texture& OgreRenderer::createTexture(const Size& size) { OgreTexture* t = new OgreTexture(size); d_textures.push_back(t); return *t; } //----------------------------------------------------------------------------// Texture& OgreRenderer::createTexture(Ogre::TexturePtr& tex, bool take_ownership) { OgreTexture* t = new OgreTexture(tex, take_ownership); d_textures.push_back(t); return *t; } //----------------------------------------------------------------------------// void OgreRenderer::destroyTexture(Texture& texture) { TextureList::iterator i = std::find(d_textures.begin(), d_textures.end(), &texture); if (d_textures.end() != i) { d_textures.erase(i); delete &static_cast<OgreTexture&>(texture); } } //----------------------------------------------------------------------------// void OgreRenderer::destroyAllTextures() { while (!d_textures.empty()) destroyTexture(**d_textures.begin()); } //----------------------------------------------------------------------------// void OgreRenderer::beginRendering() { using namespace Ogre; // initialise render settings d_renderSystem->setLightingEnabled(false); d_renderSystem->_setDepthBufferParams(false, false); d_renderSystem->_setDepthBias(0, 0); d_renderSystem->_setCullingMode(CULL_NONE); d_renderSystem->_setFog(FOG_NONE); d_renderSystem->_setColourBufferWriteEnabled(true, true, true, true); d_renderSystem->unbindGpuProgram(GPT_FRAGMENT_PROGRAM); d_renderSystem->unbindGpuProgram(GPT_VERTEX_PROGRAM); d_renderSystem->setShadingType(SO_GOURAUD); d_renderSystem->_setPolygonMode(PM_SOLID); // enable alpha blending d_renderSystem->_setSeparateSceneBlending(SBF_SOURCE_ALPHA, SBF_ONE_MINUS_SOURCE_ALPHA, SBF_SOURCE_ALPHA, SBF_ONE); d_renderSystem->_beginFrame(); } //----------------------------------------------------------------------------// void OgreRenderer::endRendering() { d_renderSystem->_endFrame(); } //----------------------------------------------------------------------------// const Size& OgreRenderer::getDisplaySize() const { return d_displaySize; } //----------------------------------------------------------------------------// const Vector2& OgreRenderer::getDisplayDPI() const { return d_displayDPI; } //----------------------------------------------------------------------------// uint OgreRenderer::getMaxTextureSize() const { return d_maxTextureSize; } //----------------------------------------------------------------------------// const String& OgreRenderer::getIdentifierString() const { return d_rendererID; } //----------------------------------------------------------------------------// OgreRenderer::OgreRenderer() : d_displayDPI(96, 96), // TODO: should be set to correct value d_maxTextureSize(2048), d_ogreRoot(Ogre::Root::getSingletonPtr()) { checkOgreInitialised(); // get auto created window Ogre::RenderWindow* rwnd = d_ogreRoot->getAutoCreatedWindow(); if (!rwnd) throw RendererException("Ogre was not initialised to automatically " "create a window, you should therefore be " "explicitly specifying a Ogre::RenderTarget in " "the OgreRenderer::create function."); constructor_impl(*rwnd); } //----------------------------------------------------------------------------// OgreRenderer::OgreRenderer(Ogre::RenderTarget& target) : d_displayDPI(96, 96), // TODO: should be set to correct value d_maxTextureSize(2048), d_ogreRoot(Ogre::Root::getSingletonPtr()) { checkOgreInitialised(); constructor_impl(target); } //----------------------------------------------------------------------------// OgreRenderer::~OgreRenderer() { d_ogreRoot->removeFrameListener(&S_frameListener); destroyAllGeometryBuffers(); destroyAllTextureTargets(); destroyAllTextures(); delete d_defaultRoot; delete d_defaultTarget; } //----------------------------------------------------------------------------// void OgreRenderer::checkOgreInitialised() { if (!d_ogreRoot) throw RendererException("The Ogre::Root object has not been created. " "You must initialise Ogre first!"); if (!d_ogreRoot->isInitialised()) throw RendererException("Ogre has not been initialised. You must " "initialise Ogre first!"); } //----------------------------------------------------------------------------// void OgreRenderer::constructor_impl(Ogre::RenderTarget& target) { d_renderSystem = d_ogreRoot->getRenderSystem(); d_displaySize.d_width = target.getWidth(); d_displaySize.d_height = target.getHeight(); // create default target & rendering root (surface) that uses it d_defaultTarget = new OgreWindowTarget(*this, *d_renderSystem, target); d_defaultRoot = new RenderingRoot(*d_defaultTarget); // hook into the rendering process d_ogreRoot->addFrameListener(&S_frameListener); } //----------------------------------------------------------------------------// void OgreRenderer::setDisplaySize(const Size& sz) { if (sz != d_displaySize) { d_displaySize = sz; // FIXME: This is probably not the right thing to do in all cases. Rect area(d_defaultTarget->getArea()); area.setSize(sz); d_defaultTarget->setArea(area); } } //----------------------------------------------------------------------------// OgreGUIFrameListener::OgreGUIFrameListener() : d_enabled(true) { } //----------------------------------------------------------------------------// void OgreGUIFrameListener::setCEGUIRenderEnabled(bool enabled) { d_enabled = enabled; } //----------------------------------------------------------------------------// bool OgreGUIFrameListener::isCEGUIRenderEnabled() const { return d_enabled; } //----------------------------------------------------------------------------// bool OgreGUIFrameListener::frameRenderingQueued(const Ogre::FrameEvent&) { if (d_enabled) System::getSingleton().renderGUI(); return true; } } // End of CEGUI namespace section <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/gview_request_interceptor.h" #include "net/base/escape.h" #include "net/base/load_flags.h" #include "net/url_request/url_request_job.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_redirect_job.h" #include "googleurl/src/gurl.h" namespace chromeos { // This is the list of mime types currently supported by the Google // Document Viewer. static const char* const supported_mime_type_list[] = { "application/pdf", "application/vnd.ms-powerpoint" }; static const char* const kGViewUrlPrefix = "http://docs.google.com/gview?url="; GViewRequestInterceptor::GViewRequestInterceptor() { URLRequest::RegisterRequestInterceptor(this); for (size_t i = 0; i < arraysize(supported_mime_type_list); ++i) { supported_mime_types_.insert(supported_mime_type_list[i]); } } GViewRequestInterceptor::~GViewRequestInterceptor() { URLRequest::UnregisterRequestInterceptor(this); } URLRequestJob* GViewRequestInterceptor::MaybeIntercept(URLRequest* request) { // Don't attempt to intercept here as we want to wait until the mime // type is fully determined. return NULL; } URLRequestJob* GViewRequestInterceptor::MaybeInterceptResponse( URLRequest* request) { // Do not intercept this request if it is a download. if (request->load_flags() & net::LOAD_IS_DOWNLOAD) { return NULL; } std::string mime_type; request->GetMimeType(&mime_type); // If supported, build the URL to the Google Document Viewer // including the origial document's URL, then create a new job that // will redirect the browser to this new URL. if (supported_mime_types_.count(mime_type) > 0) { std::string url(kGViewUrlPrefix); url += EscapePath(request->url().spec()); return new URLRequestRedirectJob(request, GURL(url)); } return NULL; } URLRequest::Interceptor* GViewRequestInterceptor::GetGViewRequestInterceptor() { return Singleton<GViewRequestInterceptor>::get(); } } // namespace chromeos <commit_msg>ChromeOS PDF handling: if the built-in PDF viewer plug-in is active, don't intercept PDF opening and forward to gView, but use the plug-in instead.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/gview_request_interceptor.h" #include "base/file_path.h" #include "base/path_service.h" #include "chrome/common/chrome_paths.h" #include "net/base/escape.h" #include "net/base/load_flags.h" #include "net/url_request/url_request_job.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_redirect_job.h" #include "googleurl/src/gurl.h" #include "webkit/glue/plugins/plugin_list.h" namespace chromeos { // The PDF mime type is treated special if the browser has a built-in // PDF viewer plug-in installed - we want to intercept only if we're // told to. static const char* const kPdfMimeType = "application/pdf"; // This is the list of mime types currently supported by the Google // Document Viewer. static const char* const supported_mime_type_list[] = { kPdfMimeType, "application/vnd.ms-powerpoint" }; static const char* const kGViewUrlPrefix = "http://docs.google.com/gview?url="; GViewRequestInterceptor::GViewRequestInterceptor() { URLRequest::RegisterRequestInterceptor(this); for (size_t i = 0; i < arraysize(supported_mime_type_list); ++i) { supported_mime_types_.insert(supported_mime_type_list[i]); } } GViewRequestInterceptor::~GViewRequestInterceptor() { URLRequest::UnregisterRequestInterceptor(this); } URLRequestJob* GViewRequestInterceptor::MaybeIntercept(URLRequest* request) { // Don't attempt to intercept here as we want to wait until the mime // type is fully determined. return NULL; } URLRequestJob* GViewRequestInterceptor::MaybeInterceptResponse( URLRequest* request) { // Do not intercept this request if it is a download. if (request->load_flags() & net::LOAD_IS_DOWNLOAD) { return NULL; } std::string mime_type; request->GetMimeType(&mime_type); // If the local PDF viewing plug-in is installed and enabled, don't // redirect PDF files to Google Document Viewer. if (mime_type == kPdfMimeType) { FilePath pdf_path; WebPluginInfo info; PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_path); if (NPAPI::PluginList::Singleton()->GetPluginInfoByPath(pdf_path, &info) && info.enabled) return NULL; } // If supported, build the URL to the Google Document Viewer // including the origial document's URL, then create a new job that // will redirect the browser to this new URL. if (supported_mime_types_.count(mime_type) > 0) { std::string url(kGViewUrlPrefix); url += EscapePath(request->url().spec()); return new URLRequestRedirectJob(request, GURL(url)); } return NULL; } URLRequest::Interceptor* GViewRequestInterceptor::GetGViewRequestInterceptor() { return Singleton<GViewRequestInterceptor>::get(); } } // namespace chromeos <|endoftext|>
<commit_before>#include <iostream> #include "kernel.h" #include "ilwisdata.h" #include "symboltable.h" #include "OperationExpression.h" #include "operationmetadata.h" #include "operation.h" #include "commandhandler.h" #include "text2output.h" using namespace Ilwis; using namespace BaseOperations; Text2Output::Text2Output() { } Text2Output::Text2Output(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr) { } bool Text2Output::execute(ExecutionContext *ctx, SymbolTable &symTable) { if (_prepState == sNOTPREPARED) if((_prepState = prepare(ctx, symTable)) != sPREPARED) return false; std::cout << _text.toStdString() << "\n" ; return true; } Ilwis::OperationImplementation *Text2Output::create(quint64 metaid, const Ilwis::OperationExpression &expr) { return new Text2Output(metaid, expr); } Ilwis::OperationImplementation::State Text2Output::prepare(ExecutionContext *ctx, const Ilwis::SymbolTable &) { for(int i=0; i < _expression.parameterCount(); ++i){ QString str = _expression.parm(i).value(); if ( str.size() > 0 && str[0] == '"' && str[str.size()-1] == '"'){ str = str.remove('"'); } _text += str; } if ( _expression.parameterCount() == 2) { //TODO, file based cases } return sPREPARED; } quint64 Text2Output::createMetadata() { QString url = QString("ilwis://operations/text2output"); Resource res(QUrl(url), itOPERATIONMETADATA); res.addProperty("namespace","ilwis"); res.addProperty("longname","text2output"); res.addProperty("syntax","text2output(text,[text]+)"); res.addProperty("inparameters","1+"); res.addProperty("pin_1_type", itANY); res.addProperty("pin_1_name", TR("input string")); res.addProperty("pin_1_desc",TR("input string")); res.addProperty("pin_2_type", itANY); res.addProperty("pin_2_name", TR("filename or path")); res.addProperty("pin_2_desc",TR("optional file were strings will be written; if no path is provided, current working folder will be used")); res.addProperty("outparameters",0); res.prepare(); url += "=" + QString::number(res.id()); res.setUrl(url); mastercatalog()->addItems({res}); return res.id(); } <commit_msg>removed a case that will not be used anymore<commit_after>#include <iostream> #include "kernel.h" #include "ilwisdata.h" #include "symboltable.h" #include "OperationExpression.h" #include "operationmetadata.h" #include "operation.h" #include "commandhandler.h" #include "text2output.h" using namespace Ilwis; using namespace BaseOperations; Text2Output::Text2Output() { } Text2Output::Text2Output(quint64 metaid, const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr) { } bool Text2Output::execute(ExecutionContext *ctx, SymbolTable &symTable) { if (_prepState == sNOTPREPARED) if((_prepState = prepare(ctx, symTable)) != sPREPARED) return false; std::cout << _text.toStdString() << "\n" ; return true; } Ilwis::OperationImplementation *Text2Output::create(quint64 metaid, const Ilwis::OperationExpression &expr) { return new Text2Output(metaid, expr); } Ilwis::OperationImplementation::State Text2Output::prepare(ExecutionContext *ctx, const Ilwis::SymbolTable &) { for(int i=0; i < _expression.parameterCount(); ++i){ QString str = _expression.parm(i).value(); if ( str.size() > 0 && str[0] == '"' && str[str.size()-1] == '"'){ str = str.remove('"'); } _text += str; } return sPREPARED; } quint64 Text2Output::createMetadata() { QString url = QString("ilwis://operations/text2output"); Resource res(QUrl(url), itOPERATIONMETADATA); res.addProperty("namespace","ilwis"); res.addProperty("longname","text2output"); res.addProperty("syntax","text2output(text,[text]+)"); res.addProperty("inparameters","1+"); res.addProperty("pin_1_type", itANY); res.addProperty("pin_1_name", TR("input string")); res.addProperty("pin_1_desc",TR("input string")); res.addProperty("pin_2_type", itANY); res.addProperty("pin_2_name", TR("filename or path")); res.addProperty("pin_2_desc",TR("optional file were strings will be written; if no path is provided, current working folder will be used")); res.addProperty("outparameters",0); res.prepare(); url += "=" + QString::number(res.id()); res.setUrl(url); mastercatalog()->addItems({res}); return res.id(); } <|endoftext|>
<commit_before>// @(#)root/eve:$Id$ // Authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007 /************************************************************************* * Copyright (C) 1995-2007, 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 "TEveMacro.h" #include "TSystem.h" #include "TROOT.h" //______________________________________________________________________________ // TEveMacro // // Sub-class of TMacro, overriding Exec to unload the previous verison // and cleanup after the execution. ClassImp(TEveMacro) //______________________________________________________________________________ TEveMacro::TEveMacro() : TMacro() { // Default constructor. } TEveMacro::TEveMacro(const TEveMacro& m) : TMacro(m) { // Copy constructor. } TEveMacro::TEveMacro(const char* name) : TMacro() { // Constructor with file name. if (!name) return; fTitle = name; char *dot = (char*)strrchr(name, '.'); char *slash = (char*)strrchr(name, '/'); if (dot) *dot = 0; if (slash) fName = slash + 1; else fName = name; ReadFile(fTitle); } /******************************************************************************/ #include "TTimer.h" //______________________________________________________________________________ Long_t TEveMacro::Exec(const char* params, Int_t* error) { // Execute the macro. Long_t retval = -1; if (gROOT->GetGlobalFunction(fName, 0, kTRUE) != 0) { gROOT->SetExecutingMacro(kTRUE); gROOT->SetExecutingMacro(kFALSE); retval = gROOT->ProcessLine(Form("%s()", fName.Data()), error); } else { // Copy from TMacro::Exec. Difference is that the file is really placed // into the /tmp. TString fname = "/tmp/"; { //the current implementation uses a file in the current directory. //should be replaced by a direct execution from memory by CINT fname += GetName(); fname += ".C"; SaveSource(fname); //disable a possible call to gROOT->Reset from the executed script gROOT->SetExecutingMacro(kTRUE); //execute script in /tmp TString exec = ".x " + fname; TString p = params; if (p == "") p = fParams; if (p != "") exec += "(" + p + ")"; retval = gROOT->ProcessLine(exec, error); //enable gROOT->Reset gROOT->SetExecutingMacro(kFALSE); //delete the temporary file gSystem->Unlink(fname); } } //G__unloadfile(fname); // In case an exception was thrown (which i do not know how to detect // the execution of next macros does not succeed. // However strange this might seem, this solves the problem. // TTimer::SingleShot(100, "TEveMacro", this, "ResetRoot()"); // // 27.8.07 - ok, this does not work any more. Seems I'll have to fix // this real soon now. // // !!!! FIX MACRO HANDLING !!!! // return retval; } #include "TApplication.h" //______________________________________________________________________________ void TEveMacro::ResetRoot() { // Call gROOT->Reset() via interpreter. // printf ("TEveMacro::ResetRoot doing 'gROOT->Reset()'.\n"); gROOT->GetApplication()->ProcessLine("gROOT->Reset()"); } <commit_msg>Use TPMERegexp to determine macro name instead of strrchr and hacking the input const char array (reported by Benjamin Hess).<commit_after>// @(#)root/eve:$Id$ // Authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007 /************************************************************************* * Copyright (C) 1995-2007, 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 "TEveMacro.h" #include "TPRegexp.h" #include "TSystem.h" #include "TROOT.h" //______________________________________________________________________________ // // Sub-class of TMacro, overriding Exec to unload the previous verison // and cleanup after the execution. ClassImp(TEveMacro); //______________________________________________________________________________ TEveMacro::TEveMacro() : TMacro() { // Default constructor. } TEveMacro::TEveMacro(const TEveMacro& m) : TMacro(m) { // Copy constructor. } TEveMacro::TEveMacro(const char* name) : TMacro() { // Constructor with file name. if (!name) return; fTitle = name; TPMERegexp re("([^/]+?)(?:\\.\\w*)?$"); Int_t nm = re.Match(fTitle); if (nm >= 2) { fName = re[1]; } else { fName = "<unknown>"; } ReadFile(fTitle); } /******************************************************************************/ #include "TTimer.h" //______________________________________________________________________________ Long_t TEveMacro::Exec(const char* params, Int_t* error) { // Execute the macro. Long_t retval = -1; if (gROOT->GetGlobalFunction(fName, 0, kTRUE) != 0) { gROOT->SetExecutingMacro(kTRUE); gROOT->SetExecutingMacro(kFALSE); retval = gROOT->ProcessLine(Form("%s()", fName.Data()), error); } else { // Copy from TMacro::Exec. Difference is that the file is really placed // into the /tmp. TString fname = "/tmp/"; { //the current implementation uses a file in the current directory. //should be replaced by a direct execution from memory by CINT fname += GetName(); fname += ".C"; SaveSource(fname); //disable a possible call to gROOT->Reset from the executed script gROOT->SetExecutingMacro(kTRUE); //execute script in /tmp TString exec = ".x " + fname; TString p = params; if (p == "") p = fParams; if (p != "") exec += "(" + p + ")"; retval = gROOT->ProcessLine(exec, error); //enable gROOT->Reset gROOT->SetExecutingMacro(kFALSE); //delete the temporary file gSystem->Unlink(fname); } } //G__unloadfile(fname); // In case an exception was thrown (which i do not know how to detect // the execution of next macros does not succeed. // However strange this might seem, this solves the problem. // TTimer::SingleShot(100, "TEveMacro", this, "ResetRoot()"); // // 27.8.07 - ok, this does not work any more. Seems I'll have to fix // this real soon now. // // !!!! FIX MACRO HANDLING !!!! // return retval; } #include "TApplication.h" //______________________________________________________________________________ void TEveMacro::ResetRoot() { // Call gROOT->Reset() via interpreter. // printf ("TEveMacro::ResetRoot doing 'gROOT->Reset()'.\n"); gROOT->GetApplication()->ProcessLine("gROOT->Reset()"); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/tabs/tab_overview_controller.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_process.h" #if defined(TOOLKIT_VIEWS) #include "chrome/common/x11_util.h" #include "chrome/browser/views/frame/browser_extender.h" #include "chrome/browser/views/frame/browser_view.h" #else #include "chrome/browser/gtk/browser_window_gtk.h" #endif #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/thumbnail_generator.h" #include "chrome/browser/views/tabs/tab_overview_cell.h" #include "chrome/browser/views/tabs/tab_overview_container.h" #include "chrome/browser/views/tabs/tab_overview_drag_controller.h" #include "chrome/browser/views/tabs/tab_overview_grid.h" #include "chrome/browser/views/tabs/tab_overview_types.h" #include "chrome/browser/window_sizer.h" #include "views/widget/root_view.h" #include "views/widget/widget_gtk.h" // Horizontal padding from the edge of the monitor to the overview. static int kMonitorPadding = 20; // Vertical padding between the overview and the windows along on the bottom. static int kWindowToOverviewPadding = 25; // Height of the windows along the bottom, as a percentage of the monitors // height. static float kWindowHeight = .30; // Height of the tab overview, as a percentage of monitors height. static float kOverviewHeight = .55; TabOverviewController::TabOverviewController( const gfx::Point& monitor_origin) : host_(NULL), container_(NULL), grid_(NULL), browser_(NULL), drag_browser_(NULL), moved_offscreen_(false), shown_(false), horizontal_center_(0), change_window_bounds_on_animate_(false), mutating_grid_(false), show_thumbnails_(false) { grid_ = new TabOverviewGrid(this); // Determine the max size for the overview. scoped_ptr<WindowSizer::MonitorInfoProvider> provider( WindowSizer::CreateDefaultMonitorInfoProvider()); monitor_bounds_ = provider->GetMonitorWorkAreaMatching( gfx::Rect(monitor_origin.x(), monitor_origin.y(), 1, 1)); // Create the host. views::WidgetGtk* host = new views::WidgetGtk(views::WidgetGtk::TYPE_POPUP); host->set_delete_on_destroy(false); host->MakeTransparent(); host->Init(NULL, CalculateHostBounds()); TabOverviewTypes::instance()->SetWindowType( host->GetNativeView(), TabOverviewTypes::WINDOW_TYPE_CHROME_TAB_SUMMARY, NULL); host_ = host; container_ = new TabOverviewContainer(); container_->AddChildView(grid_); host->GetRootView()->AddChildView(container_); container_->SetMaxSize(CalculateHostBounds().size()); horizontal_center_ = monitor_bounds_.x() + monitor_bounds_.width() / 2; } TabOverviewController::~TabOverviewController() { if (browser_) model()->RemoveObserver(this); host_->Close(); // The drag controller may call back to us from it's destructor. Make sure // it's destroyed before us. grid()->CancelDrag(); } void TabOverviewController::SetBrowser(Browser* browser, int horizontal_center) { horizontal_center_ = horizontal_center; if (browser_) model()->RemoveObserver(this); browser_ = browser; if (browser_) model()->AddObserver(this); show_thumbnails_ = false; StartDelayTimer(); gfx::Rect host_bounds = CalculateHostBounds(); if (moved_offscreen_ && model() && model()->count()) { // Need to reset the bounds if we were offscreen. host_->SetBounds(host_bounds); moved_offscreen_ = false; } else if (!model() && shown_) { MoveOffscreen(); } if (!moved_offscreen_) container_->SchedulePaint(); RecreateCells(); container_->set_arrow_center(horizontal_center_ - host_bounds.x()); if (!moved_offscreen_) container_->SchedulePaint(); } TabStripModel* TabOverviewController::model() const { return browser_ ? browser_->tabstrip_model() : NULL; } void TabOverviewController::SetMouseOverMiniWindow(bool over_mini_window) { if (grid_->drag_controller()) grid_->drag_controller()->set_mouse_over_mini_window(over_mini_window); } void TabOverviewController::Show() { if (host_->IsVisible()) return; shown_ = true; DCHECK(model()); // The model needs to be set before showing. host_->Show(); show_thumbnails_ = false; StartDelayTimer(); } void TabOverviewController::ConfigureCell(TabOverviewCell* cell, TabContents* contents) { if (contents) { cell->SetTitle(contents->GetTitle()); cell->SetFavIcon(contents->GetFavIcon()); if (show_thumbnails_) { ThumbnailGenerator* generator = g_browser_process->GetThumbnailGenerator(); cell->SetThumbnail( generator->GetThumbnailForRenderer(contents->render_view_host())); } cell->SchedulePaint(); } else { // Need to figure out under what circumstances this is null and deal. NOTIMPLEMENTED(); // Make sure we set the thumbnail, otherwise configured_thumbnail // remains false and ConfigureNextUnconfiguredCell would get stuck. if (show_thumbnails_) cell->SetThumbnail(SkBitmap()); } } void TabOverviewController::DragStarted() { DCHECK(!drag_browser_); drag_browser_ = browser_; #if defined(TOOLKIT_VIEWS) static_cast<BrowserView*>(browser_->window())-> browser_extender()->set_can_close(false); #else static_cast<BrowserWindowGtk*>(browser_->window())->set_drag_active(true); #endif } void TabOverviewController::DragEnded() { #if defined(TOOLKIT_VIEWS) static_cast<BrowserView*>(browser_->window())-> browser_extender()->set_can_close(true); #else static_cast<BrowserWindowGtk*>(drag_browser_->window())-> set_drag_active(false); #endif if (drag_browser_->tabstrip_model()->count() == 0) drag_browser_->tabstrip_model()->delegate()->CloseFrameAfterDragSession(); drag_browser_ = NULL; } void TabOverviewController::MoveOffscreen() { gfx::Rect bounds; moved_offscreen_ = true; host_->GetBounds(&bounds, true); host_->SetBounds(gfx::Rect(-10000, -10000, bounds.width(), bounds.height())); } void TabOverviewController::SelectTab(int index) { browser_->SelectTabContentsAt(index, true); } void TabOverviewController::FocusBrowser() { TabOverviewTypes::Message message; message.set_type(TabOverviewTypes::Message::WM_FOCUS_WINDOW); GtkWidget* browser_widget = GTK_WIDGET(browser_->window()->GetNativeHandle()); message.set_param(0, x11_util::GetX11WindowFromGtkWidget(browser_widget)); TabOverviewTypes::instance()->SendMessage(message); } void TabOverviewController::GridAnimationEnded() { if (moved_offscreen_ || !change_window_bounds_on_animate_ || mutating_grid_) return; container_->SetBounds(target_bounds_); grid_->UpdateDragController(); change_window_bounds_on_animate_ = false; } void TabOverviewController::GridAnimationProgressed() { if (moved_offscreen_ || !change_window_bounds_on_animate_) return; DCHECK(!mutating_grid_); // Schedule a paint before and after changing sizes to deal with the case // of the view shrinking in size. container_->SchedulePaint(); container_->SetBounds( grid_->AnimationPosition(start_bounds_, target_bounds_)); container_->SchedulePaint(); // Update the position of the dragged cell. grid_->UpdateDragController(); } void TabOverviewController::GridAnimationCanceled() { change_window_bounds_on_animate_ = false; } void TabOverviewController::TabInsertedAt(TabContents* contents, int index, bool foreground) { if (!grid_->modifying_model()) grid_->CancelDrag(); TabOverviewCell* child = new TabOverviewCell(); ConfigureCell(child, index); mutating_grid_ = true; grid_->InsertCell(index, child); mutating_grid_ = false; UpdateStartAndTargetBounds(); } void TabOverviewController::TabClosingAt(TabContents* contents, int index) { // Nothing to do, we only care when the tab is actually detached. } void TabOverviewController::TabDetachedAt(TabContents* contents, int index) { if (!grid_->modifying_model()) grid_->CancelDrag(); scoped_ptr<TabOverviewCell> child(grid_->GetTabOverviewCellAt(index)); mutating_grid_ = true; grid_->RemoveCell(index); mutating_grid_ = false; UpdateStartAndTargetBounds(); } void TabOverviewController::TabMoved(TabContents* contents, int from_index, int to_index, bool pinned_state_changed) { if (!grid_->modifying_model()) grid_->CancelDrag(); mutating_grid_ = true; grid_->MoveCell(from_index, to_index); mutating_grid_ = false; UpdateStartAndTargetBounds(); } void TabOverviewController::TabChangedAt(TabContents* contents, int index, TabChangeType change_type) { ConfigureCell(grid_->GetTabOverviewCellAt(index), index); } void TabOverviewController::TabStripEmpty() { if (!grid_->modifying_model()) { grid_->CancelDrag(); // The tab strip is empty, hide the grid. host_->Hide(); } } void TabOverviewController::ConfigureCell(TabOverviewCell* cell, int index) { ConfigureCell(cell, model()->GetTabContentsAt(index)); } void TabOverviewController::RecreateCells() { grid_->RemoveAllChildViews(true); if (model()) { for (int i = 0; i < model()->count(); ++i) { TabOverviewCell* child = new TabOverviewCell(); ConfigureCell(child, i); grid_->AddChildView(child); } } if (moved_offscreen_) return; if (grid()->GetChildViewCount() > 0) { if (shown_) host_->Show(); } else { host_->Hide(); } container_->SetBounds(CalculateContainerBounds()); } void TabOverviewController::UpdateStartAndTargetBounds() { if (moved_offscreen_ || !shown_) return; if (grid()->GetChildViewCount() == 0) { host_->Hide(); } else { start_bounds_ = container_->bounds(); target_bounds_ = CalculateContainerBounds(); change_window_bounds_on_animate_ = (start_bounds_ != target_bounds_); } } gfx::Rect TabOverviewController::CalculateContainerBounds() { gfx::Rect host_bounds = CalculateHostBounds(); const gfx::Size& host_size = CalculateHostBounds().size(); gfx::Size pref = container_->GetPreferredSize(); int relative_horizontal_center = horizontal_center_ - host_bounds.x(); int x = relative_horizontal_center - pref.width() / 2; int y = host_size.height() - pref.height(); return gfx::Rect(x, y, pref.width(), pref.height()). AdjustToFit(gfx::Rect(0, 0, host_size.width(), host_size.height())); } gfx::Rect TabOverviewController::CalculateHostBounds() { int max_width = monitor_bounds_.width() - kMonitorPadding * 2; int window_height = monitor_bounds_.height() * kWindowHeight; int max_height = static_cast<int>(monitor_bounds_.height() * kOverviewHeight); return gfx::Rect(monitor_bounds_.x() + kMonitorPadding, monitor_bounds_.bottom() - window_height - kWindowToOverviewPadding - max_height, max_width, max_height); } void TabOverviewController::StartConfiguring() { show_thumbnails_ = true; configure_timer_.Stop(); configure_timer_.Start( base::TimeDelta::FromMilliseconds(10), this, &TabOverviewController::ConfigureNextUnconfiguredCell); } void TabOverviewController::ConfigureNextUnconfiguredCell() { for (int i = 0; i < grid_->GetChildViewCount(); ++i) { TabOverviewCell* cell = grid_->GetTabOverviewCellAt(i); if (!cell->configured_thumbnail()) { ConfigureCell(cell, i); return; } } configure_timer_.Stop(); } void TabOverviewController::StartDelayTimer() { configure_timer_.Stop(); delay_timer_.Stop(); delay_timer_.Start( base::TimeDelta::FromMilliseconds(350), this, &TabOverviewController::StartConfiguring); } <commit_msg>Fixes crash in dragging a tab out in overview mode. This regression was introduced when adding the views/gtk support. As we don't need non-views/gtk support anymore, I'm nuking the defines in this file.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/tabs/tab_overview_controller.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/views/frame/browser_extender.h" #include "chrome/browser/views/frame/browser_view.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/thumbnail_generator.h" #include "chrome/browser/views/tabs/tab_overview_cell.h" #include "chrome/browser/views/tabs/tab_overview_container.h" #include "chrome/browser/views/tabs/tab_overview_drag_controller.h" #include "chrome/browser/views/tabs/tab_overview_grid.h" #include "chrome/browser/views/tabs/tab_overview_types.h" #include "chrome/browser/window_sizer.h" #include "chrome/common/x11_util.h" #include "views/widget/root_view.h" #include "views/widget/widget_gtk.h" // Horizontal padding from the edge of the monitor to the overview. static int kMonitorPadding = 20; // Vertical padding between the overview and the windows along on the bottom. static int kWindowToOverviewPadding = 25; // Height of the windows along the bottom, as a percentage of the monitors // height. static float kWindowHeight = .30; // Height of the tab overview, as a percentage of monitors height. static float kOverviewHeight = .55; TabOverviewController::TabOverviewController( const gfx::Point& monitor_origin) : host_(NULL), container_(NULL), grid_(NULL), browser_(NULL), drag_browser_(NULL), moved_offscreen_(false), shown_(false), horizontal_center_(0), change_window_bounds_on_animate_(false), mutating_grid_(false), show_thumbnails_(false) { grid_ = new TabOverviewGrid(this); // Determine the max size for the overview. scoped_ptr<WindowSizer::MonitorInfoProvider> provider( WindowSizer::CreateDefaultMonitorInfoProvider()); monitor_bounds_ = provider->GetMonitorWorkAreaMatching( gfx::Rect(monitor_origin.x(), monitor_origin.y(), 1, 1)); // Create the host. views::WidgetGtk* host = new views::WidgetGtk(views::WidgetGtk::TYPE_POPUP); host->set_delete_on_destroy(false); host->MakeTransparent(); host->Init(NULL, CalculateHostBounds()); TabOverviewTypes::instance()->SetWindowType( host->GetNativeView(), TabOverviewTypes::WINDOW_TYPE_CHROME_TAB_SUMMARY, NULL); host_ = host; container_ = new TabOverviewContainer(); container_->AddChildView(grid_); host->GetRootView()->AddChildView(container_); container_->SetMaxSize(CalculateHostBounds().size()); horizontal_center_ = monitor_bounds_.x() + monitor_bounds_.width() / 2; } TabOverviewController::~TabOverviewController() { if (browser_) model()->RemoveObserver(this); host_->Close(); // The drag controller may call back to us from it's destructor. Make sure // it's destroyed before us. grid()->CancelDrag(); } void TabOverviewController::SetBrowser(Browser* browser, int horizontal_center) { horizontal_center_ = horizontal_center; if (browser_) model()->RemoveObserver(this); browser_ = browser; if (browser_) model()->AddObserver(this); show_thumbnails_ = false; StartDelayTimer(); gfx::Rect host_bounds = CalculateHostBounds(); if (moved_offscreen_ && model() && model()->count()) { // Need to reset the bounds if we were offscreen. host_->SetBounds(host_bounds); moved_offscreen_ = false; } else if (!model() && shown_) { MoveOffscreen(); } if (!moved_offscreen_) container_->SchedulePaint(); RecreateCells(); container_->set_arrow_center(horizontal_center_ - host_bounds.x()); if (!moved_offscreen_) container_->SchedulePaint(); } TabStripModel* TabOverviewController::model() const { return browser_ ? browser_->tabstrip_model() : NULL; } void TabOverviewController::SetMouseOverMiniWindow(bool over_mini_window) { if (grid_->drag_controller()) grid_->drag_controller()->set_mouse_over_mini_window(over_mini_window); } void TabOverviewController::Show() { if (host_->IsVisible()) return; shown_ = true; DCHECK(model()); // The model needs to be set before showing. host_->Show(); show_thumbnails_ = false; StartDelayTimer(); } void TabOverviewController::ConfigureCell(TabOverviewCell* cell, TabContents* contents) { if (contents) { cell->SetTitle(contents->GetTitle()); cell->SetFavIcon(contents->GetFavIcon()); if (show_thumbnails_) { ThumbnailGenerator* generator = g_browser_process->GetThumbnailGenerator(); cell->SetThumbnail( generator->GetThumbnailForRenderer(contents->render_view_host())); } cell->SchedulePaint(); } else { // Need to figure out under what circumstances this is null and deal. NOTIMPLEMENTED(); // Make sure we set the thumbnail, otherwise configured_thumbnail // remains false and ConfigureNextUnconfiguredCell would get stuck. if (show_thumbnails_) cell->SetThumbnail(SkBitmap()); } } void TabOverviewController::DragStarted() { DCHECK(!drag_browser_); drag_browser_ = browser_; static_cast<BrowserView*>(drag_browser_->window())-> browser_extender()->set_can_close(false); } void TabOverviewController::DragEnded() { static_cast<BrowserView*>(drag_browser_->window())-> browser_extender()->set_can_close(true); if (drag_browser_->tabstrip_model()->count() == 0) drag_browser_->tabstrip_model()->delegate()->CloseFrameAfterDragSession(); drag_browser_ = NULL; } void TabOverviewController::MoveOffscreen() { gfx::Rect bounds; moved_offscreen_ = true; host_->GetBounds(&bounds, true); host_->SetBounds(gfx::Rect(-10000, -10000, bounds.width(), bounds.height())); } void TabOverviewController::SelectTab(int index) { browser_->SelectTabContentsAt(index, true); } void TabOverviewController::FocusBrowser() { TabOverviewTypes::Message message; message.set_type(TabOverviewTypes::Message::WM_FOCUS_WINDOW); GtkWidget* browser_widget = GTK_WIDGET(browser_->window()->GetNativeHandle()); message.set_param(0, x11_util::GetX11WindowFromGtkWidget(browser_widget)); TabOverviewTypes::instance()->SendMessage(message); } void TabOverviewController::GridAnimationEnded() { if (moved_offscreen_ || !change_window_bounds_on_animate_ || mutating_grid_) return; container_->SetBounds(target_bounds_); grid_->UpdateDragController(); change_window_bounds_on_animate_ = false; } void TabOverviewController::GridAnimationProgressed() { if (moved_offscreen_ || !change_window_bounds_on_animate_) return; DCHECK(!mutating_grid_); // Schedule a paint before and after changing sizes to deal with the case // of the view shrinking in size. container_->SchedulePaint(); container_->SetBounds( grid_->AnimationPosition(start_bounds_, target_bounds_)); container_->SchedulePaint(); // Update the position of the dragged cell. grid_->UpdateDragController(); } void TabOverviewController::GridAnimationCanceled() { change_window_bounds_on_animate_ = false; } void TabOverviewController::TabInsertedAt(TabContents* contents, int index, bool foreground) { if (!grid_->modifying_model()) grid_->CancelDrag(); TabOverviewCell* child = new TabOverviewCell(); ConfigureCell(child, index); mutating_grid_ = true; grid_->InsertCell(index, child); mutating_grid_ = false; UpdateStartAndTargetBounds(); } void TabOverviewController::TabClosingAt(TabContents* contents, int index) { // Nothing to do, we only care when the tab is actually detached. } void TabOverviewController::TabDetachedAt(TabContents* contents, int index) { if (!grid_->modifying_model()) grid_->CancelDrag(); scoped_ptr<TabOverviewCell> child(grid_->GetTabOverviewCellAt(index)); mutating_grid_ = true; grid_->RemoveCell(index); mutating_grid_ = false; UpdateStartAndTargetBounds(); } void TabOverviewController::TabMoved(TabContents* contents, int from_index, int to_index, bool pinned_state_changed) { if (!grid_->modifying_model()) grid_->CancelDrag(); mutating_grid_ = true; grid_->MoveCell(from_index, to_index); mutating_grid_ = false; UpdateStartAndTargetBounds(); } void TabOverviewController::TabChangedAt(TabContents* contents, int index, TabChangeType change_type) { ConfigureCell(grid_->GetTabOverviewCellAt(index), index); } void TabOverviewController::TabStripEmpty() { if (!grid_->modifying_model()) { grid_->CancelDrag(); // The tab strip is empty, hide the grid. host_->Hide(); } } void TabOverviewController::ConfigureCell(TabOverviewCell* cell, int index) { ConfigureCell(cell, model()->GetTabContentsAt(index)); } void TabOverviewController::RecreateCells() { grid_->RemoveAllChildViews(true); if (model()) { for (int i = 0; i < model()->count(); ++i) { TabOverviewCell* child = new TabOverviewCell(); ConfigureCell(child, i); grid_->AddChildView(child); } } if (moved_offscreen_) return; if (grid()->GetChildViewCount() > 0) { if (shown_) host_->Show(); } else { host_->Hide(); } container_->SetBounds(CalculateContainerBounds()); } void TabOverviewController::UpdateStartAndTargetBounds() { if (moved_offscreen_ || !shown_) return; if (grid()->GetChildViewCount() == 0) { host_->Hide(); } else { start_bounds_ = container_->bounds(); target_bounds_ = CalculateContainerBounds(); change_window_bounds_on_animate_ = (start_bounds_ != target_bounds_); } } gfx::Rect TabOverviewController::CalculateContainerBounds() { gfx::Rect host_bounds = CalculateHostBounds(); const gfx::Size& host_size = CalculateHostBounds().size(); gfx::Size pref = container_->GetPreferredSize(); int relative_horizontal_center = horizontal_center_ - host_bounds.x(); int x = relative_horizontal_center - pref.width() / 2; int y = host_size.height() - pref.height(); return gfx::Rect(x, y, pref.width(), pref.height()). AdjustToFit(gfx::Rect(0, 0, host_size.width(), host_size.height())); } gfx::Rect TabOverviewController::CalculateHostBounds() { int max_width = monitor_bounds_.width() - kMonitorPadding * 2; int window_height = monitor_bounds_.height() * kWindowHeight; int max_height = static_cast<int>(monitor_bounds_.height() * kOverviewHeight); return gfx::Rect(monitor_bounds_.x() + kMonitorPadding, monitor_bounds_.bottom() - window_height - kWindowToOverviewPadding - max_height, max_width, max_height); } void TabOverviewController::StartConfiguring() { show_thumbnails_ = true; configure_timer_.Stop(); configure_timer_.Start( base::TimeDelta::FromMilliseconds(10), this, &TabOverviewController::ConfigureNextUnconfiguredCell); } void TabOverviewController::ConfigureNextUnconfiguredCell() { for (int i = 0; i < grid_->GetChildViewCount(); ++i) { TabOverviewCell* cell = grid_->GetTabOverviewCellAt(i); if (!cell->configured_thumbnail()) { ConfigureCell(cell, i); return; } } configure_timer_.Stop(); } void TabOverviewController::StartDelayTimer() { configure_timer_.Stop(); delay_timer_.Stop(); delay_timer_.Start( base::TimeDelta::FromMilliseconds(350), this, &TabOverviewController::StartConfiguring); } <|endoftext|>
<commit_before>#include "JsDebugger.h" #include "V8GlobalHelpers.h" #include "JniLocalRef.h" #include "NativeScriptException.h" #include "NativeScriptAssert.h" #include <assert.h> #include <sstream> using namespace std; using namespace tns; JsDebugger::JsDebugger() { } void JsDebugger::Init(v8::Isolate *isolate, const string& packageName, jobject jsDebugger) { s_isolate = isolate; s_packageName = packageName; JEnv env; s_jsDebugger = env.NewGlobalRef(jsDebugger); s_JsDebuggerClass = env.FindClass("com/tns/JsDebugger"); assert(s_JsDebuggerClass != nullptr); s_EnqueueMessage = env.GetMethodID(s_JsDebuggerClass, "enqueueMessage", "(Ljava/lang/String;)V"); assert(s_EnqueueMessage != nullptr); s_EnableAgent = env.GetMethodID(s_JsDebuggerClass, "enableAgent", "()V"); assert(s_EnableAgent != nullptr); } string JsDebugger::GetPackageName() { return s_packageName; } /* * * sets who will handle the messages when they start comming from v8 */ void JsDebugger::Enable() { auto isolate = s_isolate; v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handleScope(isolate); v8::Debug::SetMessageHandler(MyMessageHandler); enabled = true; } /* * * the message that come from v8 will not be handled anymore */ void JsDebugger::Disable() { enabled = false; auto isolate = s_isolate; v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handleScope(isolate); v8::Debug::SetMessageHandler(nullptr); } /* * * schedule a debugger break to happen when JavaScript code is run in the given isolate * (cli command: tns debug android --debug-brk) ? */ void JsDebugger::DebugBreak() { auto isolate = s_isolate; v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handleScope(isolate); v8::Debug::DebugBreak(isolate); } void JsDebugger::ProcessDebugMessages() { auto isolate = s_isolate; v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handleScope(isolate); v8::Debug::ProcessDebugMessages(); } void JsDebugger::SendCommand(JNIEnv *_env, jobject obj, jbyteArray command, jint length) { tns::JEnv env(_env); auto buf = new jbyte[length]; env.GetByteArrayRegion(command, 0, length, buf); int len = length / sizeof(uint16_t); SendCommandToV8(reinterpret_cast<uint16_t*>(buf), len); delete[] buf; } void JsDebugger::DebugBreakCallback(const v8::FunctionCallbackInfo<v8::Value>& args) { if (s_jsDebugger == nullptr) { return; } try { JEnv env; env.CallStaticVoidMethod(s_JsDebuggerClass, s_EnableAgent); DebugBreak(); } catch (NativeScriptException& e) { e.ReThrowToV8(); } catch (std::exception e) { stringstream ss; ss << "Error: c++ exception: " << e.what() << endl; NativeScriptException nsEx(ss.str()); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } void JsDebugger::ConsoleMessageCallback(const v8::FunctionCallbackInfo<v8::Value>& args) { if (s_jsDebugger == nullptr || !enabled) { return; } auto isolate = s_isolate; v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handleScope(isolate); if ((args.Length() > 0) && args[0]->IsString()) { std::string message = ConvertToString(args[0]->ToString()); //jboolean isError = (jboolean) = args[1]->ToBoolean()->BooleanValue(); JEnv env; JniLocalRef s(env.NewStringUTF(message.c_str())); env.CallVoidMethod(s_jsDebugger, s_EnqueueMessage, (jstring) s); } } void JsDebugger::SendCommandToV8(uint16_t *cmd, int length) { auto isolate = s_isolate; v8::Debug::SendCommand(isolate, cmd, length, nullptr); } /* * * private method that takes debug message as json from v8 * after it gets the message the message handler passes it to enqueueMessage method in java */ void JsDebugger::MyMessageHandler(const v8::Debug::Message& message) { if (s_jsDebugger == nullptr) { return; } auto json = message.GetJSON(); auto str = ConvertToString(json); JEnv env; JniLocalRef s(env.NewStringUTF(str.c_str())); env.CallVoidMethod(s_jsDebugger, s_EnqueueMessage, (jstring) s); } bool JsDebugger::enabled = false; v8::Isolate* JsDebugger::s_isolate = nullptr; jobject JsDebugger::s_jsDebugger = nullptr; string JsDebugger::s_packageName = ""; jclass JsDebugger::s_JsDebuggerClass = nullptr; jmethodID JsDebugger::s_EnqueueMessage = nullptr; jmethodID JsDebugger::s_EnableAgent = nullptr; <commit_msg>better console message event<commit_after>#include "JsDebugger.h" #include "V8GlobalHelpers.h" #include "JniLocalRef.h" #include "NativeScriptException.h" #include "NativeScriptAssert.h" #include <assert.h> #include <sstream> using namespace std; using namespace tns; using namespace v8; JsDebugger::JsDebugger() { } void JsDebugger::Init(v8::Isolate *isolate, const string& packageName, jobject jsDebugger) { s_isolate = isolate; s_packageName = packageName; JEnv env; s_jsDebugger = env.NewGlobalRef(jsDebugger); s_JsDebuggerClass = env.FindClass("com/tns/JsDebugger"); assert(s_JsDebuggerClass != nullptr); s_EnqueueMessage = env.GetMethodID(s_JsDebuggerClass, "enqueueMessage", "(Ljava/lang/String;)V"); assert(s_EnqueueMessage != nullptr); s_EnableAgent = env.GetMethodID(s_JsDebuggerClass, "enableAgent", "()V"); assert(s_EnableAgent != nullptr); } string JsDebugger::GetPackageName() { return s_packageName; } /* * * sets who will handle the messages when they start comming from v8 */ void JsDebugger::Enable() { auto isolate = s_isolate; v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handleScope(isolate); v8::Debug::SetMessageHandler(MyMessageHandler); enabled = true; } /* * * the message that come from v8 will not be handled anymore */ void JsDebugger::Disable() { enabled = false; auto isolate = s_isolate; v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handleScope(isolate); v8::Debug::SetMessageHandler(nullptr); } /* * * schedule a debugger break to happen when JavaScript code is run in the given isolate * (cli command: tns debug android --debug-brk) ? */ void JsDebugger::DebugBreak() { auto isolate = s_isolate; v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handleScope(isolate); v8::Debug::DebugBreak(isolate); } void JsDebugger::ProcessDebugMessages() { auto isolate = s_isolate; v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handleScope(isolate); v8::Debug::ProcessDebugMessages(); } void JsDebugger::SendCommand(JNIEnv *_env, jobject obj, jbyteArray command, jint length) { tns::JEnv env(_env); auto buf = new jbyte[length]; env.GetByteArrayRegion(command, 0, length, buf); int len = length / sizeof(uint16_t); SendCommandToV8(reinterpret_cast<uint16_t*>(buf), len); delete[] buf; } void JsDebugger::DebugBreakCallback(const v8::FunctionCallbackInfo<v8::Value>& args) { if (s_jsDebugger == nullptr) { return; } try { JEnv env; env.CallStaticVoidMethod(s_JsDebuggerClass, s_EnableAgent); DebugBreak(); } catch (NativeScriptException& e) { e.ReThrowToV8(); } catch (std::exception e) { stringstream ss; ss << "Error: c++ exception: " << e.what() << endl; NativeScriptException nsEx(ss.str()); nsEx.ReThrowToV8(); } catch (...) { NativeScriptException nsEx(std::string("Error: c++ exception!")); nsEx.ReThrowToV8(); } } void JsDebugger::ConsoleMessageCallback(const v8::FunctionCallbackInfo<v8::Value>& args) { if (s_jsDebugger == nullptr || !enabled) { return; } auto isolate = s_isolate; Isolate::Scope isolate_scope(isolate); HandleScope handleScope(isolate); if ((args.Length() > 0) && args[0]->IsString()) { std::string message = ConvertToString(args[0]->ToString()); //jboolean isError = (jboolean) = args[1]->ToBoolean()->BooleanValue(); std:string type = "log"; if (args.Length() > 1 && args[1]->IsString()) { type = ConvertToString(args[1]->ToString()); } string srcFileName = ""; int lineNumber = 0; int columnNumber = 0; auto stackTrace = StackTrace::CurrentStackTrace(Isolate::GetCurrent(), 2, StackTrace::kOverview); if (!stackTrace.IsEmpty()) { auto frame = stackTrace->GetFrame(1); if (!frame.IsEmpty()) { auto scriptName = frame->GetScriptName(); if (!scriptName.IsEmpty()) { srcFileName = ConvertToString(scriptName); } lineNumber = frame->GetLineNumber(); columnNumber = frame->GetColumn(); } } // var consoleEvent = { // "seq":0, // "type":"event", // "event":"messageAdded", // "success":true, // "body": // { // "message": // { // "source":"console-api", // "type": "log", // "level": '', // "line": 0, // "column": 0, // "url": "", // "groupLevel": 7, // "repeatCount": 1, // "text": "My message" // } // } // }; stringstream consoleEventSS; consoleEventSS << "{\"seq\":0, \"type\":\"event\", \"event\":\"messageAdded\", \"success\":true, \"body\": { \"message\": { \"source\":\"console-api\", " << " \"type\": \"" << type << "\", " << " \"level\": \"\", " << " \"line\": " << lineNumber << "," << " \"colum\": " << columnNumber << "," << " \"url\" : \"" << srcFileName << "\"," << " \"groupLevel\": 7, \"repeatCount\": 1, " << " \"text\": \"" << message << "\" } } }"; JEnv env; JniLocalRef s(env.NewStringUTF(consoleEventSS.str().c_str())); env.CallVoidMethod(s_jsDebugger, s_EnqueueMessage, (jstring) s); } } void JsDebugger::SendCommandToV8(uint16_t *cmd, int length) { auto isolate = s_isolate; v8::Debug::SendCommand(isolate, cmd, length, nullptr); } /* * * private method that takes debug message as json from v8 * after it gets the message the message handler passes it to enqueueMessage method in java */ void JsDebugger::MyMessageHandler(const v8::Debug::Message& message) { if (s_jsDebugger == nullptr) { return; } auto json = message.GetJSON(); auto str = ConvertToString(json); JEnv env; JniLocalRef s(env.NewStringUTF(str.c_str())); env.CallVoidMethod(s_jsDebugger, s_EnqueueMessage, (jstring) s); } bool JsDebugger::enabled = false; v8::Isolate* JsDebugger::s_isolate = nullptr; jobject JsDebugger::s_jsDebugger = nullptr; string JsDebugger::s_packageName = ""; jclass JsDebugger::s_JsDebuggerClass = nullptr; jmethodID JsDebugger::s_EnqueueMessage = nullptr; jmethodID JsDebugger::s_EnableAgent = nullptr; <|endoftext|>
<commit_before>#include <tiramisu/tiramisu.h> #define NN 1024 #define MM 1024 using namespace tiramisu; int main(int argc, char* argv[]) { tiramisu::init("edge_tiramisu"); var i("i", 0, NN-2), j("j", 0, MM-2), c("c", 0, 3); input Img("Img", {i, j, c}, p_uint8); // Layer I /* Ring blur filter. */ computation R("R", {c, j, i}, (Img(c, j, i) + Img(c, j+1, i) + Img(c, j+2, i)+ Img(c, j, i+1) + Img(c, j+2, i+1)+ Img(c, j, i+2) + Img(c, j+1, i+2) + Img(c, j+2, i+2))/((uint8_t) 8)); /* Robert's edge detection filter. */ computation Out("Out", {c, j, i}, (R(c, j+1, i+1)-R(c, j, i+2)) + (R(c, j+1, i+2)-R(c, j, i+1))); // Layer II Out.after(R, computation::root); // Layer III buffer b_Img("Img", {NN, MM, 3}, p_uint8, a_input); buffer b_R("R", {NN, MM, 3}, p_uint8, a_temporary); Img.store_in(&b_Img); R.store_in(&b_R); Out.store_in(&b_Img); tiramisu::codegen({&b_Img}, "build/generated_fct_edge.o"); return 0; } <commit_msg>Update edge<commit_after>#include <tiramisu/tiramisu.h> #define NN 1024 #define MM 1024 using namespace tiramisu; int main(int argc, char* argv[]) { tiramisu::init("edge_tiramisu"); var i("i", 0, NN-2), j("j", 0, MM-2), c("c", 0, 3); input Img("Img", {i, j, c}, p_uint8); // Layer I /* Ring blur filter. */ computation R("R", {c, j, i}, (Img(c, j, i) + Img(c, j+1, i) + Img(c, j+2, i)+ Img(c, j, i+1) + Img(c, j+2, i+1)+ Img(c, j, i+2) + Img(c, j+1, i+2) + Img(c, j+2, i+2))/((uint8_t) 8)); /* Robert's edge detection filter. */ computation Out("Out", {c, j, i}, (R(c, j+1, i+1)-R(c, j, i+2)) + (R(c, j+1, i+2)-R(c, j, i+1))); // Layer II R.parallelize(c); Out.parallelize(c); R.tile(j, i, 32, 32); Out.tile(j, i, 32, 32); Out.after(R, computation::root); // Layer III buffer b_Img("Img", {NN, MM, 3}, p_uint8, a_input); buffer b_R("R", {NN, MM, 3}, p_uint8, a_temporary); Img.store_in(&b_Img); R.store_in(&b_R); Out.store_in(&b_Img); tiramisu::codegen({&b_Img}, "build/generated_fct_edge.o"); return 0; } <|endoftext|>
<commit_before>#pragma once #include <pip/syntax.hpp> #include <functional> #include <unordered_set> namespace pip { // Kinds of declarations. enum decl_kind : int { dk_program, dk_table, dk_meter, }; // Kinds of matching strategies. enum rule_kind : int { rk_exact, rk_prefix, rk_wildcard, rk_range, rk_expr, }; /// The base class of all declarations. A declaration introduces a named /// entity. struct decl : cc::node { decl(decl_kind k, symbol* id) : cc::node(k, {}), id(id) { } void dump(); symbol* id; virtual ~decl() {} }; /// A dataplane program. A dataplane program is defined (primarily) by a /// list of match table and their associated actions. /// /// \todo How do we (or should we?) incorporate other kinds of declarations. /// For example, should we declare ports? Should we declare meters? Group /// actions? Do we need to process the list of declarations to find e.g., /// the entry table? struct program_decl : decl { program_decl(const decl_seq& ds) : decl(dk_program, nullptr), decls(ds) { } program_decl(decl_seq&& ds) : decl(dk_program, nullptr), decls(std::move(ds)) { } /// A list of declarations. decl_seq decls; }; /// Represents a match in a table. This is a key/value pair where the key /// is a literal expression, and the value is an action list expression. /// The rule kind of this object must match that of the table it /// appears in. struct rule : cc::node { rule(rule_kind k, expr* key, const action_seq& val) : cc::node(0, {}), kind(k), key(key), acts(val) { } rule(rule_kind k, expr* key, action_seq&& val) : cc::node(0, {}), kind(k), key(key), acts(std::move(val)) { } /// The kind of matching operation. rule_kind kind; /// The matched key -- a literal. expr* key; /// The list of actions to be executed. action_seq acts; }; /// A lookup table. Match tables are determined by a matching kind, which /// prescribes the how keys are found in the table. /// /// \todo Support general purpose tables, that can include arbitrary forms /// of matching (e.g., wildcard and exact). Note an exact match in a wildcard /// table is simply one with no don't-care bits. Maybe we don't need to /// generalize this so much. struct table_decl : decl { table_decl(symbol* id, rule_kind k, const action_seq& as, const rule_seq& ms) : decl(dk_table, id), rule(k), prep(as), rules(ms) { } table_decl(symbol* id, rule_kind k, action_seq&& as, rule_seq&& ms) : decl(dk_table, id), rule(k), prep(std::move(as)), rules(std::move(ms)) { } /// The kind of table. rule_kind rule; /// The sequence of actions used to form the key for lookup. action_seq prep; /// The content of the action table. rule_seq rules; /// A hash table to match keys for exact-match tables std::unordered_set<std::uint64_t, std::hash<std::uint64_t>> key_table; }; /// A flow metering device. /// /// \todo Implement this? struct meter_decl : decl { meter_decl(symbol* id) : decl(dk_meter, id) { } }; // -------------------------------------------------------------------------- // // Operations /// Returns the kind of a declaration. inline decl_kind get_kind(const decl* d) { return static_cast<decl_kind>(d->kind); } } // namespace pip // -------------------------------------------------------------------------- // // Casting namespace cc { template<> struct node_info<pip::program_decl> { static bool has_kind(const node* n) { return get_node_kind(n) == pip::dk_program; } }; template<> struct node_info<pip::table_decl> { static bool has_kind(const node* n) { return get_node_kind(n) == pip::dk_table; } }; template<> struct node_info<pip::meter_decl> { static bool has_kind(const node* n) { return get_node_kind(n) == pip::dk_meter; } }; } // namespace cc <commit_msg>Memory management for declarations.<commit_after>#pragma once #include <pip/syntax.hpp> #include <functional> #include <unordered_set> namespace pip { // Kinds of declarations. enum decl_kind : int { dk_program, dk_table, dk_meter, }; // Kinds of matching strategies. enum rule_kind : int { rk_exact, rk_prefix, rk_wildcard, rk_range, rk_expr, }; /// The base class of all declarations. A declaration introduces a named /// entity. struct decl : cc::node { decl(decl_kind k, symbol* id) : cc::node(k, {}), id(id) { } void dump(); symbol* id; virtual ~decl() {} }; /// A dataplane program. A dataplane program is defined (primarily) by a /// list of match table and their associated actions. /// /// \todo How do we (or should we?) incorporate other kinds of declarations. /// For example, should we declare ports? Should we declare meters? Group /// actions? Do we need to process the list of declarations to find e.g., /// the entry table? struct program_decl : decl { program_decl(const decl_seq& ds) : decl(dk_program, nullptr), decls(ds) { } program_decl(decl_seq&& ds) : decl(dk_program, nullptr), decls(std::move(ds)) { } ~program_decl() { for(auto d : decls) delete d; } /// A list of declarations. decl_seq decls; }; /// Represents a match in a table. This is a key/value pair where the key /// is a literal expression, and the value is an action list expression. /// The rule kind of this object must match that of the table it /// appears in. struct rule : cc::node { rule(rule_kind k, expr* key, const action_seq& val) : cc::node(0, {}), kind(k), key(key), acts(val) { } rule(rule_kind k, expr* key, action_seq&& val) : cc::node(0, {}), kind(k), key(key), acts(std::move(val)) { } /// The kind of matching operation. rule_kind kind; /// The matched key -- a literal. expr* key; /// The list of actions to be executed. action_seq acts; }; /// A lookup table. Match tables are determined by a matching kind, which /// prescribes the how keys are found in the table. /// /// \todo Support general purpose tables, that can include arbitrary forms /// of matching (e.g., wildcard and exact). Note an exact match in a wildcard /// table is simply one with no don't-care bits. Maybe we don't need to /// generalize this so much. struct table_decl : decl { table_decl(symbol* id, rule_kind k, const action_seq& as, const rule_seq& ms) : decl(dk_table, id), rule(k), prep(as), rules(ms) { } table_decl(symbol* id, rule_kind k, action_seq&& as, rule_seq&& ms) : decl(dk_table, id), rule(k), prep(std::move(as)), rules(std::move(ms)) { } ~table_decl() { for(auto r : rules) delete r; } /// The kind of table. rule_kind rule; /// The sequence of actions used to form the key for lookup. action_seq prep; /// The content of the action table. rule_seq rules; /// A hash table to match keys for exact-match tables std::unordered_set<std::uint64_t, std::hash<std::uint64_t>> key_table; }; /// A flow metering device. /// /// \todo Implement this? struct meter_decl : decl { meter_decl(symbol* id) : decl(dk_meter, id) { } }; // -------------------------------------------------------------------------- // // Operations /// Returns the kind of a declaration. inline decl_kind get_kind(const decl* d) { return static_cast<decl_kind>(d->kind); } } // namespace pip // -------------------------------------------------------------------------- // // Casting namespace cc { template<> struct node_info<pip::program_decl> { static bool has_kind(const node* n) { return get_node_kind(n) == pip::dk_program; } }; template<> struct node_info<pip::table_decl> { static bool has_kind(const node* n) { return get_node_kind(n) == pip::dk_table; } }; template<> struct node_info<pip::meter_decl> { static bool has_kind(const node* n) { return get_node_kind(n) == pip::dk_meter; } }; } // namespace cc <|endoftext|>
<commit_before>// Copyright (c) 2012-2013 The Bitcoin Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "util/system.h" #include "support/allocators/zeroafterfree.h" #include "test/test_pivx.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(allocator_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(arena_tests) { // Fake memory base address for testing // without actually using memory. void *synth_base = reinterpret_cast<void*>(0x08000000); const size_t synth_size = 1024*1024; Arena b(synth_base, synth_size, 16); void *chunk = b.alloc(1000); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(chunk != nullptr); BOOST_CHECK(b.stats().used == 1008); // Aligned to 16 BOOST_CHECK(b.stats().total == synth_size); // Nothing has disappeared? b.free(chunk); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(b.stats().used == 0); BOOST_CHECK(b.stats().free == synth_size); try { // Test exception on double-free b.free(chunk); BOOST_CHECK(0); } catch(std::runtime_error &) { } void *a0 = b.alloc(128); BOOST_CHECK(a0 == synth_base); // first allocation must start at beginning void *a1 = b.alloc(256); void *a2 = b.alloc(512); BOOST_CHECK(b.stats().used == 896); BOOST_CHECK(b.stats().total == synth_size); #ifdef ARENA_DEBUG b.walk(); #endif b.free(a0); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(b.stats().used == 768); b.free(a1); BOOST_CHECK(b.stats().used == 512); void *a3 = b.alloc(128); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(b.stats().used == 640); b.free(a2); BOOST_CHECK(b.stats().used == 128); b.free(a3); BOOST_CHECK(b.stats().used == 0); BOOST_CHECK(b.stats().total == synth_size); BOOST_CHECK(b.stats().free == synth_size); std::vector<void*> addr; BOOST_CHECK(b.alloc(0) == nullptr); // allocating 0 always returns nullptr #ifdef ARENA_DEBUG b.walk(); #endif // Sweeping allocate all memory for (int x=0; x<1024; ++x) addr.push_back(b.alloc(1024)); BOOST_CHECK(addr[0] == synth_base); // first allocation must start at beginning BOOST_CHECK(b.stats().free == 0); BOOST_CHECK(b.alloc(1024) == nullptr); // memory is full, this must return nullptr BOOST_CHECK(b.alloc(0) == nullptr); for (int x=0; x<1024; ++x) b.free(addr[x]); addr.clear(); BOOST_CHECK(b.stats().total == synth_size); BOOST_CHECK(b.stats().free == synth_size); // Now in the other direction... for (int x=0; x<1024; ++x) addr.push_back(b.alloc(1024)); for (int x=0; x<1024; ++x) b.free(addr[1023-x]); addr.clear(); // Now allocate in smaller unequal chunks, then deallocate haphazardly // Not all the chunks will succeed allocating, but freeing nullptr is // allowed so that is no problem. for (int x=0; x<2048; ++x) addr.push_back(b.alloc(x+1)); for (int x=0; x<2048; ++x) b.free(addr[((x*23)%2048)^242]); addr.clear(); // Go entirely wild: free and alloc interleaved, // generate targets and sizes using pseudo-randomness. for (int x=0; x<2048; ++x) addr.push_back(0); uint32_t s = 0x12345678; for (int x=0; x<5000; ++x) { int idx = s & (addr.size()-1); if (s & 0x80000000) { b.free(addr[idx]); addr[idx] = 0; } else if(!addr[idx]) { addr[idx] = b.alloc((s >> 16) & 2047); } bool lsb = s & 1; s >>= 1; if (lsb) s ^= 0xf00f00f0; // LFSR period 0xf7ffffe0 } for (void *ptr: addr) b.free(ptr); addr.clear(); BOOST_CHECK(b.stats().total == synth_size); BOOST_CHECK(b.stats().free == synth_size); } /** Mock LockedPageAllocator for testing */ class TestLockedPageAllocator: public LockedPageAllocator { public: TestLockedPageAllocator(int count_in, int lockedcount_in): count(count_in), lockedcount(lockedcount_in) {} void* AllocateLocked(size_t len, bool *lockingSuccess) { *lockingSuccess = false; if (count > 0) { --count; if (lockedcount > 0) { --lockedcount; *lockingSuccess = true; } return reinterpret_cast<void*>(0x08000000 + (count<<24)); // Fake address, do not actually use this memory } return 0; } void FreeLocked(void* addr, size_t len) { } size_t GetLimit() { return std::numeric_limits<size_t>::max(); } private: int count; int lockedcount; }; BOOST_AUTO_TEST_CASE(lockedpool_tests_mock) { // Test over three virtual arenas, of which one will succeed being locked std::unique_ptr<LockedPageAllocator> x(new TestLockedPageAllocator(3, 1)); LockedPool pool(std::move(x)); BOOST_CHECK(pool.stats().total == 0); BOOST_CHECK(pool.stats().locked == 0); void *a0 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a0); BOOST_CHECK(pool.stats().locked == LockedPool::ARENA_SIZE); void *a1 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a1); void *a2 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a2); void *a3 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a3); void *a4 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a4); void *a5 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a5); // We've passed a count of three arenas, so this allocation should fail void *a6 = pool.alloc(16); BOOST_CHECK(!a6); pool.free(a0); pool.free(a2); pool.free(a4); pool.free(a1); pool.free(a3); pool.free(a5); BOOST_CHECK(pool.stats().total == 3*LockedPool::ARENA_SIZE); BOOST_CHECK(pool.stats().locked == LockedPool::ARENA_SIZE); BOOST_CHECK(pool.stats().used == 0); } // These tests used the live LockedPoolManager object, this is also used // by other tests so the conditions are somewhat less controllable and thus the // tests are somewhat more error-prone. BOOST_AUTO_TEST_CASE(lockedpool_tests_live) { LockedPoolManager &pool = LockedPoolManager::Instance(); LockedPool::Stats initial = pool.stats(); void *a0 = pool.alloc(16); BOOST_CHECK(a0); // Test reading and writing the allocated memory *((uint32_t*)a0) = 0x1234; BOOST_CHECK(*((uint32_t*)a0) == 0x1234); pool.free(a0); try { // Test exception on double-free pool.free(a0); BOOST_CHECK(0); } catch(std::runtime_error &) { } // If more than one new arena was allocated for the above tests, something is wrong BOOST_CHECK(pool.stats().total <= (initial.total + LockedPool::ARENA_SIZE)); // Usage must be back to where it started BOOST_CHECK(pool.stats().used == initial.used); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>LockedPool: test handling of invalid allocations<commit_after>// Copyright (c) 2012-2013 The Bitcoin Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "util/system.h" #include "support/allocators/zeroafterfree.h" #include "test/test_pivx.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(allocator_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(arena_tests) { // Fake memory base address for testing // without actually using memory. void *synth_base = reinterpret_cast<void*>(0x08000000); const size_t synth_size = 1024*1024; Arena b(synth_base, synth_size, 16); void *chunk = b.alloc(1000); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(chunk != nullptr); BOOST_CHECK(b.stats().used == 1008); // Aligned to 16 BOOST_CHECK(b.stats().total == synth_size); // Nothing has disappeared? b.free(chunk); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(b.stats().used == 0); BOOST_CHECK(b.stats().free == synth_size); try { // Test exception on double-free b.free(chunk); BOOST_CHECK(0); } catch(std::runtime_error &) { } void *a0 = b.alloc(128); BOOST_CHECK(a0 == synth_base); // first allocation must start at beginning void *a1 = b.alloc(256); void *a2 = b.alloc(512); BOOST_CHECK(b.stats().used == 896); BOOST_CHECK(b.stats().total == synth_size); #ifdef ARENA_DEBUG b.walk(); #endif b.free(a0); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(b.stats().used == 768); b.free(a1); BOOST_CHECK(b.stats().used == 512); void *a3 = b.alloc(128); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(b.stats().used == 640); b.free(a2); BOOST_CHECK(b.stats().used == 128); b.free(a3); BOOST_CHECK(b.stats().used == 0); BOOST_CHECK(b.stats().total == synth_size); BOOST_CHECK(b.stats().free == synth_size); std::vector<void*> addr; BOOST_CHECK(b.alloc(0) == nullptr); // allocating 0 always returns nullptr #ifdef ARENA_DEBUG b.walk(); #endif // Sweeping allocate all memory for (int x=0; x<1024; ++x) addr.push_back(b.alloc(1024)); BOOST_CHECK(addr[0] == synth_base); // first allocation must start at beginning BOOST_CHECK(b.stats().free == 0); BOOST_CHECK(b.alloc(1024) == nullptr); // memory is full, this must return nullptr BOOST_CHECK(b.alloc(0) == nullptr); for (int x=0; x<1024; ++x) b.free(addr[x]); addr.clear(); BOOST_CHECK(b.stats().total == synth_size); BOOST_CHECK(b.stats().free == synth_size); // Now in the other direction... for (int x=0; x<1024; ++x) addr.push_back(b.alloc(1024)); for (int x=0; x<1024; ++x) b.free(addr[1023-x]); addr.clear(); // Now allocate in smaller unequal chunks, then deallocate haphazardly // Not all the chunks will succeed allocating, but freeing nullptr is // allowed so that is no problem. for (int x=0; x<2048; ++x) addr.push_back(b.alloc(x+1)); for (int x=0; x<2048; ++x) b.free(addr[((x*23)%2048)^242]); addr.clear(); // Go entirely wild: free and alloc interleaved, // generate targets and sizes using pseudo-randomness. for (int x=0; x<2048; ++x) addr.push_back(0); uint32_t s = 0x12345678; for (int x=0; x<5000; ++x) { int idx = s & (addr.size()-1); if (s & 0x80000000) { b.free(addr[idx]); addr[idx] = 0; } else if(!addr[idx]) { addr[idx] = b.alloc((s >> 16) & 2047); } bool lsb = s & 1; s >>= 1; if (lsb) s ^= 0xf00f00f0; // LFSR period 0xf7ffffe0 } for (void *ptr: addr) b.free(ptr); addr.clear(); BOOST_CHECK(b.stats().total == synth_size); BOOST_CHECK(b.stats().free == synth_size); } /** Mock LockedPageAllocator for testing */ class TestLockedPageAllocator: public LockedPageAllocator { public: TestLockedPageAllocator(int count_in, int lockedcount_in): count(count_in), lockedcount(lockedcount_in) {} void* AllocateLocked(size_t len, bool *lockingSuccess) { *lockingSuccess = false; if (count > 0) { --count; if (lockedcount > 0) { --lockedcount; *lockingSuccess = true; } return reinterpret_cast<void*>(0x08000000 + (count<<24)); // Fake address, do not actually use this memory } return 0; } void FreeLocked(void* addr, size_t len) { } size_t GetLimit() { return std::numeric_limits<size_t>::max(); } private: int count; int lockedcount; }; BOOST_AUTO_TEST_CASE(lockedpool_tests_mock) { // Test over three virtual arenas, of which one will succeed being locked std::unique_ptr<LockedPageAllocator> x(new TestLockedPageAllocator(3, 1)); LockedPool pool(std::move(x)); BOOST_CHECK(pool.stats().total == 0); BOOST_CHECK(pool.stats().locked == 0); // Ensure unreasonable requests are refused without allocating anything void *invalid_toosmall = pool.alloc(0); BOOST_CHECK(invalid_toosmall == nullptr); BOOST_CHECK(pool.stats().used == 0); BOOST_CHECK(pool.stats().free == 0); void *invalid_toobig = pool.alloc(LockedPool::ARENA_SIZE+1); BOOST_CHECK(invalid_toobig == nullptr); BOOST_CHECK(pool.stats().used == 0); BOOST_CHECK(pool.stats().free == 0); void *a0 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a0); BOOST_CHECK(pool.stats().locked == LockedPool::ARENA_SIZE); void *a1 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a1); void *a2 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a2); void *a3 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a3); void *a4 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a4); void *a5 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a5); // We've passed a count of three arenas, so this allocation should fail void *a6 = pool.alloc(16); BOOST_CHECK(!a6); pool.free(a0); pool.free(a2); pool.free(a4); pool.free(a1); pool.free(a3); pool.free(a5); BOOST_CHECK(pool.stats().total == 3*LockedPool::ARENA_SIZE); BOOST_CHECK(pool.stats().locked == LockedPool::ARENA_SIZE); BOOST_CHECK(pool.stats().used == 0); } // These tests used the live LockedPoolManager object, this is also used // by other tests so the conditions are somewhat less controllable and thus the // tests are somewhat more error-prone. BOOST_AUTO_TEST_CASE(lockedpool_tests_live) { LockedPoolManager &pool = LockedPoolManager::Instance(); LockedPool::Stats initial = pool.stats(); void *a0 = pool.alloc(16); BOOST_CHECK(a0); // Test reading and writing the allocated memory *((uint32_t*)a0) = 0x1234; BOOST_CHECK(*((uint32_t*)a0) == 0x1234); pool.free(a0); try { // Test exception on double-free pool.free(a0); BOOST_CHECK(0); } catch(std::runtime_error &) { } // If more than one new arena was allocated for the above tests, something is wrong BOOST_CHECK(pool.stats().total <= (initial.total + LockedPool::ARENA_SIZE)); // Usage must be back to where it started BOOST_CHECK(pool.stats().used == initial.used); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>f4b18ade-2e4e-11e5-961b-28cfe91dbc4b<commit_msg>f4be214a-2e4e-11e5-8ae9-28cfe91dbc4b<commit_after>f4be214a-2e4e-11e5-8ae9-28cfe91dbc4b<|endoftext|>
<commit_before>5e589466-2d16-11e5-af21-0401358ea401<commit_msg>5e589467-2d16-11e5-af21-0401358ea401<commit_after>5e589467-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>10966be6-2748-11e6-8f38-e0f84713e7b8<commit_msg>ashley broke it<commit_after>10a6c2ca-2748-11e6-9c7b-e0f84713e7b8<|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "Lex.h" #include "CmdInputFactor.h" #include "GrammarAnalyzer.h" #include "JZLogger.h" //basic function declaration TEST(GrammarAnalyzer, FunctionBasic0) { int argc = 2; char argv0[128] = {0},argv1[128] = {0}; strcpy(argv0,"tester"); strcpy(argv1,"./test/GrammarSample/function_sample_0"); char* argv[2] = {argv0,argv1}; //analyze command line input CmdInputFactor::getInstance()->analyze(argc, argv); //now begin to analyze the files input from command line string toCompileFile = CmdInputFactor::getInstance()->getNextFile(); Lex lex; lex.analyzeAFile(toCompileFile); LexRecList recList = lex.getRecList(); GrammarAnalyzer grammar = GrammarAnalyzer(recList); // JZSetLoggerLevel(JZ_LOG_DEBUG|JZ_LOG_TRACE); uint32 ret = grammar.doAnalyze(); JZSetLoggerLevel(JZ_LOG_TEST); ASSERT_EQ(eGrmErrNoError, ret); JZSetLoggerLevel(JZ_LOG_TEST); } //basic function ptr declaration TEST(GrammarAnalyzer, FunctionBasic1) { int argc = 2; char argv0[128] = {0},argv1[128] = {0}; strcpy(argv0,"tester"); strcpy(argv1,"./test/GrammarSample/function_sample_1"); char* argv[2] = {argv0,argv1}; //analyze command line input CmdInputFactor::getInstance()->analyze(argc, argv); //now begin to analyze the files input from command line string toCompileFile = CmdInputFactor::getInstance()->getNextFile(); Lex lex; lex.analyzeAFile(toCompileFile); LexRecList recList = lex.getRecList(); GrammarAnalyzer grammar = GrammarAnalyzer(recList); JZSetLoggerLevel(JZ_LOG_DEBUG|JZ_LOG_TRACE); uint32 ret = grammar.doAnalyze(); JZSetLoggerLevel(JZ_LOG_TEST); ASSERT_EQ(eGrmErrNoError, ret); } <commit_msg>turn off debug<commit_after>#include <gtest/gtest.h> #include "Lex.h" #include "CmdInputFactor.h" #include "GrammarAnalyzer.h" #include "JZLogger.h" //basic function declaration TEST(GrammarAnalyzer, FunctionBasic0) { int argc = 2; char argv0[128] = {0},argv1[128] = {0}; strcpy(argv0,"tester"); strcpy(argv1,"./test/GrammarSample/function_sample_0"); char* argv[2] = {argv0,argv1}; //analyze command line input CmdInputFactor::getInstance()->analyze(argc, argv); //now begin to analyze the files input from command line string toCompileFile = CmdInputFactor::getInstance()->getNextFile(); Lex lex; lex.analyzeAFile(toCompileFile); LexRecList recList = lex.getRecList(); GrammarAnalyzer grammar = GrammarAnalyzer(recList); // JZSetLoggerLevel(JZ_LOG_DEBUG|JZ_LOG_TRACE); uint32 ret = grammar.doAnalyze(); JZSetLoggerLevel(JZ_LOG_TEST); ASSERT_EQ(eGrmErrNoError, ret); JZSetLoggerLevel(JZ_LOG_TEST); } //basic function ptr declaration TEST(GrammarAnalyzer, FunctionBasic1) { int argc = 2; char argv0[128] = {0},argv1[128] = {0}; strcpy(argv0,"tester"); strcpy(argv1,"./test/GrammarSample/function_sample_1"); char* argv[2] = {argv0,argv1}; //analyze command line input CmdInputFactor::getInstance()->analyze(argc, argv); //now begin to analyze the files input from command line string toCompileFile = CmdInputFactor::getInstance()->getNextFile(); Lex lex; lex.analyzeAFile(toCompileFile); LexRecList recList = lex.getRecList(); GrammarAnalyzer grammar = GrammarAnalyzer(recList); JZSetLoggerLevel(JZ_LOG_TRACE); uint32 ret = grammar.doAnalyze(); JZSetLoggerLevel(JZ_LOG_TEST); ASSERT_EQ(eGrmErrNoError, ret); } <|endoftext|>
<commit_before>#include "dock.h" #include "mainwindow.h" #include "connection.h" #include "dockmanagerconfig.h" #include "dockdelegates.h" #include "controlbar_dockmanager.h" #include "serialize.h" #include <ui_controlbarcommon.h> #include <QScrollBar> /*#include <ui_controlbarlogs.h> #include <ui_controlbarplots.h> #include <ui_controlbartables.h> #include <ui_controlbargantts.h>*/ DockManager::DockManager (MainWindow * mw, QStringList const & path) : DockManagerView(mw), ActionAble(path) , m_main_window(mw) , m_dockwidget(0) , m_control_bar(0) , m_model(0) , m_config(g_traceServerName) { qDebug("%s", __FUNCTION__); resizeColumnToContents(0); QString const name = path.join("/"); DockWidget * const dock = new DockWidget(*this, name, m_main_window); dock->setObjectName(name); dock->setWindowTitle(name); dock->setAllowedAreas(Qt::AllDockWidgetAreas); m_main_window->addDockWidget(Qt::BottomDockWidgetArea, dock); dock->setAttribute(Qt::WA_DeleteOnClose, false); dock->setWidget(this); //if (visible) // m_main_window->restoreDockWidget(dock); m_dockwidget = dock; connect(m_dockwidget, SIGNAL(widgetVisibilityChanged(bool)), m_main_window, SLOT(onDockManagerVisibilityChanged(bool))); m_control_bar = new ControlBarCommon(); connect(header(), SIGNAL(sectionResized(int, int, int)), this, SLOT(onColumnResized(int, int, int))); connect(m_dockwidget, SIGNAL(dockClosed()), mw, SLOT(onDockManagerClosed())); setAllColumnsShowFocus(false); setExpandsOnDoubleClick(false); //setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); //setSizeAdjustPolicy(QAbstractScrollArea::AdjustIgnored); //header()->setSectionResizeMode(0, QHeaderView::Interactive); header()->setStretchLastSection(false); setEditTriggers(QAbstractItemView::NoEditTriggers); //setItemDelegateForColumn(e_Column_Close, new CloseButtonDelegate(*this, this)); setItemDelegateForColumn(e_Column_Close, new CloseButtonDelegate(*this, this)); setItemDelegateForColumn(e_Column_ControlWidget, new ControlWidgetDelegate(*this, this)); setStyleSheet("QTreeView::item{ selection-background-color: #FFE7BA } QTreeView::item{ selection-color: #000000 }"); //horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { border: 1px solid grey; height: 15px; } QScrollBar::handle:horizontal { background: white; min-width: 10px; }"); /* setStyleSheet(QString::fromUtf8("QScrollBar:vertical { " border: 1px solid #999999;" " background:white;" " width:10px; " " margin: 0px 0px 0px 0px;" "}" "QScrollBar::handle:vertical {" " background: qlineargradient(x1:0, y1:0, x2:1, y2:0," " stop: 0 rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130), stop:1 rgb(32, 47, 130));" " min-height: 0px;" "" "}" "QScrollBar::add-line:vertical {" " background: qlineargradient(x1:0, y1:0, x2:1, y2:0," " stop: 0 rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130), stop:1 rgb(32, 47, 130));" " height: px;" " subcontrol-position: bottom;" " subcontrol-origin: margin;" "}" "QScrollBar::sub-line:vertical {" " background: qlineargradient(x1:0, y1:0, x2:1, y2:0," " stop: 0 rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130), stop:1 rgb(32, 47, 130));" " height: 0px;" " subcontrol-position: top;" " subcontrol-origin: margin;" "}" "")); */ } void DockManager::loadConfig (QString const & cfgpath) { QString const fname = cfgpath + "/" + g_dockManagerTag; DockManagerConfig config2(g_traceServerName); if (!::loadConfigTemplate(config2, fname)) { m_config.defaultConfig(); } else { m_config = config2; config2.m_data.root = 0; // @TODO: promyslet.. takle na to urcite zapomenu } m_model = new DockManagerModel(*this, this, &m_config.m_data); setModel(m_model); connect(this, SIGNAL(removeCurrentIndex(QModelIndex const &)), this, SLOT(onRemoveCurrentIndex(QModelIndex const &))); bool const on = true; addActionAble(*this, on, false, true); } void DockManager::applyConfig () { for (size_t i = 0, ie = m_config.m_columns_sizes.size(); i < ie; ++i) header()->resizeSection(static_cast<int>(i), m_config.m_columns_sizes[i]); if (m_model) m_model->syncExpandState(this); } void DockManager::saveConfig (QString const & path) { QString const fname = path + "/" + g_dockManagerTag; ::saveConfigTemplate(m_config, fname); } DockManager::~DockManager () { disconnect(m_dockwidget, SIGNAL(dockClosed()), m_main_window, SLOT(onDockManagerClosed())); disconnect(this, SIGNAL(removeCurrentIndex(QModelIndex const &)), this, SLOT(onRemoveCurrentIndex(QModelIndex const &))); disconnect(m_dockwidget, SIGNAL(widgetVisibilityChanged(bool)), m_main_window, SLOT(onDockManagerVisibilityChanged(bool))); disconnect(header(), SIGNAL(sectionResized(int, int, int)), this, SLOT(onColumnResized(int, int, int))); setParent(0); m_dockwidget->setWidget(0); delete m_dockwidget; m_dockwidget= 0; removeActionAble(*this); } DockWidget * DockManager::mkDockWidget (DockedWidgetBase & dwb, bool visible) { return mkDockWidget(dwb, visible, Qt::BottomDockWidgetArea); } DockWidget * DockManager::mkDockWidget (ActionAble & aa, bool visible, Qt::DockWidgetArea area) { qDebug("%s", __FUNCTION__); Q_ASSERT(aa.path().size() > 0); QString const name = aa.path().join("/"); DockWidget * const dock = new DockWidget(*this, name, m_main_window); dock->setObjectName(name); dock->setWindowTitle(name); dock->setAllowedAreas(Qt::AllDockWidgetAreas); //dock->setWidget(docked_widget); // @NOTE: commented, it is set by caller m_main_window->addDockWidget(area, dock); dock->setAttribute(Qt::WA_DeleteOnClose, false); if (visible) m_main_window->restoreDockWidget(dock); return dock; } void DockManager::onWidgetClosed (DockWidget * w) { qDebug("%s w=%08x", __FUNCTION__, w); } QModelIndex DockManager::addActionAble (ActionAble & aa, bool on, bool close_button, bool control_widget) { qDebug("%s aa=%s show=%i", __FUNCTION__, aa.joinedPath().toStdString().c_str(), on); QModelIndex const idx = m_model->insertItemWithPath(aa.path(), on); QString const & name = aa.joinedPath(); m_actionables.insert(name, &aa); m_model->initData(idx, QVariant(on ? Qt::Checked : Qt::Unchecked), Qt::CheckStateRole); if (close_button) { QModelIndex const jdx = m_model->index(idx.row(), e_Column_Close, idx.parent()); openPersistentEditor(jdx); } if (control_widget) { QModelIndex const kdx = m_model->index(idx.row(), e_Column_ControlWidget, idx.parent()); openPersistentEditor(kdx); } return idx; } QModelIndex DockManager::addActionAble (ActionAble & aa, bool on) { return addActionAble(aa, on, true, true); } ActionAble const * DockManager::findActionAble (QString const & dst_joined) const { actionables_t::const_iterator it = m_actionables.find(dst_joined); if (it != m_actionables.end() && it.key() == dst_joined) return *it; return 0; } ActionAble * DockManager::findActionAble (QString const & dst_joined) { actionables_t::iterator it = m_actionables.find(dst_joined); if (it != m_actionables.end() && it.key() == dst_joined) return *it; return 0; } void DockManager::removeActionAble (ActionAble & aa) { qDebug("%s aa=%s", __FUNCTION__, aa.joinedPath().toStdString().c_str()); actionables_t::iterator it = m_actionables.find(aa.joinedPath()); if (it != m_actionables.end() && it.key() == aa.joinedPath()) { QModelIndex const idx = m_model->testItemWithPath(aa.path()); if (idx.isValid()) for (int j = 1; j < e_max_dockmgr_column; ++j) closePersistentEditor(m_model->index(idx.row(), j, idx.parent())); m_actionables.erase(it); } } void DockManager::onColumnResized (int idx, int , int new_size) { if (idx < 0) return; size_t const curr_sz = m_config.m_columns_sizes.size(); if (idx < curr_sz) { //qDebug("%s this=0x%08x hsize[%i]=%i", __FUNCTION__, this, idx, new_size); } else { m_config.m_columns_sizes.resize(idx + 1); for (size_t i = curr_sz; i < idx + 1; ++i) m_config.m_columns_sizes[i] = 32; } m_config.m_columns_sizes[idx] = new_size; } bool DockManager::handleAction (Action * a, E_ActionHandleType sync) { QStringList const & src_path = a->m_src_path; QStringList const & dst_path = a->m_dst_path; QStringList const & my_addr = path(); if (dst_path.size() == 0) { qWarning("DockManager::handleAction empty dst"); return false; } Q_ASSERT(my_addr.size() == 1); int const lvl = dst_path.indexOf(my_addr.at(0), a->m_dst_curr_level); if (lvl == -1) { qWarning("DockManager::handleAction message not for me"); return false; } else if (lvl == dst_path.size() - 1) { // message just for me! gr8! a->m_dst_curr_level = lvl; a->m_dst = this; return true; } else { // message for my children a->m_dst_curr_level = lvl + 1; if (a->m_dst_curr_level >= 0 && a->m_dst_curr_level < dst_path.size()) { QString const dst_joined = dst_path.join("/"); actionables_t::iterator it = m_actionables.find(dst_joined); if (it != m_actionables.end() && it.key() == dst_joined) { qDebug("delivering action to: %s", dst_joined.toStdString().c_str()); ActionAble * const next_hop = it.value(); next_hop->handleAction(a, sync); //@NOTE: e_Close can invalidate iterator } else { //@TODO: find least common subpath } } else { qWarning("DockManager::handleAction hmm? what?"); } } return false; } void DockManager::onCloseButton () { QVariant v = QObject::sender()->property("idx"); if (v.canConvert<QModelIndex>()) { QModelIndex const idx = v.value<QModelIndex>(); if (TreeModel<DockedInfo>::node_t * const n = m_model->getItemFromIndex(idx)) { QStringList const & dst_path = n->data.m_path; Action a; a.m_type = e_Close; a.m_src_path = path(); a.m_src = this; a.m_dst_path = dst_path; handleAction(&a, e_Sync); } } } void DockManager::onRemoveCurrentIndex (QModelIndex const & idx) { //model()->removeRows(idx.row(), 1, idx.parent()); } <commit_msg>* control widget init dock area<commit_after>#include "dock.h" #include "mainwindow.h" #include "connection.h" #include "dockmanagerconfig.h" #include "dockdelegates.h" #include "controlbar_dockmanager.h" #include "serialize.h" #include <ui_controlbarcommon.h> #include <QScrollBar> /*#include <ui_controlbarlogs.h> #include <ui_controlbarplots.h> #include <ui_controlbartables.h> #include <ui_controlbargantts.h>*/ DockManager::DockManager (MainWindow * mw, QStringList const & path) : DockManagerView(mw), ActionAble(path) , m_main_window(mw) , m_dockwidget(0) , m_control_bar(0) , m_model(0) , m_config(g_traceServerName) { qDebug("%s", __FUNCTION__); resizeColumnToContents(0); QString const name = path.join("/"); DockWidget * const dock = new DockWidget(*this, name, m_main_window); dock->setObjectName(name); dock->setWindowTitle(name); dock->setAllowedAreas(Qt::AllDockWidgetAreas); m_main_window->addDockWidget(Qt::TopDockWidgetArea, dock); dock->setAttribute(Qt::WA_DeleteOnClose, false); dock->setWidget(this); //if (visible) // m_main_window->restoreDockWidget(dock); m_dockwidget = dock; connect(m_dockwidget, SIGNAL(widgetVisibilityChanged(bool)), m_main_window, SLOT(onDockManagerVisibilityChanged(bool))); m_control_bar = new ControlBarCommon(); connect(header(), SIGNAL(sectionResized(int, int, int)), this, SLOT(onColumnResized(int, int, int))); connect(m_dockwidget, SIGNAL(dockClosed()), mw, SLOT(onDockManagerClosed())); setAllColumnsShowFocus(false); setExpandsOnDoubleClick(false); //setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); //setSizeAdjustPolicy(QAbstractScrollArea::AdjustIgnored); //header()->setSectionResizeMode(0, QHeaderView::Interactive); header()->setStretchLastSection(false); setEditTriggers(QAbstractItemView::NoEditTriggers); //setItemDelegateForColumn(e_Column_Close, new CloseButtonDelegate(*this, this)); setItemDelegateForColumn(e_Column_Close, new CloseButtonDelegate(*this, this)); setItemDelegateForColumn(e_Column_ControlWidget, new ControlWidgetDelegate(*this, this)); setStyleSheet("QTreeView::item{ selection-background-color: #FFE7BA } QTreeView::item{ selection-color: #000000 }"); //horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { border: 1px solid grey; height: 15px; } QScrollBar::handle:horizontal { background: white; min-width: 10px; }"); /* setStyleSheet(QString::fromUtf8("QScrollBar:vertical { " border: 1px solid #999999;" " background:white;" " width:10px; " " margin: 0px 0px 0px 0px;" "}" "QScrollBar::handle:vertical {" " background: qlineargradient(x1:0, y1:0, x2:1, y2:0," " stop: 0 rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130), stop:1 rgb(32, 47, 130));" " min-height: 0px;" "" "}" "QScrollBar::add-line:vertical {" " background: qlineargradient(x1:0, y1:0, x2:1, y2:0," " stop: 0 rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130), stop:1 rgb(32, 47, 130));" " height: px;" " subcontrol-position: bottom;" " subcontrol-origin: margin;" "}" "QScrollBar::sub-line:vertical {" " background: qlineargradient(x1:0, y1:0, x2:1, y2:0," " stop: 0 rgb(32, 47, 130), stop: 0.5 rgb(32, 47, 130), stop:1 rgb(32, 47, 130));" " height: 0px;" " subcontrol-position: top;" " subcontrol-origin: margin;" "}" "")); */ } void DockManager::loadConfig (QString const & cfgpath) { QString const fname = cfgpath + "/" + g_dockManagerTag; DockManagerConfig config2(g_traceServerName); if (!::loadConfigTemplate(config2, fname)) { m_config.defaultConfig(); } else { m_config = config2; config2.m_data.root = 0; // @TODO: promyslet.. takle na to urcite zapomenu } m_model = new DockManagerModel(*this, this, &m_config.m_data); setModel(m_model); connect(this, SIGNAL(removeCurrentIndex(QModelIndex const &)), this, SLOT(onRemoveCurrentIndex(QModelIndex const &))); bool const on = true; addActionAble(*this, on, false, true); } void DockManager::applyConfig () { for (size_t i = 0, ie = m_config.m_columns_sizes.size(); i < ie; ++i) header()->resizeSection(static_cast<int>(i), m_config.m_columns_sizes[i]); if (m_model) m_model->syncExpandState(this); } void DockManager::saveConfig (QString const & path) { QString const fname = path + "/" + g_dockManagerTag; ::saveConfigTemplate(m_config, fname); } DockManager::~DockManager () { disconnect(m_dockwidget, SIGNAL(dockClosed()), m_main_window, SLOT(onDockManagerClosed())); disconnect(this, SIGNAL(removeCurrentIndex(QModelIndex const &)), this, SLOT(onRemoveCurrentIndex(QModelIndex const &))); disconnect(m_dockwidget, SIGNAL(widgetVisibilityChanged(bool)), m_main_window, SLOT(onDockManagerVisibilityChanged(bool))); disconnect(header(), SIGNAL(sectionResized(int, int, int)), this, SLOT(onColumnResized(int, int, int))); setParent(0); m_dockwidget->setWidget(0); delete m_dockwidget; m_dockwidget= 0; removeActionAble(*this); } DockWidget * DockManager::mkDockWidget (DockedWidgetBase & dwb, bool visible) { return mkDockWidget(dwb, visible, Qt::BottomDockWidgetArea); } DockWidget * DockManager::mkDockWidget (ActionAble & aa, bool visible, Qt::DockWidgetArea area) { qDebug("%s", __FUNCTION__); Q_ASSERT(aa.path().size() > 0); QString const name = aa.path().join("/"); DockWidget * const dock = new DockWidget(*this, name, m_main_window); dock->setObjectName(name); dock->setWindowTitle(name); dock->setAllowedAreas(Qt::AllDockWidgetAreas); //dock->setWidget(docked_widget); // @NOTE: commented, it is set by caller m_main_window->addDockWidget(area, dock); dock->setAttribute(Qt::WA_DeleteOnClose, false); if (visible) m_main_window->restoreDockWidget(dock); return dock; } void DockManager::onWidgetClosed (DockWidget * w) { qDebug("%s w=%08x", __FUNCTION__, w); } QModelIndex DockManager::addActionAble (ActionAble & aa, bool on, bool close_button, bool control_widget) { qDebug("%s aa=%s show=%i", __FUNCTION__, aa.joinedPath().toStdString().c_str(), on); QModelIndex const idx = m_model->insertItemWithPath(aa.path(), on); QString const & name = aa.joinedPath(); m_actionables.insert(name, &aa); m_model->initData(idx, QVariant(on ? Qt::Checked : Qt::Unchecked), Qt::CheckStateRole); if (close_button) { QModelIndex const jdx = m_model->index(idx.row(), e_Column_Close, idx.parent()); openPersistentEditor(jdx); } if (control_widget) { QModelIndex const kdx = m_model->index(idx.row(), e_Column_ControlWidget, idx.parent()); openPersistentEditor(kdx); } return idx; } QModelIndex DockManager::addActionAble (ActionAble & aa, bool on) { return addActionAble(aa, on, true, true); } ActionAble const * DockManager::findActionAble (QString const & dst_joined) const { actionables_t::const_iterator it = m_actionables.find(dst_joined); if (it != m_actionables.end() && it.key() == dst_joined) return *it; return 0; } ActionAble * DockManager::findActionAble (QString const & dst_joined) { actionables_t::iterator it = m_actionables.find(dst_joined); if (it != m_actionables.end() && it.key() == dst_joined) return *it; return 0; } void DockManager::removeActionAble (ActionAble & aa) { qDebug("%s aa=%s", __FUNCTION__, aa.joinedPath().toStdString().c_str()); actionables_t::iterator it = m_actionables.find(aa.joinedPath()); if (it != m_actionables.end() && it.key() == aa.joinedPath()) { QModelIndex const idx = m_model->testItemWithPath(aa.path()); if (idx.isValid()) for (int j = 1; j < e_max_dockmgr_column; ++j) closePersistentEditor(m_model->index(idx.row(), j, idx.parent())); m_actionables.erase(it); } } void DockManager::onColumnResized (int idx, int , int new_size) { if (idx < 0) return; size_t const curr_sz = m_config.m_columns_sizes.size(); if (idx < curr_sz) { //qDebug("%s this=0x%08x hsize[%i]=%i", __FUNCTION__, this, idx, new_size); } else { m_config.m_columns_sizes.resize(idx + 1); for (size_t i = curr_sz; i < idx + 1; ++i) m_config.m_columns_sizes[i] = 32; } m_config.m_columns_sizes[idx] = new_size; } bool DockManager::handleAction (Action * a, E_ActionHandleType sync) { QStringList const & src_path = a->m_src_path; QStringList const & dst_path = a->m_dst_path; QStringList const & my_addr = path(); if (dst_path.size() == 0) { qWarning("DockManager::handleAction empty dst"); return false; } Q_ASSERT(my_addr.size() == 1); int const lvl = dst_path.indexOf(my_addr.at(0), a->m_dst_curr_level); if (lvl == -1) { qWarning("DockManager::handleAction message not for me"); return false; } else if (lvl == dst_path.size() - 1) { // message just for me! gr8! a->m_dst_curr_level = lvl; a->m_dst = this; return true; } else { // message for my children a->m_dst_curr_level = lvl + 1; if (a->m_dst_curr_level >= 0 && a->m_dst_curr_level < dst_path.size()) { QString const dst_joined = dst_path.join("/"); actionables_t::iterator it = m_actionables.find(dst_joined); if (it != m_actionables.end() && it.key() == dst_joined) { qDebug("delivering action to: %s", dst_joined.toStdString().c_str()); ActionAble * const next_hop = it.value(); next_hop->handleAction(a, sync); //@NOTE: e_Close can invalidate iterator } else { //@TODO: find least common subpath } } else { qWarning("DockManager::handleAction hmm? what?"); } } return false; } void DockManager::onCloseButton () { QVariant v = QObject::sender()->property("idx"); if (v.canConvert<QModelIndex>()) { QModelIndex const idx = v.value<QModelIndex>(); if (TreeModel<DockedInfo>::node_t * const n = m_model->getItemFromIndex(idx)) { QStringList const & dst_path = n->data.m_path; Action a; a.m_type = e_Close; a.m_src_path = path(); a.m_src = this; a.m_dst_path = dst_path; handleAction(&a, e_Sync); } } } void DockManager::onRemoveCurrentIndex (QModelIndex const & idx) { //model()->removeRows(idx.row(), 1, idx.parent()); } <|endoftext|>
<commit_before>#include <cmath> #include <unistd.h> #include <iostream> #include <sstream> #define NX 50 #define NY 50 #define NZ 50 #define SX 34 #define SY 34 #define SZ 34 #define T_MAX 8000 typedef double Real; const Real Fu = 1.0/86400, Fv = 6.0/86400, Fe = 1.0/900, Du = 0.1*2.3e-9, Dv = 12.2e-11; const Real dt = 0*200, dx = 0.001; Real U[NX][NY][NZ], V[NX][NY][NZ]; Real U_other[NX][NY][NZ], V_other[NX][NY][NZ]; int global_clock; Real Uwx[T_MAX][2][SY][SZ], Uwy[T_MAX][SX][2][SZ], Uwz[T_MAX][SX][SY][2]; Real Vwx[T_MAX][2][SY][SZ], Vwy[T_MAX][SX][2][SZ], Vwz[T_MAX][SX][SY][2]; Real sU0[SX][SY][SZ], sV0[SX][SY][SZ]; Real sU[SX][SY][SZ], sV[SX][SY][SZ]; void fill_initial_condition() { global_clock=0; for (int x=0;x<NX;++x) { for (int y=0;y<NY;++y) { for (int z=0;z<NZ;++z) { U[x][y][z] = 1; V[x][y][z] = 0; } } } int bx = std::max(NX/4,NX/2-8), ex = std::min(3*NX/4+1,NX/2+8); int by = std::max(NY/4,NY/2-8), ey = std::min(3*NY/4+1,NY/2+8); int bz = std::max(NZ/4,NZ/2-8), ez = std::min(3*NZ/4+1,NZ/2+8); for (int x=bx;x<ex;++x){ for (int y=by;y<ey;++y){ for (int z=bz;z<ez;++z){ U[x][y][z] = 0.5; V[x][y][z] = 0.25+0.1*sin(x+sqrt(y)+cos(z)); } } } } inline Real periodic(Real ar[NX][NY][NZ],int x, int y, int z) { x = ((x+100*NX)%NX+NX)%NX; y = ((y+100*NY)%NY+NY)%NY; z = ((z+100*NZ)%NZ+NZ)%NZ; //x = (x+NX)%NX; //y = (y+NY)%NY; //z = (z+NZ)%NZ; return ar[x][y][z]; } void naive_proceed() { ++global_clock; auto lap = [](Real ar[NX][NY][NZ],int x, int y, int z) { auto ret = periodic(ar, x-1, y, z) + periodic(ar, x+1, y, z) + periodic(ar, x, y-1, z) + periodic(ar, x, y+1, z) + periodic(ar, x, y, z-1) + periodic(ar, x, y, z+1) - 6*ar[x][y][z]; return ret / dx / dx; }; #pragma omp parallel for collapse(2) for (int x=0;x<NX;++x) { for (int y=0;y<NY;++y) { for (int z=0;z<NZ;++z) { auto u = U[x][y][z], v = V[x][y][z]; auto du_dt = -Fe * u*v*v + Fu*(1-u) + Du * lap(U,x,y,z); auto dv_dt = Fe * u*v*v - Fv*v + Dv * lap(V,x,y,z); U_other[x][y][z] = U[x][y][z] + dt*du_dt; V_other[x][y][z] = V[x][y][z] + dt*dv_dt; } } } for (int x=0;x<NX;++x) { for (int y=0;y<NY;++y) { for (int z=0;z<NZ;++z) { U[x][y][z]=U_other[x][y][z]; } } } for (int x=0;x<NX;++x) { for (int y=0;y<NY;++y) { for (int z=0;z<NZ;++z) { V[x][y][z]=V_other[x][y][z]; } } } } void get_solution_at(int t, int x, int y, int z, Real &u, Real &v) { if(global_clock > t) fill_initial_condition(); while(global_clock < t) naive_proceed(); u = periodic(U,x,y,z); v = periodic(V,x,y,z); } int main () { fill_initial_condition(); for(int x=0;x<SX;++x) { for(int y=0;y<SY;++y) { for(int z=0;z<SZ;++z) { double u,v; get_solution_at(0,x,y,z, u,v); sU0[x][y][z]=u; sV0[x][y][z]=v; } } } std::cerr << "Setting up wall values..." << std::endl; for(int t = 0;t<T_MAX;++t){ for(int x=SX-2;x<SX;++x) { for(int y=0;y<SY;++y) { for(int z=0;z<SZ;++z) { double u,v; get_solution_at(t,x+t,y+t,z+t, u,v); Uwx[t][x-(SX-2)][y][z] = u; Vwx[t][x-(SX-2)][y][z] = v; } } } for(int x=0;x<SX;++x) { for(int y=SY-2;y<SY;++y) { for(int z=0;z<SZ;++z) { double u,v; get_solution_at(t,x+t,y+t,z+t, u,v); Uwy[t][x][y-(SY-2)][z] = u; Vwy[t][x][y-(SY-2)][z] = v; } } } for(int x=0;x<SX;++x) { for(int y=0;y<SY;++y) { for(int z=SZ-2;z<SZ;++z) { double u,v; get_solution_at(t,x+t,y+t,z+t, u,v); Uwz[t][x][y][z-(SZ-2)] = u; Vwz[t][x][y][z-(SZ-2)] = v; } } } } std::cerr << "Carrying out simulation..." << std::endl; // set initial condition for(int x=0;x<SX;++x) { for(int y=0;y<SY;++y) { for(int z=0;z<SZ;++z) { sU[x][y][z]=sU0[x][y][z]; sV[x][y][z]=sV0[x][y][z]; } } } for(int t = 0; t < T_MAX; ++t){ // load communication values #pragma omp parallel for collapse(3) for(int x=SX-2;x<SX;++x) { for(int y=0;y<SY;++y) { for(int z=0;z<SZ;++z) { sU[x][y][z] = Uwx[t][x-(SX-2)][y][z]; sV[x][y][z] = Vwx[t][x-(SX-2)][y][z]; } } } #pragma omp parallel for collapse(3) for(int x=0;x<SX-2;++x) { for(int y=SY-2;y<SY;++y) { for(int z=0;z<SZ;++z) { sU[x][y][z] = Uwy[t][x][y-(SY-2)][z]; sV[x][y][z] = Vwy[t][x][y-(SY-2)][z]; } } } #pragma omp parallel for collapse(3) for(int x=0;x<SX-2;++x) { for(int y=0;y<SY-2;++y) { for(int z=SZ-2;z<SZ;++z) { sU[x][y][z] = Uwz[t][x][y][z-(SZ-2)]; sV[x][y][z] = Vwz[t][x][y][z-(SZ-2)]; } } } /* std::cerr << "stat" <<std::endl; for(int y=0;y<SY-2;++y) { for(int z=0;z<SZ-2;++z) { // double u,v; get_solution_at(t,x+t,y+t,z+t, u,v); std::cerr << int(9.999*sU[SX/2][y][z]); } std::cerr <<std::endl; } std::cerr << "sol" <<std::endl; for(int y=0;y<SY-2;++y) { for(int z=0;z<SZ-2;++z) { int x=SX/2; double u,v; get_solution_at(t,x+t,y+t,z+t, u,v); std::cerr << int(9.999*u); } std::cerr <<std::endl; }*/ // destructively update the state const auto lap = [](Real ar[SX][SY][SZ],int x, int y, int z) { auto ret = ar[x][y+1][z+1] + ar[x+2][y+1][z+1] + ar[x+1][y][z+1] + ar[x+1][y+2][z+1] + ar[x+1][y+1][z] + ar[x+1][y+1][z+2] - 6*ar[x+1][y+1][z+1]; return ret / dx / dx; }; #pragma omp parallel for collapse(2) for(int x=0;x<SX-2;++x) { for(int y=0;y<SY-2;++y) { for(int z=0;z<SZ-2;++z) { Real u=sU[x+1][y+1][z+1] ; Real v=sV[x+1][y+1][z+1] ; auto du_dt = -Fe * u*v*v + Fu*(1-u) + Du * lap(sU,x,y,z); auto dv_dt = Fe * u*v*v - Fv*v + Dv * lap(sV,x,y,z); sU[x][y][z] = u+dt*du_dt; sV[x][y][z] = v+dt*dv_dt; } } } } { const int t = T_MAX; double num=0,den=0; for(int x=0;x<SX-2;++x) { for(int y=0;y<SY-2;++y) { for(int z=0;z<SZ-2;++z) { double u,v; get_solution_at(t,x+t,y+t,z+t, u,v); num += std::abs(u-sU[x][y][z]); den += 1; } } } std::cout << "average error: " << (num/den) << std::endl; } } <commit_msg>Correct parallelization with double buffering<commit_after>#include <cmath> #include <unistd.h> #include <iostream> #include <sstream> #define NX 50 #define NY 50 #define NZ 50 #define SX 34 #define SY 34 #define SZ 34 #define T_MAX 1000 typedef double Real; const Real Fu = 1.0/86400, Fv = 6.0/86400, Fe = 1.0/900, Du = 0.1*2.3e-9, Dv = 12.2e-11; const Real dt = 0*200, dx = 0.001; Real U[NX][NY][NZ], V[NX][NY][NZ]; Real U_other[NX][NY][NZ], V_other[NX][NY][NZ]; int global_clock; Real Uwx[T_MAX][2][SY][SZ], Uwy[T_MAX][SX][2][SZ], Uwz[T_MAX][SX][SY][2]; Real Vwx[T_MAX][2][SY][SZ], Vwy[T_MAX][SX][2][SZ], Vwz[T_MAX][SX][SY][2]; Real sU0[SX][SY][SZ], sV0[SX][SY][SZ]; Real sU[SX][SY][SZ], sV[SX][SY][SZ]; Real sU_1[SX][SY][SZ], sV_1[SX][SY][SZ]; void fill_initial_condition() { global_clock=0; for (int x=0;x<NX;++x) { for (int y=0;y<NY;++y) { for (int z=0;z<NZ;++z) { U[x][y][z] = 1; V[x][y][z] = 0; } } } int bx = std::max(NX/4,NX/2-8), ex = std::min(3*NX/4+1,NX/2+8); int by = std::max(NY/4,NY/2-8), ey = std::min(3*NY/4+1,NY/2+8); int bz = std::max(NZ/4,NZ/2-8), ez = std::min(3*NZ/4+1,NZ/2+8); for (int x=bx;x<ex;++x){ for (int y=by;y<ey;++y){ for (int z=bz;z<ez;++z){ U[x][y][z] = 0.5; V[x][y][z] = 0.25+0.1*sin(x+sqrt(y)+cos(z)); } } } } inline Real periodic(Real ar[NX][NY][NZ],int x, int y, int z) { x = ((x+100*NX)%NX+NX)%NX; y = ((y+100*NY)%NY+NY)%NY; z = ((z+100*NZ)%NZ+NZ)%NZ; //x = (x+NX)%NX; //y = (y+NY)%NY; //z = (z+NZ)%NZ; return ar[x][y][z]; } void naive_proceed() { ++global_clock; auto lap = [](Real ar[NX][NY][NZ],int x, int y, int z) { auto ret = periodic(ar, x-1, y, z) + periodic(ar, x+1, y, z) + periodic(ar, x, y-1, z) + periodic(ar, x, y+1, z) + periodic(ar, x, y, z-1) + periodic(ar, x, y, z+1) - 6*ar[x][y][z]; return ret / dx / dx; }; #pragma omp parallel for collapse(2) for (int x=0;x<NX;++x) { for (int y=0;y<NY;++y) { for (int z=0;z<NZ;++z) { auto u = U[x][y][z], v = V[x][y][z]; auto du_dt = -Fe * u*v*v + Fu*(1-u) + Du * lap(U,x,y,z); auto dv_dt = Fe * u*v*v - Fv*v + Dv * lap(V,x,y,z); U_other[x][y][z] = U[x][y][z] + dt*du_dt; V_other[x][y][z] = V[x][y][z] + dt*dv_dt; } } } for (int x=0;x<NX;++x) { for (int y=0;y<NY;++y) { for (int z=0;z<NZ;++z) { U[x][y][z]=U_other[x][y][z]; } } } for (int x=0;x<NX;++x) { for (int y=0;y<NY;++y) { for (int z=0;z<NZ;++z) { V[x][y][z]=V_other[x][y][z]; } } } } void get_solution_at(int t, int x, int y, int z, Real &u, Real &v) { if(global_clock > t) fill_initial_condition(); while(global_clock < t) naive_proceed(); u = periodic(U,x,y,z); v = periodic(V,x,y,z); } int main () { fill_initial_condition(); for(int x=0;x<SX;++x) { for(int y=0;y<SY;++y) { for(int z=0;z<SZ;++z) { double u,v; get_solution_at(0,x,y,z, u,v); sU0[x][y][z]=u; sV0[x][y][z]=v; } } } std::cerr << "Setting up wall values..." << std::endl; for(int t = 0;t<T_MAX;++t){ for(int x=SX-2;x<SX;++x) { for(int y=0;y<SY;++y) { for(int z=0;z<SZ;++z) { double u,v; get_solution_at(t,x+t,y+t,z+t, u,v); Uwx[t][x-(SX-2)][y][z] = u; Vwx[t][x-(SX-2)][y][z] = v; } } } for(int x=0;x<SX;++x) { for(int y=SY-2;y<SY;++y) { for(int z=0;z<SZ;++z) { double u,v; get_solution_at(t,x+t,y+t,z+t, u,v); Uwy[t][x][y-(SY-2)][z] = u; Vwy[t][x][y-(SY-2)][z] = v; } } } for(int x=0;x<SX;++x) { for(int y=0;y<SY;++y) { for(int z=SZ-2;z<SZ;++z) { double u,v; get_solution_at(t,x+t,y+t,z+t, u,v); Uwz[t][x][y][z-(SZ-2)] = u; Vwz[t][x][y][z-(SZ-2)] = v; } } } } std::cerr << "Carrying out simulation..." << std::endl; // set initial condition for(int x=0;x<SX;++x) { for(int y=0;y<SY;++y) { for(int z=0;z<SZ;++z) { sU[x][y][z]=sU0[x][y][z]; sV[x][y][z]=sV0[x][y][z]; } } } for(int t = 0; t < T_MAX; ++t){ // load communication values #pragma omp parallel for collapse(3) for(int x=SX-2;x<SX;++x) { for(int y=0;y<SY;++y) { for(int z=0;z<SZ;++z) { sU[x][y][z] = Uwx[t][x-(SX-2)][y][z]; sV[x][y][z] = Vwx[t][x-(SX-2)][y][z]; } } } #pragma omp parallel for collapse(3) for(int x=0;x<SX-2;++x) { for(int y=SY-2;y<SY;++y) { for(int z=0;z<SZ;++z) { sU[x][y][z] = Uwy[t][x][y-(SY-2)][z]; sV[x][y][z] = Vwy[t][x][y-(SY-2)][z]; } } } #pragma omp parallel for collapse(3) for(int x=0;x<SX-2;++x) { for(int y=0;y<SY-2;++y) { for(int z=SZ-2;z<SZ;++z) { sU[x][y][z] = Uwz[t][x][y][z-(SZ-2)]; sV[x][y][z] = Vwz[t][x][y][z-(SZ-2)]; } } } // destructively update the state const auto lap = [](Real ar[SX][SY][SZ],int x, int y, int z) { auto ret = ar[x][y+1][z+1] + ar[x+2][y+1][z+1] + ar[x+1][y][z+1] + ar[x+1][y+2][z+1] + ar[x+1][y+1][z] + ar[x+1][y+1][z+2] - 6*ar[x+1][y+1][z+1]; return ret / dx / dx; }; #pragma omp parallel for collapse(2) for(int x=0;x<SX-2;++x) { for(int y=0;y<SY-2;++y) { for(int z=0;z<SZ-2;++z) { Real u=sU[x+1][y+1][z+1] ; Real v=sV[x+1][y+1][z+1] ; auto du_dt = -Fe * u*v*v + Fu*(1-u) + Du * lap(sU,x,y,z); auto dv_dt = Fe * u*v*v - Fv*v + Dv * lap(sV,x,y,z); sU_1[x][y][z] = u+dt*du_dt; sV_1[x][y][z] = v+dt*dv_dt; } } } #pragma omp parallel for collapse(2) for(int x=0;x<SX-2;++x) { for(int y=0;y<SY-2;++y) { for(int z=0;z<SZ-2;++z) { sU[x][y][z] = sU_1[x][y][z]; sV[x][y][z] = sV_1[x][y][z]; } } } } { const int t = T_MAX; double num=0,den=0; for(int x=0;x<SX-2;++x) { for(int y=0;y<SY-2;++y) { for(int z=0;z<SZ-2;++z) { double u,v; get_solution_at(t,x+t,y+t,z+t, u,v); num += std::abs(u-sU[x][y][z]); den += 1; } } } std::cout << "average error: " << (num/den) << std::endl; } } <|endoftext|>
<commit_before>#ifndef __STRUCT_HPP #define __STRUCT_HPP #include <typeinfo> #include <vector> #include <boost/shared_ptr.hpp> #include "attribute.hpp" #include "meta_struct.hpp" //! Shared pointer to meta struct. typedef boost::shared_ptr<MetaStruct> PMetaStruct; /*! * A structure instance. This class serves to creates instance of a * MetaStruct. */ class Struct { public: //! Create structure from a metaclass description. Struct(PMetaStruct meta_struct) : meta_struct(meta_struct) { for (std::vector<MetaAttribute>::const_iterator meta_attribute = meta_struct->meta_attributes.begin(); meta_attribute != meta_struct->meta_attributes.end(); meta_attribute++) { // push back a copy of the default value attributes.push_back(Attribute(meta_attribute->default_value)); }; }; //! Copy constructor. Struct(const Struct & struc) : meta_struct(struc.meta_struct), attributes(struc.attributes) {}; //! Get the value of an attribute. template<typename ValueType> ValueType & get_attr(const std::string & name) { std::map<std::string, unsigned int>::iterator index = meta_struct->index_map.find(name); if (index != meta_struct->index_map.end()) { try { return boost::any_cast<ValueType &>(attributes[index->second]); } catch (const boost::bad_any_cast &) { throw type_error("Type mismatch on attribute \"" + name + "\" (required " + std::string(attributes[index->second].type().name()) + " but got " + std::string(typeid(ValueType).name()) + ")."); } } else { throw name_error("Struct has no attribute \"" + name + "\"."); }; }; private: PMetaStruct meta_struct; std::vector<Attribute> attributes; }; #endif <commit_msg>cffi: simplified struct code<commit_after>#ifndef __STRUCT_HPP #define __STRUCT_HPP #include <typeinfo> #include <vector> #include <boost/foreach.hpp> #include "attribute.hpp" #include "meta_struct.hpp" /*! * A structure instance. This class serves to create an instance of a * MetaStruct. */ class Struct { public: //! Create structure from a metaclass description. Struct(PMetaStruct meta_struct) : meta_struct(meta_struct) { BOOST_FOREACH(const MetaAttribute & meta_attribute, meta_struct->meta_attributes) { // push back a copy of the default value attributes.push_back(Attribute(meta_attribute.default_value)); }; } //! Copy constructor. Struct(const Struct & struc) : meta_struct(struc.meta_struct), attributes(struc.attributes) {}; //! Get reference to the value of an attribute. template<typename ValueType> ValueType & get_attr(const std::string & name) { std::map<std::string, unsigned int>::iterator index; // search name in meta struct index index = meta_struct->index_map.find(name); if (index != meta_struct->index_map.end()) { // found, so return attribute as requested type try { return boost::any_cast<ValueType &>(attributes[index->second]); } catch (const boost::bad_any_cast &) { // could not get attribute in requested type, so throw exception throw type_error("Type mismatch on attribute \"" + name + "\" (required " + std::string(attributes[index->second].type().name()) + " but got " + std::string(typeid(ValueType).name()) + ")."); } } else { // not found, so throw an exception throw name_error("Struct has no attribute \"" + name + "\"."); }; }; private: //! Metaclass information (list of attribute types, default values, ...). PMetaStruct meta_struct; //! List of attribute values. std::vector<Attribute> attributes; }; #endif // __STRUCT_HPP <|endoftext|>
<commit_before>#include "Platform.hpp" #include "SimpleProteinEnvironment.hpp" namespace Elysia { /* //Example of a pair namespace std { template <class T, class U> class pair {public: pair (const T&f, const U&s) {first=f;second=s;} T first; U second; };} */ //Initialize the main-zone-list by reading the genes and creating 1 zone per gene from Genome (and simplify) ProteinEnvironment& SimpleProteinEnvironment::initialize(const Elysia::Genome::Genome&genes){ //Zones start out as representing 1 gene (can be overlapping) //Since they can represent a collection of genes, //They are chopped during the intersection process and overlap regions become new zones const Elysia::Genome::Chromosome *fatherMother[2]; fatherMother[0]=&genes.fathers(); fatherMother[1]=&genes.mothers(); //Loop through all the genes for (int chromosomeNum=0;chromosomeNum<2;++chromosomeNum) { int num_genes=fatherMother[chromosomeNum]->genes_size(); for (int i=0;i<num_genes;++i) { //Define the new zone const Elysia::Genome::Gene*gene=&fatherMother[chromosomeNum]->genes(i); int num_bounds=gene->bounds_size(); for (int k=0;k<num_bounds;++k) { ProteinZone newZone; newZone.mGenes.push_back(*gene); int num_proteins=gene->external_proteins_size(); for (int j=0;j<num_proteins;++j) { const Elysia::Genome::Protein *protein=&gene->external_proteins(j); newZone.mSoup.push_back(ProteinZone::EffectAndDensityPair(protein->protein_code(),protein->density())); } newZone.mBounds =BoundingBox3f3f(Vector3f(gene->bounds(k).minx(), gene->bounds(k).miny(), gene->bounds(k).minz()), Vector3f(gene->bounds(k).maxx(), gene->bounds(k).maxy(), gene->bounds(k).maxz())); mMainZoneList.push_back(newZone); } } } zoneIntersection(mMainZoneList); return *this; } //Find the "specific protein density" total up the protein (given effect) //Return the magnitude of a given effect. float SimpleProteinEnvironment::ProteinZone::getSpecificProteinDensity(Elysia::Genome::Effect e){ float retval=0; std::vector< std::pair<Elysia::Genome::Effect,float> >::const_iterator i,ie; for (i=mSoup.begin(),ie=mSoup.end();i!=ie;++i) { //if the effect in the current iterator matches the desired protein effect passed in as "e", add the float to the return value if (i->first==e) retval+=i->second; } return retval; } //Get protein density at a location (given location, and protein effect interested in) //Return float of the effect's density float SimpleProteinEnvironment::getProteinDensity(const Vector3f &location, const Elysia::Genome::Effect&effect) { float density=0; ///loop through all protein zones for (std::vector<ProteinZone>::iterator i=mMainZoneList.begin(),ie=mMainZoneList.end();i!=ie;++i) { //if our test point is in the zone if (i->getBoundingBox().contains(location)) { //then accumulate the matching effect (if present) into final result density+=i->getSpecificProteinDensity(effect); } } //and return the result return density; } //Find all the proteins at a given point (given location) //Return vector of proteins std::vector<std::pair<Elysia::Genome::Effect, float> > SimpleProteinEnvironment::getCompleteProteinDensity(const Vector3f& location){ std::vector<ProteinZone::EffectAndDensityPair >proteins; //loop through all the zones for (std::vector<ProteinZone>::iterator i=mMainZoneList.begin(),ie=mMainZoneList.end();i!=ie;++i) { //if our test point is in the zone if (i->getBoundingBox().contains(location)) { //Append the effects (i.e. mSoup) to the end of the returned proteins proteins.insert(proteins.end(),i->mSoup.begin(),i->mSoup.end()); } } return proteins; } //Update ALL the mSoup (densities) for the next timestep, (given the current age) //Return nothing // These functions are not ready yet--- we should get LNK errors for them so we know when we're done //"Complicated" function to update the soup for the next time iteration void SimpleProteinEnvironment::ProteinZone::updateSoupToNextSoup(const float age){ //Will write this function last } //The area is not equal in any aspect -> not OK static bool okArea(const BoundingBox3f3f&input) { return input.min().x!=input.max().x&&input.min().y!=input.max().y; } template <class T> BoundingBox<T> intersect(const BoundingBox<T>&a, const BoundingBox<T>&b) { BoundingBox<T> retval(a.min().max(b.min()),a.max().min(b.max())); if (retval.diag().x<=0||retval.diag().y<=0) { return BoundingBox<T>(retval.min(),retval.min());//null bounding box at min } return retval; } //Combine genes into a single-shared region SimpleProteinEnvironment::ProteinZone SimpleProteinEnvironment::combineZone(const SimpleProteinEnvironment::ProteinZone &a, const SimpleProteinEnvironment::ProteinZone&b , const BoundingBox3f3f &bbox) { ProteinZone retval; retval.mBounds=bbox; assert(!a.mSoup.empty()&&!b.mSoup.empty()); //Combine the genes into a shared, common sized, region retval.mGenes.insert(retval.mGenes.end(),a.mGenes.begin(),a.mGenes.end()); retval.mGenes.insert(retval.mGenes.end(),b.mGenes.begin(),b.mGenes.end()); return retval; } //Relocate a zone to a new box location SimpleProteinEnvironment::ProteinZone SimpleProteinEnvironment::relocateZone(ProteinZone a, const BoundingBox3f3f &bbox) { //generate a box of type a a.mBounds=bbox; return a; } //Merge 2 zones of same gene type void SimpleProteinEnvironment::combineZonesFromSameGene(ProteinZone &a, const ProteinZone&b) { a.mBounds.mergeIn(b.mBounds); } //Combine 2 zones by dividing it up into parts before reassembling them void SimpleProteinEnvironment::chopZonePair(const ProteinZone &a, const ProteinZone &b, std::vector<ProteinZone> &output) { // Assume any combination of 2 zones will results in 9 subsections // Figure out using the intersections points how to generate the subsections // Subsections of area 0 --> ignore // Add subsections of significant areas to the list with the proper gene type // Combine subsections of similar gene type horizontally ProteinZone ab[2]={a,b}; //combine a and b into a list if (!okArea(intersect(ab[0].mBounds,ab[1].mBounds))) { output.push_back(a); output.push_back(b); return; } float horizedges[4]={ab[0].mBounds.min().x,ab[1].mBounds.min().x,ab[0].mBounds.max().x,ab[1].mBounds.max().x}; //generate list of x bounds float vertedges[4]={ab[0].mBounds.min().y,ab[1].mBounds.min().y,ab[0].mBounds.max().y,ab[1].mBounds.max().y}; //generate lsit of y bounds std::sort(horizedges+0,horizedges+4); //Sort the horizontal list left->right (min->max) std::sort(vertedges+0,vertedges+4); //Sort the vertical list top->bottom (min->max) bool combinable[3][3][2]; ProteinZone combiners[3][3][2]; //Loop through the subsections for (int i=0;i<3;++i) { for (int j=0;j<3;++j) { BoundingBox3f3f newBounds[2]; //Generate one section 1->9 (corner-to-corner) BoundingBox3f3f location(Vector3f(horizedges[i],vertedges[j],a.mBounds.min().z), Vector3f(horizedges[i+1],vertedges[j+1],a.mBounds.max().z)); bool valid[2]; for (int z=0;z<2;++z) { //Is it inside a or b? valid[z]=okArea(newBounds[z]=intersect(location,ab[z].mBounds)); combinable[i][j][z]=false; } if (valid[0]&&valid[1]) { //It is a subsection of A and B output.push_back(combineZone(a,b,location)); } else if (valid[0]) { //It is a subsection of A combiners[i][j][0]=relocateZone(ab[0],newBounds[0]); combinable[i][j][0]=true; } else if (valid[1]) { //It is a subsection of B combiners[i][j][0]=relocateZone(ab[1],newBounds[1]); combinable[i][j][1]=true; } } } //Results in 9 subsections of type A, B and AB //Loop through the subsections and determine zones that are neighbors (horizontal) for (int z=0;z<2;++z) { for (int i=0;i<3;++i) { for (int j=0;j<2;++j) { if (combinable[i][j][z]&&combinable[i][j+1][z]) { combineZonesFromSameGene(combiners[i][j+1][z],combiners[i][j][z]); combinable[i][j][z]=false; } } } } //send back combined zones for (int z=0;z<2;++z) { for (int i=0;i<3;++i) { for (int j=0;j<3;++j) { if (combinable[i][j][z]) { output.push_back(combiners[i][j][z]); } } } } } //Split and simplify large zone definitions into smaller component zones for calculations (given list of all zones) //Return a list of zones (post-split) void SimpleProteinEnvironment::zoneIntersection(std::vector<ProteinZone> mMainZoneList){ std::vector<ProteinZone> mLocalZoneList; std::vector<ProteinZone> mSwapZoneList; mLocalZoneList = mMainZoneList; mSwapZoneList = mMainZoneList; bool converged=false; bool restart=false; while (!converged) { //Defaults to converged incase for-loop and detection never terminates converged=true; //Loop through zones and check intersection (for row from start-->end) for (std::vector<ProteinZone>::iterator i=mMainZoneList.begin(),ie=mMainZoneList.end();i!=ie;++i) { //(for column from current-row-diagonal + 1 --> end) ==> results in half triangle w/o diagonal for (std::vector<ProteinZone>::iterator j=i+1,je=mMainZoneList.end();j!=je;++j) { if(!restart){ mLocalZoneList.clear(); //ensure that the list returned is initialized properly mSwapZoneList.clear(); //ensure that the list returned is initialized properly chopZonePair(*i,*j,mLocalZoneList); if(mLocalZoneList.size() == 2){ if( ((i->mBounds == mLocalZoneList[0].mBounds) || (i->mBounds == mLocalZoneList[1].mBounds)) || ((j->mBounds == mLocalZoneList[0].mBounds) || (j->mBounds == mLocalZoneList[1].mBounds)) ){ //Technicaly, I only need to look at only i, or j, but the 2nd set it a sanity check //No new zones were created //-No action }else{ //These are 2 new zones //-Create new zones excluding current 2 //-Append new zones to list //-Restart -> Swap rebuildZones(i,j,mMainZoneList,mSwapZoneList); addZones(mLocalZoneList,mSwapZoneList); restart = true; } }else if ((mLocalZoneList.size() > 2)||(mLocalZoneList.size() == 1)){ //These are all new zones //-Create new zones excluding current 2 //-Append new zones to list //-Restart -> Swap rebuildZones(i,j,mMainZoneList,mSwapZoneList); addZones(mLocalZoneList,mSwapZoneList); restart = true; }else{ //Serious error... should not be 0 or fewer } }//end if }//end for }//end for if(restart){ mMainZoneList.swap(mSwapZoneList); converged=false; } }//end while } //Rebuild the zone list such that it exclude the 2 zones currently in question //This allows us to throw out the 2 zones and add their replacements void SimpleProteinEnvironment::rebuildZones(std::vector<ProteinZone>::const_iterator a,std::vector<ProteinZone>::const_iterator b, const std::vector<ProteinZone> &input, std::vector<ProteinZone> &output) { // Create a new list excluding the current 2 zones for (std::vector<ProteinZone>::const_iterator i=input.begin(),ie=input.end();i!=ie;++i) { if( (i != a)&&(i != b) ){ output.push_back(*i); } } return; } //Zone management functions to add zones to the main list (given sub-list, and main-list) //Return new main-list void SimpleProteinEnvironment::addZones( const std::vector<ProteinZone> &mSubZoneList, std::vector<ProteinZone> &mMainZoneList){ //Append all the zones in the sub-list to the main-list for (std::vector<ProteinZone>::const_iterator i=mSubZoneList.begin(),ie=mSubZoneList.end();i!=ie;++i) { mMainZoneList.push_back(*i); } return; } //Zone management functions to remove zones from the main list (given sub-list, and main-list) //Return new main-list void SimpleProteinEnvironment::removeZones( std::vector<ProteinZone> mSubZoneList, std::vector<ProteinZone> mMainZoneList){ //Find and remove all matching entries in the sub-list out of the main-list } //Function to find the zone that a single point reside in (given point, and zone list) //Return THE zone from the list that is inside the point, or fail SimpleProteinEnvironment::ProteinZone &SimpleProteinEnvironment::resideInZones( const Vector3f queryPoint, std::vector<ProteinZone> mMainZoneList){ int i; static ProteinZone myFail; size_t numMainZones=mMainZoneList.size(); for(size_t i=0;i<mMainZoneList.size();++i){ if (mMainZoneList[i].mBounds.contains(queryPoint)) { return mMainZoneList[i]; } } return myFail; } const Elysia::Genome::Gene& SimpleProteinEnvironment::retrieveGene(const Vector3f &location, const Elysia::Genome::Effect&effect){ assert(0); //FIXME actually look up the responsible gene from the set of "active" genes causing the effect to be spilled at this location static Elysia::Genome::Gene retval; return retval; } SimpleProteinEnvironment::~SimpleProteinEnvironment(){ } } <commit_msg>fixed infinite loop error<commit_after>#include "Platform.hpp" #include "SimpleProteinEnvironment.hpp" namespace Elysia { /* //Example of a pair namespace std { template <class T, class U> class pair {public: pair (const T&f, const U&s) {first=f;second=s;} T first; U second; };} */ //Initialize the main-zone-list by reading the genes and creating 1 zone per gene from Genome (and simplify) ProteinEnvironment& SimpleProteinEnvironment::initialize(const Elysia::Genome::Genome&genes){ //Zones start out as representing 1 gene (can be overlapping) //Since they can represent a collection of genes, //They are chopped during the intersection process and overlap regions become new zones const Elysia::Genome::Chromosome *fatherMother[2]; fatherMother[0]=&genes.fathers(); fatherMother[1]=&genes.mothers(); //Loop through all the genes for (int chromosomeNum=0;chromosomeNum<2;++chromosomeNum) { int num_genes=fatherMother[chromosomeNum]->genes_size(); for (int i=0;i<num_genes;++i) { //Define the new zone const Elysia::Genome::Gene*gene=&fatherMother[chromosomeNum]->genes(i); int num_bounds=gene->bounds_size(); for (int k=0;k<num_bounds;++k) { ProteinZone newZone; newZone.mGenes.push_back(*gene); int num_proteins=gene->external_proteins_size(); for (int j=0;j<num_proteins;++j) { const Elysia::Genome::Protein *protein=&gene->external_proteins(j); newZone.mSoup.push_back(ProteinZone::EffectAndDensityPair(protein->protein_code(),protein->density())); } newZone.mBounds =BoundingBox3f3f(Vector3f(gene->bounds(k).minx(), gene->bounds(k).miny(), gene->bounds(k).minz()), Vector3f(gene->bounds(k).maxx(), gene->bounds(k).maxy(), gene->bounds(k).maxz())); mMainZoneList.push_back(newZone); } } } zoneIntersection(mMainZoneList); return *this; } //Find the "specific protein density" total up the protein (given effect) //Return the magnitude of a given effect. float SimpleProteinEnvironment::ProteinZone::getSpecificProteinDensity(Elysia::Genome::Effect e){ float retval=0; std::vector< std::pair<Elysia::Genome::Effect,float> >::const_iterator i,ie; for (i=mSoup.begin(),ie=mSoup.end();i!=ie;++i) { //if the effect in the current iterator matches the desired protein effect passed in as "e", add the float to the return value if (i->first==e) retval+=i->second; } return retval; } //Get protein density at a location (given location, and protein effect interested in) //Return float of the effect's density float SimpleProteinEnvironment::getProteinDensity(const Vector3f &location, const Elysia::Genome::Effect&effect) { float density=0; ///loop through all protein zones for (std::vector<ProteinZone>::iterator i=mMainZoneList.begin(),ie=mMainZoneList.end();i!=ie;++i) { //if our test point is in the zone if (i->getBoundingBox().contains(location)) { //then accumulate the matching effect (if present) into final result density+=i->getSpecificProteinDensity(effect); } } //and return the result return density; } //Find all the proteins at a given point (given location) //Return vector of proteins std::vector<std::pair<Elysia::Genome::Effect, float> > SimpleProteinEnvironment::getCompleteProteinDensity(const Vector3f& location){ std::vector<ProteinZone::EffectAndDensityPair >proteins; //loop through all the zones for (std::vector<ProteinZone>::iterator i=mMainZoneList.begin(),ie=mMainZoneList.end();i!=ie;++i) { //if our test point is in the zone if (i->getBoundingBox().contains(location)) { //Append the effects (i.e. mSoup) to the end of the returned proteins proteins.insert(proteins.end(),i->mSoup.begin(),i->mSoup.end()); } } return proteins; } //Update ALL the mSoup (densities) for the next timestep, (given the current age) //Return nothing // These functions are not ready yet--- we should get LNK errors for them so we know when we're done //"Complicated" function to update the soup for the next time iteration void SimpleProteinEnvironment::ProteinZone::updateSoupToNextSoup(const float age){ //Will write this function last } //The area is not equal in any aspect -> not OK static bool okArea(const BoundingBox3f3f&input) { return input.min().x!=input.max().x&&input.min().y!=input.max().y; } template <class T> BoundingBox<T> intersect(const BoundingBox<T>&a, const BoundingBox<T>&b) { BoundingBox<T> retval(a.min().max(b.min()),a.max().min(b.max())); if (retval.diag().x<=0||retval.diag().y<=0) { return BoundingBox<T>(retval.min(),retval.min());//null bounding box at min } return retval; } //Combine genes into a single-shared region SimpleProteinEnvironment::ProteinZone SimpleProteinEnvironment::combineZone(const SimpleProteinEnvironment::ProteinZone &a, const SimpleProteinEnvironment::ProteinZone&b , const BoundingBox3f3f &bbox) { ProteinZone retval; retval.mBounds=bbox; assert(!a.mSoup.empty()&&!b.mSoup.empty()); //Combine the genes into a shared, common sized, region retval.mGenes.insert(retval.mGenes.end(),a.mGenes.begin(),a.mGenes.end()); retval.mGenes.insert(retval.mGenes.end(),b.mGenes.begin(),b.mGenes.end()); return retval; } //Relocate a zone to a new box location SimpleProteinEnvironment::ProteinZone SimpleProteinEnvironment::relocateZone(ProteinZone a, const BoundingBox3f3f &bbox) { //generate a box of type a a.mBounds=bbox; return a; } //Merge 2 zones of same gene type void SimpleProteinEnvironment::combineZonesFromSameGene(ProteinZone &a, const ProteinZone&b) { a.mBounds.mergeIn(b.mBounds); } //Combine 2 zones by dividing it up into parts before reassembling them void SimpleProteinEnvironment::chopZonePair(const ProteinZone &a, const ProteinZone &b, std::vector<ProteinZone> &output) { // Assume any combination of 2 zones will results in 9 subsections // Figure out using the intersections points how to generate the subsections // Subsections of area 0 --> ignore // Add subsections of significant areas to the list with the proper gene type // Combine subsections of similar gene type horizontally ProteinZone ab[2]={a,b}; //combine a and b into a list if (!okArea(intersect(ab[0].mBounds,ab[1].mBounds))) { output.push_back(a); output.push_back(b); return; } float horizedges[4]={ab[0].mBounds.min().x,ab[1].mBounds.min().x,ab[0].mBounds.max().x,ab[1].mBounds.max().x}; //generate list of x bounds float vertedges[4]={ab[0].mBounds.min().y,ab[1].mBounds.min().y,ab[0].mBounds.max().y,ab[1].mBounds.max().y}; //generate lsit of y bounds std::sort(horizedges+0,horizedges+4); //Sort the horizontal list left->right (min->max) std::sort(vertedges+0,vertedges+4); //Sort the vertical list top->bottom (min->max) bool combinable[3][3][2]; ProteinZone combiners[3][3][2]; //Loop through the subsections for (int i=0;i<3;++i) { for (int j=0;j<3;++j) { BoundingBox3f3f newBounds[2]; //Generate one section 1->9 (corner-to-corner) BoundingBox3f3f location(Vector3f(horizedges[i],vertedges[j],a.mBounds.min().z), Vector3f(horizedges[i+1],vertedges[j+1],a.mBounds.max().z)); bool valid[2]; for (int z=0;z<2;++z) { //Is it inside a or b? valid[z]=okArea(newBounds[z]=intersect(location,ab[z].mBounds)); combinable[i][j][z]=false; } if (valid[0]&&valid[1]) { //It is a subsection of A and B output.push_back(combineZone(a,b,location)); } else if (valid[0]) { //It is a subsection of A combiners[i][j][0]=relocateZone(ab[0],newBounds[0]); combinable[i][j][0]=true; } else if (valid[1]) { //It is a subsection of B combiners[i][j][0]=relocateZone(ab[1],newBounds[1]); combinable[i][j][1]=true; } } } //Results in 9 subsections of type A, B and AB //Loop through the subsections and determine zones that are neighbors (horizontal) for (int z=0;z<2;++z) { for (int i=0;i<3;++i) { for (int j=0;j<2;++j) { if (combinable[i][j][z]&&combinable[i][j+1][z]) { combineZonesFromSameGene(combiners[i][j+1][z],combiners[i][j][z]); combinable[i][j][z]=false; } } } } //send back combined zones for (int z=0;z<2;++z) { for (int i=0;i<3;++i) { for (int j=0;j<3;++j) { if (combinable[i][j][z]) { output.push_back(combiners[i][j][z]); } } } } } //Split and simplify large zone definitions into smaller component zones for calculations (given list of all zones) //Return a list of zones (post-split) void SimpleProteinEnvironment::zoneIntersection(std::vector<ProteinZone> mMainZoneList){ std::vector<ProteinZone> mLocalZoneList; std::vector<ProteinZone> mSwapZoneList; mLocalZoneList = mMainZoneList; mSwapZoneList = mMainZoneList; bool converged=false; bool restart=false; while (!converged) { //Defaults to converged incase for-loop and detection never terminates converged=true; //Loop through zones and check intersection (for row from start-->end) for (std::vector<ProteinZone>::iterator i=mMainZoneList.begin(),ie=mMainZoneList.end();i!=ie;++i) { //(for column from current-row-diagonal + 1 --> end) ==> results in half triangle w/o diagonal for (std::vector<ProteinZone>::iterator j=i+1,je=mMainZoneList.end();j!=je;++j) { if(!restart){ mLocalZoneList.clear(); //ensure that the list returned is initialized properly mSwapZoneList.clear(); //ensure that the list returned is initialized properly chopZonePair(*i,*j,mLocalZoneList); if(mLocalZoneList.size() == 2){ if( ((i->mBounds == mLocalZoneList[0].mBounds) || (i->mBounds == mLocalZoneList[1].mBounds)) || ((j->mBounds == mLocalZoneList[0].mBounds) || (j->mBounds == mLocalZoneList[1].mBounds)) ){ //Technicaly, I only need to look at only i, or j, but the 2nd set it a sanity check //No new zones were created //-No action }else{ //These are 2 new zones //-Create new zones excluding current 2 //-Append new zones to list //-Restart -> Swap rebuildZones(i,j,mMainZoneList,mSwapZoneList); addZones(mLocalZoneList,mSwapZoneList); restart = true; } }else if ((mLocalZoneList.size() > 2)||(mLocalZoneList.size() == 1)){ //These are all new zones //-Create new zones excluding current 2 //-Append new zones to list //-Restart -> Swap rebuildZones(i,j,mMainZoneList,mSwapZoneList); addZones(mLocalZoneList,mSwapZoneList); restart = true; }else{ //Serious error... should not be 0 or fewer } }//end if }//end for }//end for if(restart){ mMainZoneList.swap(mSwapZoneList); converged=false; restart=false; } }//end while } //Rebuild the zone list such that it exclude the 2 zones currently in question //This allows us to throw out the 2 zones and add their replacements void SimpleProteinEnvironment::rebuildZones(std::vector<ProteinZone>::const_iterator a,std::vector<ProteinZone>::const_iterator b, const std::vector<ProteinZone> &input, std::vector<ProteinZone> &output) { // Create a new list excluding the current 2 zones for (std::vector<ProteinZone>::const_iterator i=input.begin(),ie=input.end();i!=ie;++i) { if( (i != a)&&(i != b) ){ output.push_back(*i); } } return; } //Zone management functions to add zones to the main list (given sub-list, and main-list) //Return new main-list void SimpleProteinEnvironment::addZones( const std::vector<ProteinZone> &mSubZoneList, std::vector<ProteinZone> &mMainZoneList){ //Append all the zones in the sub-list to the main-list for (std::vector<ProteinZone>::const_iterator i=mSubZoneList.begin(),ie=mSubZoneList.end();i!=ie;++i) { mMainZoneList.push_back(*i); } return; } //Zone management functions to remove zones from the main list (given sub-list, and main-list) //Return new main-list void SimpleProteinEnvironment::removeZones( std::vector<ProteinZone> mSubZoneList, std::vector<ProteinZone> mMainZoneList){ //Find and remove all matching entries in the sub-list out of the main-list } //Function to find the zone that a single point reside in (given point, and zone list) //Return THE zone from the list that is inside the point, or fail SimpleProteinEnvironment::ProteinZone &SimpleProteinEnvironment::resideInZones( const Vector3f queryPoint, std::vector<ProteinZone> mMainZoneList){ int i; static ProteinZone myFail; size_t numMainZones=mMainZoneList.size(); for(size_t i=0;i<mMainZoneList.size();++i){ if (mMainZoneList[i].mBounds.contains(queryPoint)) { return mMainZoneList[i]; } } return myFail; } const Elysia::Genome::Gene& SimpleProteinEnvironment::retrieveGene(const Vector3f &location, const Elysia::Genome::Effect&effect){ assert(0); //FIXME actually look up the responsible gene from the set of "active" genes causing the effect to be spilled at this location static Elysia::Genome::Gene retval; return retval; } SimpleProteinEnvironment::~SimpleProteinEnvironment(){ } } <|endoftext|>
<commit_before>/** * KQOAuth - An OAuth authentication library for Qt. * * Author: Johan Paul ([email protected]) * http://www.d-pointer.com * * KQOAuth is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * KQOAuth 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 KQOAuth. If not, see <http://www.gnu.org/licenses/>. */ #include <QByteArray> #include <QDateTime> #include <QCryptographicHash> #include <QPair> #include <QStringList> #include <QtDebug> #include <QtAlgorithms> #include "kqoauthrequest.h" #include "kqoauthrequest_p.h" #include "kqoauthutils.h" #include "kqoauthglobals.h" //////////// Private d_ptr implementation ///////// KQOAuthRequestPrivate::KQOAuthRequestPrivate() { } KQOAuthRequestPrivate::~KQOAuthRequestPrivate() { } // This method will not include the "oauthSignature" paramater, since it is calculated from these parameters. void KQOAuthRequestPrivate::prepareRequest() { // If parameter list is not empty, we don't want to insert these values by // accident a second time. So giving up. if( !requestParameters.isEmpty() ) { return; } switch ( requestType ) { case KQOAuthRequest::TemporaryCredentials: requestParameters.append( qMakePair( OAUTH_KEY_CALLBACK, QString(QUrl::toPercentEncoding( oauthCallbackUrl.toString()) ))); // This is so ugly that it is almost beautiful. requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE_METHOD, oauthSignatureMethod )); requestParameters.append( qMakePair( OAUTH_KEY_CONSUMER_KEY, oauthConsumerKey )); requestParameters.append( qMakePair( OAUTH_KEY_VERSION, oauthVersion )); requestParameters.append( qMakePair( OAUTH_KEY_TIMESTAMP, this->oauthTimestamp() )); requestParameters.append( qMakePair( OAUTH_KEY_NONCE, this->oauthNonce() )); insertAdditionalParams(requestParameters); break; case KQOAuthRequest::AccessToken: requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE_METHOD, oauthSignatureMethod )); requestParameters.append( qMakePair( OAUTH_KEY_CONSUMER_KEY, oauthConsumerKey )); requestParameters.append( qMakePair( OAUTH_KEY_VERSION, oauthVersion )); requestParameters.append( qMakePair( OAUTH_KEY_TIMESTAMP, this->oauthTimestamp() )); requestParameters.append( qMakePair( OAUTH_KEY_NONCE, this->oauthNonce() )); requestParameters.append( qMakePair( OAUTH_KEY_VERIFIER, oauthVerifier )); requestParameters.append( qMakePair( OAUTH_KEY_TOKEN, oauthToken )); insertAdditionalParams(requestParameters); break; case KQOAuthRequest::AuthorizedRequest: requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE_METHOD, oauthSignatureMethod )); requestParameters.append( qMakePair( OAUTH_KEY_CONSUMER_KEY, oauthConsumerKey )); requestParameters.append( qMakePair( OAUTH_KEY_VERSION, oauthVersion )); requestParameters.append( qMakePair( OAUTH_KEY_TIMESTAMP, this->oauthTimestamp() )); requestParameters.append( qMakePair( OAUTH_KEY_NONCE, this->oauthNonce() )); requestParameters.append( qMakePair( OAUTH_KEY_TOKEN, oauthToken )); insertAdditionalParams(requestParameters); break; default: break; } } void KQOAuthRequestPrivate::insertAdditionalParams(QList< QPair<QString, QString> > &requestParams) { QList<QString> additionalKeys = this->additionalParams.keys(); QList<QString> additionalValues = this->additionalParams.values(); for(int i=0; i<additionalKeys.size(); i++) { requestParams.append( qMakePair(QString(QUrl::toPercentEncoding(additionalKeys.at(i))), QString(QUrl::toPercentEncoding(additionalValues.at(i)))) ); } if (oauthHttpMethod == KQOAuthRequest::POST) { insertPostBody(); } } void KQOAuthRequestPrivate::insertPostBody() { QList<QString> postBodyKeys = this->additionalParams.keys(); QList<QString> postBodyValues = this->additionalParams.values(); postBodyContent.clear(); bool first = true; for(int i=0; i<postBodyKeys.size(); i++) { if(!first) { postBodyContent.append("&"); } else { first = false; } QString key = postBodyKeys.at(i); QString value = postBodyValues.at(i); postBodyContent.append(QUrl::toPercentEncoding(key) + QString("=").toUtf8() + QUrl::toPercentEncoding(value)); } } void KQOAuthRequestPrivate::signRequest() { QString signature = this->oauthSignature(); requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE, signature) ); } QString KQOAuthRequestPrivate::oauthSignature() { QByteArray baseString = this->requestBaseString(); QString signature = KQOAuthUtils::hmac_sha1(baseString, oauthConsumerSecretKey + "&" + oauthTokenSecret); return QString( QUrl::toPercentEncoding( signature ) ); } bool normalizedParameterSort(const QPair<QString, QString> &left, const QPair<QString, QString> &right) { QString keyLeft = left.first; QString valueLeft = left.second; QString keyRight = right.first; QString valueRight = right.second; if(keyLeft == keyRight) { return (valueLeft < valueRight); } else { return (keyLeft < keyRight); } } QByteArray KQOAuthRequestPrivate::requestBaseString() { QByteArray baseString; // Every request has these as the commont parameters. baseString.append( oauthHttpMethodString.toUtf8() + "&"); // HTTP method baseString.append( QUrl::toPercentEncoding( oauthRequestEndpoint.toString(QUrl::RemoveQuery) ) + "&" ); // The path and query components QList< QPair<QString, QString> > baseStringParameters; baseStringParameters.append(requestParameters); // Sort the request parameters. These parameters have been // initialized earlier. qSort(baseStringParameters.begin(), baseStringParameters.end(), normalizedParameterSort ); // Last append the request parameters correctly encoded. baseString.append( encodedParamaterList(baseStringParameters) ); return baseString; } QByteArray KQOAuthRequestPrivate::encodedParamaterList(const QList< QPair<QString, QString> > &parameters) { QByteArray resultList; bool first = true; QPair<QString, QString> parameter; foreach (parameter, parameters) { if(!first) { resultList.append( "%26" ); } else { first = false; } // Here we don't need to explicitely encode the strings to UTF-8 since // QUrl::toPercentEncoding() takes care of that for us. resultList.append( QUrl::toPercentEncoding(parameter.first) // Parameter key + "%3D" // '=' encoded + QUrl::toPercentEncoding(parameter.second) // Parameter value ); } return resultList; } QString KQOAuthRequestPrivate::oauthTimestamp() const { // This is basically for unit tests only. In most cases we don't set the nonce beforehand. if (!oauthTimestamp_.isEmpty()) { return oauthTimestamp_; } #if QT_VERSION >= 0x040700 return QString::number(QDateTime::currentDateTimeUtc().toTime_t()); #else return QString::number(QDateTime::currentDateTime().toUTC().toTime_t()); #endif } QString KQOAuthRequestPrivate::oauthNonce() const { // This is basically for unit tests only. In most cases we don't set the nonce beforehand. if (!oauthNonce_.isEmpty()) { return oauthNonce_; } return QString::number(qrand()); } bool KQOAuthRequestPrivate::validateRequest() const { switch ( requestType ) { case KQOAuthRequest::TemporaryCredentials: if (oauthRequestEndpoint.isEmpty() || oauthConsumerKey.isEmpty() || oauthNonce_.isEmpty() || oauthSignatureMethod.isEmpty() || oauthTimestamp_.isEmpty() || oauthVersion.isEmpty()) { return false; } return true; case KQOAuthRequest::AccessToken: if (oauthRequestEndpoint.isEmpty() || oauthVerifier.isEmpty() || oauthConsumerKey.isEmpty() || oauthNonce_.isEmpty() || oauthSignatureMethod.isEmpty() || oauthTimestamp_.isEmpty() || oauthToken.isEmpty() || oauthTokenSecret.isEmpty() || oauthVersion.isEmpty()) { return false; } return true; case KQOAuthRequest::AuthorizedRequest: if (oauthRequestEndpoint.isEmpty() || oauthConsumerKey.isEmpty() || oauthNonce_.isEmpty() || oauthSignatureMethod.isEmpty() || oauthTimestamp_.isEmpty() || oauthToken.isEmpty() || oauthTokenSecret.isEmpty() || oauthVersion.isEmpty()) { return false; } return true; default: return false; } // We should not come here. return false; } QByteArray KQOAuthRequestPrivate::requestBody() const { return postBodyContent; } //////////// Public implementation //////////////// KQOAuthRequest::KQOAuthRequest(QObject *parent) : QObject(parent), d_ptr(new KQOAuthRequestPrivate) { } KQOAuthRequest::~KQOAuthRequest() { delete d_ptr; } void KQOAuthRequest::initRequest(KQOAuthRequest::RequestType type, const QUrl &requestEndpoint) { Q_D(KQOAuthRequest); if (!requestEndpoint.isValid()) { qWarning() << "Endpoint URL is not valid. Ignoring. This request might not work."; return; } if (type < 0 || type > KQOAuthRequest::AuthorizedRequest) { qWarning() << "Invalid request type. Ignoring. This request might not work."; return; } // Clear the request clearRequest(); // Set smart defaults. d->requestType = type; d->oauthRequestEndpoint = requestEndpoint; d->oauthTimestamp_ = d->oauthTimestamp(); d->oauthNonce_ = d->oauthNonce(); this->setSignatureMethod(KQOAuthRequest::HMAC_SHA1); this->setHttpMethod(KQOAuthRequest::POST); d->oauthVersion = "1.0"; // Currently supports only version 1.0 } void KQOAuthRequest::setConsumerKey(const QString &consumerKey) { Q_D(KQOAuthRequest); d->oauthConsumerKey = consumerKey; } void KQOAuthRequest::setConsumerSecretKey(const QString &consumerSecretKey) { Q_D(KQOAuthRequest); d->oauthConsumerSecretKey = consumerSecretKey; } void KQOAuthRequest::setCallbackUrl(const QUrl &callbackUrl) { Q_D(KQOAuthRequest); d->oauthCallbackUrl = callbackUrl; } void KQOAuthRequest::setSignatureMethod(KQOAuthRequest::RequestSignatureMethod requestMethod) { Q_D(KQOAuthRequest); QString requestMethodString; switch (requestMethod) { case KQOAuthRequest::PLAINTEXT: requestMethodString = "PLAINTEXT"; break; case KQOAuthRequest::HMAC_SHA1: requestMethodString = "HMAC-SHA1"; break; case KQOAuthRequest::RSA_SHA1: requestMethodString = "RSA-SHA1"; break; default: // We should not come here qWarning() << "Invalid signature method set."; break; } d->oauthSignatureMethod = requestMethodString; } void KQOAuthRequest::setTokenSecret(const QString &tokenSecret) { Q_D(KQOAuthRequest); d->oauthTokenSecret = tokenSecret; } void KQOAuthRequest::setToken(const QString &token) { Q_D(KQOAuthRequest); d->oauthToken = token; } void KQOAuthRequest::setVerifier(const QString &verifier) { Q_D(KQOAuthRequest); d->oauthVerifier = verifier; } void KQOAuthRequest::setHttpMethod(KQOAuthRequest::RequestHttpMethod httpMethod) { Q_D(KQOAuthRequest); QString requestHttpMethodString; switch (httpMethod) { case KQOAuthRequest::GET: requestHttpMethodString = "GET"; break; case KQOAuthRequest::POST: requestHttpMethodString = "POST"; break; default: qWarning() << "Invalid HTTP method set."; break; } d->oauthHttpMethod = httpMethod; d->oauthHttpMethodString = requestHttpMethodString; } KQOAuthRequest::RequestHttpMethod KQOAuthRequest::httpMethod() const { Q_D(const KQOAuthRequest); return d->oauthHttpMethod; } void KQOAuthRequest::setAdditionalParameters(const KQOAuthParameters &additionalParams) { Q_D(KQOAuthRequest); d->additionalParams = additionalParams; } KQOAuthParameters KQOAuthRequest::additionalParameters() const { Q_D(const KQOAuthRequest); return d->additionalParams; } KQOAuthRequest::RequestType KQOAuthRequest::requestType() const { Q_D(const KQOAuthRequest); return d->requestType; } QUrl KQOAuthRequest::requestEndpoint() const { Q_D(const KQOAuthRequest); return d->oauthRequestEndpoint; } QList<QByteArray> KQOAuthRequest::requestParameters() { Q_D(KQOAuthRequest); QList<QByteArray> requestParamList; d->prepareRequest(); if (!d->validateRequest() ) { qWarning() << "Request is not valid! I will still sign it, but it will probably not work."; } d->signRequest(); QPair<QString, QString> requestParam; QString param; QString value; foreach (requestParam, d->requestParameters) { param = requestParam.first; value = requestParam.second; requestParamList.append(QString(param + "=\"" + value +"\"").toUtf8()); } return requestParamList; } bool KQOAuthRequest::isValid() const { Q_D(const KQOAuthRequest); return d->validateRequest(); } void KQOAuthRequest::clearRequest() { Q_D(KQOAuthRequest); d->oauthRequestEndpoint = ""; d->oauthHttpMethodString = ""; d->oauthConsumerKey = ""; d->oauthConsumerSecretKey = ""; d->oauthToken = ""; d->oauthTokenSecret = ""; d->oauthSignatureMethod = ""; d->oauthCallbackUrl = ""; d->oauthVerifier = ""; d->oauthTimestamp_ = ""; d->oauthNonce_ = ""; d->requestParameters.clear(); d->additionalParams.clear(); } <commit_msg>Fixed HMAC-SHA1 secret creation as per OAuth 1.0 spec<commit_after>/** * KQOAuth - An OAuth authentication library for Qt. * * Author: Johan Paul ([email protected]) * http://www.d-pointer.com * * KQOAuth is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * KQOAuth 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 KQOAuth. If not, see <http://www.gnu.org/licenses/>. */ #include <QByteArray> #include <QDateTime> #include <QCryptographicHash> #include <QPair> #include <QStringList> #include <QtDebug> #include <QtAlgorithms> #include "kqoauthrequest.h" #include "kqoauthrequest_p.h" #include "kqoauthutils.h" #include "kqoauthglobals.h" //////////// Private d_ptr implementation ///////// KQOAuthRequestPrivate::KQOAuthRequestPrivate() { } KQOAuthRequestPrivate::~KQOAuthRequestPrivate() { } // This method will not include the "oauthSignature" paramater, since it is calculated from these parameters. void KQOAuthRequestPrivate::prepareRequest() { // If parameter list is not empty, we don't want to insert these values by // accident a second time. So giving up. if( !requestParameters.isEmpty() ) { return; } switch ( requestType ) { case KQOAuthRequest::TemporaryCredentials: requestParameters.append( qMakePair( OAUTH_KEY_CALLBACK, QString(QUrl::toPercentEncoding( oauthCallbackUrl.toString()) ))); // This is so ugly that it is almost beautiful. requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE_METHOD, oauthSignatureMethod )); requestParameters.append( qMakePair( OAUTH_KEY_CONSUMER_KEY, oauthConsumerKey )); requestParameters.append( qMakePair( OAUTH_KEY_VERSION, oauthVersion )); requestParameters.append( qMakePair( OAUTH_KEY_TIMESTAMP, this->oauthTimestamp() )); requestParameters.append( qMakePair( OAUTH_KEY_NONCE, this->oauthNonce() )); insertAdditionalParams(requestParameters); break; case KQOAuthRequest::AccessToken: requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE_METHOD, oauthSignatureMethod )); requestParameters.append( qMakePair( OAUTH_KEY_CONSUMER_KEY, oauthConsumerKey )); requestParameters.append( qMakePair( OAUTH_KEY_VERSION, oauthVersion )); requestParameters.append( qMakePair( OAUTH_KEY_TIMESTAMP, this->oauthTimestamp() )); requestParameters.append( qMakePair( OAUTH_KEY_NONCE, this->oauthNonce() )); requestParameters.append( qMakePair( OAUTH_KEY_VERIFIER, oauthVerifier )); requestParameters.append( qMakePair( OAUTH_KEY_TOKEN, oauthToken )); insertAdditionalParams(requestParameters); break; case KQOAuthRequest::AuthorizedRequest: requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE_METHOD, oauthSignatureMethod )); requestParameters.append( qMakePair( OAUTH_KEY_CONSUMER_KEY, oauthConsumerKey )); requestParameters.append( qMakePair( OAUTH_KEY_VERSION, oauthVersion )); requestParameters.append( qMakePair( OAUTH_KEY_TIMESTAMP, this->oauthTimestamp() )); requestParameters.append( qMakePair( OAUTH_KEY_NONCE, this->oauthNonce() )); requestParameters.append( qMakePair( OAUTH_KEY_TOKEN, oauthToken )); insertAdditionalParams(requestParameters); break; default: break; } } void KQOAuthRequestPrivate::insertAdditionalParams(QList< QPair<QString, QString> > &requestParams) { QList<QString> additionalKeys = this->additionalParams.keys(); QList<QString> additionalValues = this->additionalParams.values(); for(int i=0; i<additionalKeys.size(); i++) { requestParams.append( qMakePair(QString(QUrl::toPercentEncoding(additionalKeys.at(i))), QString(QUrl::toPercentEncoding(additionalValues.at(i)))) ); } if (oauthHttpMethod == KQOAuthRequest::POST) { insertPostBody(); } } void KQOAuthRequestPrivate::insertPostBody() { QList<QString> postBodyKeys = this->additionalParams.keys(); QList<QString> postBodyValues = this->additionalParams.values(); postBodyContent.clear(); bool first = true; for(int i=0; i<postBodyKeys.size(); i++) { if(!first) { postBodyContent.append("&"); } else { first = false; } QString key = postBodyKeys.at(i); QString value = postBodyValues.at(i); postBodyContent.append(QUrl::toPercentEncoding(key) + QString("=").toUtf8() + QUrl::toPercentEncoding(value)); } } void KQOAuthRequestPrivate::signRequest() { QString signature = this->oauthSignature(); requestParameters.append( qMakePair( OAUTH_KEY_SIGNATURE, signature) ); } QString KQOAuthRequestPrivate::oauthSignature() { /** * http://oauth.net/core/1.0/#anchor16 * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104] where the * Signature Base String is the text and the key is the concatenated values (each first encoded per Parameter * Encoding) of the Consumer Secret and Token Secret, separated by an ‘&’ character (ASCII code 38) even if empty. **/ QByteArray baseString = this->requestBaseString(); QString secret = QString(QUrl::toPercentEncoding(oauthConsumerSecretKey)) + "&" + QString(QUrl::toPercentEncoding(oauthTokenSecret)); QString signature = KQOAuthUtils::hmac_sha1(baseString, secret); return QString( QUrl::toPercentEncoding( signature ) ); } bool normalizedParameterSort(const QPair<QString, QString> &left, const QPair<QString, QString> &right) { QString keyLeft = left.first; QString valueLeft = left.second; QString keyRight = right.first; QString valueRight = right.second; if(keyLeft == keyRight) { return (valueLeft < valueRight); } else { return (keyLeft < keyRight); } } QByteArray KQOAuthRequestPrivate::requestBaseString() { QByteArray baseString; // Every request has these as the commont parameters. baseString.append( oauthHttpMethodString.toUtf8() + "&"); // HTTP method baseString.append( QUrl::toPercentEncoding( oauthRequestEndpoint.toString(QUrl::RemoveQuery) ) + "&" ); // The path and query components QList< QPair<QString, QString> > baseStringParameters; baseStringParameters.append(requestParameters); // Sort the request parameters. These parameters have been // initialized earlier. qSort(baseStringParameters.begin(), baseStringParameters.end(), normalizedParameterSort ); // Last append the request parameters correctly encoded. baseString.append( encodedParamaterList(baseStringParameters) ); return baseString; } QByteArray KQOAuthRequestPrivate::encodedParamaterList(const QList< QPair<QString, QString> > &parameters) { QByteArray resultList; bool first = true; QPair<QString, QString> parameter; foreach (parameter, parameters) { if(!first) { resultList.append( "%26" ); } else { first = false; } // Here we don't need to explicitely encode the strings to UTF-8 since // QUrl::toPercentEncoding() takes care of that for us. resultList.append( QUrl::toPercentEncoding(parameter.first) // Parameter key + "%3D" // '=' encoded + QUrl::toPercentEncoding(parameter.second) // Parameter value ); } return resultList; } QString KQOAuthRequestPrivate::oauthTimestamp() const { // This is basically for unit tests only. In most cases we don't set the nonce beforehand. if (!oauthTimestamp_.isEmpty()) { return oauthTimestamp_; } #if QT_VERSION >= 0x040700 return QString::number(QDateTime::currentDateTimeUtc().toTime_t()); #else return QString::number(QDateTime::currentDateTime().toUTC().toTime_t()); #endif } QString KQOAuthRequestPrivate::oauthNonce() const { // This is basically for unit tests only. In most cases we don't set the nonce beforehand. if (!oauthNonce_.isEmpty()) { return oauthNonce_; } return QString::number(qrand()); } bool KQOAuthRequestPrivate::validateRequest() const { switch ( requestType ) { case KQOAuthRequest::TemporaryCredentials: if (oauthRequestEndpoint.isEmpty() || oauthConsumerKey.isEmpty() || oauthNonce_.isEmpty() || oauthSignatureMethod.isEmpty() || oauthTimestamp_.isEmpty() || oauthVersion.isEmpty()) { return false; } return true; case KQOAuthRequest::AccessToken: if (oauthRequestEndpoint.isEmpty() || oauthVerifier.isEmpty() || oauthConsumerKey.isEmpty() || oauthNonce_.isEmpty() || oauthSignatureMethod.isEmpty() || oauthTimestamp_.isEmpty() || oauthToken.isEmpty() || oauthTokenSecret.isEmpty() || oauthVersion.isEmpty()) { return false; } return true; case KQOAuthRequest::AuthorizedRequest: if (oauthRequestEndpoint.isEmpty() || oauthConsumerKey.isEmpty() || oauthNonce_.isEmpty() || oauthSignatureMethod.isEmpty() || oauthTimestamp_.isEmpty() || oauthToken.isEmpty() || oauthTokenSecret.isEmpty() || oauthVersion.isEmpty()) { return false; } return true; default: return false; } // We should not come here. return false; } QByteArray KQOAuthRequestPrivate::requestBody() const { return postBodyContent; } //////////// Public implementation //////////////// KQOAuthRequest::KQOAuthRequest(QObject *parent) : QObject(parent), d_ptr(new KQOAuthRequestPrivate) { } KQOAuthRequest::~KQOAuthRequest() { delete d_ptr; } void KQOAuthRequest::initRequest(KQOAuthRequest::RequestType type, const QUrl &requestEndpoint) { Q_D(KQOAuthRequest); if (!requestEndpoint.isValid()) { qWarning() << "Endpoint URL is not valid. Ignoring. This request might not work."; return; } if (type < 0 || type > KQOAuthRequest::AuthorizedRequest) { qWarning() << "Invalid request type. Ignoring. This request might not work."; return; } // Clear the request clearRequest(); // Set smart defaults. d->requestType = type; d->oauthRequestEndpoint = requestEndpoint; d->oauthTimestamp_ = d->oauthTimestamp(); d->oauthNonce_ = d->oauthNonce(); this->setSignatureMethod(KQOAuthRequest::HMAC_SHA1); this->setHttpMethod(KQOAuthRequest::POST); d->oauthVersion = "1.0"; // Currently supports only version 1.0 } void KQOAuthRequest::setConsumerKey(const QString &consumerKey) { Q_D(KQOAuthRequest); d->oauthConsumerKey = consumerKey; } void KQOAuthRequest::setConsumerSecretKey(const QString &consumerSecretKey) { Q_D(KQOAuthRequest); d->oauthConsumerSecretKey = consumerSecretKey; } void KQOAuthRequest::setCallbackUrl(const QUrl &callbackUrl) { Q_D(KQOAuthRequest); d->oauthCallbackUrl = callbackUrl; } void KQOAuthRequest::setSignatureMethod(KQOAuthRequest::RequestSignatureMethod requestMethod) { Q_D(KQOAuthRequest); QString requestMethodString; switch (requestMethod) { case KQOAuthRequest::PLAINTEXT: requestMethodString = "PLAINTEXT"; break; case KQOAuthRequest::HMAC_SHA1: requestMethodString = "HMAC-SHA1"; break; case KQOAuthRequest::RSA_SHA1: requestMethodString = "RSA-SHA1"; break; default: // We should not come here qWarning() << "Invalid signature method set."; break; } d->oauthSignatureMethod = requestMethodString; } void KQOAuthRequest::setTokenSecret(const QString &tokenSecret) { Q_D(KQOAuthRequest); d->oauthTokenSecret = tokenSecret; } void KQOAuthRequest::setToken(const QString &token) { Q_D(KQOAuthRequest); d->oauthToken = token; } void KQOAuthRequest::setVerifier(const QString &verifier) { Q_D(KQOAuthRequest); d->oauthVerifier = verifier; } void KQOAuthRequest::setHttpMethod(KQOAuthRequest::RequestHttpMethod httpMethod) { Q_D(KQOAuthRequest); QString requestHttpMethodString; switch (httpMethod) { case KQOAuthRequest::GET: requestHttpMethodString = "GET"; break; case KQOAuthRequest::POST: requestHttpMethodString = "POST"; break; default: qWarning() << "Invalid HTTP method set."; break; } d->oauthHttpMethod = httpMethod; d->oauthHttpMethodString = requestHttpMethodString; } KQOAuthRequest::RequestHttpMethod KQOAuthRequest::httpMethod() const { Q_D(const KQOAuthRequest); return d->oauthHttpMethod; } void KQOAuthRequest::setAdditionalParameters(const KQOAuthParameters &additionalParams) { Q_D(KQOAuthRequest); d->additionalParams = additionalParams; } KQOAuthParameters KQOAuthRequest::additionalParameters() const { Q_D(const KQOAuthRequest); return d->additionalParams; } KQOAuthRequest::RequestType KQOAuthRequest::requestType() const { Q_D(const KQOAuthRequest); return d->requestType; } QUrl KQOAuthRequest::requestEndpoint() const { Q_D(const KQOAuthRequest); return d->oauthRequestEndpoint; } QList<QByteArray> KQOAuthRequest::requestParameters() { Q_D(KQOAuthRequest); QList<QByteArray> requestParamList; d->prepareRequest(); if (!d->validateRequest() ) { qWarning() << "Request is not valid! I will still sign it, but it will probably not work."; } d->signRequest(); QPair<QString, QString> requestParam; QString param; QString value; foreach (requestParam, d->requestParameters) { param = requestParam.first; value = requestParam.second; requestParamList.append(QString(param + "=\"" + value +"\"").toUtf8()); } return requestParamList; } bool KQOAuthRequest::isValid() const { Q_D(const KQOAuthRequest); return d->validateRequest(); } void KQOAuthRequest::clearRequest() { Q_D(KQOAuthRequest); d->oauthRequestEndpoint = ""; d->oauthHttpMethodString = ""; d->oauthConsumerKey = ""; d->oauthConsumerSecretKey = ""; d->oauthToken = ""; d->oauthTokenSecret = ""; d->oauthSignatureMethod = ""; d->oauthCallbackUrl = ""; d->oauthVerifier = ""; d->oauthTimestamp_ = ""; d->oauthNonce_ = ""; d->requestParameters.clear(); d->additionalParams.clear(); } <|endoftext|>
<commit_before>// Author: Wim Lavrijsen March 2008 // Bindings #include "PyROOT.h" #include "TPySelector.h" #include "TPyReturn.h" #include "ObjectProxy.h" #include "MethodProxy.h" #include "RootWrapper.h" #include "MemoryRegulator.h" //- ROOT #include "TPython.h" #include "TString.h" //______________________________________________________________________________ // Python equivalent PROOF base class // ================================== // // The problem with deriving a python class from a PyROOT bound class and then // handing it back to a C++ framework, is that the virtual function dispatching // of C++ is completely oblivious to the methods overridden in python. To work // within the PROOF (C++) framework, a python class should derive from the class // TPySelector. This class provides the proper overrides on the C++ side, and // then forwards them, as apropriate, to python. // // This is an example set of scripts: // // ### PROOF running script, very close to equivalent .C (prooftest.py) // import time // from ROOT import * // // dataset = TDSet( 'TTree', 'h42' ) // dataset.Add( 'root:// .... myfile.root' ) // // proof = TProof.Open('') // time.sleep(1) # needed for GUI to settle // print dataset.Process( 'TPySelector', 'aapje' ) // ### EOF // // ### selector module (aapje.py, name has to match as per above) // from ROOT import TPySelector // // class MyPySelector( TPySelector ): // def Begin( self ): // print 'py: beginning' // // def SlaveBegin( self, tree ): // print 'py: slave beginning' // // def Process( self, entry ): // if self.fChain.GetEntry( entry ) <= 0: // return 0 // print 'py: processing', self.fChain.MyVar // return 1 // // def SlaveTerminate( self ): // print 'py: slave terminating' // // def Terminate( self ): // print 'py: terminating' // ### EOF //- data --------------------------------------------------------------------- ClassImp(TPySelector) //- private helpers ---------------------------------------------------------- void TPySelector::SetupPySelf() { if ( fPySelf && fPySelf != Py_None ) return; // already created ... TString impst = TString::Format( "import %s", GetOption() ); // use TPython to ensure that the interpreter is initialized if ( ! TPython::Exec( (const char*)impst ) ) { Abort( "failed to load provided python module" ); // Exec already printed error trace return; } // get the TPySelector python class PyObject* tpysel = PyObject_GetAttrString( PyImport_AddModule( const_cast< char* >( "libPyROOT" ) ), const_cast< char* >( "TPySelector" ) ); // get handle to the module PyObject* pymod = PyImport_AddModule( const_cast< char* >( GetOption() ) ); // get the module dictionary to loop over PyObject* dict = PyModule_GetDict( pymod ); Py_INCREF( dict ); // locate the TSelector derived class PyObject* allvalues = PyDict_Values( dict ); PyObject* pyclass = 0; for ( int i = 0; i < PyList_GET_SIZE( allvalues ); ++i ) { PyObject* value = PyList_GET_ITEM( allvalues, i ); Py_INCREF( value ); if ( PyType_Check( value ) && PyObject_IsSubclass( value, tpysel ) ) { if ( PyObject_Compare( value, tpysel ) ) { // i.e., if not equal pyclass = value; break; } } Py_DECREF( value ); } Py_DECREF( allvalues ); Py_DECREF( dict ); Py_DECREF( tpysel ); if ( ! pyclass ) { Abort( "no TSelector derived class available in provided module" ); return; } PyObject* args = PyTuple_New( 0 ); PyObject* self = PyObject_Call( pyclass, args, 0 ); Py_DECREF( args ); Py_DECREF( pyclass ); // final check before declaring success ... if ( ! self || ! PyROOT::ObjectProxy_Check( self ) ) { if ( ! PyErr_Occurred() ) PyErr_SetString( PyExc_RuntimeError, "could not create python selector" ); Py_XDECREF( self ); Abort( 0 ); return; } // steal reference to new self, since the deletion will come from the C++ side Py_DECREF( fPySelf ); fPySelf = self; // inject ourselves into the base of self; destroy old identity if need be (which happens // if the user calls the default ctor unnecessarily) TPySelector* oldselector = (TPySelector*)((PyROOT::ObjectProxy*)fPySelf)->fObject; ((PyROOT::ObjectProxy*)fPySelf)->fObject = this; if ( oldselector ) { PyROOT::TMemoryRegulator::UnregisterObject( oldselector ); delete oldselector; } } //____________________________________________________________________________ PyObject* TPySelector::CallSelf( const char* method, PyObject* pyobject ) { // Forward <method> to python. if ( ! fPySelf || fPySelf == Py_None ) { Py_INCREF( Py_None ); return Py_None; } PyObject* result = 0; // get the named method and check for python side overload by not accepting the // binding's methodproxy PyObject* pymethod = PyObject_GetAttrString( fPySelf, const_cast< char* >( method ) ); if ( ! PyROOT::MethodProxy_CheckExact( pymethod ) ) { if ( pyobject ) result = PyObject_CallFunction( pymethod, const_cast< char* >( "O" ), pyobject ); else result = PyObject_CallFunction( pymethod, const_cast< char* >( "" ) ); } else { // silently ignore if method not overridden (note that the above can't lead // to a python exception, since this (TPySelector) class contains the method // so it is always to be found) Py_INCREF( Py_None ); result = Py_None; } Py_XDECREF( pymethod ); if ( ! result ) Abort( 0 ); return result; } //- constructors/destructor -------------------------------------------------- TPySelector::TPySelector( TTree*, PyObject* self ) : fChain( 0 ), fPySelf( 0 ) { // Construct a TSelector derived with <self> as the underlying, which is // generally 0 to start out with in the current PROOF framework. if ( self ) { // steal reference as this is us, as seen from python fPySelf = self; } else { Py_INCREF( Py_None ); // using None allows clearer diagnostics fPySelf = Py_None; } } //____________________________________________________________________________ TPySelector::~TPySelector() { // Destructor. Only deref if still holding on to Py_None (circular otherwise). if ( fPySelf == Py_None ) Py_DECREF( fPySelf ); } //- public functions --------------------------------------------------------- Int_t TPySelector::Version() const { // Return version number of this selector. First forward; if not overridden, then // yield an obvious "undefined" number, PyObject* result = const_cast< TPySelector* >( this )->CallSelf( "Version" ); if ( result && result != Py_None ) { Int_t ires = (Int_t)PyLong_AsLong( result ); Py_DECREF( result ); return ires; } else if ( result == Py_None ) { Py_DECREF( result ); } return -99; } //____________________________________________________________________________ Int_t TPySelector::GetEntry( Long64_t entry, Int_t getall ) { // Boilerplate get entry; same as for generated code; not forwarded. return fChain ? fChain->GetTree()->GetEntry( entry, getall ) : 0; } //____________________________________________________________________________ void TPySelector::Init( TTree* tree ) { // Initialize with the current tree to be used; not forwarded (may be called // multiple times, and is called from Begin() and SlaveBegin() ). if ( ! tree ) return; // set the fChain beforehand so that the python side may correct if needed fChain = tree; // forward call PyObject* pytree = PyROOT::BindRootObject( (void*)tree, tree->IsA() ); PyObject* result = CallSelf( "Init", pytree ); Py_DECREF( pytree ); if ( ! result ) Abort( 0 ); Py_XDECREF( result ); } //____________________________________________________________________________ Bool_t TPySelector::Notify() { // Forward call to derived Notify() if available. PyObject* result = CallSelf( "Notify" ); if ( ! result ) Abort( 0 ); Py_XDECREF( result ); // by default, return kTRUE, b/c the Abort will stop the processing anyway on // a real error, so if we get here it usually means that there is no Notify() // override on the python side of things return kTRUE; } //____________________________________________________________________________ void TPySelector::Begin( TTree* ) { // First function called, and used to setup the python self; forward call. SetupPySelf(); // As per the generated code: the tree argument is deprecated (on PROOF 0 is // passed), and hence not forwarded. PyObject* result = CallSelf( "Begin" ); if ( ! result ) Abort( 0 ); Py_XDECREF( result ); } //____________________________________________________________________________ void TPySelector::SlaveBegin( TTree* tree ) { // First function called on worker node, needs to make sure python self is setup, // then store the tree to be used, initialize client, and forward call. SetupPySelf(); Init( tree ); PyObject* result = 0; if ( tree ) { PyObject* pytree = PyROOT::BindRootObject( (void*)tree, tree->IsA() ); result = CallSelf( "SlaveBegin", pytree ); Py_DECREF( pytree ); } else { result = CallSelf( "SlaveBegin", Py_None ); } if ( ! result ) Abort( 0 ); Py_XDECREF( result ); } //____________________________________________________________________________ Bool_t TPySelector::Process( Long64_t entry ) { // Actual processing; call is forwarded to python self. if ( ! fPySelf || fPySelf == Py_None ) { // would like to set a python error, but can't risk that in case of a // configuration problem, as it would be absorbed ... // simply returning kFALSE will not stop processing; need to set abort Abort( "no python selector instance available" ); return kFALSE; } PyObject* result = PyObject_CallMethod( fPySelf, const_cast< char* >( "Process" ), const_cast< char* >( "L" ), entry ); if ( ! result ) { Abort( 0 ); return kFALSE; } Bool_t bresult = (Bool_t)PyLong_AsLong( result ); Py_DECREF( result ); return bresult; } //____________________________________________________________________________ void TPySelector::SlaveTerminate() { // End of client; call is forwarded to python self. PyObject* result = CallSelf( "SlaveTerminate" ); if ( ! result ) Abort( 0 ); Py_XDECREF( result ); } //____________________________________________________________________________ void TPySelector::Terminate() { // End of job; call is forwarded to python self. PyObject* result = CallSelf( "Terminate" ); if ( ! result ) Abort( 0 ); Py_XDECREF( result ); } //____________________________________________________________________________ void TPySelector::Abort( const char* why, EAbort what ) { // If no 'why' given, read from python error if ( ! why && PyErr_Occurred() ) { PyObject *pytype = 0, *pyvalue = 0, *pytrace = 0; PyErr_Fetch( &pytype, &pyvalue, &pytrace ); // abort is delayed (done at end of loop, message is current) PyObject* pystr = PyObject_Str( pyvalue ); Abort( PyString_AS_STRING( pystr ), what ); Py_DECREF( pystr ); PyErr_Restore( pytype, pyvalue, pytrace ); } else TSelector::Abort( why ? why : "", what ); } <commit_msg> o) fix for: "warning: suggest explicit braces to avoid ambiguous 'else'" on slc4_amd64_gcc43<commit_after>// Author: Wim Lavrijsen March 2008 // Bindings #include "PyROOT.h" #include "TPySelector.h" #include "TPyReturn.h" #include "ObjectProxy.h" #include "MethodProxy.h" #include "RootWrapper.h" #include "MemoryRegulator.h" //- ROOT #include "TPython.h" #include "TString.h" //______________________________________________________________________________ // Python equivalent PROOF base class // ================================== // // The problem with deriving a python class from a PyROOT bound class and then // handing it back to a C++ framework, is that the virtual function dispatching // of C++ is completely oblivious to the methods overridden in python. To work // within the PROOF (C++) framework, a python class should derive from the class // TPySelector. This class provides the proper overrides on the C++ side, and // then forwards them, as apropriate, to python. // // This is an example set of scripts: // // ### PROOF running script, very close to equivalent .C (prooftest.py) // import time // from ROOT import * // // dataset = TDSet( 'TTree', 'h42' ) // dataset.Add( 'root:// .... myfile.root' ) // // proof = TProof.Open('') // time.sleep(1) # needed for GUI to settle // print dataset.Process( 'TPySelector', 'aapje' ) // ### EOF // // ### selector module (aapje.py, name has to match as per above) // from ROOT import TPySelector // // class MyPySelector( TPySelector ): // def Begin( self ): // print 'py: beginning' // // def SlaveBegin( self, tree ): // print 'py: slave beginning' // // def Process( self, entry ): // if self.fChain.GetEntry( entry ) <= 0: // return 0 // print 'py: processing', self.fChain.MyVar // return 1 // // def SlaveTerminate( self ): // print 'py: slave terminating' // // def Terminate( self ): // print 'py: terminating' // ### EOF //- data --------------------------------------------------------------------- ClassImp(TPySelector) //- private helpers ---------------------------------------------------------- void TPySelector::SetupPySelf() { if ( fPySelf && fPySelf != Py_None ) return; // already created ... TString impst = TString::Format( "import %s", GetOption() ); // use TPython to ensure that the interpreter is initialized if ( ! TPython::Exec( (const char*)impst ) ) { Abort( "failed to load provided python module" ); // Exec already printed error trace return; } // get the TPySelector python class PyObject* tpysel = PyObject_GetAttrString( PyImport_AddModule( const_cast< char* >( "libPyROOT" ) ), const_cast< char* >( "TPySelector" ) ); // get handle to the module PyObject* pymod = PyImport_AddModule( const_cast< char* >( GetOption() ) ); // get the module dictionary to loop over PyObject* dict = PyModule_GetDict( pymod ); Py_INCREF( dict ); // locate the TSelector derived class PyObject* allvalues = PyDict_Values( dict ); PyObject* pyclass = 0; for ( int i = 0; i < PyList_GET_SIZE( allvalues ); ++i ) { PyObject* value = PyList_GET_ITEM( allvalues, i ); Py_INCREF( value ); if ( PyType_Check( value ) && PyObject_IsSubclass( value, tpysel ) ) { if ( PyObject_Compare( value, tpysel ) ) { // i.e., if not equal pyclass = value; break; } } Py_DECREF( value ); } Py_DECREF( allvalues ); Py_DECREF( dict ); Py_DECREF( tpysel ); if ( ! pyclass ) { Abort( "no TSelector derived class available in provided module" ); return; } PyObject* args = PyTuple_New( 0 ); PyObject* self = PyObject_Call( pyclass, args, 0 ); Py_DECREF( args ); Py_DECREF( pyclass ); // final check before declaring success ... if ( ! self || ! PyROOT::ObjectProxy_Check( self ) ) { if ( ! PyErr_Occurred() ) PyErr_SetString( PyExc_RuntimeError, "could not create python selector" ); Py_XDECREF( self ); Abort( 0 ); return; } // steal reference to new self, since the deletion will come from the C++ side Py_DECREF( fPySelf ); fPySelf = self; // inject ourselves into the base of self; destroy old identity if need be (which happens // if the user calls the default ctor unnecessarily) TPySelector* oldselector = (TPySelector*)((PyROOT::ObjectProxy*)fPySelf)->fObject; ((PyROOT::ObjectProxy*)fPySelf)->fObject = this; if ( oldselector ) { PyROOT::TMemoryRegulator::UnregisterObject( oldselector ); delete oldselector; } } //____________________________________________________________________________ PyObject* TPySelector::CallSelf( const char* method, PyObject* pyobject ) { // Forward <method> to python. if ( ! fPySelf || fPySelf == Py_None ) { Py_INCREF( Py_None ); return Py_None; } PyObject* result = 0; // get the named method and check for python side overload by not accepting the // binding's methodproxy PyObject* pymethod = PyObject_GetAttrString( fPySelf, const_cast< char* >( method ) ); if ( ! PyROOT::MethodProxy_CheckExact( pymethod ) ) { if ( pyobject ) result = PyObject_CallFunction( pymethod, const_cast< char* >( "O" ), pyobject ); else result = PyObject_CallFunction( pymethod, const_cast< char* >( "" ) ); } else { // silently ignore if method not overridden (note that the above can't lead // to a python exception, since this (TPySelector) class contains the method // so it is always to be found) Py_INCREF( Py_None ); result = Py_None; } Py_XDECREF( pymethod ); if ( ! result ) Abort( 0 ); return result; } //- constructors/destructor -------------------------------------------------- TPySelector::TPySelector( TTree*, PyObject* self ) : fChain( 0 ), fPySelf( 0 ) { // Construct a TSelector derived with <self> as the underlying, which is // generally 0 to start out with in the current PROOF framework. if ( self ) { // steal reference as this is us, as seen from python fPySelf = self; } else { Py_INCREF( Py_None ); // using None allows clearer diagnostics fPySelf = Py_None; } } //____________________________________________________________________________ TPySelector::~TPySelector() { // Destructor. Only deref if still holding on to Py_None (circular otherwise). if ( fPySelf == Py_None ) { Py_DECREF( fPySelf ); } } //- public functions --------------------------------------------------------- Int_t TPySelector::Version() const { // Return version number of this selector. First forward; if not overridden, then // yield an obvious "undefined" number, PyObject* result = const_cast< TPySelector* >( this )->CallSelf( "Version" ); if ( result && result != Py_None ) { Int_t ires = (Int_t)PyLong_AsLong( result ); Py_DECREF( result ); return ires; } else if ( result == Py_None ) { Py_DECREF( result ); } return -99; } //____________________________________________________________________________ Int_t TPySelector::GetEntry( Long64_t entry, Int_t getall ) { // Boilerplate get entry; same as for generated code; not forwarded. return fChain ? fChain->GetTree()->GetEntry( entry, getall ) : 0; } //____________________________________________________________________________ void TPySelector::Init( TTree* tree ) { // Initialize with the current tree to be used; not forwarded (may be called // multiple times, and is called from Begin() and SlaveBegin() ). if ( ! tree ) return; // set the fChain beforehand so that the python side may correct if needed fChain = tree; // forward call PyObject* pytree = PyROOT::BindRootObject( (void*)tree, tree->IsA() ); PyObject* result = CallSelf( "Init", pytree ); Py_DECREF( pytree ); if ( ! result ) Abort( 0 ); Py_XDECREF( result ); } //____________________________________________________________________________ Bool_t TPySelector::Notify() { // Forward call to derived Notify() if available. PyObject* result = CallSelf( "Notify" ); if ( ! result ) Abort( 0 ); Py_XDECREF( result ); // by default, return kTRUE, b/c the Abort will stop the processing anyway on // a real error, so if we get here it usually means that there is no Notify() // override on the python side of things return kTRUE; } //____________________________________________________________________________ void TPySelector::Begin( TTree* ) { // First function called, and used to setup the python self; forward call. SetupPySelf(); // As per the generated code: the tree argument is deprecated (on PROOF 0 is // passed), and hence not forwarded. PyObject* result = CallSelf( "Begin" ); if ( ! result ) Abort( 0 ); Py_XDECREF( result ); } //____________________________________________________________________________ void TPySelector::SlaveBegin( TTree* tree ) { // First function called on worker node, needs to make sure python self is setup, // then store the tree to be used, initialize client, and forward call. SetupPySelf(); Init( tree ); PyObject* result = 0; if ( tree ) { PyObject* pytree = PyROOT::BindRootObject( (void*)tree, tree->IsA() ); result = CallSelf( "SlaveBegin", pytree ); Py_DECREF( pytree ); } else { result = CallSelf( "SlaveBegin", Py_None ); } if ( ! result ) Abort( 0 ); Py_XDECREF( result ); } //____________________________________________________________________________ Bool_t TPySelector::Process( Long64_t entry ) { // Actual processing; call is forwarded to python self. if ( ! fPySelf || fPySelf == Py_None ) { // would like to set a python error, but can't risk that in case of a // configuration problem, as it would be absorbed ... // simply returning kFALSE will not stop processing; need to set abort Abort( "no python selector instance available" ); return kFALSE; } PyObject* result = PyObject_CallMethod( fPySelf, const_cast< char* >( "Process" ), const_cast< char* >( "L" ), entry ); if ( ! result ) { Abort( 0 ); return kFALSE; } Bool_t bresult = (Bool_t)PyLong_AsLong( result ); Py_DECREF( result ); return bresult; } //____________________________________________________________________________ void TPySelector::SlaveTerminate() { // End of client; call is forwarded to python self. PyObject* result = CallSelf( "SlaveTerminate" ); if ( ! result ) Abort( 0 ); Py_XDECREF( result ); } //____________________________________________________________________________ void TPySelector::Terminate() { // End of job; call is forwarded to python self. PyObject* result = CallSelf( "Terminate" ); if ( ! result ) Abort( 0 ); Py_XDECREF( result ); } //____________________________________________________________________________ void TPySelector::Abort( const char* why, EAbort what ) { // If no 'why' given, read from python error if ( ! why && PyErr_Occurred() ) { PyObject *pytype = 0, *pyvalue = 0, *pytrace = 0; PyErr_Fetch( &pytype, &pyvalue, &pytrace ); // abort is delayed (done at end of loop, message is current) PyObject* pystr = PyObject_Str( pyvalue ); Abort( PyString_AS_STRING( pystr ), what ); Py_DECREF( pystr ); PyErr_Restore( pytype, pyvalue, pytrace ); } else TSelector::Abort( why ? why : "", what ); } <|endoftext|>
<commit_before>/* @Copyright Barrett Adair 2015-2017 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_CLBL_TRTS_BOOST_CLBL_TRTS_HPP #define BOOST_CLBL_TRTS_BOOST_CLBL_TRTS_HPP #include <boost/callable_traits/detail/core.hpp> #include <boost/callable_traits/add_member_const.hpp> #include <boost/callable_traits/add_member_cv.hpp> #include <boost/callable_traits/add_member_lvalue_reference.hpp> #include <boost/callable_traits/add_member_rvalue_reference.hpp> #include <boost/callable_traits/add_member_volatile.hpp> #include <boost/callable_traits/add_noexcept.hpp> #include <boost/callable_traits/add_transaction_safe.hpp> #include <boost/callable_traits/add_varargs.hpp> #include <boost/callable_traits/apply_member_pointer.hpp> #include <boost/callable_traits/apply_return.hpp> #include <boost/callable_traits/args.hpp> #include <boost/callable_traits/class_of.hpp> #include <boost/callable_traits/function_type.hpp> #include <boost/callable_traits/has_member_qualifiers.hpp> #include <boost/callable_traits/has_varargs.hpp> #include <boost/callable_traits/has_void_return.hpp> #include <boost/callable_traits/is_const_member.hpp> #include <boost/callable_traits/is_invocable.hpp> #include <boost/callable_traits/is_lvalue_reference_member.hpp> #include <boost/callable_traits/is_reference_member.hpp> #include <boost/callable_traits/is_rvalue_reference_member.hpp> #include <boost/callable_traits/is_noexcept.hpp> #include <boost/callable_traits/is_transaction_safe.hpp> #include <boost/callable_traits/is_volatile_member.hpp> #include <boost/callable_traits/qualified_class_of.hpp> #include <boost/callable_traits/remove_member_const.hpp> #include <boost/callable_traits/remove_member_cv.hpp> #include <boost/callable_traits/remove_member_reference.hpp> #include <boost/callable_traits/remove_member_volatile.hpp> #include <boost/callable_traits/remove_noexcept.hpp> #include <boost/callable_traits/remove_transaction_safe.hpp> #include <boost/callable_traits/remove_varargs.hpp> #include <boost/callable_traits/return_type.hpp> #endif <commit_msg>Delete callable_traits.hpp<commit_after><|endoftext|>
<commit_before>#include "tlang.h" #include <taichi/util.h> #include <taichi/visual/gui.h> TC_NAMESPACE_BEGIN using namespace Tlang; auto test_loop = []() { CoreState::set_trigger_gdb_when_crash(true); Float a, b; int n = 16; Program prog(Arch::x86_64, n); prog.config.group_size = 8; prog.buffer(0).stream(0).group(0).place(a, b); Expr i = Expr::index(0); for_loop(i, range(0, n), [&]() { // *** a[i] = a[i] * b[i]; }); prog.materialize_layout(); for (int i = 0; i < n; i++) { prog.data(a, i) = i; prog.data(b, i) = i * 2; } prog(); for (int i = 0; i < n; i++) { auto val = prog.data(a, i); auto gt = i * i * 2; if (abs(gt - val) > 1e-5_f) { TC_P(i); TC_P(val); TC_P(gt); TC_ERROR(""); } } }; TC_REGISTER_TASK(test_loop); auto advection = []() { bool use_adapter = true; const int n = 512, nattr = 4; Float attr[2][nattr], v[2]; Program prog(Arch::x86_64, n * n); for (int k = 0; k < 2; k++) { for (int i = 0; i < nattr; i++) { prog.buffer(k).stream(0).group(0).place(attr[k][i]); } prog.buffer(2).stream(0).group(0).place(v[k]); } prog.config.group_size = use_adapter ? nattr : 1; prog.config.num_groups = 2; // ** gs = 2 auto index = Expr::index(0); Int32 xi = index % imm(n) / imm(1); Int32 yi = index % imm(n * n) / imm(n); auto offset_x = floor(v[0][index]); auto offset_y = floor(v[1][index]); auto wx = v[0][index] - offset_x; auto wy = v[1][index] - offset_y; if (use_adapter) { prog.adapter(0).set(2, 1); prog.adapter(0).convert(offset_x); prog.adapter(0).convert(offset_y); prog.adapter(1).set(2, 1); prog.adapter(1).convert(wx); prog.adapter(1).convert(wy); } // ** gs = 1 auto offset = cast<int32>(offset_x) * imm(n) + cast<int32>(offset_y) * imm(1); auto clamp = [](const Expr &e) { return min(max(imm(2), e), imm(n - 2)); }; // weights auto w00 = (imm(1.0f) - wx) * (imm(1.0f) - wy); auto w01 = (imm(1.0f) - wx) * wy; auto w10 = wx * (imm(1.0f) - wy); auto w11 = wx * wy; w00.name("w00"); w01.name("w01"); w10.name("w10"); w11.name("w11"); Expr node = Expr::index(0) + offset; Int32 i = clamp(node / imm(n)).name("i"); Int32 j = clamp(node % imm(n)).name("j"); node = i * imm(n) + j; node.name("node"); if (use_adapter) { prog.adapter(2).set(1, 4); prog.adapter(2).convert(w00); prog.adapter(2).convert(w01); prog.adapter(2).convert(w10); prog.adapter(2).convert(w11); prog.adapter(3).set(1, 4); prog.adapter(3).convert(node); } // ** gs = 4 for (int k = 0; k < nattr; k++) { auto v00 = attr[0][k][node + imm(0)]; auto v01 = attr[0][k][node + imm(1)]; auto v10 = attr[0][k][node + imm(n)]; auto v11 = attr[0][k][node + imm(n + 1)]; attr[1][k][index] = w00 * v00 + w01 * v01 + w10 * v10 + w11 * v11; // attr[1][k][index] = v00; attr[1][k][index].name(fmt::format("output{}", k)); } prog.compile(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < nattr; k++) { prog.data(attr[0][k], i * n + j) = i % 128 / 128.0_f; } real s = 3.0_f / n; prog.data(v[0], i * n + j) = s * (j - n / 2); prog.data(v[1], i * n + j) = -s * (i - n / 2); } } GUI gui("Advection", n, n); for (int f = 0; f < 1000; f++) { for (int t = 0; t < 3; t++) { prog(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < nattr; k++) { gui.buffer[i][j] = Vector4(prog.data(attr[1][k], i * n + j)); } } } } gui.update(); gui.screenshot(fmt::format("images/{:04d}.png", f)); prog.swap_buffers(0, 1); } }; TC_REGISTER_TASK(advection); // a * b * vec void test_adapter1(int vec_size) { Float a, b; Vector v(vec_size), u(vec_size); int n = 128; Program prog(Arch::x86_64, n); prog.config.group_size = vec_size; prog.config.num_groups = 8; prog.buffer(0).stream(0).group(0).place(a, b); for (int i = 0; i < vec_size; i++) { prog.buffer(1).stream(0).group(0).place(v(i)); } auto ind = Expr::index(0); auto &adapter = prog.adapter(0); auto ab = a[ind] * b[ind]; adapter.set(1, vec_size); adapter.convert(ab); for (int d = 0; d < vec_size; d++) { v(d)[ind] = ab * v(d)[ind]; } prog.materialize_layout(); for (int i = 0; i < n; i++) { prog.data(a, i) = i; prog.data(b, i) = 2.0_f * (i + 1); for (int j = 0; j < vec_size; j++) { prog.data(v(j), i) = 1.0_f * j / (i + 1); } } prog(); for (int i = 0; i < n; i++) { for (int j = 0; j < vec_size; j++) { auto val = prog.data(v(j), i); auto gt = i * j * 2; if (abs(gt - val) > 1e-3_f) { TC_P(i); TC_P(j); TC_P(val); TC_P(gt); TC_ERROR(""); } } } } // Vec<vec_size> reduction void test_adapter2(int vec_size) { Vector v(vec_size); Float sum; int n = 64; Program prog(Arch::x86_64, n); prog.config.group_size = 1; prog.config.num_groups = 8; for (int i = 0; i < vec_size; i++) { prog.buffer(1).stream(0).group(0).place(v(i)); } prog.buffer(0).stream(0).group(0).place(sum); auto ind = Expr::index(0); auto v_ind = v[ind]; for (int i = 0; i < vec_size; i++) { v_ind(i).set(Expr::load_if_pointer(v_ind(i))); TC_P(v_ind(i)->node_type_name()); } auto &adapter = prog.adapter(0); adapter.set(vec_size, 1); for (int i = 0; i < vec_size; i++) { adapter.convert(v_ind(i)); } Expr acc = Expr::create_imm(0.0_f); for (int d = 0; d < vec_size; d++) { acc = acc + v_ind(d); } sum[ind] = acc; prog.materialize_layout(); for (int i = 0; i < n; i++) { for (int j = 0; j < vec_size; j++) { prog.data(v(j), i) = j + i; } } prog(); for (int i = 0; i < n; i++) { auto val = prog.data(sum, i); auto gt = vec_size * (vec_size - 1) / 2 + i * vec_size; if (abs(gt - val) > 1e-5_f) { TC_P(i); TC_P(val); TC_P(gt); TC_ERROR(""); } } } // reduce(vec_a<n> - vec_b<n>) * vec_c<2n> void test_adapter3(int vec_size) { Vector a(vec_size), b(vec_size), c(vec_size * 2); Float sum; int n = 64; Program prog(Arch::x86_64, n); prog.config.group_size = vec_size * 2; prog.config.num_groups = 8; for (int i = 0; i < vec_size; i++) { prog.buffer(0).stream(0).group(0).place(a(i)); prog.buffer(1).stream(0).group(0).place(b(i)); } for (int i = 0; i < vec_size * 2; i++) { prog.buffer(2).stream(0).group(0).place(c(i)); } auto ind = Expr::index(0); auto aind = a[ind]; auto bind = b[ind]; auto cind = c[ind]; auto diff = aind.element_wise_prod(aind) - bind.element_wise_prod(bind); { auto &adapter = prog.adapter(0); adapter.set(vec_size, 1); for (int i = 0; i < vec_size; i++) adapter.convert(diff(i)); } Expr acc = Expr::create_imm(0.0_f); for (int d = 0; d < vec_size; d++) { acc = acc + diff(d); } { auto &adapter = prog.adapter(1); adapter.set(1, vec_size * 2); adapter.convert(acc); for (int i = 0; i < vec_size * 2; i++) c(i)[ind] = c(i)[ind] * acc; } prog.materialize_layout(); for (int i = 0; i < n; i++) { for (int j = 0; j < vec_size; j++) { prog.data(a(j), i) = i + j + 1; prog.data(b(j), i) = i + j; } for (int j = 0; j < vec_size * 2; j++) { prog.data(c(j), i) = i - 2 + j; } } prog(); for (int i = 0; i < n; i++) { real s = 0; for (int j = 0; j < vec_size; j++) { s += sqr(i + j + 1) - sqr(i + j); } for (int j = 0; j < vec_size * 2; j++) { auto val = prog.data(c(j), i); auto gt = s * (i - 2 + j); if (abs(gt - val) > 1e-3_f) { TC_P(i); TC_P(j); TC_P(val); TC_P(gt); TC_ERROR(""); } } } } auto test_adapter = []() { test_adapter3(1); test_adapter3(2); test_adapter3(4); test_adapter3(8); test_adapter1(1); test_adapter1(2); test_adapter1(4); test_adapter1(8); test_adapter2(1); test_adapter2(2); test_adapter2(4); test_adapter2(8); }; // TODO: random access TC_REGISTER_TASK(test_adapter); /* #define For(i, range) \ { \ Index i; for_loop(i, range, [&](Index i) #define End ) */ TC_NAMESPACE_END<commit_msg>prepare for intrinsics codegen<commit_after>#include "tlang.h" #include <taichi/util.h> #include <taichi/visual/gui.h> TC_NAMESPACE_BEGIN using namespace Tlang; auto test_loop = []() { CoreState::set_trigger_gdb_when_crash(true); Float a, b; int n = 16; Program prog(Arch::x86_64, n); prog.config.group_size = 8; prog.buffer(0).stream(0).group(0).place(a, b); Expr i = Expr::index(0); for_loop(i, range(0, n), [&]() { // *** a[i] = a[i] * b[i]; }); prog.materialize_layout(); for (int i = 0; i < n; i++) { prog.data(a, i) = i; prog.data(b, i) = i * 2; } prog(); for (int i = 0; i < n; i++) { auto val = prog.data(a, i); auto gt = i * i * 2; if (abs(gt - val) > 1e-5_f) { TC_P(i); TC_P(val); TC_P(gt); TC_ERROR(""); } } }; TC_REGISTER_TASK(test_loop); auto advection = []() { bool use_adapter = true; const int n = 512, nattr = 4; Float attr[2][nattr], v[2]; Program prog(Arch::x86_64, n * n); for (int k = 0; k < 2; k++) { for (int i = 0; i < nattr; i++) { prog.buffer(k).stream(0).group(0).place(attr[k][i]); } prog.buffer(2).stream(0).group(0).place(v[k]); } prog.config.group_size = use_adapter ? nattr : 1; prog.config.num_groups = 8; // ** gs = 2 auto index = Expr::index(0); Int32 xi = index % imm(n) / imm(1); Int32 yi = index % imm(n * n) / imm(n); auto offset_x = floor(v[0][index]); auto offset_y = floor(v[1][index]); auto wx = v[0][index] - offset_x; auto wy = v[1][index] - offset_y; if (use_adapter) { prog.adapter(0).set(2, 1); prog.adapter(0).convert(offset_x); prog.adapter(0).convert(offset_y); prog.adapter(1).set(2, 1); prog.adapter(1).convert(wx); prog.adapter(1).convert(wy); } // ** gs = 1 auto offset = cast<int32>(offset_x) * imm(n) + cast<int32>(offset_y) * imm(1); auto clamp = [](const Expr &e) { return min(max(imm(2), e), imm(n - 2)); }; // weights auto w00 = (imm(1.0f) - wx) * (imm(1.0f) - wy); auto w01 = (imm(1.0f) - wx) * wy; auto w10 = wx * (imm(1.0f) - wy); auto w11 = wx * wy; w00.name("w00"); w01.name("w01"); w10.name("w10"); w11.name("w11"); Expr node = Expr::index(0) + offset; Int32 i = clamp(node / imm(n)).name("i"); Int32 j = clamp(node % imm(n)).name("j"); node = i * imm(n) + j; node.name("node"); if (use_adapter) { prog.adapter(2).set(1, 4); prog.adapter(2).convert(w00); prog.adapter(2).convert(w01); prog.adapter(2).convert(w10); prog.adapter(2).convert(w11); prog.adapter(3).set(1, 4); prog.adapter(3).convert(node); } // ** gs = 4 for (int k = 0; k < nattr; k++) { auto v00 = attr[0][k][node + imm(0)]; auto v01 = attr[0][k][node + imm(1)]; auto v10 = attr[0][k][node + imm(n)]; auto v11 = attr[0][k][node + imm(n + 1)]; attr[1][k][index] = w00 * v00 + w01 * v01 + w10 * v10 + w11 * v11; // attr[1][k][index] = v00; attr[1][k][index].name(fmt::format("output{}", k)); } prog.compile(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < nattr; k++) { prog.data(attr[0][k], i * n + j) = i % 128 / 128.0_f; } real s = 3.0_f / n; prog.data(v[0], i * n + j) = s * (j - n / 2); prog.data(v[1], i * n + j) = -s * (i - n / 2); } } GUI gui("Advection", n, n); for (int f = 0; f < 1000; f++) { for (int t = 0; t < 3; t++) { prog(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < nattr; k++) { gui.buffer[i][j] = Vector4(prog.data(attr[1][k], i * n + j)); } } } } gui.update(); gui.screenshot(fmt::format("images/{:04d}.png", f)); prog.swap_buffers(0, 1); } }; TC_REGISTER_TASK(advection); // a * b * vec void test_adapter1(int vec_size) { Float a, b; Vector v(vec_size), u(vec_size); int n = 128; Program prog(Arch::x86_64, n); prog.config.group_size = vec_size; prog.config.num_groups = 8; prog.buffer(0).stream(0).group(0).place(a, b); for (int i = 0; i < vec_size; i++) { prog.buffer(1).stream(0).group(0).place(v(i)); } auto ind = Expr::index(0); auto &adapter = prog.adapter(0); auto ab = a[ind] * b[ind]; adapter.set(1, vec_size); adapter.convert(ab); for (int d = 0; d < vec_size; d++) { v(d)[ind] = ab * v(d)[ind]; } prog.materialize_layout(); for (int i = 0; i < n; i++) { prog.data(a, i) = i; prog.data(b, i) = 2.0_f * (i + 1); for (int j = 0; j < vec_size; j++) { prog.data(v(j), i) = 1.0_f * j / (i + 1); } } prog(); for (int i = 0; i < n; i++) { for (int j = 0; j < vec_size; j++) { auto val = prog.data(v(j), i); auto gt = i * j * 2; if (abs(gt - val) > 1e-3_f) { TC_P(i); TC_P(j); TC_P(val); TC_P(gt); TC_ERROR(""); } } } } // Vec<vec_size> reduction void test_adapter2(int vec_size) { Vector v(vec_size); Float sum; int n = 64; Program prog(Arch::x86_64, n); prog.config.group_size = 1; prog.config.num_groups = 8; for (int i = 0; i < vec_size; i++) { prog.buffer(1).stream(0).group(0).place(v(i)); } prog.buffer(0).stream(0).group(0).place(sum); auto ind = Expr::index(0); auto v_ind = v[ind]; for (int i = 0; i < vec_size; i++) { v_ind(i).set(Expr::load_if_pointer(v_ind(i))); TC_P(v_ind(i)->node_type_name()); } auto &adapter = prog.adapter(0); adapter.set(vec_size, 1); for (int i = 0; i < vec_size; i++) { adapter.convert(v_ind(i)); } Expr acc = Expr::create_imm(0.0_f); for (int d = 0; d < vec_size; d++) { acc = acc + v_ind(d); } sum[ind] = acc; prog.materialize_layout(); for (int i = 0; i < n; i++) { for (int j = 0; j < vec_size; j++) { prog.data(v(j), i) = j + i; } } prog(); for (int i = 0; i < n; i++) { auto val = prog.data(sum, i); auto gt = vec_size * (vec_size - 1) / 2 + i * vec_size; if (abs(gt - val) > 1e-5_f) { TC_P(i); TC_P(val); TC_P(gt); TC_ERROR(""); } } } // reduce(vec_a<n> - vec_b<n>) * vec_c<2n> void test_adapter3(int vec_size) { Vector a(vec_size), b(vec_size), c(vec_size * 2); Float sum; int n = 64; Program prog(Arch::x86_64, n); prog.config.group_size = vec_size * 2; prog.config.num_groups = 8; for (int i = 0; i < vec_size; i++) { prog.buffer(0).stream(0).group(0).place(a(i)); prog.buffer(1).stream(0).group(0).place(b(i)); } for (int i = 0; i < vec_size * 2; i++) { prog.buffer(2).stream(0).group(0).place(c(i)); } auto ind = Expr::index(0); auto aind = a[ind]; auto bind = b[ind]; auto cind = c[ind]; auto diff = aind.element_wise_prod(aind) - bind.element_wise_prod(bind); { auto &adapter = prog.adapter(0); adapter.set(vec_size, 1); for (int i = 0; i < vec_size; i++) adapter.convert(diff(i)); } Expr acc = Expr::create_imm(0.0_f); for (int d = 0; d < vec_size; d++) { acc = acc + diff(d); } { auto &adapter = prog.adapter(1); adapter.set(1, vec_size * 2); adapter.convert(acc); for (int i = 0; i < vec_size * 2; i++) c(i)[ind] = c(i)[ind] * acc; } prog.materialize_layout(); for (int i = 0; i < n; i++) { for (int j = 0; j < vec_size; j++) { prog.data(a(j), i) = i + j + 1; prog.data(b(j), i) = i + j; } for (int j = 0; j < vec_size * 2; j++) { prog.data(c(j), i) = i - 2 + j; } } prog(); for (int i = 0; i < n; i++) { real s = 0; for (int j = 0; j < vec_size; j++) { s += sqr(i + j + 1) - sqr(i + j); } for (int j = 0; j < vec_size * 2; j++) { auto val = prog.data(c(j), i); auto gt = s * (i - 2 + j); if (abs(gt - val) > 1e-3_f) { TC_P(i); TC_P(j); TC_P(val); TC_P(gt); TC_ERROR(""); } } } } auto test_adapter = []() { test_adapter3(1); test_adapter3(2); test_adapter3(4); test_adapter3(8); test_adapter1(1); test_adapter1(2); test_adapter1(4); test_adapter1(8); test_adapter2(1); test_adapter2(2); test_adapter2(4); test_adapter2(8); }; // TODO: random access TC_REGISTER_TASK(test_adapter); /* #define For(i, range) \ { \ Index i; for_loop(i, range, [&](Index i) #define End ) */ TC_NAMESPACE_END<|endoftext|>
<commit_before>#include <sys/wait.h> #include <stdlib.h> #include <signal.h> #include <stdio.h> #include <unistd.h> #include "test_common.h" int main() { printf("Starting scout\n"); pid_t scout_pid = fork(); switch (scout_pid) { case -1: perror("fork"); exit(1); case 0: if (execlp("conn_scout", "conn_scout", "socket_control", "rmnet0", "12500", "100", "tiwlan0", "125000", "1", NULL) < 0) { perror("execlp"); exit(1); } } sleep(1); pid_t test_pid = fork(); switch (test_pid) { case -1: perror("fork"); exit(1); case 0: if (execlp("fake_intnw_test", "fake_intnw_test", "-h", "141.212.110.132", NULL) < 0) { perror("execlp"); exit(1); } } int status = -1; if (waitpid(test_pid, &status, 0) != test_pid) { perror("test waitpid"); exit(1); } if (WEXITSTATUS(status) != 0) { printf("Tests failed?\n"); } else { printf("Tests passed.\n"); } kill(scout_pid, SIGINT); if (waitpid(scout_pid, NULL, 0) != scout_pid) { perror("scout waitpid"); exit(1); } return 0; } <commit_msg>Update wifi iface name for nexus one.<commit_after>#include <sys/wait.h> #include <stdlib.h> #include <signal.h> #include <stdio.h> #include <unistd.h> #include "test_common.h" int main() { printf("Starting scout\n"); pid_t scout_pid = fork(); switch (scout_pid) { case -1: perror("fork"); exit(1); case 0: if (execlp("conn_scout", "conn_scout", "socket_control", "rmnet0", "12500", "100", "eth0", "125000", "1", NULL) < 0) { perror("execlp"); exit(1); } } sleep(1); pid_t test_pid = fork(); switch (test_pid) { case -1: perror("fork"); exit(1); case 0: if (execlp("fake_intnw_test", "fake_intnw_test", "-h", "141.212.110.132", NULL) < 0) { perror("execlp"); exit(1); } } int status = -1; if (waitpid(test_pid, &status, 0) != test_pid) { perror("test waitpid"); exit(1); } if (WEXITSTATUS(status) != 0) { printf("Tests failed?\n"); } else { printf("Tests passed.\n"); } kill(scout_pid, SIGINT); if (waitpid(scout_pid, NULL, 0) != scout_pid) { perror("scout waitpid"); exit(1); } return 0; } <|endoftext|>
<commit_before>#include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <fstream> #include <boost/format.hpp> #include <object/file.hh> #include <object/output-stream.hh> #include <object/symbols.hh> #include <runner/raise.hh> namespace object { OutputStream::OutputStream(int fd, bool own) : fd_(fd) , own_(own) { proto_add(proto ? proto : Object::proto); } OutputStream::OutputStream(rOutputStream model) : fd_(model->fd_) , own_(false) { proto_add(proto); } OutputStream::~OutputStream() { if (own_ && fd_ != -1) if (::close(fd_)) RAISE(libport::strerror(errno)); } void OutputStream::checkFD_() const { if (fd_ == -1) RAISE("Stream is closed"); } /*-------------. | Urbi methods | `-------------*/ void OutputStream::init(rFile f) { libport::path path = f->value_get()->value_get(); fd_ = open(path.to_string().c_str(), O_WRONLY | O_APPEND | O_CREAT, S_IRWXU); if (fd_ < 0) { boost::format fmt("Unable to open file for writing: %s"); fd_ = 0; RAISE(str(fmt % path)); } own_ = true; } rOutputStream OutputStream::putByte(unsigned char c) { checkFD_(); // FIXME: bufferize size_t size = write(fd_, &c, 1); assert_eq(size, 1); (void)size; return this; } void OutputStream::flush() { checkFD_(); // FIXME: nothing since not bufferized for now } rOutputStream OutputStream::put(rObject o) { checkFD_(); std::string str = o->call(SYMBOL(asString))->as<String>()->value_get(); size_t str_size = str.size(); size_t size = write(fd_, str.c_str(), str_size); assert_eq(size, str_size); (void)size; return this; } void OutputStream::close() { checkFD_(); if (::close(fd_)) RAISE(libport::strerror(errno)); fd_ = -1; } /*--------------. | Urbi bindings | `--------------*/ rObject OutputStream::proto_make() { return new OutputStream(STDOUT_FILENO, false); } void OutputStream::initialize(object::CxxObject::Binder<object::OutputStream>& bind) { bind(SYMBOL(LT_LT), &OutputStream::put ); bind(SYMBOL(close), &OutputStream::close ); bind(SYMBOL(flush), &OutputStream::flush ); bind(SYMBOL(init), &OutputStream::init ); bind(SYMBOL(put), &OutputStream::putByte); } URBI_CXX_OBJECT_REGISTER(OutputStream); } <commit_msg>build: fix warning.<commit_after>#include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <fstream> #include <boost/format.hpp> #include <object/file.hh> #include <object/output-stream.hh> #include <object/symbols.hh> #include <runner/raise.hh> namespace object { OutputStream::OutputStream(int fd, bool own) : fd_(fd) , own_(own) { proto_add(proto ? proto : Object::proto); } OutputStream::OutputStream(rOutputStream model) : fd_(model->fd_) , own_(false) { proto_add(proto); } OutputStream::~OutputStream() { if (own_ && fd_ != -1) if (::close(fd_)) RAISE(libport::strerror(errno)); } void OutputStream::checkFD_() const { if (fd_ == -1) RAISE("Stream is closed"); } /*-------------. | Urbi methods | `-------------*/ void OutputStream::init(rFile f) { libport::path path = f->value_get()->value_get(); fd_ = open(path.to_string().c_str(), O_WRONLY | O_APPEND | O_CREAT, S_IRWXU); if (fd_ < 0) { boost::format fmt("Unable to open file for writing: %s"); fd_ = 0; RAISE(str(fmt % path)); } own_ = true; } rOutputStream OutputStream::putByte(unsigned char c) { checkFD_(); // FIXME: bufferize size_t size = write(fd_, &c, 1); assert_eq(size, 1u); (void)size; return this; } void OutputStream::flush() { checkFD_(); // FIXME: nothing since not bufferized for now } rOutputStream OutputStream::put(rObject o) { checkFD_(); std::string str = o->call(SYMBOL(asString))->as<String>()->value_get(); size_t str_size = str.size(); size_t size = write(fd_, str.c_str(), str_size); assert_eq(size, str_size); (void)size; return this; } void OutputStream::close() { checkFD_(); if (::close(fd_)) RAISE(libport::strerror(errno)); fd_ = -1; } /*--------------. | Urbi bindings | `--------------*/ rObject OutputStream::proto_make() { return new OutputStream(STDOUT_FILENO, false); } void OutputStream::initialize(object::CxxObject::Binder<object::OutputStream>& bind) { bind(SYMBOL(LT_LT), &OutputStream::put ); bind(SYMBOL(close), &OutputStream::close ); bind(SYMBOL(flush), &OutputStream::flush ); bind(SYMBOL(init), &OutputStream::init ); bind(SYMBOL(put), &OutputStream::putByte); } URBI_CXX_OBJECT_REGISTER(OutputStream); } <|endoftext|>
<commit_before><commit_msg>Remove unused include.<commit_after><|endoftext|>
<commit_before>#include "newcertificatewizard.h" #include "ui_chooseprotocolpage.h" #include "ui_enterdetailspage.h" #include "ui_overviewpage.h" #include "ui_resultpage.h" #include <kleo/dn.h> #include <KConfigGroup> #include <KGlobal> #include <KLocale> #include <KDebug> #include <QRegExpValidator> #include <QLineEdit> using namespace Kleo; using namespace Kleo::NewCertificateUi; namespace { class ChooseProtocolPage : public QWizardPage { Q_OBJECT public: explicit ChooseProtocolPage( QWidget * p=0 ) : QWizardPage( p ), initialized( false ), ui() { ui.setupUi( this ); connect( ui.pgpCLB, SIGNAL(clicked()), wizard(), SLOT(next()), Qt::QueuedConnection ); connect( ui.x509CLB, SIGNAL(clicked()), wizard(), SLOT(next()), Qt::QueuedConnection ); registerField( "pgp", ui.pgpCLB ); } /* reimp */ void initializePage() { if ( !initialized ) { connect( ui.pgpCLB, SIGNAL(clicked()), wizard(), SLOT(next()), Qt::QueuedConnection ); connect( ui.x509CLB, SIGNAL(clicked()), wizard(), SLOT(next()), Qt::QueuedConnection ); } initialized = true; } /* reimp */ bool isComplete() const { return ui.pgpCLB->isChecked() || ui.x509CLB->isChecked() ; } private: bool initialized : 1; Ui_ChooseProtocolPage ui; }; class EnterDetailsPage : public QWizardPage { Q_OBJECT public: explicit EnterDetailsPage( QWidget * p=0 ) : QWizardPage( p ), ui() { ui.setupUi( this ); updateForm(); } /* reimp */ bool isComplete() const; /* reimp */ void initializePage() { updateForm(); } /* reimp */ void cleanupPage() { savedValues.clear(); for ( QVector< QPair<QString,QLineEdit*> >::const_iterator it = attributePairList.begin(), end = attributePairList.end() ; it != end ; ++it ) savedValues[it->first] = it->second->text().trimmed(); } private: void updateForm(); void clearForm(); private: QVector< QPair<QString,QLineEdit*> > attributePairList; QList<QWidget*> dynamicWidgets; QMap<QString,QString> savedValues; Ui_EnterDetailsPage ui; }; class OverviewPage : public QWizardPage { Q_OBJECT public: explicit OverviewPage( QWidget * p=0 ) : QWizardPage( p ), ui() { setCommitPage( true ); setButtonText( QWizard::CommitButton, i18nc("@action", "Create") ); } private: Ui_OverviewPage ui; }; class ResultPage : public QWizardPage { Q_OBJECT public: explicit ResultPage( QWidget * p=0 ) : QWizardPage( p ), ui() { } private: Ui_ResultPage ui; }; } class NewCertificateWizard::Private { friend class ::Kleo::NewCertificateWizard; NewCertificateWizard * const q; public: explicit Private( NewCertificateWizard * qq ) : q( qq ), ui( q ) { } private: struct Ui { ChooseProtocolPage chooseProtocolPage; EnterDetailsPage enterDetailsPage; OverviewPage overviewPage; ResultPage resultPage; explicit Ui( NewCertificateWizard * q ) : chooseProtocolPage( q ), enterDetailsPage( q ), overviewPage( q ), resultPage( q ) { q->setPage( ChooseProtocolPageId, &chooseProtocolPage ); q->setPage( EnterDetailsPageId, &enterDetailsPage ); q->setPage( OverviewPageId, &overviewPage ); q->setPage( ResultPageId, &resultPage ); q->setStartId( ChooseProtocolPageId ); } } ui; }; NewCertificateWizard::NewCertificateWizard( QWidget * p ) : QWizard( p ), d( new Private( this ) ) { } NewCertificateWizard::~NewCertificateWizard() {} static QString pgpLabel( const QString & attr ) { if ( attr == "NAME" ) return i18n("Name"); if ( attr == "COMMENT" ) return i18n("Comment"); if ( attr == "EMAIL" ) return i18n("EMail"); return QString(); } static QString attributeLabel( const QString & attr, bool required, bool pgp ) { if ( attr.isEmpty() ) return QString(); const QString label = pgp ? pgpLabel( attr ) : Kleo::DNAttributeMapper::instance()->name2label( attr ) ; if ( !label.isEmpty() ) if ( pgp ) return label + ':'; else return i18nc("Format string for the labels in the \"Your Personal Data\" page", "%1 (%2):", label, attr ); else return attr + ':'; } static QString attributeFromKey( QString key ) { return key.remove( '!' ); } namespace { class LineEdit : public QWidget { Q_OBJECT public: explicit LineEdit( const QString & text, bool required, QWidget * parent ) : QWidget( parent ), lineEdit( text, this ), label( required ? i18n("(required)") : i18n("(optional)"), this ), layout( this ) { KDAB_SET_OBJECT_NAME( lineEdit ); KDAB_SET_OBJECT_NAME( label ); KDAB_SET_OBJECT_NAME( layout ); layout.addWidget( &lineEdit ); layout.addWidget( &label ); } public: QLineEdit lineEdit; QLabel label; QHBoxLayout layout; }; } void EnterDetailsPage::updateForm() { clearForm(); const KConfigGroup config( KGlobal::config(), "CertificateCreationWizard" ); const bool pgp = field("pgp").toBool(); QStringList attrOrder = config.readEntry( pgp ? "OpenPGPAttributeOrder" : "DNAttributeOrder", QStringList() ); if ( attrOrder.empty() ) if ( pgp ) attrOrder << "NAME!" << "EMAIL!" << "COMMENT"; else attrOrder << "CN!" << "L" << "OU" << "O!" << "C!" << "EMAIL!"; Q_FOREACH( const QString & rawKey, attrOrder ) { const QString key = rawKey.trimmed().toUpper(); const QString attr = attributeFromKey( key ); if ( attr.isEmpty() ) continue; const QString preset = savedValues.value( attr, config.readEntry( attr, QString() ) ); const bool required = key.endsWith( QLatin1Char('!') ); const QString label = config.readEntry( attr + "_label", attributeLabel( attr, required, pgp ) ); LineEdit * const le = new LineEdit( preset, required, ui.formLayout->parentWidget() ); ui.formLayout->addRow( label, le ); if ( config.isEntryImmutable( attr ) ) le->lineEdit.setEnabled( false ); QString regex = config.readEntry( attr + "_regex" ); if ( regex.isEmpty() ) regex = "[^\\s].*"; // !empty le->lineEdit.setValidator( new QRegExpValidator( QRegExp( regex ), le ) ); attributePairList.append( qMakePair(key, &le->lineEdit) ); connect( &le->lineEdit, SIGNAL(textChanged(QString)), SIGNAL(completeChanged()) ); dynamicWidgets.push_back( ui.formLayout->labelForField( le ) ); dynamicWidgets.push_back( le ); } } void EnterDetailsPage::clearForm() { qDeleteAll( dynamicWidgets ); dynamicWidgets.clear(); attributePairList.clear(); } static bool requirementsAreMet( const QVector< QPair<QString,QLineEdit*> > & list ) { for ( QVector< QPair<QString,QLineEdit*> >::const_iterator it = list.begin() ; it != list.end() ; ++it ) { const QLineEdit * le = (*it).second; if ( !le ) continue; const QString key = (*it).first; kDebug() << "requirementsAreMet(): checking \"" << key << "\" against \"" << le->text() << "\":"; if ( key.endsWith('!') && !le->hasAcceptableInput() ) { kDebug() << "required field has non-acceptable input!"; return false; } kDebug() << "ok" << endl; } return true; } namespace { bool EnterDetailsPage::isComplete() const { return requirementsAreMet( attributePairList ); } } #include "moc_newcertificatewizard.cpp" #include "newcertificatewizard.moc" <commit_msg>Fix required fields forgetting their value on Back<commit_after>#include "newcertificatewizard.h" #include "ui_chooseprotocolpage.h" #include "ui_enterdetailspage.h" #include "ui_overviewpage.h" #include "ui_resultpage.h" #include <kleo/dn.h> #include <KConfigGroup> #include <KGlobal> #include <KLocale> #include <KDebug> #include <QRegExpValidator> #include <QLineEdit> using namespace Kleo; using namespace Kleo::NewCertificateUi; namespace { class ChooseProtocolPage : public QWizardPage { Q_OBJECT public: explicit ChooseProtocolPage( QWidget * p=0 ) : QWizardPage( p ), initialized( false ), ui() { ui.setupUi( this ); connect( ui.pgpCLB, SIGNAL(clicked()), wizard(), SLOT(next()), Qt::QueuedConnection ); connect( ui.x509CLB, SIGNAL(clicked()), wizard(), SLOT(next()), Qt::QueuedConnection ); registerField( "pgp", ui.pgpCLB ); } /* reimp */ void initializePage() { if ( !initialized ) { connect( ui.pgpCLB, SIGNAL(clicked()), wizard(), SLOT(next()), Qt::QueuedConnection ); connect( ui.x509CLB, SIGNAL(clicked()), wizard(), SLOT(next()), Qt::QueuedConnection ); } initialized = true; } /* reimp */ bool isComplete() const { return ui.pgpCLB->isChecked() || ui.x509CLB->isChecked() ; } private: bool initialized : 1; Ui_ChooseProtocolPage ui; }; class EnterDetailsPage : public QWizardPage { Q_OBJECT public: explicit EnterDetailsPage( QWidget * p=0 ) : QWizardPage( p ), ui() { ui.setupUi( this ); updateForm(); } /* reimp */ bool isComplete() const; /* reimp */ void initializePage() { updateForm(); } /* reimp */ void cleanupPage() { savedValues.clear(); for ( QVector< QPair<QString,QLineEdit*> >::const_iterator it = attributePairList.begin(), end = attributePairList.end() ; it != end ; ++it ) savedValues[it->first] = it->second->text().trimmed(); } private: void updateForm(); void clearForm(); private: QVector< QPair<QString,QLineEdit*> > attributePairList; QList<QWidget*> dynamicWidgets; QMap<QString,QString> savedValues; Ui_EnterDetailsPage ui; }; class OverviewPage : public QWizardPage { Q_OBJECT public: explicit OverviewPage( QWidget * p=0 ) : QWizardPage( p ), ui() { setCommitPage( true ); setButtonText( QWizard::CommitButton, i18nc("@action", "Create") ); } private: Ui_OverviewPage ui; }; class ResultPage : public QWizardPage { Q_OBJECT public: explicit ResultPage( QWidget * p=0 ) : QWizardPage( p ), ui() { } private: Ui_ResultPage ui; }; } class NewCertificateWizard::Private { friend class ::Kleo::NewCertificateWizard; NewCertificateWizard * const q; public: explicit Private( NewCertificateWizard * qq ) : q( qq ), ui( q ) { } private: struct Ui { ChooseProtocolPage chooseProtocolPage; EnterDetailsPage enterDetailsPage; OverviewPage overviewPage; ResultPage resultPage; explicit Ui( NewCertificateWizard * q ) : chooseProtocolPage( q ), enterDetailsPage( q ), overviewPage( q ), resultPage( q ) { q->setPage( ChooseProtocolPageId, &chooseProtocolPage ); q->setPage( EnterDetailsPageId, &enterDetailsPage ); q->setPage( OverviewPageId, &overviewPage ); q->setPage( ResultPageId, &resultPage ); q->setStartId( ChooseProtocolPageId ); } } ui; }; NewCertificateWizard::NewCertificateWizard( QWidget * p ) : QWizard( p ), d( new Private( this ) ) { } NewCertificateWizard::~NewCertificateWizard() {} static QString pgpLabel( const QString & attr ) { if ( attr == "NAME" ) return i18n("Name"); if ( attr == "COMMENT" ) return i18n("Comment"); if ( attr == "EMAIL" ) return i18n("EMail"); return QString(); } static QString attributeLabel( const QString & attr, bool required, bool pgp ) { if ( attr.isEmpty() ) return QString(); const QString label = pgp ? pgpLabel( attr ) : Kleo::DNAttributeMapper::instance()->name2label( attr ) ; if ( !label.isEmpty() ) if ( pgp ) return label + ':'; else return i18nc("Format string for the labels in the \"Your Personal Data\" page", "%1 (%2):", label, attr ); else return attr + ':'; } static QString attributeFromKey( QString key ) { return key.remove( '!' ); } namespace { class LineEdit : public QWidget { Q_OBJECT public: explicit LineEdit( const QString & text, bool required, QWidget * parent ) : QWidget( parent ), lineEdit( text, this ), label( required ? i18n("(required)") : i18n("(optional)"), this ), layout( this ) { KDAB_SET_OBJECT_NAME( lineEdit ); KDAB_SET_OBJECT_NAME( label ); KDAB_SET_OBJECT_NAME( layout ); layout.addWidget( &lineEdit ); layout.addWidget( &label ); } public: QLineEdit lineEdit; QLabel label; QHBoxLayout layout; }; } void EnterDetailsPage::updateForm() { clearForm(); const KConfigGroup config( KGlobal::config(), "CertificateCreationWizard" ); const bool pgp = field("pgp").toBool(); QStringList attrOrder = config.readEntry( pgp ? "OpenPGPAttributeOrder" : "DNAttributeOrder", QStringList() ); if ( attrOrder.empty() ) if ( pgp ) attrOrder << "NAME!" << "EMAIL!" << "COMMENT"; else attrOrder << "CN!" << "L" << "OU" << "O!" << "C!" << "EMAIL!"; Q_FOREACH( const QString & rawKey, attrOrder ) { const QString key = rawKey.trimmed().toUpper(); const QString attr = attributeFromKey( key ); if ( attr.isEmpty() ) continue; const QString preset = savedValues.value( key, config.readEntry( attr, QString() ) ); const bool required = key.endsWith( QLatin1Char('!') ); const QString label = config.readEntry( attr + "_label", attributeLabel( attr, required, pgp ) ); LineEdit * const le = new LineEdit( preset, required, ui.formLayout->parentWidget() ); ui.formLayout->addRow( label, le ); if ( config.isEntryImmutable( attr ) ) le->lineEdit.setEnabled( false ); QString regex = config.readEntry( attr + "_regex" ); if ( regex.isEmpty() ) regex = "[^\\s].*"; // !empty le->lineEdit.setValidator( new QRegExpValidator( QRegExp( regex ), le ) ); attributePairList.append( qMakePair(key, &le->lineEdit) ); connect( &le->lineEdit, SIGNAL(textChanged(QString)), SIGNAL(completeChanged()) ); dynamicWidgets.push_back( ui.formLayout->labelForField( le ) ); dynamicWidgets.push_back( le ); } } void EnterDetailsPage::clearForm() { qDeleteAll( dynamicWidgets ); dynamicWidgets.clear(); attributePairList.clear(); } static bool requirementsAreMet( const QVector< QPair<QString,QLineEdit*> > & list ) { for ( QVector< QPair<QString,QLineEdit*> >::const_iterator it = list.begin() ; it != list.end() ; ++it ) { const QLineEdit * le = (*it).second; if ( !le ) continue; const QString key = (*it).first; kDebug() << "requirementsAreMet(): checking \"" << key << "\" against \"" << le->text() << "\":"; if ( key.endsWith('!') && !le->hasAcceptableInput() ) { kDebug() << "required field has non-acceptable input!"; return false; } kDebug() << "ok" << endl; } return true; } namespace { bool EnterDetailsPage::isComplete() const { return requirementsAreMet( attributePairList ); } } #include "moc_newcertificatewizard.cpp" #include "newcertificatewizard.moc" <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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 software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.2 2002/02/20 18:17:01 tng * [Bug 5977] Warnings on generating apiDocs. * * Revision 1.1.1.1 2002/02/01 22:22:08 peiyongz * sane_include * * Revision 1.10 2001/11/21 16:14:32 tng * Schema: New method InputSource::get/setIssueFatalErrorIfNotFound to tell the parser whether to issue fatal error or not if cannot find it (the InputSource). This is required for schema processing as it shouldn't be a fatal error if the schema is not found. * * Revision 1.9 2000/03/02 19:54:35 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.8 2000/02/24 20:12:55 abagchi * Swat for removing Log from API docs * * Revision 1.7 2000/02/12 03:42:21 rahulj * Fixed DOC++ documentation formatting errors. * * Revision 1.6 2000/02/12 03:31:55 rahulj * Removed duplicate CVS Log entries. * * Revision 1.5 2000/02/12 01:27:19 aruna1 * Documentation updated * * Revision 1.4 2000/02/09 02:15:28 abagchi * Documented destructor * * Revision 1.3 2000/02/06 07:47:58 rahulj * Year 2K copyright swat. * * Revision 1.2 2000/01/12 00:15:39 roddey * Changes to deal with multiply nested, relative pathed, entities and to deal * with the new URL class changes. * * Revision 1.1.1.1 1999/11/09 01:07:46 twl * Initial checkin * * Revision 1.2 1999/11/08 20:45:01 rahul * Swat for adding in Product name and CVS comment log variable. * */ #ifndef INPUTSOURCE_HPP #define INPUTSOURCE_HPP #include <xercesc/util/XercesDefs.hpp> class BinInputStream; /** * A single input source for an XML entity. * * <p>This class encapsulates information about an input source in a * single object, which may include a public identifier or a system * identifier</p> * * <p>There are two places that the application will deliver this input * source to the parser: as the argument to the Parser::parse method, or as * the return value of the EntityResolver::resolveEntity method.</p> * * <p>InputSource is never used directly, but is the base class for a number * of derived classes for particular types of input sources. Derivatives are * provided (in the internal/ directory) for URL input sources, memory buffer * input sources, and so on.</p> * * <p>When it is time to parse the input described by an input source, it * will be asked to create a binary stream for that source. That stream will * be used to input the data of the source. The derived class provides the * implementation of the makeStream() method, and provides a type of stream * of the correct type for the input source it represents. * * <p>An InputSource object belongs to the application: the parser never * modifies them in any way. They are always passed by const reference so * the parser will make a copy of any input sources that it must keep * around beyond the call.</p> * * @see Parser#parse * @see EntityResolver#resolveEntity */ class SAX_EXPORT InputSource { public: // ----------------------------------------------------------------------- // All constructors are hidden, just the destructor is available // ----------------------------------------------------------------------- /** @name Destructor */ //@{ /** * Destructor * */ virtual ~InputSource(); //@} // ----------------------------------------------------------------------- /** @name Virtual input source interface */ //@{ /** * Makes the byte stream for this input source. * * <p>The derived class must create and return a binary input stream of an * appropriate type for its kind of data source. The returned stream must * be dynamically allocated and becomes the parser's property. * </p> * * @see BinInputStream */ virtual BinInputStream* makeStream() const = 0; //@} // ----------------------------------------------------------------------- /** @name Getter methods */ //@{ /** * An input source can be set to force the parser to assume a particular * encoding for the data that input source reprsents, via the setEncoding() * method. This method returns name of the encoding that is to be forced. * If the encoding has never been forced, it returns a null pointer. * * @return The forced encoding, or null if none was supplied. * @see #setEncoding */ const XMLCh* getEncoding() const; /** * Get the public identifier for this input source. * * @return The public identifier, or null if none was supplied. * @see #setPublicId */ const XMLCh* getPublicId() const; /** * Get the system identifier for this input source. * * <p>If the system ID is a URL, it will be fully resolved.</p> * * @return The system identifier. * @see #setSystemId */ const XMLCh* getSystemId() const; /** * Get the flag that indicates if the parser should issue fatal error if this input source * is not found. * * @return True if the parser should issue fatal error if this input source is not found. * False if the parser issue warning message instead. * @see #setIssueFatalErrorIfNotFound */ const bool getIssueFatalErrorIfNotFound() const; //@} // ----------------------------------------------------------------------- /** @name Setter methods */ //@{ /** * Set the encoding which will be required for use with the XML text read * via a stream opened by this input source. * * <p>This is usually not set, allowing the encoding to be sensed in the * usual XML way. However, in some cases, the encoding in the file is known * to be incorrect because of intermediate transcoding, for instance * encapsulation within a MIME document. * * @param encodingStr The name of the encoding to force. */ void setEncoding(const XMLCh* const encodingStr); /** * Set the public identifier for this input source. * * <p>The public identifier is always optional: if the application writer * includes one, it will be provided as part of the location information.</p> * * @param publicId The public identifier as a string. * @see Locator#getPublicId * @see SAXParseException#getPublicId * @see #getPublicId */ void setPublicId(const XMLCh* const publicId); /** * Set the system identifier for this input source. * * <p>Set the system identifier for this input source. * * </p>The system id is always required. The public id may be used to map * to another system id, but the system id must always be present as a fall * back. * * <p>If the system ID is a URL, it must be fully resolved.</p> * * @param systemId The system identifier as a string. * @see #getSystemId * @see Locator#getSystemId * @see SAXParseException#getSystemId */ void setSystemId(const XMLCh* const systemId); /** * Indicates if the parser should issue fatal error if this input source * is not found. If set to false, the parser issue warning message instead. * * @param flag True if the parser should issue fatal error if this input source is not found. * If set to false, the parser issue warning message instead. (Default: true) * * @see #getIssueFatalErrorIfNotFound */ void setIssueFatalErrorIfNotFound(const bool flag); //@} protected : // ----------------------------------------------------------------------- // Hidden constructors // ----------------------------------------------------------------------- /** @name Constructors and Destructor */ //@{ /** Default constructor */ InputSource(); /** Constructor with a system identifier as XMLCh type. * @param systemId The system identifier (URI). */ InputSource(const XMLCh* const systemId); /** Constructor with a system and public identifiers * @param systemId The system identifier (URI). * @param publicId The public identifier as in the entity definition. */ InputSource ( const XMLCh* const systemId , const XMLCh* const publicId ); /** Constructor witha system identifier as string * @param systemId The system identifier (URI). */ InputSource(const char* const systemId); /** Constructor witha system and public identifiers. Both as string * @param systemId The system identifier (URI). * @param publicId The public identifier as in the entity definition. */ InputSource ( const char* const systemId , const char* const publicId ); //@} private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- InputSource(const InputSource&); void operator=(const InputSource&); // ----------------------------------------------------------------------- // Private data members // // fEncoding // This is the encoding to use. Usually this is null, which means // to use the information found in the file itself. But, if set, // this encoding will be used without question. // // fPublicId // This is the optional public id for the input source. It can be // null if none is desired. // // fSystemId // This is the system id for the input source. This is what is // actually used to open the source. // // fFatalErrorIfNotFound // ----------------------------------------------------------------------- XMLCh* fEncoding; XMLCh* fPublicId; XMLCh* fSystemId; bool fFatalErrorIfNotFound; }; // --------------------------------------------------------------------------- // InputSource: Getter methods // --------------------------------------------------------------------------- inline const XMLCh* InputSource::getEncoding() const { return fEncoding; } inline const XMLCh* InputSource::getPublicId() const { return fPublicId; } inline const XMLCh* InputSource::getSystemId() const { return fSystemId; } inline const bool InputSource::getIssueFatalErrorIfNotFound() const { return fFatalErrorIfNotFound; } // --------------------------------------------------------------------------- // InputSource: Setter methods // --------------------------------------------------------------------------- inline void InputSource::setIssueFatalErrorIfNotFound(const bool flag) { fFatalErrorIfNotFound = flag; } #endif <commit_msg>Since the derived class Wrapper4DOMInputSource has overwritten the set/getEncoding, SystemId, PublicId ... etc., these functions has to be virtual for them to work.<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software 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. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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 software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.3 2002/09/30 18:26:18 tng * Since the derived class Wrapper4DOMInputSource has overwritten the set/getEncoding, SystemId, PublicId ... etc., these functions has to be virtual for them to work. * * Revision 1.2 2002/02/20 18:17:01 tng * [Bug 5977] Warnings on generating apiDocs. * * Revision 1.1.1.1 2002/02/01 22:22:08 peiyongz * sane_include * * Revision 1.10 2001/11/21 16:14:32 tng * Schema: New method InputSource::get/setIssueFatalErrorIfNotFound to tell the parser whether to issue fatal error or not if cannot find it (the InputSource). This is required for schema processing as it shouldn't be a fatal error if the schema is not found. * * Revision 1.9 2000/03/02 19:54:35 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.8 2000/02/24 20:12:55 abagchi * Swat for removing Log from API docs * * Revision 1.7 2000/02/12 03:42:21 rahulj * Fixed DOC++ documentation formatting errors. * * Revision 1.6 2000/02/12 03:31:55 rahulj * Removed duplicate CVS Log entries. * * Revision 1.5 2000/02/12 01:27:19 aruna1 * Documentation updated * * Revision 1.4 2000/02/09 02:15:28 abagchi * Documented destructor * * Revision 1.3 2000/02/06 07:47:58 rahulj * Year 2K copyright swat. * * Revision 1.2 2000/01/12 00:15:39 roddey * Changes to deal with multiply nested, relative pathed, entities and to deal * with the new URL class changes. * * Revision 1.1.1.1 1999/11/09 01:07:46 twl * Initial checkin * * Revision 1.2 1999/11/08 20:45:01 rahul * Swat for adding in Product name and CVS comment log variable. * */ #ifndef INPUTSOURCE_HPP #define INPUTSOURCE_HPP #include <xercesc/util/XercesDefs.hpp> class BinInputStream; /** * A single input source for an XML entity. * * <p>This class encapsulates information about an input source in a * single object, which may include a public identifier or a system * identifier</p> * * <p>There are two places that the application will deliver this input * source to the parser: as the argument to the Parser::parse method, or as * the return value of the EntityResolver::resolveEntity method.</p> * * <p>InputSource is never used directly, but is the base class for a number * of derived classes for particular types of input sources. Derivatives are * provided (in the internal/ directory) for URL input sources, memory buffer * input sources, and so on.</p> * * <p>When it is time to parse the input described by an input source, it * will be asked to create a binary stream for that source. That stream will * be used to input the data of the source. The derived class provides the * implementation of the makeStream() method, and provides a type of stream * of the correct type for the input source it represents. * * <p>An InputSource object belongs to the application: the parser never * modifies them in any way. They are always passed by const reference so * the parser will make a copy of any input sources that it must keep * around beyond the call.</p> * * @see Parser#parse * @see EntityResolver#resolveEntity */ class SAX_EXPORT InputSource { public: // ----------------------------------------------------------------------- // All constructors are hidden, just the destructor is available // ----------------------------------------------------------------------- /** @name Destructor */ //@{ /** * Destructor * */ virtual ~InputSource(); //@} // ----------------------------------------------------------------------- /** @name Virtual input source interface */ //@{ /** * Makes the byte stream for this input source. * * <p>The derived class must create and return a binary input stream of an * appropriate type for its kind of data source. The returned stream must * be dynamically allocated and becomes the parser's property. * </p> * * @see BinInputStream */ virtual BinInputStream* makeStream() const = 0; //@} // ----------------------------------------------------------------------- /** @name Getter methods */ //@{ /** * An input source can be set to force the parser to assume a particular * encoding for the data that input source reprsents, via the setEncoding() * method. This method returns name of the encoding that is to be forced. * If the encoding has never been forced, it returns a null pointer. * * @return The forced encoding, or null if none was supplied. * @see #setEncoding */ virtual const XMLCh* getEncoding() const; /** * Get the public identifier for this input source. * * @return The public identifier, or null if none was supplied. * @see #setPublicId */ virtual const XMLCh* getPublicId() const; /** * Get the system identifier for this input source. * * <p>If the system ID is a URL, it will be fully resolved.</p> * * @return The system identifier. * @see #setSystemId */ virtual const XMLCh* getSystemId() const; /** * Get the flag that indicates if the parser should issue fatal error if this input source * is not found. * * @return True if the parser should issue fatal error if this input source is not found. * False if the parser issue warning message instead. * @see #setIssueFatalErrorIfNotFound */ virtual const bool getIssueFatalErrorIfNotFound() const; //@} // ----------------------------------------------------------------------- /** @name Setter methods */ //@{ /** * Set the encoding which will be required for use with the XML text read * via a stream opened by this input source. * * <p>This is usually not set, allowing the encoding to be sensed in the * usual XML way. However, in some cases, the encoding in the file is known * to be incorrect because of intermediate transcoding, for instance * encapsulation within a MIME document. * * @param encodingStr The name of the encoding to force. */ virtual void setEncoding(const XMLCh* const encodingStr); /** * Set the public identifier for this input source. * * <p>The public identifier is always optional: if the application writer * includes one, it will be provided as part of the location information.</p> * * @param publicId The public identifier as a string. * @see Locator#getPublicId * @see SAXParseException#getPublicId * @see #getPublicId */ virtual void setPublicId(const XMLCh* const publicId); /** * Set the system identifier for this input source. * * <p>Set the system identifier for this input source. * * </p>The system id is always required. The public id may be used to map * to another system id, but the system id must always be present as a fall * back. * * <p>If the system ID is a URL, it must be fully resolved.</p> * * @param systemId The system identifier as a string. * @see #getSystemId * @see Locator#getSystemId * @see SAXParseException#getSystemId */ virtual void setSystemId(const XMLCh* const systemId); /** * Indicates if the parser should issue fatal error if this input source * is not found. If set to false, the parser issue warning message instead. * * @param flag True if the parser should issue fatal error if this input source is not found. * If set to false, the parser issue warning message instead. (Default: true) * * @see #getIssueFatalErrorIfNotFound */ virtual void setIssueFatalErrorIfNotFound(const bool flag); //@} protected : // ----------------------------------------------------------------------- // Hidden constructors // ----------------------------------------------------------------------- /** @name Constructors and Destructor */ //@{ /** Default constructor */ InputSource(); /** Constructor with a system identifier as XMLCh type. * @param systemId The system identifier (URI). */ InputSource(const XMLCh* const systemId); /** Constructor with a system and public identifiers * @param systemId The system identifier (URI). * @param publicId The public identifier as in the entity definition. */ InputSource ( const XMLCh* const systemId , const XMLCh* const publicId ); /** Constructor witha system identifier as string * @param systemId The system identifier (URI). */ InputSource(const char* const systemId); /** Constructor witha system and public identifiers. Both as string * @param systemId The system identifier (URI). * @param publicId The public identifier as in the entity definition. */ InputSource ( const char* const systemId , const char* const publicId ); //@} private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- InputSource(const InputSource&); void operator=(const InputSource&); // ----------------------------------------------------------------------- // Private data members // // fEncoding // This is the encoding to use. Usually this is null, which means // to use the information found in the file itself. But, if set, // this encoding will be used without question. // // fPublicId // This is the optional public id for the input source. It can be // null if none is desired. // // fSystemId // This is the system id for the input source. This is what is // actually used to open the source. // // fFatalErrorIfNotFound // ----------------------------------------------------------------------- XMLCh* fEncoding; XMLCh* fPublicId; XMLCh* fSystemId; bool fFatalErrorIfNotFound; }; // --------------------------------------------------------------------------- // InputSource: Getter methods // --------------------------------------------------------------------------- inline const XMLCh* InputSource::getEncoding() const { return fEncoding; } inline const XMLCh* InputSource::getPublicId() const { return fPublicId; } inline const XMLCh* InputSource::getSystemId() const { return fSystemId; } inline const bool InputSource::getIssueFatalErrorIfNotFound() const { return fFatalErrorIfNotFound; } // --------------------------------------------------------------------------- // InputSource: Setter methods // --------------------------------------------------------------------------- inline void InputSource::setIssueFatalErrorIfNotFound(const bool flag) { fFatalErrorIfNotFound = flag; } #endif <|endoftext|>
<commit_before>/* * This file is part of Peli - universal JSON interaction library * Copyright (C) 2014 Alexey Chernov <[email protected]> * * Peli is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. * */ #include <cassert> #include "peli/json/value.h" using namespace std; using namespace peli; int main(int, char**) { json::value v1(json::make_value<json::object>()); json::object& obj1(v1); obj1["test"] = json::value(52); json::value v2; static_assert(noexcept(json::value() = std::move(v2)), "Move assignment isn't noexcept"); v2 = std::move(v1); json::object& obj2(v2); obj2["tost"] = json::value(false); return 0; } <commit_msg>Fix static assertion of exception safety of move assignment<commit_after>/* * This file is part of Peli - universal JSON interaction library * Copyright (C) 2014 Alexey Chernov <[email protected]> * * Peli is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. * */ #include <cassert> #include "peli/json/value.h" using namespace std; using namespace peli; int main(int, char**) { json::value v1(json::make_value<json::object>()); json::object& obj1(v1); obj1["test"] = json::value(52); json::value v2; static_assert(noexcept(declval<json::value>().operator=(std::move(v2))), "Move assignment isn't noexcept"); v2 = std::move(v1); json::object& obj2(v2); obj2["tost"] = json::value(false); return 0; } <|endoftext|>
<commit_before>#include "VisPlugin.h" #include <cairo/cairo.h> #include <math.h> #define MIN_FREQ 100 #define MAX_FREQ 22050 #define PALETTE_RED {0.196, 0, 1, 1} #define PALETTE_GREEN {0, 0.863, 0.878, 0.274} #define PALETTE_BLUE {0.784, 0.314, 0, 0} #define PALETTE_LENGTH 4 class SpecCent: public VisPlugin { private: // given a list of gradient values, return the value of a point // on that gradient // // e.g. colour={1.0, 0.5, 0.0} // colourmap(0.25, colour, 3) returns 0.75 double colourmap(double value, double colour[], int length) { int iter=0; double step = 1.0/(double)length; if (value>1) return 0; while (value > step*(iter+1)) iter++; double weight = (value-step*(double)iter)/step; return (1.0-weight)*colour[iter] + weight*colour[iter+1]; } double red(double value) { double colours[] = PALETTE_RED; return colourmap(value, colours, PALETTE_LENGTH); } double green(double value) { double colours[] = PALETTE_GREEN; return colourmap(value, colours, PALETTE_LENGTH); } double blue(double value) { double colours[] = PALETTE_BLUE; return colourmap(value, colours, PALETTE_LENGTH); } public: virtual double getVersion() const { return 0.1; } virtual int ARGB(Plugin::FeatureSet features, int width, int height, unsigned char *bitmap) { const double lower = MIN_FREQ; const double higher = MAX_FREQ; const double lower_log = log10(lower); const double higher_log = log10(higher); // set up cairo surface cairo_surface_t *surface; cairo_format_t format = CAIRO_FORMAT_ARGB32; int stride = cairo_format_stride_for_width(format, width); surface = cairo_image_surface_create_for_data (bitmap, format, width, height, stride); // set up cairo context cairo_t *cr; cr = cairo_create(surface); cairo_scale(cr, width, height); cairo_set_source_rgba(cr, 0, 0, 0, 1); cairo_paint(cr); // find number of frames for peak/spec centroid unsigned int peakFrames = features[0].size(); unsigned int scFrames = features[1].size(); double scScale = (double)scFrames/(double)peakFrames; // for each peak frame, draw a coloured line for (unsigned int peakFrame=0; peakFrame<peakFrames; peakFrame++) { // find spectral contrast, clip and scale double sc = features[1].at(floor(scScale*peakFrame)).values[0]; if (sc < lower) sc=lower; if (sc > higher) sc=higher; sc = (log10(sc)-lower_log)/(higher_log-lower_log); // get peak values double peak1 = features[0].at(peakFrame).values[0]; double peak2 = features[0].at(peakFrame).values[1]; // draw waveform cairo_set_source_rgba(cr, red(sc), green(sc), blue(sc), 1.0); cairo_line_to(cr, (double)peakFrame/(double)peakFrames, 0.5-(peak1*0.5)); cairo_line_to(cr, (double)peakFrame/(double)peakFrames, 0.5-(peak2*0.5)); cairo_set_line_width (cr, 1.0/(double)peakFrames); cairo_stroke (cr); } // clean up cairo_destroy(cr); cairo_surface_destroy (surface); return 0; } virtual VampOutputList getVampPlugins() { VampOutputList pluginList; VampPlugin bbcPeaks = {"bbc-vamp-plugins:bbc-peaks", 0, 0}; VampOutput peaks = {bbcPeaks, "peaks"}; VampPlugin libxSpecCent = {"vamp-libxtract:spectral_centroid", 0, 0}; VampOutput specCent = {libxSpecCent, "spectral_centroid"}; pluginList.push_back(peaks); pluginList.push_back(specCent); return pluginList; } }; extern "C" VisPlugin* create() { return new SpecCent; } extern "C" void destroy(VisPlugin* p) { delete p; } <commit_msg>Changed colour to color so as not to confuse the yanks.<commit_after>#include "VisPlugin.h" #include <cairo/cairo.h> #include <math.h> #define MIN_FREQ 100 #define MAX_FREQ 22050 #define PALETTE_RED {0.196, 0, 1, 1} #define PALETTE_GREEN {0, 0.863, 0.878, 0.274} #define PALETTE_BLUE {0.784, 0.314, 0, 0} #define PALETTE_LENGTH 4 class SpecCent: public VisPlugin { private: // given a list of gradient values, return the value of a point // on that gradient // // e.g. color={1.0, 0.5, 0.0} // colormap(0.25, color, 3) returns 0.75 double colormap(double value, double color[], int length) { int iter=0; double step = 1.0/(double)length; if (value>1) return 0; while (value > step*(iter+1)) iter++; double weight = (value-step*(double)iter)/step; return (1.0-weight)*color[iter] + weight*color[iter+1]; } double red(double value) { double colors[] = PALETTE_RED; return colormap(value, colors, PALETTE_LENGTH); } double green(double value) { double colors[] = PALETTE_GREEN; return colormap(value, colors, PALETTE_LENGTH); } double blue(double value) { double colors[] = PALETTE_BLUE; return colormap(value, colors, PALETTE_LENGTH); } public: virtual double getVersion() const { return 0.1; } virtual int ARGB(Plugin::FeatureSet features, int width, int height, unsigned char *bitmap) { const double lower = MIN_FREQ; const double higher = MAX_FREQ; const double lower_log = log10(lower); const double higher_log = log10(higher); // set up cairo surface cairo_surface_t *surface; cairo_format_t format = CAIRO_FORMAT_ARGB32; int stride = cairo_format_stride_for_width(format, width); surface = cairo_image_surface_create_for_data (bitmap, format, width, height, stride); // set up cairo context cairo_t *cr; cr = cairo_create(surface); cairo_scale(cr, width, height); cairo_set_source_rgba(cr, 0, 0, 0, 1); cairo_paint(cr); // find number of frames for peak/spec centroid unsigned int peakFrames = features[0].size(); unsigned int scFrames = features[1].size(); double scScale = (double)scFrames/(double)peakFrames; // for each peak frame, draw a colored line for (unsigned int peakFrame=0; peakFrame<peakFrames; peakFrame++) { // find spectral contrast, clip and scale double sc = features[1].at(floor(scScale*peakFrame)).values[0]; if (sc < lower) sc=lower; if (sc > higher) sc=higher; sc = (log10(sc)-lower_log)/(higher_log-lower_log); // get peak values double peak1 = features[0].at(peakFrame).values[0]; double peak2 = features[0].at(peakFrame).values[1]; // draw waveform cairo_set_source_rgba(cr, red(sc), green(sc), blue(sc), 1.0); cairo_line_to(cr, (double)peakFrame/(double)peakFrames, 0.5-(peak1*0.5)); cairo_line_to(cr, (double)peakFrame/(double)peakFrames, 0.5-(peak2*0.5)); cairo_set_line_width (cr, 1.0/(double)peakFrames); cairo_stroke (cr); } // clean up cairo_destroy(cr); cairo_surface_destroy (surface); return 0; } virtual VampOutputList getVampPlugins() { VampOutputList pluginList; VampPlugin bbcPeaks = {"bbc-vamp-plugins:bbc-peaks", 0, 0}; VampOutput peaks = {bbcPeaks, "peaks"}; VampPlugin libxSpecCent = {"vamp-libxtract:spectral_centroid", 0, 0}; VampOutput specCent = {libxSpecCent, "spectral_centroid"}; pluginList.push_back(peaks); pluginList.push_back(specCent); return pluginList; } }; extern "C" VisPlugin* create() { return new SpecCent; } extern "C" void destroy(VisPlugin* p) { delete p; } <|endoftext|>
<commit_before>#include <cmath> #include <stdlib.h> #include <assert.h> #include "ys_matrix.h" double ran_uniform() { return rand()/((double)RAND_MAX + 1); } using namespace ys; int main(void) { DMatrix<double> dmatrix(100, 1000); for (int i = 0; i < dmatrix.getDimX(); ++i) { for (int j = 0; j < dmatrix.getDimY(); ++j) { dmatrix(i, j) = ran_uniform(); } } dmatrix.save("tmpfile"); DMatrix<double> dmatrix1(); dmatrix1.load("tmpfile"); for (int i = 0; i < dmatrix1.getDimX(); ++i) { for (int j = 0; j < dmatrix1.getDimY(); ++j) { assert (dmatrix1[i][j] = dmatrix[i][j]); } } DMatrix<double> dmatrix2(); dmatrix2 = dmatrix; for (int i = 0; i < dmatrix2.getDimX(); ++i) { for (int j = 0; j < dmatrix2.getDimY(); ++j) { assert (dmatrix1[i][j] = dmatrix2[i][j]); } } DMatrix<double> dmatrix3(); dmatrix3.assign(dmatrix1); for (int i = 0; i < dmatrix3.getDimX(); ++i) { for (int j = 0; j < dmatrix3.getDimY(); ++j) { assert (dmatrix3[i][j] = dmatrix2[i][j]); } } DMatrix<double> dmatrix4(dmatrix2); for (int i = 0; i < dmatrix4.getDimX(); ++i) { for (int j = 0; j < dmatrix4.getDimY(); ++j) { assert (dmatrix4[i][j] = dmatrix[i][j]); } } return 0; } <commit_msg>modify<commit_after>#include <cmath> #include <stdlib.h> #include <assert.h> #include "ys_matrix.h" double ran_uniform() { return rand()/((double)RAND_MAX + 1); } using namespace ys; int main(void) { DMatrix<double> dmatrix(100, 1000); for (int i = 0; i < dmatrix.getDimX(); ++i) { for (int j = 0; j < dmatrix.getDimY(); ++j) { dmatrix(i, j) = ran_uniform(); } } dmatrix.save("tmpfile"); DMatrix<double> dmatrix1; dmatrix1.load("tmpfile"); for (int i = 0; i < dmatrix1.getDimX(); ++i) { for (int j = 0; j < dmatrix1.getDimY(); ++j) { assert (dmatrix1[i][j] = dmatrix[i][j]); } } DMatrix<double> dmatrix2; dmatrix2 = dmatrix; for (int i = 0; i < dmatrix2.getDimX(); ++i) { for (int j = 0; j < dmatrix2.getDimY(); ++j) { assert (dmatrix1[i][j] = dmatrix2[i][j]); } } DMatrix<double> dmatrix3; dmatrix3.assign(dmatrix1); for (int i = 0; i < dmatrix3.getDimX(); ++i) { for (int j = 0; j < dmatrix3.getDimY(); ++j) { assert (dmatrix3[i][j] = dmatrix2[i][j]); } } DMatrix<double> dmatrix4(dmatrix2); for (int i = 0; i < dmatrix4.getDimX(); ++i) { for (int j = 0; j < dmatrix4.getDimY(); ++j) { assert (dmatrix4[i][j] = dmatrix[i][j]); } } return 0; } <|endoftext|>
<commit_before>#include "mediamodel.h" #include "mediascanner.h" #include "dbreader.h" #include "backend.h" #define DEBUG if (1) qDebug() << __PRETTY_FUNCTION__ MediaModel::MediaModel(QObject *parent) : QAbstractItemModel(parent), m_loading(false), m_loaded(false), m_reader(0), m_readerThread(0) { } MediaModel::~MediaModel() { } QString MediaModel::part() const { return m_structure.split("|").value(m_cursor.length()); } QString MediaModel::mediaType() const { return m_mediaType; } void MediaModel::setMediaType(const QString &type) { m_mediaType = type; emit mediaTypeChanged(); initialize(); QSqlDriver *driver = Backend::instance()->mediaDatabase().driver(); QSqlRecord record = driver->record(m_mediaType); if (record.isEmpty()) qWarning() << "Table " << type << " is not valid it seems"; QHash<int, QByteArray> hash = roleNames(); hash.insert(Qt::UserRole, "dotdot"); hash.insert(Qt::UserRole+1, "isLeaf"); for (int i = 0; i < record.count(); i++) { hash.insert(Qt::UserRole + i + 2, record.fieldName(i).toUtf8()); } setRoleNames(hash); } void MediaModel::addSearchPath(const QString &path, const QString &name) { QMetaObject::invokeMethod(MediaScanner::instance(), "addSearchPath", Qt::QueuedConnection, Q_ARG(QString, "picture"), Q_ARG(QString, path), Q_ARG(QString, name)); } void MediaModel::removeSearchPath(int index) { Q_UNUSED(index); } QString MediaModel::structure() const { return m_structure; } void MediaModel::setStructure(const QString &str) { m_structure = str; emit structureChanged(); initialize(); } void MediaModel::enter(int index) { Q_UNUSED(index); if (m_cursor.count() + 1 == m_structure.split("|").count() && index != 0 /* up on leaf node is OK */) { DEBUG << "Refusing to enter leaf node"; return; } if (index == 0 && !m_cursor.isEmpty()) { back(); return; } DEBUG << "Entering " << index; m_cursor.append(m_data[index]); initialize(); emit partChanged(); } void MediaModel::back() { m_cursor.removeLast(); initialize(); emit partChanged(); } QVariant MediaModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); const QHash<QString, QVariant> &data = m_data[index.row()]; const QHash<int, QByteArray> hash = roleNames(); return data.value(hash.value(role)); } QModelIndex MediaModel::index(int row, int col, const QModelIndex &parent) const { if (parent.isValid()) return QModelIndex(); return createIndex(row, col); } QModelIndex MediaModel::parent(const QModelIndex &idx) const { Q_UNUSED(idx); return QModelIndex(); } int MediaModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return m_data.count(); } int MediaModel::columnCount(const QModelIndex &idx) const { Q_UNUSED(idx); return 1; } bool MediaModel::hasChildren(const QModelIndex &parent) const { return !parent.isValid(); } bool MediaModel::canFetchMore(const QModelIndex &parent) const { if (parent.isValid() || m_mediaType.isEmpty() || m_structure.isEmpty()) return false; return !m_loading && !m_loaded; } void MediaModel::fetchMore(const QModelIndex &parent) { if (!canFetchMore(parent)) return; initialize(); QSqlQuery q = query(); DEBUG << q.lastQuery(); m_loading = true; QMetaObject::invokeMethod(m_reader, "execute", Qt::QueuedConnection, Q_ARG(QSqlQuery, q)); } void MediaModel::initialize() { beginResetModel(); m_data.clear(); DbReader *newReader = new DbReader; if (m_reader) { disconnect(m_reader, 0, this, 0); m_reader->stop(); m_reader->deleteLater(); } m_reader = newReader; if (!m_readerThread) { m_readerThread = new QThread(this); m_readerThread->start(); } m_reader->moveToThread(m_readerThread); QMetaObject::invokeMethod(m_reader, "initialize", Q_ARG(QSqlDatabase, Backend::instance()->mediaDatabase())); connect(m_reader, SIGNAL(dataReady(DbReader *, QList<QSqlRecord>, void *)), this, SLOT(handleDataReady(DbReader *, QList<QSqlRecord>, void *))); m_loading = m_loaded = false; endResetModel(); } void MediaModel::handleDataReady(DbReader *reader, const QList<QSqlRecord> &records, void *node) { Q_ASSERT(reader == m_reader); Q_UNUSED(reader); Q_UNUSED(node); DEBUG << "Received response from db of size " << records.size(); if (records.isEmpty()) return; if (!m_cursor.isEmpty()) { beginInsertRows(QModelIndex(), 0, records.count()); QHash<QString, QVariant> data; data.insert("display", tr("..")); data.insert("dotdot", true); data.insert("isLeaf", false); m_data.append(data); } else { beginInsertRows(QModelIndex(), 0, records.count() - 1); } bool isLeaf = false; if (m_cursor.count() + 1 == m_structure.split("|").count()) isLeaf = true; for (int i = 0; i < records.count(); i++) { QHash<QString, QVariant> data; for (int j = 0; j < records[i].count(); j++) { data.insert(records[i].fieldName(j), records[i].value(j)); } QStringList cols = m_structure.split("|").value(m_cursor.count()).split(","); QStringList displayString; for (int j = 0; j < cols.count(); j++) { displayString << records[i].value(cols[j]).toString(); } data.insert("display", displayString.join(", ")); data.insert("dotdot", false); data.insert("isLeaf", isLeaf); m_data.append(data); } m_loading = false; m_loaded = true; endInsertRows(); } void MediaModel::handleDatabaseUpdated(const QList<QSqlRecord> &records) { Q_UNUSED(records); // not implemented yet } QSqlQuery MediaModel::query() { QString q; QStringList parts = m_structure.split("|"); QSqlDriver *driver = Backend::instance()->mediaDatabase().driver(); QString curPart = parts[m_cursor.count()]; QStringList curParts = curPart.split(","); QStringList escapedCurParts; for (int i = 0; i < curParts.count(); i++) escapedCurParts.append(driver->escapeIdentifier(curParts[i], QSqlDriver::FieldName)); QString escapedCurPart = escapedCurParts.join(","); QSqlQuery query(Backend::instance()->mediaDatabase()); query.setForwardOnly(true); QStringList placeHolders; const bool lastPart = m_cursor.count() == parts.count()-1; QString queryString = QString("SELECT %1 FROM %2 ").arg(lastPart ? "*" : escapedCurPart).arg(driver->escapeIdentifier(m_mediaType, QSqlDriver::TableName)); if (!m_cursor.isEmpty()) { QStringList where; for (int i = 0; i < m_cursor.count(); i++) { QString part = parts[i]; QStringList subParts = part.split(","); for (int j = 0; j < subParts.count(); j++) { where.append(subParts[j] + " = ?"); placeHolders << m_cursor[i].value(subParts[j]).toString(); } } queryString.append(QString("WHERE %1 ").arg(where.join(" AND "))); } if (!lastPart) queryString.append(QString("GROUP BY %1 ").arg(escapedCurPart)); queryString.append(QString("ORDER BY %1").arg(escapedCurPart)); query.prepare(queryString); foreach(const QString &placeHolder, placeHolders) query.addBindValue(placeHolder); return query; } <commit_msg>Code beautification<commit_after>#include "mediamodel.h" #include "mediascanner.h" #include "dbreader.h" #include "backend.h" #define DEBUG if (1) qDebug() << __PRETTY_FUNCTION__ MediaModel::MediaModel(QObject *parent) : QAbstractItemModel(parent), m_loading(false), m_loaded(false), m_reader(0), m_readerThread(0) { } MediaModel::~MediaModel() { } QString MediaModel::part() const { return m_structure.split("|").value(m_cursor.length()); } QString MediaModel::mediaType() const { return m_mediaType; } void MediaModel::setMediaType(const QString &type) { if (type == m_mediaType) return; initialize(); m_mediaType = type; emit mediaTypeChanged(); // Add the fields of the table as role names QSqlDriver *driver = Backend::instance()->mediaDatabase().driver(); QSqlRecord record = driver->record(m_mediaType); if (record.isEmpty()) qWarning() << "Table " << type << " is not valid it seems"; QHash<int, QByteArray> hash = roleNames(); hash.insert(Qt::UserRole, "dotdot"); hash.insert(Qt::UserRole+1, "isLeaf"); for (int i = 0; i < record.count(); i++) { hash.insert(Qt::UserRole + i + 2, record.fieldName(i).toUtf8()); } setRoleNames(hash); } void MediaModel::addSearchPath(const QString &path, const QString &name) { if (m_mediaType.isEmpty()) { qWarning() << m_mediaType << " is not set yet"; return; } QMetaObject::invokeMethod(MediaScanner::instance(), "addSearchPath", Qt::QueuedConnection, Q_ARG(QString, m_mediaType), Q_ARG(QString, path), Q_ARG(QString, name)); } void MediaModel::removeSearchPath(int index) { Q_UNUSED(index); } QString MediaModel::structure() const { return m_structure; } void MediaModel::setStructure(const QString &str) { m_structure = str; initialize(); emit structureChanged(); } void MediaModel::enter(int index) { Q_UNUSED(index); if (m_cursor.count() + 1 == m_structure.split("|").count() && index != 0 /* up on leaf node is OK */) { DEBUG << "Refusing to enter leaf node"; return; } if (index == 0 && !m_cursor.isEmpty()) { back(); return; } DEBUG << "Entering " << index; m_cursor.append(m_data[index]); initialize(); emit partChanged(); } void MediaModel::back() { m_cursor.removeLast(); initialize(); emit partChanged(); } QVariant MediaModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); const QHash<QString, QVariant> &data = m_data[index.row()]; const QHash<int, QByteArray> hash = roleNames(); return data.value(hash.value(role)); } QModelIndex MediaModel::index(int row, int col, const QModelIndex &parent) const { if (parent.isValid()) return QModelIndex(); return createIndex(row, col); } QModelIndex MediaModel::parent(const QModelIndex &idx) const { Q_UNUSED(idx); return QModelIndex(); } int MediaModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return m_data.count(); } int MediaModel::columnCount(const QModelIndex &idx) const { Q_UNUSED(idx); return 1; } bool MediaModel::hasChildren(const QModelIndex &parent) const { return !parent.isValid(); } bool MediaModel::canFetchMore(const QModelIndex &parent) const { if (parent.isValid() || m_mediaType.isEmpty() || m_structure.isEmpty()) return false; return !m_loading && !m_loaded; } void MediaModel::fetchMore(const QModelIndex &parent) { if (!canFetchMore(parent)) return; initialize(); QSqlQuery q = query(); DEBUG << q.lastQuery(); m_loading = true; QMetaObject::invokeMethod(m_reader, "execute", Qt::QueuedConnection, Q_ARG(QSqlQuery, q)); } void MediaModel::initialize() { beginResetModel(); m_data.clear(); if (m_reader) { disconnect(m_reader, 0, this, 0); m_reader->stop(); m_reader->deleteLater(); } m_reader = new DbReader; if (!m_readerThread) { m_readerThread = new QThread(this); m_readerThread->start(); } m_reader->moveToThread(m_readerThread); QMetaObject::invokeMethod(m_reader, "initialize", Q_ARG(QSqlDatabase, Backend::instance()->mediaDatabase())); connect(m_reader, SIGNAL(dataReady(DbReader *, QList<QSqlRecord>, void *)), this, SLOT(handleDataReady(DbReader *, QList<QSqlRecord>, void *))); m_loading = m_loaded = false; endResetModel(); } void MediaModel::handleDataReady(DbReader *reader, const QList<QSqlRecord> &records, void *node) { Q_ASSERT(reader == m_reader); Q_UNUSED(reader); Q_UNUSED(node); DEBUG << "Received response from db of size " << records.size(); if (records.isEmpty()) return; if (!m_cursor.isEmpty()) { beginInsertRows(QModelIndex(), 0, records.count()); QHash<QString, QVariant> data; data.insert("display", tr("..")); data.insert("dotdot", true); data.insert("isLeaf", false); m_data.append(data); } else { beginInsertRows(QModelIndex(), 0, records.count() - 1); } const bool isLeaf = m_cursor.count() + 1 == m_structure.split("|").count(); for (int i = 0; i < records.count(); i++) { QHash<QString, QVariant> data; for (int j = 0; j < records[i].count(); j++) { data.insert(records[i].fieldName(j), records[i].value(j)); } QStringList cols = m_structure.split("|").value(m_cursor.count()).split(","); QStringList displayString; for (int j = 0; j < cols.count(); j++) { displayString << records[i].value(cols[j]).toString(); } data.insert("display", displayString.join(", ")); data.insert("dotdot", false); data.insert("isLeaf", isLeaf); m_data.append(data); } m_loading = false; m_loaded = true; endInsertRows(); } void MediaModel::handleDatabaseUpdated(const QList<QSqlRecord> &records) { Q_UNUSED(records); // not implemented yet } QSqlQuery MediaModel::query() { QString q; QStringList parts = m_structure.split("|"); QSqlDriver *driver = Backend::instance()->mediaDatabase().driver(); QString curPart = parts[m_cursor.count()]; QStringList curParts = curPart.split(","); QStringList escapedCurParts; for (int i = 0; i < curParts.count(); i++) escapedCurParts.append(driver->escapeIdentifier(curParts[i], QSqlDriver::FieldName)); QString escapedCurPart = escapedCurParts.join(","); QSqlQuery query(Backend::instance()->mediaDatabase()); query.setForwardOnly(true); QStringList placeHolders; const bool lastPart = m_cursor.count() == parts.count()-1; QString queryString = QString("SELECT %1 FROM %2 ").arg(lastPart ? "*" : escapedCurPart).arg(driver->escapeIdentifier(m_mediaType, QSqlDriver::TableName)); if (!m_cursor.isEmpty()) { QStringList where; for (int i = 0; i < m_cursor.count(); i++) { QString part = parts[i]; QStringList subParts = part.split(","); for (int j = 0; j < subParts.count(); j++) { where.append(subParts[j] + " = ?"); placeHolders << m_cursor[i].value(subParts[j]).toString(); } } queryString.append(QString("WHERE %1 ").arg(where.join(" AND "))); } if (!lastPart) queryString.append(QString("GROUP BY %1 ").arg(escapedCurPart)); queryString.append(QString("ORDER BY %1").arg(escapedCurPart)); query.prepare(queryString); foreach(const QString &placeHolder, placeHolders) query.addBindValue(placeHolder); return query; } <|endoftext|>
<commit_before>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <string> #include "util/test.h" #include "util/exception.h" #include "util/sstream.h" using namespace lean; static void tst1() { try { throw exception(std::string("foo")); } catch (exception & ex) { lean_assert(std::string("foo") == ex.what()); } } static void tst2() { try { throw parser_exception(std::string("foo"), 10, 100); } catch (parser_exception & ex) { lean_assert(std::string("(line: 10, pos: 100) foo") == ex.what()); } } static void tst3() { try { throw parser_exception(sstream() << "msg " << 10 << " " << 20, 10, 100); } catch (parser_exception & ex) { lean_assert(std::string("(line: 10, pos: 100) msg 10 20") == ex.what()); } } int main() { tst1(); tst2(); tst3(); return has_violations() ? 1 : 0; } <commit_msg>test(exception): add tests for improving coverage<commit_after>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <string> #include "util/test.h" #include "util/exception.h" #include "util/sstream.h" using namespace lean; static void tst1() { try { throw exception(std::string("foo")); } catch (exception & ex) { lean_assert(std::string("foo") == ex.what()); } } static void tst2() { try { throw parser_exception(std::string("foo"), 10, 100); } catch (parser_exception & ex) { lean_assert(std::string("(line: 10, pos: 100) foo") == ex.what()); } } static void tst3() { try { throw parser_exception(sstream() << "msg " << 10 << " " << 20, 10, 100); } catch (parser_exception & ex) { lean_assert(std::string("(line: 10, pos: 100) msg 10 20") == ex.what()); } } static void tst4() { try { throw interrupted(); } catch (exception & ex) { lean_assert(std::string("interrupted") == ex.what()); } } int main() { tst1(); tst2(); tst3(); tst4(); return has_violations() ? 1 : 0; } <|endoftext|>
<commit_before>/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tianfeng Han <[email protected]> | +----------------------------------------------------------------------+ */ #include "swoole.h" #include "swoole_memory.h" namespace swoole { struct FixedPoolSlice { uint8_t lock; FixedPoolSlice *next; FixedPoolSlice *prev; char data[0]; }; struct FixedPoolImpl { void *memory; size_t size; FixedPoolSlice *head; FixedPoolSlice *tail; // total memory size uint32_t slice_num; // memory usage uint32_t slice_use; // Fixed slice size, not include the memory used by FixedPoolSlice uint32_t slice_size; bool shared; bool allocated; void init(); }; /** * create new FixedPool, random alloc/free fixed size memory */ FixedPool::FixedPool(uint32_t slice_num, uint32_t slice_size, bool shared) { if (slice_num < 2) { throw Exception(SW_ERROR_INVALID_PARAMS); } slice_size = SW_MEM_ALIGNED_SIZE(slice_size); size_t size = slice_num * (sizeof(FixedPoolSlice) + slice_size); size_t alloc_size = size + sizeof(*impl); void *memory = shared ? ::sw_shm_malloc(alloc_size) : ::sw_malloc(alloc_size); if (!memory) { throw std::bad_alloc(); } impl = (FixedPoolImpl *) memory; memory = (char *) memory + sizeof(*impl); sw_memset_zero(impl, sizeof(*impl)); impl->shared = shared; impl->slice_num = slice_num; impl->slice_size = slice_size; impl->size = size; impl->memory = memory; impl->allocated = true; impl->init(); } /** * create new FixedPool, Using the given memory */ FixedPool::FixedPool(uint32_t slice_size, void *memory, size_t size, bool shared) { impl = (FixedPoolImpl *) memory; memory = (char *) memory + sizeof(*impl); sw_memset_zero(impl, sizeof(*impl)); impl->shared = shared; impl->slice_size = slice_size; impl->size = size - sizeof(*impl); uint32_t slice_num = impl->size / (slice_size + sizeof(FixedPoolSlice)); if (slice_num < 2) { throw Exception(SW_ERROR_INVALID_PARAMS); } impl->slice_num = slice_num; impl->memory = memory; impl->allocated = false; impl->init(); } size_t FixedPool::sizeof_struct_slice() { return sizeof(FixedPoolSlice); } size_t FixedPool::sizeof_struct_impl() { return sizeof(FixedPoolImpl); } /** * linked list */ void FixedPoolImpl::init() { FixedPoolSlice *slice; void *cur = memory; void *max = (char *) memory + size; do { slice = (FixedPoolSlice *) cur; sw_memset_zero(slice, sizeof(FixedPoolSlice)); if (head != nullptr) { head->prev = slice; slice->next = head; } else { tail = slice; } head = slice; cur = (char *) cur + (sizeof(FixedPoolSlice) + slice_size); if (cur < max) { slice->prev = (FixedPoolSlice *) cur; } else { slice->prev = nullptr; break; } } while (1); } uint32_t FixedPool::get_number_of_spare_slice() { return impl->slice_num - impl->slice_use; } uint32_t FixedPool::get_number_of_total_slice() { return impl->slice_num; } uint32_t FixedPool::get_slice_size() { return impl->slice_size; } void *FixedPool::alloc(uint32_t size) { FixedPoolSlice *slice = impl->head; if (slice->lock) { swoole_set_last_error(SW_ERROR_MALLOC_FAIL); return nullptr; } slice->lock = 1; impl->slice_use++; // move next slice to head (idle list) impl->head = slice->next; impl->head->prev = nullptr; // move this slice to tail (busy list) impl->tail->next = slice; slice->next = nullptr; slice->prev = impl->tail; impl->tail = slice; return slice->data; } void FixedPool::free(void *ptr) { FixedPoolSlice *slice = (FixedPoolSlice *) ((char *) ptr - sizeof(FixedPoolSlice)); assert(ptr > impl->memory && (char *) ptr < (char *) impl->memory + impl->size); assert(slice->lock == 1); impl->slice_use--; slice->lock = 0; if (slice == impl->head) { return; } if (slice == impl->tail) { slice->prev->next = nullptr; impl->tail = slice->prev; } else { slice->prev->next = slice->next; slice->next->prev = slice->prev; } // move slice to head (idle) slice->prev = nullptr; slice->next = impl->head; impl->head->prev = slice; impl->head = slice; } FixedPool::~FixedPool() { if (!impl->allocated) { return; } if (impl->shared) { ::sw_shm_free(impl); } else { ::sw_free(impl); } } void FixedPool::debug(int max_lines) { int line = 0; FixedPoolSlice *slice = impl->head; printf("===============================%s=================================\n", __FUNCTION__); while (slice != nullptr) { if (slice->next == slice) { printf("-------------------@@@@@@@@@@@@@@@@@@@@@@----------------\n"); } printf("#%d\t", line); printf("slice[%p]\t", slice); printf("prev=%p\t", slice->prev); printf("next=%p\t", slice->next); printf("tag=%d\t", slice->lock); printf("data=%p\n", slice->data); slice = slice->next; if (line++ > max_lines) { break; } } } } // namespace swoole <commit_msg>Add assertion<commit_after>/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tianfeng Han <[email protected]> | +----------------------------------------------------------------------+ */ #include "swoole.h" #include "swoole_memory.h" namespace swoole { struct FixedPoolSlice { uint8_t lock; FixedPoolSlice *next; FixedPoolSlice *prev; char data[0]; }; struct FixedPoolImpl { void *memory; size_t size; FixedPoolSlice *head; FixedPoolSlice *tail; // total memory size uint32_t slice_num; // memory usage uint32_t slice_use; // Fixed slice size, not include the memory used by FixedPoolSlice uint32_t slice_size; bool shared; bool allocated; void init(); }; /** * create new FixedPool, random alloc/free fixed size memory */ FixedPool::FixedPool(uint32_t slice_num, uint32_t slice_size, bool shared) { if (slice_num < 2) { throw Exception(SW_ERROR_INVALID_PARAMS); } slice_size = SW_MEM_ALIGNED_SIZE(slice_size); size_t size = slice_num * (sizeof(FixedPoolSlice) + slice_size); size_t alloc_size = size + sizeof(*impl); void *memory = shared ? ::sw_shm_malloc(alloc_size) : ::sw_malloc(alloc_size); if (!memory) { throw std::bad_alloc(); } impl = (FixedPoolImpl *) memory; memory = (char *) memory + sizeof(*impl); sw_memset_zero(impl, sizeof(*impl)); impl->shared = shared; impl->slice_num = slice_num; impl->slice_size = slice_size; impl->size = size; impl->memory = memory; impl->allocated = true; impl->init(); } /** * create new FixedPool, Using the given memory */ FixedPool::FixedPool(uint32_t slice_size, void *memory, size_t size, bool shared) { impl = (FixedPoolImpl *) memory; memory = (char *) memory + sizeof(*impl); sw_memset_zero(impl, sizeof(*impl)); impl->shared = shared; impl->slice_size = slice_size; impl->size = size - sizeof(*impl); uint32_t slice_num = impl->size / (slice_size + sizeof(FixedPoolSlice)); if (slice_num < 2) { throw Exception(SW_ERROR_INVALID_PARAMS); } impl->slice_num = slice_num; impl->memory = memory; impl->allocated = false; impl->init(); } size_t FixedPool::sizeof_struct_slice() { return sizeof(FixedPoolSlice); } size_t FixedPool::sizeof_struct_impl() { return sizeof(FixedPoolImpl); } /** * linked list */ void FixedPoolImpl::init() { FixedPoolSlice *slice; void *cur = memory; void *max = (char *) memory + size; do { slice = (FixedPoolSlice *) cur; sw_memset_zero(slice, sizeof(FixedPoolSlice)); if (head != nullptr) { head->prev = slice; slice->next = head; } else { tail = slice; } head = slice; cur = (char *) cur + (sizeof(FixedPoolSlice) + slice_size); if (cur < max) { slice->prev = (FixedPoolSlice *) cur; } else { slice->prev = nullptr; break; } } while (1); } uint32_t FixedPool::get_number_of_spare_slice() { return impl->slice_num - impl->slice_use; } uint32_t FixedPool::get_number_of_total_slice() { return impl->slice_num; } uint32_t FixedPool::get_slice_size() { return impl->slice_size; } void *FixedPool::alloc(uint32_t size) { FixedPoolSlice *slice = impl->head; if (slice->lock) { swoole_set_last_error(SW_ERROR_MALLOC_FAIL); assert(get_number_of_spare_slice() == 0); return nullptr; } slice->lock = 1; impl->slice_use++; // move next slice to head (idle list) impl->head = slice->next; impl->head->prev = nullptr; // move this slice to tail (busy list) impl->tail->next = slice; slice->next = nullptr; slice->prev = impl->tail; impl->tail = slice; return slice->data; } void FixedPool::free(void *ptr) { FixedPoolSlice *slice = (FixedPoolSlice *) ((char *) ptr - sizeof(FixedPoolSlice)); assert(ptr > impl->memory && (char *) ptr < (char *) impl->memory + impl->size); assert(slice->lock == 1); impl->slice_use--; slice->lock = 0; if (slice == impl->head) { return; } if (slice == impl->tail) { slice->prev->next = nullptr; impl->tail = slice->prev; } else { slice->prev->next = slice->next; slice->next->prev = slice->prev; } // move slice to head (idle) slice->prev = nullptr; slice->next = impl->head; impl->head->prev = slice; impl->head = slice; } FixedPool::~FixedPool() { if (!impl->allocated) { return; } if (impl->shared) { ::sw_shm_free(impl); } else { ::sw_free(impl); } } void FixedPool::debug(int max_lines) { int line = 0; FixedPoolSlice *slice = impl->head; printf("===============================%s=================================\n", __FUNCTION__); while (slice != nullptr) { if (slice->next == slice) { printf("-------------------@@@@@@@@@@@@@@@@@@@@@@----------------\n"); } printf("#%d\t", line); printf("slice[%p]\t", slice); printf("prev=%p\t", slice->prev); printf("next=%p\t", slice->next); printf("tag=%d\t", slice->lock); printf("data=%p\n", slice->data); slice = slice->next; if (line++ > max_lines) { break; } } } } // namespace swoole <|endoftext|>
<commit_before>#include "orwell/com/Receiver.hpp" //std #include <iostream> #include <unistd.h> #include <zmq.hpp> #include <sstream> #include "orwell/support/GlobalLogger.hpp" #include "orwell/com/RawMessage.hpp" using std::string; namespace orwell { namespace com { Receiver::Receiver( std::string const & iUrl, unsigned int const iSocketType, ConnectionMode const iConnectionMode, zmq::context_t & ioZmqContext, unsigned int const iSleep) : m_zmqSocket(new zmq::socket_t(ioZmqContext, iSocketType)) , m_url(iUrl) { int aLinger = 10; // linger 0.01 second max after being closed m_zmqSocket->setsockopt(ZMQ_LINGER, &aLinger, sizeof(aLinger)); if (ZMQ_SUB == iSocketType) { string atag; m_zmqSocket->setsockopt(ZMQ_SUBSCRIBE, atag.c_str(), atag.size()); } if (ConnectionMode::BIND == iConnectionMode) { m_zmqSocket->bind(iUrl.c_str()); ORWELL_LOG_INFO("Puller binds on " << iUrl.c_str()); } else { assert(ConnectionMode::CONNECT == iConnectionMode); m_zmqSocket->connect(iUrl.c_str()); ORWELL_LOG_INFO("Subscriber connects to " << iUrl.c_str() << " - it subscribes to everything"); } if (iSleep > 0) { sleep(iSleep); } } Receiver::Receiver(Receiver const & iOther) { } Receiver::~Receiver() { delete(m_zmqSocket); } bool Receiver::receiveString( std::string & oMessage, bool const iBlocking) { zmq::message_t aZmqMessage; int aFlags = 0; if (not iBlocking) { aFlags = ZMQ_NOBLOCK; } bool const aReceived = m_zmqSocket->recv(&aZmqMessage, aFlags); if (aReceived) { ORWELL_LOG_DEBUG("message received"); oMessage = string(static_cast<char*>(aZmqMessage.data()), aZmqMessage.size()); } return aReceived; } bool Receiver::receive(RawMessage & oMessage) { zmq::message_t aZmqMessage; string aType; string aPayload; string aDest; std::string aMessageData; bool const aReceived = receiveString(aMessageData); if (aReceived) { size_t aEndDestFlag = aMessageData.find( " ", 0 ); if (string::npos != aEndDestFlag) { aDest = aMessageData.substr(0, aEndDestFlag); size_t aEndTypeFlag = aMessageData.find(" ", aEndDestFlag + 1); if ( aEndTypeFlag != string::npos ) { aType = aMessageData.substr( aEndDestFlag + 1, aEndTypeFlag - aEndDestFlag - 1 ); aPayload = aMessageData.substr( aEndTypeFlag + 1 ); } } oMessage._type = aType; oMessage._routingId = aDest; oMessage._payload = aPayload; ORWELL_LOG_DEBUG("Received " << aZmqMessage.size() << " bytes : type=" << aType << "- dest=" << aDest << "-"); } return aReceived; } std::string const & Receiver::getUrl() const { return m_url; } }} <commit_msg>Remove wrong message size in logs.<commit_after>#include "orwell/com/Receiver.hpp" //std #include <iostream> #include <unistd.h> #include <zmq.hpp> #include <sstream> #include "orwell/support/GlobalLogger.hpp" #include "orwell/com/RawMessage.hpp" using std::string; namespace orwell { namespace com { Receiver::Receiver( std::string const & iUrl, unsigned int const iSocketType, ConnectionMode const iConnectionMode, zmq::context_t & ioZmqContext, unsigned int const iSleep) : m_zmqSocket(new zmq::socket_t(ioZmqContext, iSocketType)) , m_url(iUrl) { int aLinger = 10; // linger 0.01 second max after being closed m_zmqSocket->setsockopt(ZMQ_LINGER, &aLinger, sizeof(aLinger)); if (ZMQ_SUB == iSocketType) { string atag; m_zmqSocket->setsockopt(ZMQ_SUBSCRIBE, atag.c_str(), atag.size()); } if (ConnectionMode::BIND == iConnectionMode) { m_zmqSocket->bind(iUrl.c_str()); ORWELL_LOG_INFO("Puller binds on " << iUrl.c_str()); } else { assert(ConnectionMode::CONNECT == iConnectionMode); m_zmqSocket->connect(iUrl.c_str()); ORWELL_LOG_INFO("Subscriber connects to " << iUrl.c_str() << " - it subscribes to everything"); } if (iSleep > 0) { sleep(iSleep); } } Receiver::Receiver(Receiver const & iOther) { } Receiver::~Receiver() { delete(m_zmqSocket); } bool Receiver::receiveString( std::string & oMessage, bool const iBlocking) { zmq::message_t aZmqMessage; int aFlags = 0; if (not iBlocking) { aFlags = ZMQ_NOBLOCK; } bool const aReceived = m_zmqSocket->recv(&aZmqMessage, aFlags); if (aReceived) { ORWELL_LOG_DEBUG("message received"); oMessage = string(static_cast<char*>(aZmqMessage.data()), aZmqMessage.size()); } return aReceived; } bool Receiver::receive(RawMessage & oMessage) { string aType; string aPayload; string aDest; std::string aMessageData; bool const aReceived = receiveString(aMessageData); if (aReceived) { size_t aEndDestFlag = aMessageData.find( " ", 0 ); if (string::npos != aEndDestFlag) { aDest = aMessageData.substr(0, aEndDestFlag); size_t aEndTypeFlag = aMessageData.find(" ", aEndDestFlag + 1); if ( aEndTypeFlag != string::npos ) { aType = aMessageData.substr( aEndDestFlag + 1, aEndTypeFlag - aEndDestFlag - 1 ); aPayload = aMessageData.substr( aEndTypeFlag + 1 ); } } oMessage._type = aType; oMessage._routingId = aDest; oMessage._payload = aPayload; ORWELL_LOG_DEBUG("Received message : type=" << aType << "- dest=" << aDest << "-"); } return aReceived; } std::string const & Receiver::getUrl() const { return m_url; } } } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <stdlib.h> #include <string.h> #include <limits.h> #include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #ifdef WIN32 #define _WIN32_WINNT 0x0500 #include <windows.h> #endif #if defined(__sgi) #include <ctype.h> #elif defined(__GNUC__) || !defined(WIN32) || defined(__MWERKS__) #include <cctype> using std::tolower; #endif using namespace std; std::string osgDB::getFilePath(const std::string& fileName) { std::string::size_type slash1 = fileName.find_last_of('/'); std::string::size_type slash2 = fileName.find_last_of('\\'); if (slash1==std::string::npos) { if (slash2==std::string::npos) return std::string(); return std::string(fileName,0,slash2); } if (slash2==std::string::npos) return std::string(fileName,0,slash1); return std::string(fileName, 0, slash1>slash2 ? slash1 : slash2); } std::string osgDB::getSimpleFileName(const std::string& fileName) { std::string::size_type slash1 = fileName.find_last_of('/'); std::string::size_type slash2 = fileName.find_last_of('\\'); if (slash1==std::string::npos) { if (slash2==std::string::npos) return fileName; return std::string(fileName.begin()+slash2+1,fileName.end()); } if (slash2==std::string::npos) return std::string(fileName.begin()+slash1+1,fileName.end()); return std::string(fileName.begin()+(slash1>slash2?slash1:slash2)+1,fileName.end()); } std::string osgDB::getFileExtension(const std::string& fileName) { std::string::size_type dot = fileName.find_last_of('.'); if (dot==std::string::npos) return std::string(""); return std::string(fileName.begin()+dot+1,fileName.end()); } std::string osgDB::getFileExtensionIncludingDot(const std::string& fileName) { std::string::size_type dot = fileName.find_last_of('.'); if (dot==std::string::npos) return std::string(""); return std::string(fileName.begin()+dot,fileName.end()); } std::string osgDB::convertFileNameToWindowsStyle(const std::string& fileName) { std::string new_fileName(fileName); std::string::size_type slash = 0; while( (slash=new_fileName.find_first_of('/',slash)) != std::string::npos) { new_fileName[slash]='\\'; } return new_fileName; } std::string osgDB::convertFileNameToUnixStyle(const std::string& fileName) { std::string new_fileName(fileName); std::string::size_type slash = 0; while( (slash=new_fileName.find_first_of('\\',slash)) != std::string::npos) { new_fileName[slash]='/'; } return new_fileName; } bool osgDB::isFileNameNativeStyle(const std::string& fileName) { #if defined(WIN32) && !defined(__CYGWIN__) return fileName.find('/') == std::string::npos; // return true if no unix style slash exist #else return fileName.find('\\') == std::string::npos; // return true if no windows style slash exist #endif } std::string osgDB::convertFileNameToNativeStyle(const std::string& fileName) { #if defined(WIN32) && !defined(__CYGWIN__) return convertFileNameToWindowsStyle(fileName); #else return convertFileNameToUnixStyle(fileName); #endif } std::string osgDB::getLowerCaseFileExtension(const std::string& filename) { return convertToLowerCase(osgDB::getFileExtension(filename)); } std::string osgDB::convertToLowerCase(const std::string& str) { std::string lowcase_str(str); for(std::string::iterator itr=lowcase_str.begin(); itr!=lowcase_str.end(); ++itr) { *itr = tolower(*itr); } return lowcase_str; } // strip one level of extension from the filename. std::string osgDB::getNameLessExtension(const std::string& fileName) { std::string::size_type dot = fileName.find_last_of('.'); std::string::size_type back_slash = fileName.find_last_of('\\'); std::string::size_type slash = fileName.find_last_of('/'); if (dot==std::string::npos || (dot<back_slash && dot<slash)) return fileName; return std::string(fileName.begin(),fileName.begin()+dot); } std::string osgDB::getStrippedName(const std::string& fileName) { std::string simpleName = getSimpleFileName(fileName); return getNameLessExtension( simpleName ); } bool osgDB::equalCaseInsensitive(const std::string& lhs,const std::string& rhs) { if (lhs.size()!=rhs.size()) return false; std::string::const_iterator litr = lhs.begin(); std::string::const_iterator ritr = rhs.begin(); while (litr!=lhs.end()) { if (tolower(*litr)!=tolower(*ritr)) return false; ++litr; ++ritr; } return true; } bool osgDB::equalCaseInsensitive(const std::string& lhs,const char* rhs) { if (rhs==NULL || lhs.size()!=strlen(rhs)) return false; std::string::const_iterator litr = lhs.begin(); const char* cptr = rhs; while (litr!=lhs.end()) { if (tolower(*litr)!=tolower(*cptr)) return false; ++litr; ++cptr; } return true; } bool osgDB::containsServerAddress(const std::string& filename) { // need to check for :// std::string::size_type pos(filename.find("://")); if (pos == std::string::npos) return false; std::string proto(filename.substr(0, pos)); return Registry::instance()->isProtocolRegistered(proto); } std::string osgDB::getServerProtocol(const std::string& filename) { std::string::size_type pos(filename.find("://")); if (pos != std::string::npos) return filename.substr(0,pos); return ""; } std::string osgDB::getServerAddress(const std::string& filename) { std::string::size_type pos(filename.find("://")); if (pos != std::string::npos) { std::string::size_type pos_slash = filename.find_first_of('/',pos+3); if (pos_slash!=std::string::npos) { return filename.substr(pos+3,pos_slash-pos-3); } else { return filename.substr(pos+3,std::string::npos); } } return ""; } std::string osgDB::getServerFileName(const std::string& filename) { std::string::size_type pos(filename.find_first_of("://")); if (pos != std::string::npos) { std::string::size_type pos_slash = filename.find_first_of('/',pos+3); if (pos_slash!=std::string::npos) { return filename.substr(pos_slash+1,std::string::npos); } else { return ""; } } return filename; } std::string osgDB::concatPaths(const std::string& left, const std::string& right) { #if defined(WIN32) && !defined(__CYGWIN__) const char delimiterNative = '\\'; const char delimiterForeign = '/'; #else const char delimiterNative = '/'; const char delimiterForeign = '\\'; #endif if(left.empty()) { return(right); } char lastChar = left[left.size() - 1]; if(lastChar == delimiterNative) { return left + right; } else if(lastChar == delimiterForeign) { return left.substr(0, left.size() - 1) + delimiterNative + right; } else // lastChar != a delimiter { return left + delimiterNative + right; } } std::string osgDB::getRealPath(const std::string& path) { #if defined(WIN32) && !defined(__CYGWIN__) // Not unicode compatible should give an error if UNICODE defined char retbuf[MAX_PATH + 1]; char tempbuf1[MAX_PATH + 1]; GetFullPathName(path.c_str(), sizeof(retbuf), retbuf, NULL); // Force drive letter to upper case if ((retbuf[1] == ':') && islower(retbuf[0])) retbuf[0] = _toupper(retbuf[0]); if (fileExists(std::string(retbuf))) { // Canonicalise the full path GetShortPathName(retbuf, tempbuf1, sizeof(tempbuf1)); GetLongPathName(tempbuf1, retbuf, sizeof(retbuf)); return std::string(retbuf); } else { // Canonicalise the directories std::string FilePath = getFilePath(retbuf); char tempbuf2[MAX_PATH + 1]; if (0 == GetShortPathName(FilePath.c_str(), tempbuf1, sizeof(tempbuf1))) return std::string(retbuf); if (0 == GetLongPathName(tempbuf1, tempbuf2, sizeof(tempbuf2))) return std::string(retbuf); FilePath = std::string(tempbuf2); FilePath.append("\\"); FilePath.append(getSimpleFileName(std::string(retbuf))); return FilePath; } #else char resolved_path[PATH_MAX]; char* result = realpath(path.c_str(), resolved_path); if (result) return std::string(resolved_path); else return path; #endif } <commit_msg>Replaced find_first_of with find<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <stdlib.h> #include <string.h> #include <limits.h> #include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #ifdef WIN32 #define _WIN32_WINNT 0x0500 #include <windows.h> #endif #if defined(__sgi) #include <ctype.h> #elif defined(__GNUC__) || !defined(WIN32) || defined(__MWERKS__) #include <cctype> using std::tolower; #endif using namespace std; std::string osgDB::getFilePath(const std::string& fileName) { std::string::size_type slash1 = fileName.find_last_of('/'); std::string::size_type slash2 = fileName.find_last_of('\\'); if (slash1==std::string::npos) { if (slash2==std::string::npos) return std::string(); return std::string(fileName,0,slash2); } if (slash2==std::string::npos) return std::string(fileName,0,slash1); return std::string(fileName, 0, slash1>slash2 ? slash1 : slash2); } std::string osgDB::getSimpleFileName(const std::string& fileName) { std::string::size_type slash1 = fileName.find_last_of('/'); std::string::size_type slash2 = fileName.find_last_of('\\'); if (slash1==std::string::npos) { if (slash2==std::string::npos) return fileName; return std::string(fileName.begin()+slash2+1,fileName.end()); } if (slash2==std::string::npos) return std::string(fileName.begin()+slash1+1,fileName.end()); return std::string(fileName.begin()+(slash1>slash2?slash1:slash2)+1,fileName.end()); } std::string osgDB::getFileExtension(const std::string& fileName) { std::string::size_type dot = fileName.find_last_of('.'); if (dot==std::string::npos) return std::string(""); return std::string(fileName.begin()+dot+1,fileName.end()); } std::string osgDB::getFileExtensionIncludingDot(const std::string& fileName) { std::string::size_type dot = fileName.find_last_of('.'); if (dot==std::string::npos) return std::string(""); return std::string(fileName.begin()+dot,fileName.end()); } std::string osgDB::convertFileNameToWindowsStyle(const std::string& fileName) { std::string new_fileName(fileName); std::string::size_type slash = 0; while( (slash=new_fileName.find_first_of('/',slash)) != std::string::npos) { new_fileName[slash]='\\'; } return new_fileName; } std::string osgDB::convertFileNameToUnixStyle(const std::string& fileName) { std::string new_fileName(fileName); std::string::size_type slash = 0; while( (slash=new_fileName.find_first_of('\\',slash)) != std::string::npos) { new_fileName[slash]='/'; } return new_fileName; } bool osgDB::isFileNameNativeStyle(const std::string& fileName) { #if defined(WIN32) && !defined(__CYGWIN__) return fileName.find('/') == std::string::npos; // return true if no unix style slash exist #else return fileName.find('\\') == std::string::npos; // return true if no windows style slash exist #endif } std::string osgDB::convertFileNameToNativeStyle(const std::string& fileName) { #if defined(WIN32) && !defined(__CYGWIN__) return convertFileNameToWindowsStyle(fileName); #else return convertFileNameToUnixStyle(fileName); #endif } std::string osgDB::getLowerCaseFileExtension(const std::string& filename) { return convertToLowerCase(osgDB::getFileExtension(filename)); } std::string osgDB::convertToLowerCase(const std::string& str) { std::string lowcase_str(str); for(std::string::iterator itr=lowcase_str.begin(); itr!=lowcase_str.end(); ++itr) { *itr = tolower(*itr); } return lowcase_str; } // strip one level of extension from the filename. std::string osgDB::getNameLessExtension(const std::string& fileName) { std::string::size_type dot = fileName.find_last_of('.'); std::string::size_type back_slash = fileName.find_last_of('\\'); std::string::size_type slash = fileName.find_last_of('/'); if (dot==std::string::npos || (dot<back_slash && dot<slash)) return fileName; return std::string(fileName.begin(),fileName.begin()+dot); } std::string osgDB::getStrippedName(const std::string& fileName) { std::string simpleName = getSimpleFileName(fileName); return getNameLessExtension( simpleName ); } bool osgDB::equalCaseInsensitive(const std::string& lhs,const std::string& rhs) { if (lhs.size()!=rhs.size()) return false; std::string::const_iterator litr = lhs.begin(); std::string::const_iterator ritr = rhs.begin(); while (litr!=lhs.end()) { if (tolower(*litr)!=tolower(*ritr)) return false; ++litr; ++ritr; } return true; } bool osgDB::equalCaseInsensitive(const std::string& lhs,const char* rhs) { if (rhs==NULL || lhs.size()!=strlen(rhs)) return false; std::string::const_iterator litr = lhs.begin(); const char* cptr = rhs; while (litr!=lhs.end()) { if (tolower(*litr)!=tolower(*cptr)) return false; ++litr; ++cptr; } return true; } bool osgDB::containsServerAddress(const std::string& filename) { // need to check for :// std::string::size_type pos(filename.find("://")); if (pos == std::string::npos) return false; std::string proto(filename.substr(0, pos)); return Registry::instance()->isProtocolRegistered(proto); } std::string osgDB::getServerProtocol(const std::string& filename) { std::string::size_type pos(filename.find("://")); if (pos != std::string::npos) return filename.substr(0,pos); return ""; } std::string osgDB::getServerAddress(const std::string& filename) { std::string::size_type pos(filename.find("://")); if (pos != std::string::npos) { std::string::size_type pos_slash = filename.find_first_of('/',pos+3); if (pos_slash!=std::string::npos) { return filename.substr(pos+3,pos_slash-pos-3); } else { return filename.substr(pos+3,std::string::npos); } } return ""; } std::string osgDB::getServerFileName(const std::string& filename) { std::string::size_type pos(filename.find("://")); if (pos != std::string::npos) { std::string::size_type pos_slash = filename.find_first_of('/',pos+3); if (pos_slash!=std::string::npos) { return filename.substr(pos_slash+1,std::string::npos); } else { return ""; } } return filename; } std::string osgDB::concatPaths(const std::string& left, const std::string& right) { #if defined(WIN32) && !defined(__CYGWIN__) const char delimiterNative = '\\'; const char delimiterForeign = '/'; #else const char delimiterNative = '/'; const char delimiterForeign = '\\'; #endif if(left.empty()) { return(right); } char lastChar = left[left.size() - 1]; if(lastChar == delimiterNative) { return left + right; } else if(lastChar == delimiterForeign) { return left.substr(0, left.size() - 1) + delimiterNative + right; } else // lastChar != a delimiter { return left + delimiterNative + right; } } std::string osgDB::getRealPath(const std::string& path) { #if defined(WIN32) && !defined(__CYGWIN__) // Not unicode compatible should give an error if UNICODE defined char retbuf[MAX_PATH + 1]; char tempbuf1[MAX_PATH + 1]; GetFullPathName(path.c_str(), sizeof(retbuf), retbuf, NULL); // Force drive letter to upper case if ((retbuf[1] == ':') && islower(retbuf[0])) retbuf[0] = _toupper(retbuf[0]); if (fileExists(std::string(retbuf))) { // Canonicalise the full path GetShortPathName(retbuf, tempbuf1, sizeof(tempbuf1)); GetLongPathName(tempbuf1, retbuf, sizeof(retbuf)); return std::string(retbuf); } else { // Canonicalise the directories std::string FilePath = getFilePath(retbuf); char tempbuf2[MAX_PATH + 1]; if (0 == GetShortPathName(FilePath.c_str(), tempbuf1, sizeof(tempbuf1))) return std::string(retbuf); if (0 == GetLongPathName(tempbuf1, tempbuf2, sizeof(tempbuf2))) return std::string(retbuf); FilePath = std::string(tempbuf2); FilePath.append("\\"); FilePath.append(getSimpleFileName(std::string(retbuf))); return FilePath; } #else char resolved_path[PATH_MAX]; char* result = realpath(path.c_str(), resolved_path); if (result) return std::string(resolved_path); else return path; #endif } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/syscall_time.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* COPYRIGHT International Business Machines Corp. 2010,2014 */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include <time.h> #include <sys/time.h> #include <sys/syscall.h> #include <errno.h> #include <kernel/timemgr.H> using namespace Systemcalls; void nanosleep(uint64_t sec, uint64_t nsec) { // If the delay is short then simpleDelay() will perform the delay if(unlikely(!TimeManager::simpleDelay(sec, nsec))) { _syscall2(TIME_NANOSLEEP, (void*)sec, (void*)nsec); } } int clock_gettime(clockid_t clk_id, timespec_t* tp) { if (unlikely(NULL == tp)) { return -EFAULT; } int rc = 0; switch(clk_id) { case CLOCK_REALTIME: // TODO: Need a message to the FSP to get the // real-time. rc = -EINVAL; break; case CLOCK_MONOTONIC: TimeManager::convertTicksToSec(getTB(), tp->tv_sec, tp->tv_nsec); break; default: rc = -EINVAL; break; } return rc; } <commit_msg>Handle overruns in nanosleep<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/syscall_time.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2010,2018 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include <time.h> #include <sys/time.h> #include <sys/syscall.h> #include <errno.h> #include <kernel/timemgr.H> #include <kernel/console.H> #include <sys/task.h> using namespace Systemcalls; void nanosleep(uint64_t i_sec, uint64_t i_nsec) { uint64_t l_sec = i_sec + i_nsec/NS_PER_SEC; uint64_t l_nsec = i_nsec%NS_PER_SEC; // If the delay is short then simpleDelay() will perform the delay if(unlikely(!TimeManager::simpleDelay(l_sec, l_nsec))) { _syscall2(TIME_NANOSLEEP, (void*)l_sec, (void*)l_nsec); } } int clock_gettime(clockid_t clk_id, timespec_t* tp) { if (unlikely(NULL == tp)) { return -EFAULT; } int rc = 0; switch(clk_id) { case CLOCK_REALTIME: // TODO: Need a message to the FSP to get the // real-time. rc = -EINVAL; break; case CLOCK_MONOTONIC: TimeManager::convertTicksToSec(getTB(), tp->tv_sec, tp->tv_nsec); break; default: rc = -EINVAL; break; } return rc; } <|endoftext|>
<commit_before>#include <stdio.h> #include <osg/Notify> #include <osg/Statistics> #include <osgUtil/RenderStage> using namespace osg; using namespace osgUtil; // register a RenderStage prototype with the RenderBin prototype list. //RegisterRenderBinProxy<RenderStage> s_registerRenderStageProxy; RenderStage::RenderStage(SortMode mode): RenderBin(mode) { // point RenderBin's _stage to this to ensure that references to // stage don't go tempted away to any other stage. _stage = this; _stageDrawnThisFrame = false; _clearMask = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT; _clearColor.set(0.0f,0.0f,0.0f,0.0f); _clearAccum.set(0.0f,0.0f,0.0f,0.0f); _clearDepth = 1.0; _clearStencil = 0; } RenderStage::RenderStage(const RenderStage& rhs,const osg::CopyOp& copyop): RenderBin(rhs,copyop), _stageDrawnThisFrame(false), _dependencyList(rhs._dependencyList), _viewport(rhs._viewport), _clearMask(rhs._clearMask), _colorMask(rhs._colorMask), _clearColor(rhs._clearColor), _clearAccum(rhs._clearAccum), _clearDepth(rhs._clearDepth), _clearStencil(rhs._clearStencil), _renderStageLighting(rhs._renderStageLighting) { } RenderStage::~RenderStage() { } void RenderStage::reset() { _dependencyList.clear(); _stageDrawnThisFrame = false; if (_renderStageLighting.valid()) _renderStageLighting->reset(); RenderBin::reset(); } void RenderStage::addToDependencyList(RenderStage* rs) { if (rs) _dependencyList.push_back(rs); } void RenderStage::draw(osg::State& state,RenderLeaf*& previous) { if (_stageDrawnThisFrame) return; if (!_viewport) { notify(FATAL) << "Error: cannot draw stage due to undefined viewport."<< std::endl; return; } _stageDrawnThisFrame = true; for(DependencyList::iterator itr=_dependencyList.begin(); itr!=_dependencyList.end(); ++itr) { (*itr)->draw(state,previous); } // set up the back buffer. state.applyAttribute(_viewport.get()); #define USE_SISSOR_TEST #ifdef USE_SISSOR_TEST glScissor( _viewport->x(), _viewport->y(), _viewport->width(), _viewport->height() ); glEnable( GL_SCISSOR_TEST ); #endif // glEnable( GL_DEPTH_TEST ); // set which color planes to operate on. if (_colorMask.valid()) _colorMask->apply(state); else glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE); if (_clearMask & GL_COLOR_BUFFER_BIT) glClearColor( _clearColor[0], _clearColor[1], _clearColor[2], _clearColor[3]); if (_clearMask & GL_DEPTH_BUFFER_BIT) glClearDepth( _clearDepth); if (_clearMask & GL_STENCIL_BUFFER_BIT) glClearStencil( _clearStencil); if (_clearMask & GL_ACCUM_BUFFER_BIT) glClearAccum( _clearAccum[0], _clearAccum[1], _clearAccum[2], _clearAccum[3]); glClear( _clearMask ); #ifdef USE_SISSOR_TEST glDisable( GL_SCISSOR_TEST ); #endif glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); // apply the lights. if (_renderStageLighting.valid()) _renderStageLighting->draw(state,previous); // draw the children and local. RenderBin::draw(state,previous); // now reset the state so its back in its default state. if (previous) { RenderGraph::moveToRootRenderGraph(state,previous->_parent); state.apply(); previous = NULL; } } // Statistics features bool RenderStage::getStats(Statistics* primStats) { if (_renderStageLighting.valid()) { // need to re-implement by checking for lights in the scene // by downcasting the positioned attribute list. RO. May 2002. //primStats->addLight(_renderStageLighting->_lightList.size()); } return RenderBin::getStats(primStats); } <commit_msg>Fixed copy constructor so that the _stage member variable was set to this correctly.<commit_after>#include <stdio.h> #include <osg/Notify> #include <osg/Statistics> #include <osgUtil/RenderStage> using namespace osg; using namespace osgUtil; // register a RenderStage prototype with the RenderBin prototype list. //RegisterRenderBinProxy<RenderStage> s_registerRenderStageProxy; RenderStage::RenderStage(SortMode mode): RenderBin(mode) { // point RenderBin's _stage to this to ensure that references to // stage don't go tempted away to any other stage. _stage = this; _stageDrawnThisFrame = false; _clearMask = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT; _clearColor.set(0.0f,0.0f,0.0f,0.0f); _clearAccum.set(0.0f,0.0f,0.0f,0.0f); _clearDepth = 1.0; _clearStencil = 0; } RenderStage::RenderStage(const RenderStage& rhs,const osg::CopyOp& copyop): RenderBin(rhs,copyop), _stageDrawnThisFrame(false), _dependencyList(rhs._dependencyList), _viewport(rhs._viewport), _clearMask(rhs._clearMask), _colorMask(rhs._colorMask), _clearColor(rhs._clearColor), _clearAccum(rhs._clearAccum), _clearDepth(rhs._clearDepth), _clearStencil(rhs._clearStencil), _renderStageLighting(rhs._renderStageLighting) { _stage = this; } RenderStage::~RenderStage() { } void RenderStage::reset() { _dependencyList.clear(); _stageDrawnThisFrame = false; if (_renderStageLighting.valid()) _renderStageLighting->reset(); RenderBin::reset(); } void RenderStage::addToDependencyList(RenderStage* rs) { if (rs) _dependencyList.push_back(rs); } void RenderStage::draw(osg::State& state,RenderLeaf*& previous) { if (_stageDrawnThisFrame) return; if (!_viewport) { notify(FATAL) << "Error: cannot draw stage due to undefined viewport."<< std::endl; return; } _stageDrawnThisFrame = true; for(DependencyList::iterator itr=_dependencyList.begin(); itr!=_dependencyList.end(); ++itr) { (*itr)->draw(state,previous); } // set up the back buffer. state.applyAttribute(_viewport.get()); #define USE_SISSOR_TEST #ifdef USE_SISSOR_TEST glScissor( _viewport->x(), _viewport->y(), _viewport->width(), _viewport->height() ); glEnable( GL_SCISSOR_TEST ); #endif // glEnable( GL_DEPTH_TEST ); // set which color planes to operate on. if (_colorMask.valid()) _colorMask->apply(state); else glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE); if (_clearMask & GL_COLOR_BUFFER_BIT) glClearColor( _clearColor[0], _clearColor[1], _clearColor[2], _clearColor[3]); if (_clearMask & GL_DEPTH_BUFFER_BIT) glClearDepth( _clearDepth); if (_clearMask & GL_STENCIL_BUFFER_BIT) glClearStencil( _clearStencil); if (_clearMask & GL_ACCUM_BUFFER_BIT) glClearAccum( _clearAccum[0], _clearAccum[1], _clearAccum[2], _clearAccum[3]); glClear( _clearMask ); #ifdef USE_SISSOR_TEST glDisable( GL_SCISSOR_TEST ); #endif glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); // apply the lights. if (_renderStageLighting.valid()) _renderStageLighting->draw(state,previous); // draw the children and local. RenderBin::draw(state,previous); // now reset the state so its back in its default state. if (previous) { RenderGraph::moveToRootRenderGraph(state,previous->_parent); state.apply(); previous = NULL; } } // Statistics features bool RenderStage::getStats(Statistics* primStats) { if (_renderStageLighting.valid()) { // need to re-implement by checking for lights in the scene // by downcasting the positioned attribute list. RO. May 2002. //primStats->addLight(_renderStageLighting->_lightList.size()); } return RenderBin::getStats(primStats); } <|endoftext|>
<commit_before>// ****************************************************************************************** // * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com * // ****************************************************************************************** #include "player_sys.sqf" class playerSettings { idd = playersys_DIALOG; movingEnable = true; enableSimulation = true; onLoad = "[] execVM 'client\systems\playerMenu\item_list.sqf'"; class controlsBackground { class MainBG : w_RscPicture { idc = -1; colorText[] = {1, 1, 1, 1}; colorBackground[] = {0,0,0,0}; text = "#(argb,8,8,3)color(0,0,0,0.6)"; moving = true; x = 0.0; y = 0.1; w = .745; h = 0.65; }; class TopBar: w_RscPicture { idc = -1; colorText[] = {1, 1, 1, 1}; colorBackground[] = {0,0,0,0}; text = "#(argb,8,8,3)color(0.25,0.51,0.96,0.8)"; x = 0; y = 0.1; w = 0.745; h = 0.05; }; class MainTitle : w_RscText { idc = -1; text = "Player Inventory"; sizeEx = 0.04; shadow = 2; x = 0.260; y = 0.1; w = 0.3; h = 0.05; }; class waterIcon : w_RscPicture { idc = -1; text = "client\icons\water.paa"; x = 0.022; y = 0.2; w = 0.04 / (4/3); h = 0.04; }; class foodIcon : w_RscPicture { idc = -1; text = "client\icons\food.paa"; x = 0.022; y = 0.26; w = 0.04 / (4/3); h = 0.04; }; class moneyIcon : w_RscPicture { idc = -1; text = "client\icons\money.paa"; x = 0.022; y = 0.32; w = 0.04 / (4/3); h = 0.04; }; class waterText : w_RscText { idc = water_text; text = ""; sizeEx = 0.03; x = 0.06; y = 0.193; w = 0.3; h = 0.05; }; class foodText : w_RscText { idc = food_text; sizeEx = 0.03; text = ""; x = 0.06; y = 0.254; w = 0.3; h = 0.05; }; class moneyText : w_RscText { idc = money_text; text = ""; sizeEx = 0.03; x = 0.06; y = 0.313; w = 0.3; h = 0.05; }; class distanceText : w_RscText { idc = view_range_text; text = "View range:"; sizeEx = 0.025; x = 0.03; y = 0.40; w = 0.3; h = 0.02; }; class uptimeText : w_RscText { idc = uptime_text; text = ""; sizeEx = 0.030; x = 0.52; y = 0.69; w = 0.225; h = 0.03; }; }; class controls { class itemList : w_Rsclist { idc = item_list; x = 0.49; y = 0.185; w = 0.235; h = 0.325; }; class DropButton : w_RscButton { idc = -1; text = "Drop"; onButtonClick = "[1] execVM 'client\systems\playerMenu\itemfnc.sqf'"; x = 0.610; y = 0.525; w = 0.116; h = 0.033 * safezoneH; }; class UseButton : w_RscButton { idc = -1; text = "Use"; onButtonClick = "[0] execVM 'client\systems\playerMenu\itemfnc.sqf'"; x = 0.489; y = 0.525; w = 0.116; h = 0.033 * safezoneH; }; class moneyInput: w_RscCombo { idc = money_value; x = 0.610; y = 0.618; w = .116; h = .030; }; class DropcButton : w_RscButton { idc = -1; text = "Drop"; onButtonClick = "[] execVM 'client\systems\playerMenu\dropMoney.sqf'"; x = 0.489; y = 0.60; w = 0.116; h = 0.033 * safezoneH; }; class CloseButton : w_RscButton { idc = close_button; text = "Close"; onButtonClick = "[] execVM 'client\systems\playerMenu\closePlayerMenu.sqf'"; x = 0.02; y = 0.66; w = 0.125; h = 0.033 * safezoneH; }; class GroupsButton : w_RscButton { idc = groupButton; text = "Group Management"; onButtonClick = "[] execVM 'client\systems\groups\loadGroupManagement.sqf'"; x = 0.158; y = 0.66; w = 0.225; h = 0.033 * safezoneH; }; class btnDistanceNear : w_RscButton { idc = -1; text = "Near"; onButtonClick = "setViewDistance 1100;"; x = 0.02; y = 0.43; w = 0.125; h = 0.033 * safezoneH; }; class btnDistanceMedium : w_RscButton { idc = -1; text = "Medium"; onButtonClick = "setViewDistance 2200;"; x = 0.02; y = 0.5; w = 0.125; h = 0.033 * safezoneH; }; class btnDistanceFar : w_RscButton { idc = -1; text = "Far"; onButtonClick = "setViewDistance 3300;"; x = 0.02; y = 0.57; w = 0.125; h = 0.033 * safezoneH; }; class btnDistanceInsane : w_RscButton { text = "Insane"; onButtonClick = "setViewDistance 5000;"; x = 0.02; y = 0.60; w = 0.125; h = 0.033 * safezoneH; }; }; }; <commit_msg>Adjust position to reveal Insane View Distance Button<commit_after>// ****************************************************************************************** // * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com * // ****************************************************************************************** #include "player_sys.sqf" class playerSettings { idd = playersys_DIALOG; movingEnable = true; enableSimulation = true; onLoad = "[] execVM 'client\systems\playerMenu\item_list.sqf'"; class controlsBackground { class MainBG : w_RscPicture { idc = -1; colorText[] = {1, 1, 1, 1}; colorBackground[] = {0,0,0,0}; text = "#(argb,8,8,3)color(0,0,0,0.6)"; moving = true; x = 0.0; y = 0.1; w = .745; h = 0.65; }; class TopBar: w_RscPicture { idc = -1; colorText[] = {1, 1, 1, 1}; colorBackground[] = {0,0,0,0}; text = "#(argb,8,8,3)color(0.25,0.51,0.96,0.8)"; x = 0; y = 0.1; w = 0.745; h = 0.05; }; class MainTitle : w_RscText { idc = -1; text = "Player Inventory"; sizeEx = 0.04; shadow = 2; x = 0.260; y = 0.1; w = 0.3; h = 0.05; }; class waterIcon : w_RscPicture { idc = -1; text = "client\icons\water.paa"; x = 0.022; y = 0.2; w = 0.04 / (4/3); h = 0.04; }; class foodIcon : w_RscPicture { idc = -1; text = "client\icons\food.paa"; x = 0.022; y = 0.26; w = 0.04 / (4/3); h = 0.04; }; class moneyIcon : w_RscPicture { idc = -1; text = "client\icons\money.paa"; x = 0.022; y = 0.32; w = 0.04 / (4/3); h = 0.04; }; class waterText : w_RscText { idc = water_text; text = ""; sizeEx = 0.03; x = 0.06; y = 0.193; w = 0.3; h = 0.05; }; class foodText : w_RscText { idc = food_text; sizeEx = 0.03; text = ""; x = 0.06; y = 0.254; w = 0.3; h = 0.05; }; class moneyText : w_RscText { idc = money_text; text = ""; sizeEx = 0.03; x = 0.06; y = 0.313; w = 0.3; h = 0.05; }; class distanceText : w_RscText { idc = view_range_text; text = "View range:"; sizeEx = 0.025; x = 0.03; y = 0.40; w = 0.3; h = 0.02; }; class uptimeText : w_RscText { idc = uptime_text; text = ""; sizeEx = 0.030; x = 0.52; y = 0.69; w = 0.225; h = 0.03; }; }; class controls { class itemList : w_Rsclist { idc = item_list; x = 0.49; y = 0.185; w = 0.235; h = 0.325; }; class DropButton : w_RscButton { idc = -1; text = "Drop"; onButtonClick = "[1] execVM 'client\systems\playerMenu\itemfnc.sqf'"; x = 0.610; y = 0.525; w = 0.116; h = 0.033 * safezoneH; }; class UseButton : w_RscButton { idc = -1; text = "Use"; onButtonClick = "[0] execVM 'client\systems\playerMenu\itemfnc.sqf'"; x = 0.489; y = 0.525; w = 0.116; h = 0.033 * safezoneH; }; class moneyInput: w_RscCombo { idc = money_value; x = 0.610; y = 0.618; w = .116; h = .030; }; class DropcButton : w_RscButton { idc = -1; text = "Drop"; onButtonClick = "[] execVM 'client\systems\playerMenu\dropMoney.sqf'"; x = 0.489; y = 0.60; w = 0.116; h = 0.033 * safezoneH; }; class CloseButton : w_RscButton { idc = close_button; text = "Close"; onButtonClick = "[] execVM 'client\systems\playerMenu\closePlayerMenu.sqf'"; x = 0.02; y = 0.66; w = 0.125; h = 0.033 * safezoneH; }; class GroupsButton : w_RscButton { idc = groupButton; text = "Group Management"; onButtonClick = "[] execVM 'client\systems\groups\loadGroupManagement.sqf'"; x = 0.158; y = 0.66; w = 0.225; h = 0.033 * safezoneH; }; class btnDistanceNear : w_RscButton { idc = -1; text = "Near"; onButtonClick = "setViewDistance 1100;"; x = 0.02; y = 0.43; w = 0.125; h = 0.033 * safezoneH; }; class btnDistanceMedium : w_RscButton { idc = -1; text = "Medium"; onButtonClick = "setViewDistance 2200;"; x = 0.02; y = 0.5; w = 0.125; h = 0.033 * safezoneH; }; class btnDistanceFar : w_RscButton { idc = -1; text = "Far"; onButtonClick = "setViewDistance 3300;"; x = 0.02; y = 0.57; w = 0.125; h = 0.033 * safezoneH; }; class btnDistanceInsane : w_RscButton { text = "Insane"; onButtonClick = "setViewDistance 5000;"; x = 0.158; y = 0.57; w = 0.125; h = 0.033 * safezoneH; }; }; }; <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include "TableFieldDescription.hxx" #include <tools/debug.hxx> #include <com/sun/star/sdbc/DataType.hpp> #include <comphelper/namedvaluecollection.hxx> #include <functional> using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace comphelper; using namespace dbaui; OTableFieldDesc::OTableFieldDesc() :m_pTabWindow(0) ,m_eDataType(1000) ,m_eFunctionType( FKT_NONE ) ,m_eFieldType(TAB_NORMAL_FIELD) ,m_eOrderDir( ORDER_NONE ) ,m_nIndex(0) ,m_nColWidth(0) ,m_nColumnId((sal_uInt16)-1) ,m_bGroupBy(false) ,m_bVisible(false) { } OTableFieldDesc::OTableFieldDesc(const OTableFieldDesc& rRS) : ::salhelper::SimpleReferenceObject() { *this = rRS; } OTableFieldDesc::OTableFieldDesc(const OUString& rT, const OUString& rF ) :m_pTabWindow(0) ,m_eDataType(1000) ,m_eFunctionType( FKT_NONE ) ,m_eFieldType(TAB_NORMAL_FIELD) ,m_eOrderDir( ORDER_NONE ) ,m_nIndex(0) ,m_nColWidth(0) ,m_nColumnId((sal_uInt16)-1) ,m_bGroupBy(false) ,m_bVisible(false) { SetField( rF ); SetTable( rT ); } OTableFieldDesc::~OTableFieldDesc() { } OTableFieldDesc& OTableFieldDesc::operator=( const OTableFieldDesc& rRS ) { if (&rRS == this) return *this; m_aCriteria = rRS.GetCriteria(); m_aTableName = rRS.GetTable(); m_aAliasName = rRS.GetAlias(); // table range m_aFieldName = rRS.GetField(); // column m_aFieldAlias = rRS.GetFieldAlias(); // column alias m_aFunctionName = rRS.GetFunction(); // Funktionsname m_pTabWindow = rRS.GetTabWindow(); m_eDataType = rRS.GetDataType(); m_eFunctionType = rRS.GetFunctionType(); m_eFieldType = rRS.GetFieldType(); m_eOrderDir = rRS.GetOrderDir(); m_nIndex = rRS.GetFieldIndex(); m_nColWidth = rRS.GetColWidth(); m_nColumnId = rRS.m_nColumnId; m_bGroupBy = rRS.IsGroupBy(); m_bVisible = rRS.IsVisible(); return *this; } bool OTableFieldDesc::operator==( const OTableFieldDesc& rDesc ) { return ( m_eOrderDir != rDesc.GetOrderDir() || m_eDataType != rDesc.GetDataType() || m_aAliasName != rDesc.GetAlias() || m_aFunctionName != rDesc.GetFunction() || m_aFieldName != rDesc.GetField() || m_aTableName != rDesc.GetTable() || m_bGroupBy != rDesc.IsGroupBy() || m_aCriteria != rDesc.GetCriteria() || m_bVisible != rDesc.IsVisible() ); } void OTableFieldDesc::SetCriteria( sal_uInt16 nIdx, const OUString& rCrit) { if (nIdx < m_aCriteria.size()) m_aCriteria[nIdx] = rCrit; else { for(sal_Int32 i=m_aCriteria.size();i<nIdx;++i) m_aCriteria.push_back( OUString()); m_aCriteria.push_back(rCrit); } } OUString OTableFieldDesc::GetCriteria( sal_uInt16 nIdx ) const { OUString aRetStr; if( nIdx < m_aCriteria.size()) aRetStr = m_aCriteria[nIdx]; return aRetStr; } namespace { struct SelectPropertyValueAsString : public ::std::unary_function< PropertyValue, OUString > { OUString operator()( const PropertyValue& i_rPropValue ) const { OUString sValue; OSL_VERIFY( i_rPropValue.Value >>= sValue ); return sValue; } }; } void OTableFieldDesc::Load( const ::com::sun::star::beans::PropertyValue& i_rSettings, const bool i_bIncludingCriteria ) { ::comphelper::NamedValueCollection aFieldDesc( i_rSettings.Value ); m_aAliasName = aFieldDesc.getOrDefault( "AliasName", m_aAliasName ); m_aTableName = aFieldDesc.getOrDefault( "TableName", m_aTableName ); m_aFieldName = aFieldDesc.getOrDefault( "FieldName", m_aFieldName ); m_aFieldAlias = aFieldDesc.getOrDefault( "FieldAlias", m_aFieldAlias ); m_aFunctionName = aFieldDesc.getOrDefault( "FunctionName", m_aFunctionName ); m_eDataType = aFieldDesc.getOrDefault( "DataType", m_eDataType ); m_eFunctionType = aFieldDesc.getOrDefault( "FunctionType", m_eFunctionType ); m_nColWidth = aFieldDesc.getOrDefault( "ColWidth", m_nColWidth ); m_bGroupBy = aFieldDesc.getOrDefault( "GroupBy", m_bGroupBy ); m_bVisible = aFieldDesc.getOrDefault( "Visible", m_bVisible ); m_eFieldType = static_cast< ETableFieldType >( aFieldDesc.getOrDefault( "FieldType", static_cast< sal_Int32 >( m_eFieldType ) ) ); m_eOrderDir = static_cast< EOrderDir >( aFieldDesc.getOrDefault( "OrderDir", static_cast< sal_Int32 >( m_eOrderDir ) ) ); if ( i_bIncludingCriteria ) { const Sequence< PropertyValue > aCriteria( aFieldDesc.getOrDefault( "Criteria", Sequence< PropertyValue >() ) ); m_aCriteria.resize( aCriteria.getLength() ); ::std::transform( aCriteria.getConstArray(), aCriteria.getConstArray() + aCriteria.getLength(), m_aCriteria.begin(), SelectPropertyValueAsString() ); } } void OTableFieldDesc::Save( ::comphelper::NamedValueCollection& o_rSettings, const bool i_bIncludingCriteria ) { o_rSettings.put( "AliasName", m_aAliasName ); o_rSettings.put( "TableName", m_aTableName ); o_rSettings.put( "FieldName", m_aFieldName ); o_rSettings.put( "FieldAlias", m_aFieldAlias ); o_rSettings.put( "FunctionName", m_aFunctionName ); o_rSettings.put( "DataType", m_eDataType ); o_rSettings.put( "FunctionType", (sal_Int32)m_eFunctionType ); o_rSettings.put( "FieldType", (sal_Int32)m_eFieldType ); o_rSettings.put( "OrderDir", (sal_Int32)m_eOrderDir ); o_rSettings.put( "ColWidth", m_nColWidth ); o_rSettings.put( "GroupBy", m_bGroupBy ); o_rSettings.put( "Visible", m_bVisible ); if ( i_bIncludingCriteria ) { if ( !m_aCriteria.empty() ) { sal_Int32 c = 0; Sequence< PropertyValue > aCriteria( m_aCriteria.size() ); for ( ::std::vector< OUString >::const_iterator crit = m_aCriteria.begin(); crit != m_aCriteria.end(); ++crit, ++c ) { aCriteria[c].Name = "Criterion_" + OUString::number( c ); aCriteria[c].Value <<= *crit; } o_rSettings.put( "Criteria", aCriteria ); } } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>coverity#707746 Uninitialized pointer field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include "TableFieldDescription.hxx" #include <tools/debug.hxx> #include <com/sun/star/sdbc/DataType.hpp> #include <comphelper/namedvaluecollection.hxx> #include <functional> using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace comphelper; using namespace dbaui; OTableFieldDesc::OTableFieldDesc() :m_pTabWindow(0) ,m_eDataType(1000) ,m_eFunctionType( FKT_NONE ) ,m_eFieldType(TAB_NORMAL_FIELD) ,m_eOrderDir( ORDER_NONE ) ,m_nIndex(0) ,m_nColWidth(0) ,m_nColumnId((sal_uInt16)-1) ,m_bGroupBy(false) ,m_bVisible(false) { } OTableFieldDesc::OTableFieldDesc(const OTableFieldDesc& rRS) : ::salhelper::SimpleReferenceObject() , m_pTabWindow(NULL) { *this = rRS; } OTableFieldDesc::OTableFieldDesc(const OUString& rT, const OUString& rF ) :m_pTabWindow(0) ,m_eDataType(1000) ,m_eFunctionType( FKT_NONE ) ,m_eFieldType(TAB_NORMAL_FIELD) ,m_eOrderDir( ORDER_NONE ) ,m_nIndex(0) ,m_nColWidth(0) ,m_nColumnId((sal_uInt16)-1) ,m_bGroupBy(false) ,m_bVisible(false) { SetField( rF ); SetTable( rT ); } OTableFieldDesc::~OTableFieldDesc() { } OTableFieldDesc& OTableFieldDesc::operator=( const OTableFieldDesc& rRS ) { if (&rRS == this) return *this; m_aCriteria = rRS.GetCriteria(); m_aTableName = rRS.GetTable(); m_aAliasName = rRS.GetAlias(); // table range m_aFieldName = rRS.GetField(); // column m_aFieldAlias = rRS.GetFieldAlias(); // column alias m_aFunctionName = rRS.GetFunction(); // Funktionsname m_pTabWindow = rRS.GetTabWindow(); m_eDataType = rRS.GetDataType(); m_eFunctionType = rRS.GetFunctionType(); m_eFieldType = rRS.GetFieldType(); m_eOrderDir = rRS.GetOrderDir(); m_nIndex = rRS.GetFieldIndex(); m_nColWidth = rRS.GetColWidth(); m_nColumnId = rRS.m_nColumnId; m_bGroupBy = rRS.IsGroupBy(); m_bVisible = rRS.IsVisible(); return *this; } bool OTableFieldDesc::operator==( const OTableFieldDesc& rDesc ) { return ( m_eOrderDir != rDesc.GetOrderDir() || m_eDataType != rDesc.GetDataType() || m_aAliasName != rDesc.GetAlias() || m_aFunctionName != rDesc.GetFunction() || m_aFieldName != rDesc.GetField() || m_aTableName != rDesc.GetTable() || m_bGroupBy != rDesc.IsGroupBy() || m_aCriteria != rDesc.GetCriteria() || m_bVisible != rDesc.IsVisible() ); } void OTableFieldDesc::SetCriteria( sal_uInt16 nIdx, const OUString& rCrit) { if (nIdx < m_aCriteria.size()) m_aCriteria[nIdx] = rCrit; else { for(sal_Int32 i=m_aCriteria.size();i<nIdx;++i) m_aCriteria.push_back( OUString()); m_aCriteria.push_back(rCrit); } } OUString OTableFieldDesc::GetCriteria( sal_uInt16 nIdx ) const { OUString aRetStr; if( nIdx < m_aCriteria.size()) aRetStr = m_aCriteria[nIdx]; return aRetStr; } namespace { struct SelectPropertyValueAsString : public ::std::unary_function< PropertyValue, OUString > { OUString operator()( const PropertyValue& i_rPropValue ) const { OUString sValue; OSL_VERIFY( i_rPropValue.Value >>= sValue ); return sValue; } }; } void OTableFieldDesc::Load( const ::com::sun::star::beans::PropertyValue& i_rSettings, const bool i_bIncludingCriteria ) { ::comphelper::NamedValueCollection aFieldDesc( i_rSettings.Value ); m_aAliasName = aFieldDesc.getOrDefault( "AliasName", m_aAliasName ); m_aTableName = aFieldDesc.getOrDefault( "TableName", m_aTableName ); m_aFieldName = aFieldDesc.getOrDefault( "FieldName", m_aFieldName ); m_aFieldAlias = aFieldDesc.getOrDefault( "FieldAlias", m_aFieldAlias ); m_aFunctionName = aFieldDesc.getOrDefault( "FunctionName", m_aFunctionName ); m_eDataType = aFieldDesc.getOrDefault( "DataType", m_eDataType ); m_eFunctionType = aFieldDesc.getOrDefault( "FunctionType", m_eFunctionType ); m_nColWidth = aFieldDesc.getOrDefault( "ColWidth", m_nColWidth ); m_bGroupBy = aFieldDesc.getOrDefault( "GroupBy", m_bGroupBy ); m_bVisible = aFieldDesc.getOrDefault( "Visible", m_bVisible ); m_eFieldType = static_cast< ETableFieldType >( aFieldDesc.getOrDefault( "FieldType", static_cast< sal_Int32 >( m_eFieldType ) ) ); m_eOrderDir = static_cast< EOrderDir >( aFieldDesc.getOrDefault( "OrderDir", static_cast< sal_Int32 >( m_eOrderDir ) ) ); if ( i_bIncludingCriteria ) { const Sequence< PropertyValue > aCriteria( aFieldDesc.getOrDefault( "Criteria", Sequence< PropertyValue >() ) ); m_aCriteria.resize( aCriteria.getLength() ); ::std::transform( aCriteria.getConstArray(), aCriteria.getConstArray() + aCriteria.getLength(), m_aCriteria.begin(), SelectPropertyValueAsString() ); } } void OTableFieldDesc::Save( ::comphelper::NamedValueCollection& o_rSettings, const bool i_bIncludingCriteria ) { o_rSettings.put( "AliasName", m_aAliasName ); o_rSettings.put( "TableName", m_aTableName ); o_rSettings.put( "FieldName", m_aFieldName ); o_rSettings.put( "FieldAlias", m_aFieldAlias ); o_rSettings.put( "FunctionName", m_aFunctionName ); o_rSettings.put( "DataType", m_eDataType ); o_rSettings.put( "FunctionType", (sal_Int32)m_eFunctionType ); o_rSettings.put( "FieldType", (sal_Int32)m_eFieldType ); o_rSettings.put( "OrderDir", (sal_Int32)m_eOrderDir ); o_rSettings.put( "ColWidth", m_nColWidth ); o_rSettings.put( "GroupBy", m_bGroupBy ); o_rSettings.put( "Visible", m_bVisible ); if ( i_bIncludingCriteria ) { if ( !m_aCriteria.empty() ) { sal_Int32 c = 0; Sequence< PropertyValue > aCriteria( m_aCriteria.size() ); for ( ::std::vector< OUString >::const_iterator crit = m_aCriteria.begin(); crit != m_aCriteria.end(); ++crit, ++c ) { aCriteria[c].Name = "Criterion_" + OUString::number( c ); aCriteria[c].Value <<= *crit; } o_rSettings.put( "Criteria", aCriteria ); } } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* Copyright (C) 2005-2018 Steven L. Scott 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 "test_utils/check_derivatives.hpp" #include "test_utils/test_utils.hpp" #include "numopt/NumericalDerivatives.hpp" #include <sstream> namespace BOOM { namespace { // If everything in g and h is within epsilon of 0 return true. Otherwise // return false. bool all_zeros(const Vector &g, const Matrix &h, double epsilon) { for (int i = 0; i < g.size(); ++i) { if (fabs(g[i]) > epsilon) return false; } for (int i = 0; i < h.nrow(); ++i) { for (int j = 0; j < h.ncol(); ++j) { if (fabs(h(i, j)) > epsilon) { return false; } } } return true; } } std::string CheckDerivatives(DerivativeTestTarget target, const Vector &evaluation_point, double epsilon) { using std::endl; NumericalDerivatives derivs( [&target](const Vector &x) { Vector g; Matrix h; return target(x, g, h, 0); }); int dim = evaluation_point.size(); Vector analytic_gradient(dim); Matrix analytic_hessian(dim, dim); target(evaluation_point, analytic_gradient, analytic_hessian, 2); std::ostringstream err; if (all_zeros(analytic_gradient, analytic_hessian, epsilon)) { return "Test function was constant at evaluation point."; } Vector numeric_gradient = derivs.gradient(evaluation_point); if (!VectorEquals(analytic_gradient, numeric_gradient, epsilon)) { err << "gradient does not match." << endl << "analytic numeric" << endl << cbind(analytic_gradient, numeric_gradient) << "maximum absolute deviation: " << (numeric_gradient - analytic_gradient).max_abs(); return err.str(); } Matrix numeric_hessian = derivs.Hessian(evaluation_point); if (!MatrixEquals(analytic_hessian, numeric_hessian, epsilon)) { err << "Hessian does not match." << endl << "Analytic Hessian: " << endl << analytic_hessian << "Numeric Hessian: " << endl << numeric_hessian << "maximum absolute deviation: " << (numeric_hessian - analytic_hessian).max_abs(); return err.str(); } return ""; } //=========================================================================== std::string CheckDerivatives(PointerDerivativeTestTarget &target, const Vector &evaluation_point, double epsilon) { using std::endl; DerivativeTestTarget real_target = [&target](const Vector &v, Vector &gradient, Matrix &hessian, int nd) { return target(v, nd > 0 ? &gradient : nullptr, nd > 1 ? &hessian : nullptr); }; return CheckDerivatives(real_target, evaluation_point, epsilon); } //=========================================================================== std::string CheckDerivatives(ScalarDerivativeTestTarget target, double evaluation_point, double epsilon) { // Compute analytic derivatives. double g = 0, h = 0; target(evaluation_point, g, h, 2); if (fabs(g) < epsilon && fabs(h) < epsilon) { return "Test function was constant at the evaluation point."; } ScalarNumericalDerivatives derivs([target](double x) { double g, h; return target(x, g, h, 0); }); // Check first derivative. double d1_numeric = derivs.first_derivative(evaluation_point); std::ostringstream err; if (fabs(g - d1_numeric) > epsilon) { err << "first derivative does not match." << std::endl << "analytic: " << g << std::endl << "numeric: " << d1_numeric << std::endl; return err.str(); } // Check second derivative. double d2_numeric = derivs.second_derivative(evaluation_point); if (fabs(h - d2_numeric) > epsilon) { err << "second derivative does not match." << std::endl << "analytic: " << h << std::endl << "numeric: " << d2_numeric << std::endl; return err.str(); } return ""; } } // namespace BOOM <commit_msg>trival comment update<commit_after>/* Copyright (C) 2005-2018 Steven L. Scott 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 "test_utils/check_derivatives.hpp" #include "test_utils/test_utils.hpp" #include "numopt/NumericalDerivatives.hpp" #include <sstream> namespace BOOM { namespace { // If everything in g and h is within epsilon of 0 return true. Otherwise // return false. bool all_zeros(const Vector &g, const Matrix &h, double epsilon) { for (int i = 0; i < g.size(); ++i) { if (fabs(g[i]) > epsilon) return false; } for (int i = 0; i < h.nrow(); ++i) { for (int j = 0; j < h.ncol(); ++j) { if (fabs(h(i, j)) > epsilon) { return false; } } } return true; } } // namespace std::string CheckDerivatives(DerivativeTestTarget target, const Vector &evaluation_point, double epsilon) { using std::endl; NumericalDerivatives derivs( [&target](const Vector &x) { Vector g; Matrix h; return target(x, g, h, 0); }); int dim = evaluation_point.size(); Vector analytic_gradient(dim); Matrix analytic_hessian(dim, dim); target(evaluation_point, analytic_gradient, analytic_hessian, 2); std::ostringstream err; if (all_zeros(analytic_gradient, analytic_hessian, epsilon)) { return "Test function was constant at evaluation point."; } Vector numeric_gradient = derivs.gradient(evaluation_point); if (!VectorEquals(analytic_gradient, numeric_gradient, epsilon)) { err << "gradient does not match." << endl << "analytic numeric" << endl << cbind(analytic_gradient, numeric_gradient) << "maximum absolute deviation: " << (numeric_gradient - analytic_gradient).max_abs(); return err.str(); } Matrix numeric_hessian = derivs.Hessian(evaluation_point); if (!MatrixEquals(analytic_hessian, numeric_hessian, epsilon)) { err << "Hessian does not match." << endl << "Analytic Hessian: " << endl << analytic_hessian << "Numeric Hessian: " << endl << numeric_hessian << "maximum absolute deviation: " << (numeric_hessian - analytic_hessian).max_abs(); return err.str(); } return ""; } //=========================================================================== std::string CheckDerivatives(PointerDerivativeTestTarget &target, const Vector &evaluation_point, double epsilon) { using std::endl; DerivativeTestTarget real_target = [&target](const Vector &v, Vector &gradient, Matrix &hessian, int nd) { return target(v, nd > 0 ? &gradient : nullptr, nd > 1 ? &hessian : nullptr); }; return CheckDerivatives(real_target, evaluation_point, epsilon); } //=========================================================================== std::string CheckDerivatives(ScalarDerivativeTestTarget target, double evaluation_point, double epsilon) { // Compute analytic derivatives. double g = 0, h = 0; target(evaluation_point, g, h, 2); if (fabs(g) < epsilon && fabs(h) < epsilon) { return "Test function was constant at the evaluation point."; } ScalarNumericalDerivatives derivs([target](double x) { double g, h; return target(x, g, h, 0); }); // Check first derivative. double d1_numeric = derivs.first_derivative(evaluation_point); std::ostringstream err; if (fabs(g - d1_numeric) > epsilon) { err << "first derivative does not match." << std::endl << "analytic: " << g << std::endl << "numeric: " << d1_numeric << std::endl; return err.str(); } // Check second derivative. double d2_numeric = derivs.second_derivative(evaluation_point); if (fabs(h - d2_numeric) > epsilon) { err << "second derivative does not match." << std::endl << "analytic: " << h << std::endl << "numeric: " << d2_numeric << std::endl; return err.str(); } return ""; } } // namespace BOOM <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QGraphicsWidget> #include <QTest> #include <QString> #include <QPixmap> #include <QSignalSpy> #include <QGraphicsSceneMouseEvent> #include <mimagewidget.h> #include "mcomponentdata.h" #include "ut_mimagewidget.h" Ut_MImageWidget::Ut_MImageWidget() : m_subject(0) { } void Ut_MImageWidget::initTestCase() { QImage img(qApp->applicationDirPath() + "/ut_mimagewidget-test.png"); if (! MComponentData::instance()) { static char *argv = 0; static int argc = 0; new MComponentData(argc, &argv, QString("ut_mimagewidget"), NULL); } m_subject = new MImageWidget(&img); QVERIFY(m_subject != 0); } void Ut_MImageWidget::cleanupTestCase() { delete m_subject; m_subject = 0; delete MComponentData::instance(); } void Ut_MImageWidget::testConstructor_data() { QTest::addColumn<QString>("fname"); QTest::newRow("png") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png"; } void Ut_MImageWidget::testConstructor() { QFETCH(QString, fname); QSize s; QPixmap pixmap(fname); s = pixmap.size(); // test load image files QImage img(fname); MImageWidget *myImage = new MImageWidget(&img); QCOMPARE(myImage->imageSize(), s); // test constructor from pixmap QPixmap *source = new QPixmap(s); source->fill(QColor(0, 0, 0, 0)); MImageWidget *myImage3 = new MImageWidget(source); QCOMPARE(myImage3->imageSize(), s); delete myImage3; // test copy constructor MImageWidget *myImage4 = new MImageWidget(*myImage); QCOMPARE(myImage4->imageSize(), myImage->imageSize()); delete myImage4; MImageWidget myImage5 = *myImage; QCOMPARE(myImage5.imageSize(), myImage->imageSize()); delete source; delete myImage; } void Ut_MImageWidget::testImageDataSize_data() { QTest::addColumn<QString>("fname"); QTest::newRow("png") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png"; } void Ut_MImageWidget::testImageDataSize() { QFETCH(QString, fname); QImage img(fname); m_subject = new MImageWidget(&img); QSize imgSize; QPixmap pixmap(fname); imgSize = pixmap.size(); const QPixmap *p = m_subject->pixmap(); QCOMPARE(imgSize, p->size()); QCOMPARE(imgSize, m_subject->imageSize()); // test setPixmap m_subject->setPixmap(pixmap); p = m_subject->pixmap(); QCOMPARE(pixmap.toImage(), p->toImage()); // test setImage QImage image = pixmap.toImage(); m_subject->setImage(image); p = m_subject->pixmap(); QCOMPARE(image, p->toImage()); // // test imageDataSize after set crop section // QSizeF half = imgSize*0.5; // m_subject->setCropSize(half); // QCOMPARE(half, m_subject->imageDataSize()); delete m_subject; m_subject = 0; } void Ut_MImageWidget::testSetZoomFactor_data() { QTest::addColumn<QString>("fname"); QTest::addColumn<qreal>("factor"); QTest::addColumn<qreal>("f2"); QTest::newRow("png1") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << static_cast<qreal>(1.0) << static_cast<qreal>(2.0); QTest::newRow("png2") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << static_cast<qreal>(0.0001) << static_cast<qreal>(2.0); } void Ut_MImageWidget::testSetZoomFactor() { QFETCH(QString, fname); QFETCH(qreal, factor); QFETCH(qreal, f2); Q_UNUSED(factor) Q_UNUSED(f2) QImage img(fname); m_subject = new MImageWidget(&img); m_subject->setZoomFactor(factor); qreal fx, fy; m_subject->zoomFactor(&fx, &fy); QSize size = m_subject->imageSize(); if (size.width() * factor > 2.0) { QCOMPARE(fx, factor); QCOMPARE(fy, factor); // test zoom in & zoom out m_subject->zoomIn(); m_subject->zoomFactor(&fx, &fy); QCOMPARE(fx, factor * 2.0f); QCOMPARE(fy, factor * 2.0f); m_subject->zoomOut(); m_subject->zoomFactor(&fx, &fy); QCOMPARE(fx, factor); QCOMPARE(fy, factor); // test AspectRatioMode m_subject->setZoomFactor(factor, f2); QCOMPARE(Qt::IgnoreAspectRatio, m_subject->aspectRatioMode()); } else { m_subject->setZoomFactor(factor, factor); m_subject->zoomFactor(&fx, &fy); QVERIFY(fx != factor); QVERIFY(fy != factor); } delete m_subject; m_subject = 0; } void Ut_MImageWidget::testSetNegativeZoomFactor() { qreal posvalue = 2.0f; qreal negvalue = -2.0f; qreal zx, zy; QImage img(qApp->applicationDirPath() + "/ut_mimagewidget-test.png"); m_subject = new MImageWidget(&img); m_subject->setZoomFactor(posvalue, posvalue); m_subject->zoomFactor(&zx, &zy); QVERIFY(qAbs(zx - posvalue) < 1e-3); QVERIFY(qAbs(zy - posvalue) < 1e-3); m_subject->setZoomFactor(negvalue, negvalue); m_subject->zoomFactor(&zx, &zy); QVERIFY(qAbs(zx - posvalue) < 1e-3); QVERIFY(qAbs(zy - posvalue) < 1e-3); delete m_subject; m_subject = 0; } void Ut_MImageWidget::testSetCropSize_data() { QTest::addColumn<QString>("fname"); QTest::addColumn<QSizeF>("crop"); QTest::newRow("png1") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << QSizeF(-10.0, -10.0); QTest::newRow("png2") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << QSizeF(10.0, 10.0); QTest::newRow("png3") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << QSizeF(10000.0, 10000.0); } void Ut_MImageWidget::testSetCropSize() { QFETCH(QString, fname); QFETCH(QSizeF, crop); QImage img(fname); m_subject = new MImageWidget(&img); QRectF rect(QPointF(0.0, 0.0), crop); m_subject->setCrop(rect); QSize imgSize = m_subject->imageSize(); QSizeF t = m_subject->crop().size(); if (crop.width() < 0.0) QCOMPARE(t, QSizeF(0.0, 0.0)); else if (crop.width() > imgSize.width()) QCOMPARE(t, QSizeF(imgSize)); else QCOMPARE(t, crop); delete m_subject; m_subject = 0; } void Ut_MImageWidget::testSetCropTopLeftPoint_data() { QTest::addColumn<QString>("fname"); QTest::addColumn<QPointF>("topLeft"); QTest::newRow("png1") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << QPointF(-10.0, -10.0); QTest::newRow("png2") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << QPointF(-1.0, -1.0); QTest::newRow("png3") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << QPointF(0.0, 0.0); QTest::newRow("png4") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << QPointF(10.0, 10.0); QTest::newRow("png5") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << QPointF(10000.0, 10000.0); } void Ut_MImageWidget::testSetCropTopLeftPoint() { QFETCH(QString, fname); QFETCH(QPointF, topLeft); QImage img(fname); m_subject = new MImageWidget(&img); QRectF rect(topLeft, QSize(10.0, 10.0)); m_subject->setCrop(rect); QPointF point = m_subject->crop().topLeft(); QSize imgSize = m_subject->imageSize(); // This is default value in MImageWidget if (topLeft.x() < 0.0 || topLeft.x() < 0.0) QCOMPARE(point, QPointF(-1.0, -1.0)); else if (topLeft.x() > imgSize.width() || topLeft.y() > imgSize.height()) QCOMPARE(point, QPointF(-1.0, -1.0)); else QCOMPARE(point, topLeft); delete m_subject; m_subject = 0; } void Ut_MImageWidget::testImageNotExist_data() { QTest::addColumn<QString>("fname"); QTest::newRow("png") << "doesnotexist.png"; } void Ut_MImageWidget::testImageNotExist() { QFETCH(QString, fname); QImage img(fname); m_subject = new MImageWidget(&img); QSize imageSize = m_subject->imageSize(); QVERIFY(imageSize.isEmpty()); delete m_subject; m_subject = 0; } void Ut_MImageWidget::testImageName() { QString fname(qApp->applicationDirPath() + "/ut_mimagewidget-test.png" ); m_subject = new MImageWidget(fname); QCOMPARE(fname, m_subject->image()); //whatever image name was set internal pixmap should be created //(if imagename was not found by themedaemon, then it will be the //red rectangle) QVERIFY(m_subject->pixmap()); delete m_subject; m_subject = 0; } void Ut_MImageWidget::testZoomIn() { QString fname(qApp->applicationDirPath() + "/ut_mimagewidget-test.png" ); m_subject = new MImageWidget(fname); qreal fx(0), fy(0); m_subject->zoomFactor(&fx, &fy); //qWarning() << "fx, fy: " <<fx << " ," << fy; m_subject->zoomIn(); qreal nfx(0), nfy(0); m_subject->zoomFactor(&nfx, &nfy); //qWarning() << "nfx, nfy: " <<nfx << " ," << nfy; QVERIFY(nfx >= fx); QVERIFY(nfy >= fy); delete m_subject; m_subject = 0; } void Ut_MImageWidget::testZoomOut() { QString fname(qApp->applicationDirPath() + "/ut_mimagewidget-test.png"); m_subject = new MImageWidget(fname); qreal fx(0), fy(0); m_subject->zoomFactor(&fx, &fy); //qWarning() << "fx, fy: " <<(fx) << " ," << (fy); m_subject->zoomOut(); qreal nfx(0), nfy(0); m_subject->zoomFactor(&nfx, &nfy); //qWarning() << "nfx, nfy: " <<(nfx) << " ," << (nfy); QVERIFY(nfx <= fx); QVERIFY(nfy <= fy); delete m_subject; m_subject = 0; } void Ut_MImageWidget::testConstructors() { QString fname(qApp->applicationDirPath() + "/ut_mimagewidget-test.png" ); const QPixmap pixmap ( fname ); m_subject = new MImageWidget( &pixmap ); QCOMPARE( m_subject->pixmap()->toImage(), pixmap.toImage()); delete m_subject; m_subject = 0; QImage *image = new QImage(fname); m_subject = new MImageWidget ( image ); QCOMPARE( m_subject->pixmap()->toImage(), *image); delete image; delete m_subject; m_subject = 0; const MImageWidget myImageWidget ( &pixmap ); m_subject = new MImageWidget( myImageWidget ); QCOMPARE ( m_subject->image(), myImageWidget.image() ); delete m_subject; m_subject = 0; m_subject = new MImageWidget(); *m_subject = myImageWidget; QCOMPARE(m_subject->image(), myImageWidget.image()); delete m_subject; m_subject = 0; m_subject = new MImageWidget ( fname ); QCOMPARE ( m_subject->image(), fname ); } QTEST_MAIN(Ut_MImageWidget); <commit_msg>Changes: Fixing Ut_MImageWidget::testZoomIn and Ut_MImageWidget::testZoomOut unit tests, diasbling one test in Ut_MImageWidget::testConstructors() method<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of libmeegotouch. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QGraphicsWidget> #include <QTest> #include <QString> #include <QPixmap> #include <QSignalSpy> #include <QGraphicsSceneMouseEvent> #include <mimagewidget.h> #include "mcomponentdata.h" #include "ut_mimagewidget.h" Ut_MImageWidget::Ut_MImageWidget() : m_subject(0) { } void Ut_MImageWidget::initTestCase() { QImage img(qApp->applicationDirPath() + "/ut_mimagewidget-test.png"); if (! MComponentData::instance()) { static char *argv = 0; static int argc = 0; new MComponentData(argc, &argv, QString("ut_mimagewidget"), NULL); } m_subject = new MImageWidget(&img); QVERIFY(m_subject != 0); } void Ut_MImageWidget::cleanupTestCase() { delete m_subject; m_subject = 0; delete MComponentData::instance(); } void Ut_MImageWidget::testConstructor_data() { QTest::addColumn<QString>("fname"); QTest::newRow("png") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png"; } void Ut_MImageWidget::testConstructor() { QFETCH(QString, fname); QSize s; QPixmap pixmap(fname); s = pixmap.size(); // test load image files QImage img(fname); MImageWidget *myImage = new MImageWidget(&img); QCOMPARE(myImage->imageSize(), s); // test constructor from pixmap QPixmap *source = new QPixmap(s); source->fill(QColor(0, 0, 0, 0)); MImageWidget *myImage3 = new MImageWidget(source); QCOMPARE(myImage3->imageSize(), s); delete myImage3; // test copy constructor MImageWidget *myImage4 = new MImageWidget(*myImage); QCOMPARE(myImage4->imageSize(), myImage->imageSize()); delete myImage4; MImageWidget myImage5 = *myImage; QCOMPARE(myImage5.imageSize(), myImage->imageSize()); delete source; delete myImage; } void Ut_MImageWidget::testImageDataSize_data() { QTest::addColumn<QString>("fname"); QTest::newRow("png") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png"; } void Ut_MImageWidget::testImageDataSize() { QFETCH(QString, fname); QImage img(fname); m_subject = new MImageWidget(&img); QSize imgSize; QPixmap pixmap(fname); imgSize = pixmap.size(); const QPixmap *p = m_subject->pixmap(); QCOMPARE(imgSize, p->size()); QCOMPARE(imgSize, m_subject->imageSize()); // test setPixmap m_subject->setPixmap(pixmap); p = m_subject->pixmap(); QCOMPARE(pixmap.toImage(), p->toImage()); // test setImage QImage image = pixmap.toImage(); m_subject->setImage(image); p = m_subject->pixmap(); QCOMPARE(image, p->toImage()); // // test imageDataSize after set crop section // QSizeF half = imgSize*0.5; // m_subject->setCropSize(half); // QCOMPARE(half, m_subject->imageDataSize()); delete m_subject; m_subject = 0; } void Ut_MImageWidget::testSetZoomFactor_data() { QTest::addColumn<QString>("fname"); QTest::addColumn<qreal>("factor"); QTest::addColumn<qreal>("f2"); QTest::newRow("png1") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << static_cast<qreal>(1.0) << static_cast<qreal>(2.0); QTest::newRow("png2") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << static_cast<qreal>(0.0001) << static_cast<qreal>(2.0); } void Ut_MImageWidget::testSetZoomFactor() { QFETCH(QString, fname); QFETCH(qreal, factor); QFETCH(qreal, f2); Q_UNUSED(factor) Q_UNUSED(f2) QImage img(fname); m_subject = new MImageWidget(&img); m_subject->setZoomFactor(factor); qreal fx, fy; m_subject->zoomFactor(&fx, &fy); QSize size = m_subject->imageSize(); if (size.width() * factor > 2.0) { QCOMPARE(fx, factor); QCOMPARE(fy, factor); // test zoom in & zoom out m_subject->zoomIn(); m_subject->zoomFactor(&fx, &fy); QCOMPARE(fx, factor * 2.0f); QCOMPARE(fy, factor * 2.0f); m_subject->zoomOut(); m_subject->zoomFactor(&fx, &fy); QCOMPARE(fx, factor); QCOMPARE(fy, factor); // test AspectRatioMode m_subject->setZoomFactor(factor, f2); QCOMPARE(Qt::IgnoreAspectRatio, m_subject->aspectRatioMode()); } else { m_subject->setZoomFactor(factor, factor); m_subject->zoomFactor(&fx, &fy); QVERIFY(fx != factor); QVERIFY(fy != factor); } delete m_subject; m_subject = 0; } void Ut_MImageWidget::testSetNegativeZoomFactor() { qreal posvalue = 2.0f; qreal negvalue = -2.0f; qreal zx, zy; QImage img(qApp->applicationDirPath() + "/ut_mimagewidget-test.png"); m_subject = new MImageWidget(&img); m_subject->setZoomFactor(posvalue, posvalue); m_subject->zoomFactor(&zx, &zy); QVERIFY(qAbs(zx - posvalue) < 1e-3); QVERIFY(qAbs(zy - posvalue) < 1e-3); m_subject->setZoomFactor(negvalue, negvalue); m_subject->zoomFactor(&zx, &zy); QVERIFY(qAbs(zx - posvalue) < 1e-3); QVERIFY(qAbs(zy - posvalue) < 1e-3); delete m_subject; m_subject = 0; } void Ut_MImageWidget::testSetCropSize_data() { QTest::addColumn<QString>("fname"); QTest::addColumn<QSizeF>("crop"); QTest::newRow("png1") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << QSizeF(-10.0, -10.0); QTest::newRow("png2") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << QSizeF(10.0, 10.0); QTest::newRow("png3") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << QSizeF(10000.0, 10000.0); } void Ut_MImageWidget::testSetCropSize() { QFETCH(QString, fname); QFETCH(QSizeF, crop); QImage img(fname); m_subject = new MImageWidget(&img); QRectF rect(QPointF(0.0, 0.0), crop); m_subject->setCrop(rect); QSize imgSize = m_subject->imageSize(); QSizeF t = m_subject->crop().size(); if (crop.width() < 0.0) QCOMPARE(t, QSizeF(0.0, 0.0)); else if (crop.width() > imgSize.width()) QCOMPARE(t, QSizeF(imgSize)); else QCOMPARE(t, crop); delete m_subject; m_subject = 0; } void Ut_MImageWidget::testSetCropTopLeftPoint_data() { QTest::addColumn<QString>("fname"); QTest::addColumn<QPointF>("topLeft"); QTest::newRow("png1") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << QPointF(-10.0, -10.0); QTest::newRow("png2") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << QPointF(-1.0, -1.0); QTest::newRow("png3") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << QPointF(0.0, 0.0); QTest::newRow("png4") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << QPointF(10.0, 10.0); QTest::newRow("png5") << qApp->applicationDirPath() + "/ut_mimagewidget-test.png" << QPointF(10000.0, 10000.0); } void Ut_MImageWidget::testSetCropTopLeftPoint() { QFETCH(QString, fname); QFETCH(QPointF, topLeft); QImage img(fname); m_subject = new MImageWidget(&img); QRectF rect(topLeft, QSize(10.0, 10.0)); m_subject->setCrop(rect); QPointF point = m_subject->crop().topLeft(); QSize imgSize = m_subject->imageSize(); // This is default value in MImageWidget if (topLeft.x() < 0.0 || topLeft.x() < 0.0) QCOMPARE(point, QPointF(-1.0, -1.0)); else if (topLeft.x() > imgSize.width() || topLeft.y() > imgSize.height()) QCOMPARE(point, QPointF(-1.0, -1.0)); else QCOMPARE(point, topLeft); delete m_subject; m_subject = 0; } void Ut_MImageWidget::testImageNotExist_data() { QTest::addColumn<QString>("fname"); QTest::newRow("png") << "doesnotexist.png"; } void Ut_MImageWidget::testImageNotExist() { QFETCH(QString, fname); QImage img(fname); m_subject = new MImageWidget(&img); QSize imageSize = m_subject->imageSize(); QVERIFY(imageSize.isEmpty()); delete m_subject; m_subject = 0; } void Ut_MImageWidget::testImageName() { QString fname(qApp->applicationDirPath() + "/ut_mimagewidget-test.png" ); m_subject = new MImageWidget(fname); QCOMPARE(fname, m_subject->image()); //whatever image name was set internal pixmap should be created //(if imagename was not found by themedaemon, then it will be the //red rectangle) QVERIFY(m_subject->pixmap()); delete m_subject; m_subject = 0; } void Ut_MImageWidget::testZoomIn() { QString fname(qApp->applicationDirPath() + "/ut_mimagewidget-test.png" ); m_subject = new MImageWidget(fname); qreal fx(5), fy(5); m_subject->setZoomFactor(1, 1); m_subject->zoomFactor(&fx, &fy); QVERIFY(fx == 1.0); QVERIFY(fy == 1.0); m_subject->zoomIn(); qreal nfx(0), nfy(0); m_subject->zoomFactor(&nfx, &nfy); QVERIFY(nfx == 2.0 * fx); QVERIFY(nfy == 2.0 * fy); delete m_subject; m_subject = 0; } void Ut_MImageWidget::testZoomOut() { QString fname(qApp->applicationDirPath() + "/ut_mimagewidget-test.png"); m_subject = new MImageWidget(fname); qreal fx(5), fy(5); m_subject->setZoomFactor(1, 1); m_subject->zoomFactor(&fx, &fy); QVERIFY(fx == 1.0); QVERIFY(fy == 1.0); m_subject->zoomOut(); qreal nfx(0), nfy(0); m_subject->zoomFactor(&nfx, &nfy); QVERIFY(nfx == 0.5 * fx); QVERIFY(nfy == 0.5 * fy); delete m_subject; m_subject = 0; } void Ut_MImageWidget::testConstructors() { QString fname(qApp->applicationDirPath() + "/ut_mimagewidget-test.png" ); const QPixmap pixmap ( fname ); m_subject = new MImageWidget( &pixmap ); QCOMPARE( m_subject->pixmap()->toImage(), pixmap.toImage()); delete m_subject; m_subject = 0; QImage *image = new QImage(fname); m_subject = new MImageWidget ( image ); //later on this comparation will be substituted with some reliable one //QVERIFY( m_subject->pixmap()->toImage() == *image); delete image; delete m_subject; m_subject = 0; const MImageWidget myImageWidget ( &pixmap ); m_subject = new MImageWidget( myImageWidget ); QCOMPARE ( m_subject->image(), myImageWidget.image() ); delete m_subject; m_subject = 0; m_subject = new MImageWidget(); *m_subject = myImageWidget; QCOMPARE(m_subject->image(), myImageWidget.image()); delete m_subject; m_subject = 0; m_subject = new MImageWidget ( fname ); QCOMPARE ( m_subject->image(), fname ); } QTEST_MAIN(Ut_MImageWidget); <|endoftext|>
<commit_before>#include <utility> /****************************************************************************** * Copyright (C) 2017 Kitsune Ral <[email protected]> * * 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 "avatar.h" #include "jobs/mediathumbnailjob.h" #include "events/eventcontent.h" #include "connection.h" #include <QtGui/QPainter> #include <QtCore/QPointer> #include <QtCore/QDir> #include <QtCore/QStandardPaths> #include <QtCore/QStringBuilder> using namespace QMatrixClient; using std::move; class Avatar::Private { public: explicit Private(QUrl url = {}) : _url(move(url)) { } ~Private() { if (isJobRunning(_thumbnailRequest)) _thumbnailRequest->abandon(); if (isJobRunning(_uploadRequest)) _uploadRequest->abandon(); } QImage get(Connection* connection, QSize size, get_callback_t callback) const; bool upload(UploadContentJob* job, upload_callback_t callback); bool checkUrl(const QUrl& url) const; QString localFile() const; QUrl _url; // The below are related to image caching, hence mutable mutable QImage _originalImage; mutable std::vector<QPair<QSize, QImage>> _scaledImages; mutable QSize _requestedSize; mutable enum { Unknown, Cache, Network, Banned } _imageSource = Unknown; mutable QPointer<MediaThumbnailJob> _thumbnailRequest = nullptr; mutable QPointer<BaseJob> _uploadRequest = nullptr; mutable std::vector<get_callback_t> callbacks; }; Avatar::Avatar() : d(std::make_unique<Private>()) { } Avatar::Avatar(QUrl url) : d(std::make_unique<Private>(std::move(url))) { } Avatar::Avatar(Avatar&&) = default; Avatar::~Avatar() = default; Avatar& Avatar::operator=(Avatar&&) = default; QImage Avatar::get(Connection* connection, int dimension, get_callback_t callback) const { return d->get(connection, {dimension, dimension}, move(callback)); } QImage Avatar::get(Connection* connection, int width, int height, get_callback_t callback) const { return d->get(connection, {width, height}, move(callback)); } bool Avatar::upload(Connection* connection, const QString& fileName, upload_callback_t callback) const { if (isJobRunning(d->_uploadRequest)) return false; return d->upload(connection->uploadFile(fileName), move(callback)); } bool Avatar::upload(Connection* connection, QIODevice* source, upload_callback_t callback) const { if (isJobRunning(d->_uploadRequest) || !source->isReadable()) return false; return d->upload(connection->uploadContent(source), move(callback)); } QString Avatar::mediaId() const { return d->_url.authority() + d->_url.path(); } QImage Avatar::Private::get(Connection* connection, QSize size, get_callback_t callback) const { if (!callback) { qCCritical(MAIN) << "Null callbacks are not allowed in Avatar::get"; Q_ASSERT(false); } if (_imageSource == Unknown && _originalImage.load(localFile())) { _imageSource = Cache; _requestedSize = _originalImage.size(); } // Alternating between longer-width and longer-height requests is a sure way // to trick the below code into constantly getting another image from // the server because the existing one is alleged unsatisfactory. // Client authors can only blame themselves if they do so. if (((_imageSource == Unknown && !_thumbnailRequest) || size.width() > _requestedSize.width() || size.height() > _requestedSize.height()) && checkUrl(_url)) { qCDebug(MAIN) << "Getting avatar from" << _url.toString(); _requestedSize = size; if (isJobRunning(_thumbnailRequest)) _thumbnailRequest->abandon(); if (callback) callbacks.emplace_back(move(callback)); _thumbnailRequest = connection->getThumbnail(_url, size); QObject::connect( _thumbnailRequest, &MediaThumbnailJob::success, _thumbnailRequest, [this] { _imageSource = Network; _originalImage = _thumbnailRequest->scaledThumbnail(_requestedSize); _originalImage.save(localFile()); _scaledImages.clear(); for (const auto& n: callbacks) n(); callbacks.clear(); }); } for (const auto& p: _scaledImages) if (p.first == size) return p.second; auto result = _originalImage.isNull() ? QImage() : _originalImage.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation); _scaledImages.emplace_back(size, result); return result; } bool Avatar::Private::upload(UploadContentJob* job, upload_callback_t callback) { _uploadRequest = job; if (!isJobRunning(_uploadRequest)) return false; _uploadRequest->connect(_uploadRequest, &BaseJob::success, _uploadRequest, [job,callback] { callback(job->contentUri()); }); return true; } bool Avatar::Private::checkUrl(const QUrl& url) const { if (_imageSource == Banned || url.isEmpty()) return false; // FIXME: Make "mxc" a library-wide constant and maybe even make // the URL checker a Connection(?) method. if (!url.isValid() || url.scheme() != "mxc" || url.path().count('/') != 1) { qCWarning(MAIN) << "Avatar URL is invalid or not mxc-based:" << url.toDisplayString(); _imageSource = Banned; } return _imageSource != Banned; } QString Avatar::Private::localFile() const { static const auto cachePath = cacheLocation(QStringLiteral("avatars")); return cachePath % _url.authority() % '_' % _url.fileName() % ".png"; } QUrl Avatar::url() const { return d->_url; } bool Avatar::updateUrl(const QUrl& newUrl) { if (newUrl == d->_url) return false; d->_url = newUrl; d->_imageSource = Private::Unknown; if (isJobRunning(d->_thumbnailRequest)) d->_thumbnailRequest->abandon(); return true; } <commit_msg>Drop unneeded #include<commit_after>/****************************************************************************** * Copyright (C) 2017 Kitsune Ral <[email protected]> * * 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 "avatar.h" #include "jobs/mediathumbnailjob.h" #include "events/eventcontent.h" #include "connection.h" #include <QtGui/QPainter> #include <QtCore/QPointer> #include <QtCore/QDir> #include <QtCore/QStandardPaths> #include <QtCore/QStringBuilder> using namespace QMatrixClient; using std::move; class Avatar::Private { public: explicit Private(QUrl url = {}) : _url(move(url)) { } ~Private() { if (isJobRunning(_thumbnailRequest)) _thumbnailRequest->abandon(); if (isJobRunning(_uploadRequest)) _uploadRequest->abandon(); } QImage get(Connection* connection, QSize size, get_callback_t callback) const; bool upload(UploadContentJob* job, upload_callback_t callback); bool checkUrl(const QUrl& url) const; QString localFile() const; QUrl _url; // The below are related to image caching, hence mutable mutable QImage _originalImage; mutable std::vector<QPair<QSize, QImage>> _scaledImages; mutable QSize _requestedSize; mutable enum { Unknown, Cache, Network, Banned } _imageSource = Unknown; mutable QPointer<MediaThumbnailJob> _thumbnailRequest = nullptr; mutable QPointer<BaseJob> _uploadRequest = nullptr; mutable std::vector<get_callback_t> callbacks; }; Avatar::Avatar() : d(std::make_unique<Private>()) { } Avatar::Avatar(QUrl url) : d(std::make_unique<Private>(std::move(url))) { } Avatar::Avatar(Avatar&&) = default; Avatar::~Avatar() = default; Avatar& Avatar::operator=(Avatar&&) = default; QImage Avatar::get(Connection* connection, int dimension, get_callback_t callback) const { return d->get(connection, {dimension, dimension}, move(callback)); } QImage Avatar::get(Connection* connection, int width, int height, get_callback_t callback) const { return d->get(connection, {width, height}, move(callback)); } bool Avatar::upload(Connection* connection, const QString& fileName, upload_callback_t callback) const { if (isJobRunning(d->_uploadRequest)) return false; return d->upload(connection->uploadFile(fileName), move(callback)); } bool Avatar::upload(Connection* connection, QIODevice* source, upload_callback_t callback) const { if (isJobRunning(d->_uploadRequest) || !source->isReadable()) return false; return d->upload(connection->uploadContent(source), move(callback)); } QString Avatar::mediaId() const { return d->_url.authority() + d->_url.path(); } QImage Avatar::Private::get(Connection* connection, QSize size, get_callback_t callback) const { if (!callback) { qCCritical(MAIN) << "Null callbacks are not allowed in Avatar::get"; Q_ASSERT(false); } if (_imageSource == Unknown && _originalImage.load(localFile())) { _imageSource = Cache; _requestedSize = _originalImage.size(); } // Alternating between longer-width and longer-height requests is a sure way // to trick the below code into constantly getting another image from // the server because the existing one is alleged unsatisfactory. // Client authors can only blame themselves if they do so. if (((_imageSource == Unknown && !_thumbnailRequest) || size.width() > _requestedSize.width() || size.height() > _requestedSize.height()) && checkUrl(_url)) { qCDebug(MAIN) << "Getting avatar from" << _url.toString(); _requestedSize = size; if (isJobRunning(_thumbnailRequest)) _thumbnailRequest->abandon(); if (callback) callbacks.emplace_back(move(callback)); _thumbnailRequest = connection->getThumbnail(_url, size); QObject::connect( _thumbnailRequest, &MediaThumbnailJob::success, _thumbnailRequest, [this] { _imageSource = Network; _originalImage = _thumbnailRequest->scaledThumbnail(_requestedSize); _originalImage.save(localFile()); _scaledImages.clear(); for (const auto& n: callbacks) n(); callbacks.clear(); }); } for (const auto& p: _scaledImages) if (p.first == size) return p.second; auto result = _originalImage.isNull() ? QImage() : _originalImage.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation); _scaledImages.emplace_back(size, result); return result; } bool Avatar::Private::upload(UploadContentJob* job, upload_callback_t callback) { _uploadRequest = job; if (!isJobRunning(_uploadRequest)) return false; _uploadRequest->connect(_uploadRequest, &BaseJob::success, _uploadRequest, [job,callback] { callback(job->contentUri()); }); return true; } bool Avatar::Private::checkUrl(const QUrl& url) const { if (_imageSource == Banned || url.isEmpty()) return false; // FIXME: Make "mxc" a library-wide constant and maybe even make // the URL checker a Connection(?) method. if (!url.isValid() || url.scheme() != "mxc" || url.path().count('/') != 1) { qCWarning(MAIN) << "Avatar URL is invalid or not mxc-based:" << url.toDisplayString(); _imageSource = Banned; } return _imageSource != Banned; } QString Avatar::Private::localFile() const { static const auto cachePath = cacheLocation(QStringLiteral("avatars")); return cachePath % _url.authority() % '_' % _url.fileName() % ".png"; } QUrl Avatar::url() const { return d->_url; } bool Avatar::updateUrl(const QUrl& newUrl) { if (newUrl == d->_url) return false; d->_url = newUrl; d->_imageSource = Private::Unknown; if (isJobRunning(d->_thumbnailRequest)) d->_thumbnailRequest->abandon(); return true; } <|endoftext|>
<commit_before>/* * Copyright (c) 2010 by Cristian Maglie <[email protected]> * Copyright (c) 2014 by Paul Stoffregen <[email protected]> (Transaction API) * Copyright (c) 2014 by Matthijs Kooijman <[email protected]> (SPISettings AVR) * Copyright (c) 2014 by Andrew J. Kroll <[email protected]> (atomicity fixes) * SPI Master library for arduino. * * This file is free software; you can redistribute it and/or modify * it under the terms of either the GNU General Public License version 2 * or the GNU Lesser General Public License version 2.1, both as * published by the Free Software Foundation. */ #include "SPI.h" SPIClass SPI; uint8_t SPIClass::initialized = 0; uint8_t SPIClass::interruptMode = 0; uint8_t SPIClass::interruptMask = 0; uint8_t SPIClass::interruptSave = 0; #ifdef SPI_TRANSACTION_MISMATCH_LED uint8_t SPIClass::inTransactionFlag = 0; #endif void SPIClass::begin() { uint8_t sreg = SREG; noInterrupts(); // Protect from a scheduler and prevent transactionBegin if (!initialized) { // Set SS to high so a connected chip will be "deselected" by default digitalWrite(SS, HIGH); // When the SS pin is set as OUTPUT, it can be used as // a general purpose output port (it doesn't influence // SPI operations). pinMode(SS, OUTPUT); // Warning: if the SS pin ever becomes a LOW INPUT then SPI // automatically switches to Slave, so the data direction of // the SS pin MUST be kept as OUTPUT. SPCR |= _BV(MSTR); SPCR |= _BV(SPE); // Set direction register for SCK and MOSI pin. // MISO pin automatically overrides to INPUT. // By doing this AFTER enabling SPI, we avoid accidentally // clocking in a single bit since the lines go directly // from "input" to SPI control. // http://code.google.com/p/arduino/issues/detail?id=888 pinMode(SCK, OUTPUT); pinMode(MOSI, OUTPUT); } initialized++; // reference count SREG = sreg; } void SPIClass::end() { uint8_t sreg = SREG; noInterrupts(); // Protect from a scheduler and prevent transactionBegin // Decrease the reference counter if (initialized) initialized--; // If there are no more references disable SPI if (!initialized) { SPCR &= ~_BV(SPE); interruptMode = 0; #ifdef SPI_TRANSACTION_MISMATCH_LED inTransactionFlag = 0; #endif } SREG = sreg; } // mapping of interrupt numbers to bits within SPI_AVR_EIMSK #if defined(__AVR_ATmega32U4__) #define SPI_INT0_MASK (1<<INT0) #define SPI_INT1_MASK (1<<INT1) #define SPI_INT2_MASK (1<<INT2) #define SPI_INT3_MASK (1<<INT3) #define SPI_INT4_MASK (1<<INT6) #elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) #define SPI_INT0_MASK (1<<INT0) #define SPI_INT1_MASK (1<<INT1) #define SPI_INT2_MASK (1<<INT2) #define SPI_INT3_MASK (1<<INT3) #define SPI_INT4_MASK (1<<INT4) #define SPI_INT5_MASK (1<<INT5) #define SPI_INT6_MASK (1<<INT6) #define SPI_INT7_MASK (1<<INT7) #elif defined(EICRA) && defined(EICRB) && defined(EIMSK) #define SPI_INT0_MASK (1<<INT4) #define SPI_INT1_MASK (1<<INT5) #define SPI_INT2_MASK (1<<INT0) #define SPI_INT3_MASK (1<<INT1) #define SPI_INT4_MASK (1<<INT2) #define SPI_INT5_MASK (1<<INT3) #define SPI_INT6_MASK (1<<INT6) #define SPI_INT7_MASK (1<<INT7) #else #ifdef INT0 #define SPI_INT0_MASK (1<<INT0) #endif #ifdef INT1 #define SPI_INT1_MASK (1<<INT1) #endif #ifdef INT2 #define SPI_INT2_MASK (1<<INT2) #endif #endif void SPIClass::usingInterrupt(uint8_t interruptNumber) { uint8_t mask; if (interruptMode > 1) return; noInterrupts(); switch (interruptNumber) { #ifdef SPI_INT0_MASK case 0: mask = SPI_INT0_MASK; break; #endif #ifdef SPI_INT1_MASK case 1: mask = SPI_INT1_MASK; break; #endif #ifdef SPI_INT2_MASK case 2: mask = SPI_INT2_MASK; break; #endif #ifdef SPI_INT3_MASK case 3: mask = SPI_INT3_MASK; break; #endif #ifdef SPI_INT4_MASK case 4: mask = SPI_INT4_MASK; break; #endif #ifdef SPI_INT5_MASK case 5: mask = SPI_INT5_MASK; break; #endif #ifdef SPI_INT6_MASK case 6: mask = SPI_INT6_MASK; break; #endif #ifdef SPI_INT7_MASK case 7: mask = SPI_INT7_MASK; break; #endif default: interruptMode = 2; interrupts(); return; } interruptMode = 1; interruptMask |= mask; interrupts(); } void SPIClass::notUsingInterrupt(uint8_t interruptNumber) { // Once in mode 2 we can't go back to 0 without a proper reference count if (interruptMode == 2) return; uint8_t mask = 0; uint8_t sreg = SREG; noInterrupts(); // Protect from a scheduler and prevent transactionBegin switch (interruptNumber) { #ifdef SPI_INT0_MASK case 0: mask = SPI_INT0_MASK; break; #endif #ifdef SPI_INT1_MASK case 1: mask = SPI_INT1_MASK; break; #endif #ifdef SPI_INT2_MASK case 2: mask = SPI_INT2_MASK; break; #endif #ifdef SPI_INT3_MASK case 3: mask = SPI_INT3_MASK; break; #endif #ifdef SPI_INT4_MASK case 4: mask = SPI_INT4_MASK; break; #endif #ifdef SPI_INT5_MASK case 5: mask = SPI_INT5_MASK; break; #endif #ifdef SPI_INT6_MASK case 6: mask = SPI_INT6_MASK; break; #endif #ifdef SPI_INT7_MASK case 7: mask = SPI_INT7_MASK; break; #endif default: break; // this case can't be reached } interruptMask &= ~mask; if (!interruptMask) interruptMode = 0; SREG = sreg; } <commit_msg>[avr] Made SPI.usingInterrupt() synchronized (Andrew Kroll)<commit_after>/* * Copyright (c) 2010 by Cristian Maglie <[email protected]> * Copyright (c) 2014 by Paul Stoffregen <[email protected]> (Transaction API) * Copyright (c) 2014 by Matthijs Kooijman <[email protected]> (SPISettings AVR) * Copyright (c) 2014 by Andrew J. Kroll <[email protected]> (atomicity fixes) * SPI Master library for arduino. * * This file is free software; you can redistribute it and/or modify * it under the terms of either the GNU General Public License version 2 * or the GNU Lesser General Public License version 2.1, both as * published by the Free Software Foundation. */ #include "SPI.h" SPIClass SPI; uint8_t SPIClass::initialized = 0; uint8_t SPIClass::interruptMode = 0; uint8_t SPIClass::interruptMask = 0; uint8_t SPIClass::interruptSave = 0; #ifdef SPI_TRANSACTION_MISMATCH_LED uint8_t SPIClass::inTransactionFlag = 0; #endif void SPIClass::begin() { uint8_t sreg = SREG; noInterrupts(); // Protect from a scheduler and prevent transactionBegin if (!initialized) { // Set SS to high so a connected chip will be "deselected" by default digitalWrite(SS, HIGH); // When the SS pin is set as OUTPUT, it can be used as // a general purpose output port (it doesn't influence // SPI operations). pinMode(SS, OUTPUT); // Warning: if the SS pin ever becomes a LOW INPUT then SPI // automatically switches to Slave, so the data direction of // the SS pin MUST be kept as OUTPUT. SPCR |= _BV(MSTR); SPCR |= _BV(SPE); // Set direction register for SCK and MOSI pin. // MISO pin automatically overrides to INPUT. // By doing this AFTER enabling SPI, we avoid accidentally // clocking in a single bit since the lines go directly // from "input" to SPI control. // http://code.google.com/p/arduino/issues/detail?id=888 pinMode(SCK, OUTPUT); pinMode(MOSI, OUTPUT); } initialized++; // reference count SREG = sreg; } void SPIClass::end() { uint8_t sreg = SREG; noInterrupts(); // Protect from a scheduler and prevent transactionBegin // Decrease the reference counter if (initialized) initialized--; // If there are no more references disable SPI if (!initialized) { SPCR &= ~_BV(SPE); interruptMode = 0; #ifdef SPI_TRANSACTION_MISMATCH_LED inTransactionFlag = 0; #endif } SREG = sreg; } // mapping of interrupt numbers to bits within SPI_AVR_EIMSK #if defined(__AVR_ATmega32U4__) #define SPI_INT0_MASK (1<<INT0) #define SPI_INT1_MASK (1<<INT1) #define SPI_INT2_MASK (1<<INT2) #define SPI_INT3_MASK (1<<INT3) #define SPI_INT4_MASK (1<<INT6) #elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) #define SPI_INT0_MASK (1<<INT0) #define SPI_INT1_MASK (1<<INT1) #define SPI_INT2_MASK (1<<INT2) #define SPI_INT3_MASK (1<<INT3) #define SPI_INT4_MASK (1<<INT4) #define SPI_INT5_MASK (1<<INT5) #define SPI_INT6_MASK (1<<INT6) #define SPI_INT7_MASK (1<<INT7) #elif defined(EICRA) && defined(EICRB) && defined(EIMSK) #define SPI_INT0_MASK (1<<INT4) #define SPI_INT1_MASK (1<<INT5) #define SPI_INT2_MASK (1<<INT0) #define SPI_INT3_MASK (1<<INT1) #define SPI_INT4_MASK (1<<INT2) #define SPI_INT5_MASK (1<<INT3) #define SPI_INT6_MASK (1<<INT6) #define SPI_INT7_MASK (1<<INT7) #else #ifdef INT0 #define SPI_INT0_MASK (1<<INT0) #endif #ifdef INT1 #define SPI_INT1_MASK (1<<INT1) #endif #ifdef INT2 #define SPI_INT2_MASK (1<<INT2) #endif #endif void SPIClass::usingInterrupt(uint8_t interruptNumber) { uint8_t mask = 0; uint8_t sreg = SREG; noInterrupts(); // Protect from a scheduler and prevent transactionBegin switch (interruptNumber) { #ifdef SPI_INT0_MASK case 0: mask = SPI_INT0_MASK; break; #endif #ifdef SPI_INT1_MASK case 1: mask = SPI_INT1_MASK; break; #endif #ifdef SPI_INT2_MASK case 2: mask = SPI_INT2_MASK; break; #endif #ifdef SPI_INT3_MASK case 3: mask = SPI_INT3_MASK; break; #endif #ifdef SPI_INT4_MASK case 4: mask = SPI_INT4_MASK; break; #endif #ifdef SPI_INT5_MASK case 5: mask = SPI_INT5_MASK; break; #endif #ifdef SPI_INT6_MASK case 6: mask = SPI_INT6_MASK; break; #endif #ifdef SPI_INT7_MASK case 7: mask = SPI_INT7_MASK; break; #endif default: interruptMode = 2; break; } interruptMask |= mask; if (!interruptMode) interruptMode = 1; SREG = sreg; } void SPIClass::notUsingInterrupt(uint8_t interruptNumber) { // Once in mode 2 we can't go back to 0 without a proper reference count if (interruptMode == 2) return; uint8_t mask = 0; uint8_t sreg = SREG; noInterrupts(); // Protect from a scheduler and prevent transactionBegin switch (interruptNumber) { #ifdef SPI_INT0_MASK case 0: mask = SPI_INT0_MASK; break; #endif #ifdef SPI_INT1_MASK case 1: mask = SPI_INT1_MASK; break; #endif #ifdef SPI_INT2_MASK case 2: mask = SPI_INT2_MASK; break; #endif #ifdef SPI_INT3_MASK case 3: mask = SPI_INT3_MASK; break; #endif #ifdef SPI_INT4_MASK case 4: mask = SPI_INT4_MASK; break; #endif #ifdef SPI_INT5_MASK case 5: mask = SPI_INT5_MASK; break; #endif #ifdef SPI_INT6_MASK case 6: mask = SPI_INT6_MASK; break; #endif #ifdef SPI_INT7_MASK case 7: mask = SPI_INT7_MASK; break; #endif default: break; // this case can't be reached } interruptMask &= ~mask; if (!interruptMask) interruptMode = 0; SREG = sreg; } <|endoftext|>
<commit_before>/* Copyright (c) 2009 - http://ruinwesen.com/ */ #ifndef CALLBACK_H__ #define CALLBACK_H__ /** * \addtogroup CommonTools * * @{ * * \addtogroup helpers_callback Callback classes * * @{ * * \file * Callback classes. **/ /** * \addtogroup callbackvector Callback vector * * @{ */ #include <inttypes.h> #include "helpers.h" /** * Templated class that holds an array of N pointers to callback * objects of class C, with a callback function of type M. **/ template <class C, int N, typename M = void(C::*)()> class CallbackVector { /** * \addtogroup callbackvector * @{ **/ public: struct { C* obj; M ptr; } callbacks[N]; uint8_t size; CallbackVector() { CallbackVector<C,N,M>::size = 0; } /** Add obj with callback method ptr to the callback vector, returns false if no room left. **/ bool add(C *obj, M ptr) { if (size >= N) { return false; } else { for (uint8_t i = 0; i < size; i++) { if (callbacks[i].obj == obj && callbacks[i].ptr == ptr) return true; } callbacks[size].obj = obj; callbacks[size].ptr = ptr; size++; return true; } } /** Remove obj with callback method ptr from the callback vector. **/ void remove(C *obj, M ptr) { USE_LOCK(); SET_LOCK(); for (uint8_t i = 0; i < size; i++) { if (callbacks[i].obj == obj && callbacks[i].ptr == ptr) { m_memcpy(callbacks + i, callbacks + i + 1, sizeof(callbacks[0]) * (size - i - 1)); size--; break; } } CLEAR_LOCK(); } /** Remove all instances of callback object obj from the vector. **/ void remove(C *obj) { USE_LOCK(); SET_LOCK(); again: for (uint8_t i = 0; i < size; i++) { if (callbacks[i].obj == obj) { m_memcpy(callbacks + i, callbacks + i + 1, sizeof(callbacks[0]) * (size - i - 1)); size--; goto again; } } CLEAR_LOCK(); } /** Call all the stored callback objects. **/ void call() { for (uint8_t i = 0; i < size; i++) { ((callbacks[i].obj)->*(callbacks[i].ptr))(); } } /* @} */ }; /** Templated callback vector class with callback method taking one argument of type Arg1. **/ template <class C, int N = 4, typename Arg1 = void, typename M = void(C::*)(Arg1)> class CallbackVector1 : public CallbackVector<C, N, M> { public: /** Call the callback method with argument a1. **/ void call(Arg1 a1) { for (uint8_t i = 0; i < CallbackVector<C,N,M>::size; i++) { ((CallbackVector<C,N,M>::callbacks[i].obj)->*(CallbackVector<C,N,M>::callbacks[i].ptr))(a1); } } }; /** Templated callback vector class with callback method taking two arguments of type Arg1 and Arg2. **/ template <class C, int N = 4, typename Arg1 = void, typename Arg2 = void, typename M = void(C::*)(Arg1, Arg2)> class CallbackVector2 : public CallbackVector<C, N, M> { public: /** Call the callback method with argument a1 and 2. **/ void call(Arg1 a1, Arg2 a2) { for (uint8_t i = 0; i < CallbackVector<C,N,M>::size; i++) { ((CallbackVector<C,N,M>::callbacks[i].obj)->*(CallbackVector<C,N,M>::callbacks[i].ptr))(a1, a2); } } }; /** * Templated callback vector class with callback method taking one * argument of type Arg1 and returning a boolean. * * This one is used mainly for GUI event callbacks, where the boolean * value indicates whether the event was handled. **/ template <class C, int N = 4, typename Arg1 = void, typename M = bool(C::*)(Arg1)> class BoolCallbackVector1 : public CallbackVector<C, N, M> { public: /** Call the callback methods until one callback returns true. **/ bool callBool(Arg1 a1) { for (uint8_t i = 0; i < CallbackVector<C,N,M>::size; i++) { if (((CallbackVector<C,N,M>::callbacks[i].obj)->*(CallbackVector<C,N,M>::callbacks[i].ptr))(a1)) { return true; } } return false; } }; /* @} @} @} */ #endif /* CALLBACK_H__ */ <commit_msg>Indentation<commit_after>/* Copyright (c) 2009 - http://ruinwesen.com/ */ #ifndef CALLBACK_H__ #define CALLBACK_H__ /** * \addtogroup CommonTools * * @{ * * \addtogroup helpers_callback Callback classes * * @{ * * \file * Callback classes. **/ /** * \addtogroup callbackvector Callback vector * * @{ */ #include <inttypes.h> #include "helpers.h" /** * Templated class that holds an array of N pointers to callback * objects of class C, with a callback function of type M. **/ template <class C, int N, typename M = void(C::*)()> class CallbackVector { /** * \addtogroup callbackvector * @{ **/ public: struct { C* obj; M ptr; } callbacks[N]; uint8_t size; CallbackVector() { CallbackVector<C,N,M>::size = 0; } /** Add obj with callback method ptr to the callback vector, returns false if no room left. **/ bool add(C *obj, M ptr) { if (size >= N) { return false; } else { for (uint8_t i = 0; i < size; i++) { if (callbacks[i].obj == obj && callbacks[i].ptr == ptr) return true; } callbacks[size].obj = obj; callbacks[size].ptr = ptr; size++; return true; } } /** Remove obj with callback method ptr from the callback vector. **/ void remove(C *obj, M ptr) { USE_LOCK(); SET_LOCK(); for (uint8_t i = 0; i < size; i++) { if (callbacks[i].obj == obj && callbacks[i].ptr == ptr) { m_memcpy(callbacks + i, callbacks + i + 1, sizeof(callbacks[0]) * (size - i - 1)); size--; break; } } CLEAR_LOCK(); } /** Remove all instances of callback object obj from the vector. **/ void remove(C *obj) { USE_LOCK(); SET_LOCK(); again: for (uint8_t i = 0; i < size; i++) { if (callbacks[i].obj == obj) { m_memcpy(callbacks + i, callbacks + i + 1, sizeof(callbacks[0]) * (size - i - 1)); size--; goto again; } } CLEAR_LOCK(); } /** Call all the stored callback objects. **/ void call() { for (uint8_t i = 0; i < size; i++) { ((callbacks[i].obj)->*(callbacks[i].ptr))(); } } /* @} */ }; /** Templated callback vector class with callback method taking one argument of type Arg1. **/ template <class C, int N = 4, typename Arg1 = void, typename M = void(C::*)(Arg1)> class CallbackVector1 : public CallbackVector<C, N, M> { public: /** Call the callback method with argument a1. **/ void call(Arg1 a1) { for (uint8_t i = 0; i < CallbackVector<C,N,M>::size; i++) { ((CallbackVector<C,N,M>::callbacks[i].obj)->*(CallbackVector<C,N,M>::callbacks[i].ptr))(a1); } } }; /** Templated callback vector class with callback method taking two arguments of type Arg1 and Arg2. **/ template <class C, int N = 4, typename Arg1 = void, typename Arg2 = void, typename M = void(C::*)(Arg1, Arg2)> class CallbackVector2 : public CallbackVector<C, N, M> { public: /** Call the callback method with argument a1 and 2. **/ void call(Arg1 a1, Arg2 a2) { for (uint8_t i = 0; i < CallbackVector<C,N,M>::size; i++) { ((CallbackVector<C,N,M>::callbacks[i].obj)->*(CallbackVector<C,N,M>::callbacks[i].ptr))(a1, a2); } } }; /** * Templated callback vector class with callback method taking one * argument of type Arg1 and returning a boolean. * * This one is used mainly for GUI event callbacks, where the boolean * value indicates whether the event was handled. **/ template <class C, int N = 4, typename Arg1 = void, typename M = bool(C::*)(Arg1)> class BoolCallbackVector1 : public CallbackVector<C, N, M> { public: /** Call the callback methods until one callback returns true. **/ bool callBool(Arg1 a1) { for (uint8_t i = 0; i < CallbackVector<C,N,M>::size; i++) { if (((CallbackVector<C,N,M>::callbacks[i].obj)->*(CallbackVector<C,N,M>::callbacks[i].ptr))(a1)) { return true; } } return false; } }; /* @} @} @} */ #endif /* CALLBACK_H__ */ <|endoftext|>
<commit_before>#ifndef AMGCL_RELAXATION_ILUT_HPP #define AMGCL_RELAXATION_ILUT_HPP /* The MIT License Copyright (c) 2012-2016 Denis Demidov <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file amgcl/relaxation/ilut.hpp * \author Denis Demidov <[email protected]> * \brief Incomplete LU with thresholding relaxation scheme. */ #include <vector> #include <queue> #include <cmath> #include <boost/typeof/typeof.hpp> #include <boost/foreach.hpp> #include <amgcl/backend/builtin.hpp> #include <amgcl/util.hpp> #include <amgcl/relaxation/detail/ilu_solve.hpp> namespace amgcl { namespace relaxation { /// ILUT(p, tau) smoother. /** * \note ILUT is a serial algorithm and is only applicable to backends that * support matrix row iteration (e.g. amgcl::backend::builtin or * amgcl::backend::eigen). * * \param Backend Backend for temporary structures allocation. * \ingroup relaxation */ template <class Backend> struct ilut { typedef typename Backend::value_type value_type; typedef typename Backend::matrix matrix; typedef typename Backend::matrix_diagonal matrix_diagonal; typedef typename Backend::vector vector; typedef typename math::scalar_of<value_type>::type scalar_type; /// Relaxation parameters. struct params { /// Maximum fill-in. int p; /// Minimum magnitude of non-zero elements relative to the current row norm. scalar_type tau; /// Damping factor. scalar_type damping; /// Number of Jacobi iterations. /** \note Used for approximate solution of triangular systems on parallel backends */ unsigned jacobi_iters; params() : p(2), tau(1e-2f), damping(1), jacobi_iters(2) {} params(const boost::property_tree::ptree &p) : AMGCL_PARAMS_IMPORT_VALUE(p, p) , AMGCL_PARAMS_IMPORT_VALUE(p, tau) , AMGCL_PARAMS_IMPORT_VALUE(p, damping) , AMGCL_PARAMS_IMPORT_VALUE(p, jacobi_iters) {} void get(boost::property_tree::ptree &p, const std::string &path) const { AMGCL_PARAMS_EXPORT_VALUE(p, path, p); AMGCL_PARAMS_EXPORT_VALUE(p, path, tau); AMGCL_PARAMS_EXPORT_VALUE(p, path, damping); AMGCL_PARAMS_EXPORT_VALUE(p, path, jacobi_iters); } }; /// \copydoc amgcl::relaxation::damped_jacobi::damped_jacobi template <class Matrix> ilut( const Matrix &A, const params &prm, const typename Backend::params &bprm) { typedef typename backend::row_iterator<Matrix>::type row_iterator; const size_t n = backend::rows(A); BOOST_AUTO(Aptr, A.ptr_data()); BOOST_AUTO(Acol, A.col_data()); size_t Lnz = 0, Unz = 0; for(ptrdiff_t i = 0; i < static_cast<ptrdiff_t>(n); ++i) { ptrdiff_t row_beg = Aptr[i]; ptrdiff_t row_end = Aptr[i + 1]; for(ptrdiff_t j = row_beg; j < row_end; ++j) { ptrdiff_t c = Acol[j]; if (c < i) ++Lnz; else if (c > i) ++Unz; } } boost::shared_ptr<build_matrix> L = boost::make_shared<build_matrix>(); boost::shared_ptr<build_matrix> U = boost::make_shared<build_matrix>(); L->nrows = L->ncols = n; L->ptr.reserve(n+1); L->ptr.push_back(0); L->col.reserve(Lnz + n * prm.p); L->val.reserve(Lnz + n * prm.p); U->nrows = U->ncols = n; U->ptr.reserve(n+1); U->ptr.push_back(0); U->col.reserve(Unz + n * prm.p); U->val.reserve(Unz + n * prm.p); std::vector<value_type> D; D.reserve(n); sparse_vector w(n); for(ptrdiff_t i = 0; i < static_cast<ptrdiff_t>(n); ++i) { w.dia = i; int lenL = 0; int lenU = 0; scalar_type tol = math::zero<scalar_type>(); for(row_iterator a = backend::row_begin(A, i); a; ++a) { w[a.col()] = a.value(); tol += math::norm(a.value()); if (a.col() < i) ++lenL; if (a.col() >= i) ++lenU; } tol = prm.tau / (lenL + lenU); while(!w.q.empty()) { ptrdiff_t k = w.next_nonzero(); w[k] = D[k] * w[k]; value_type wk = w[k]; if (math::norm(wk) > tol) { for(ptrdiff_t j = U->ptr[k]; j < U->ptr[k+1]; ++j) w[U->col[j]] -= wk * U->val[j]; } } w.move_to(lenL + prm.p, lenU + prm.p, tol, *L, *U, D); } this->D = Backend::copy_vector(D, bprm); this->L = Backend::copy_matrix(L, bprm); this->U = Backend::copy_matrix(U, bprm); if (!serial_backend::value) { t1 = Backend::create_vector(n, bprm); t2 = Backend::create_vector(n, bprm); } } /// \copydoc amgcl::relaxation::damped_jacobi::apply_pre template <class Matrix, class VectorRHS, class VectorX, class VectorTMP> void apply_pre( const Matrix &A, const VectorRHS &rhs, VectorX &x, VectorTMP &tmp, const params &prm ) const { backend::residual(rhs, A, x, tmp); solve(tmp, prm, serial_backend()); backend::axpby(prm.damping, tmp, math::identity<scalar_type>(), x); } /// \copydoc amgcl::relaxation::damped_jacobi::apply_post template <class Matrix, class VectorRHS, class VectorX, class VectorTMP> void apply_post( const Matrix &A, const VectorRHS &rhs, VectorX &x, VectorTMP &tmp, const params &prm ) const { backend::residual(rhs, A, x, tmp); solve(tmp, prm, serial_backend()); backend::axpby(prm.damping, tmp, math::identity<scalar_type>(), x); } template <class Matrix, class VectorRHS, class VectorX> void apply(const Matrix &A, const VectorRHS &rhs, VectorX &x, const params &prm) const { backend::copy(rhs, x); solve(x, prm, serial_backend()); } private: typedef typename boost::is_same< Backend, backend::builtin<value_type> >::type serial_backend; typedef typename backend::builtin<value_type>::matrix build_matrix; boost::shared_ptr<matrix> L, U; boost::shared_ptr<matrix_diagonal> D; boost::shared_ptr<vector> t1, t2; struct sparse_vector { struct nonzero { ptrdiff_t col; value_type val; nonzero() : col(-1) {} nonzero(ptrdiff_t col, value_type val = value_type()) : col(col), val(val) {} }; struct comp_indices { const std::vector<nonzero> &nz; comp_indices(const std::vector<nonzero> &nz) : nz(nz) {} bool operator()(int a, int b) const { return nz[a].col > nz[b].col; } }; typedef std::priority_queue<int, std::vector<int>, comp_indices> priority_queue; std::vector<nonzero> nz; std::vector<ptrdiff_t> idx; priority_queue q; ptrdiff_t dia; sparse_vector(size_t n) : idx(n, -1), q(comp_indices(nz)), dia(0) { nz.reserve(16); } value_type operator[](ptrdiff_t i) const { if (idx[i] >= 0) return nz[idx[i]].val; return value_type(); } value_type& operator[](ptrdiff_t i) { if (idx[i] == -1) { int p = nz.size(); idx[i] = p; nz.push_back(nonzero(i)); if (i < dia) q.push(p); } return nz[idx[i]].val; } typename std::vector<nonzero>::iterator begin() { return nz.begin(); } typename std::vector<nonzero>::iterator end() { return nz.end(); } ptrdiff_t next_nonzero() { int p = q.top(); q.pop(); return nz[p].col; } struct higher_than { scalar_type tol; ptrdiff_t dia; higher_than(scalar_type tol, ptrdiff_t dia) : tol(tol), dia(dia) {} bool operator()(const nonzero &v) const { return v.col == dia || math::norm(v.val) > tol; } }; struct L_first { ptrdiff_t dia; L_first(ptrdiff_t dia) : dia(dia) {} bool operator()(const nonzero &v) const { return v.col < dia; } }; struct by_abs_val { ptrdiff_t dia; by_abs_val(ptrdiff_t dia) : dia(dia) {} bool operator()(const nonzero &a, const nonzero &b) const { if (a.col == dia) return true; if (b.col == dia) return false; return math::norm(a.val) > math::norm(b.val); } }; struct by_col { bool operator()(const nonzero &a, const nonzero &b) const { return a.col < b.col; } }; void move_to( int lp, int up, scalar_type tol, build_matrix &L, build_matrix &U, std::vector<value_type> &D ) { typedef typename std::vector<nonzero>::iterator ptr; ptr b = nz.begin(); ptr e = nz.end(); // Move zeros to back: e = std::partition(b, e, higher_than(tol, dia)); // Split L and U: ptr m = std::partition(b, e, L_first(dia)); // Get largest p elements in L and U. ptr lend = std::min(b + lp, m); ptr uend = std::min(m + up, e); if (lend != m) std::nth_element(b, lend, m, by_abs_val(dia)); if (uend != e) std::nth_element(m, uend, e, by_abs_val(dia)); // Sort entries by column number std::sort(b, lend, by_col()); std::sort(m, uend, by_col()); // copy L to the output matrix. for(ptr a = b; a != lend; ++a) { L.col.push_back(a->col); L.val.push_back(a->val); } L.ptr.push_back(L.val.size()); // Store inverted diagonal. D.push_back(math::inverse(m->val)); ++m; // copy U to the output matrix. for(ptr a = m; a != uend; ++a) { U.col.push_back(a->col); U.val.push_back(a->val); } U.ptr.push_back(U.val.size()); BOOST_FOREACH(const nonzero &e, nz) idx[e.col] = -1; nz.clear(); } }; template <class VectorX> void solve(VectorX &x, const params &prm, boost::true_type) const { relaxation::detail::serial_ilu_solve(*L, *U, *D, x); } template <class VectorX> void solve(VectorX &x, const params &prm, boost::false_type) const { relaxation::detail::parallel_ilu_solve( *L, *U, *D, x, *t1, *t2, prm.jacobi_iters ); } }; } // namespace relaxation } // namespace amgcl #endif <commit_msg>Fix an embarassing error in ILUT<commit_after>#ifndef AMGCL_RELAXATION_ILUT_HPP #define AMGCL_RELAXATION_ILUT_HPP /* The MIT License Copyright (c) 2012-2016 Denis Demidov <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file amgcl/relaxation/ilut.hpp * \author Denis Demidov <[email protected]> * \brief Incomplete LU with thresholding relaxation scheme. */ #include <vector> #include <queue> #include <cmath> #include <boost/typeof/typeof.hpp> #include <boost/foreach.hpp> #include <amgcl/backend/builtin.hpp> #include <amgcl/util.hpp> #include <amgcl/relaxation/detail/ilu_solve.hpp> namespace amgcl { namespace relaxation { /// ILUT(p, tau) smoother. /** * \note ILUT is a serial algorithm and is only applicable to backends that * support matrix row iteration (e.g. amgcl::backend::builtin or * amgcl::backend::eigen). * * \param Backend Backend for temporary structures allocation. * \ingroup relaxation */ template <class Backend> struct ilut { typedef typename Backend::value_type value_type; typedef typename Backend::matrix matrix; typedef typename Backend::matrix_diagonal matrix_diagonal; typedef typename Backend::vector vector; typedef typename math::scalar_of<value_type>::type scalar_type; /// Relaxation parameters. struct params { /// Maximum fill-in. int p; /// Minimum magnitude of non-zero elements relative to the current row norm. scalar_type tau; /// Damping factor. scalar_type damping; /// Number of Jacobi iterations. /** \note Used for approximate solution of triangular systems on parallel backends */ unsigned jacobi_iters; params() : p(2), tau(1e-2f), damping(1), jacobi_iters(2) {} params(const boost::property_tree::ptree &p) : AMGCL_PARAMS_IMPORT_VALUE(p, p) , AMGCL_PARAMS_IMPORT_VALUE(p, tau) , AMGCL_PARAMS_IMPORT_VALUE(p, damping) , AMGCL_PARAMS_IMPORT_VALUE(p, jacobi_iters) {} void get(boost::property_tree::ptree &p, const std::string &path) const { AMGCL_PARAMS_EXPORT_VALUE(p, path, p); AMGCL_PARAMS_EXPORT_VALUE(p, path, tau); AMGCL_PARAMS_EXPORT_VALUE(p, path, damping); AMGCL_PARAMS_EXPORT_VALUE(p, path, jacobi_iters); } }; /// \copydoc amgcl::relaxation::damped_jacobi::damped_jacobi template <class Matrix> ilut( const Matrix &A, const params &prm, const typename Backend::params &bprm) { typedef typename backend::row_iterator<Matrix>::type row_iterator; const size_t n = backend::rows(A); BOOST_AUTO(Aptr, A.ptr_data()); BOOST_AUTO(Acol, A.col_data()); size_t Lnz = 0, Unz = 0; for(ptrdiff_t i = 0; i < static_cast<ptrdiff_t>(n); ++i) { ptrdiff_t row_beg = Aptr[i]; ptrdiff_t row_end = Aptr[i + 1]; for(ptrdiff_t j = row_beg; j < row_end; ++j) { ptrdiff_t c = Acol[j]; if (c < i) ++Lnz; else if (c > i) ++Unz; } } boost::shared_ptr<build_matrix> L = boost::make_shared<build_matrix>(); boost::shared_ptr<build_matrix> U = boost::make_shared<build_matrix>(); L->nrows = L->ncols = n; L->ptr.reserve(n+1); L->ptr.push_back(0); L->col.reserve(Lnz + n * prm.p); L->val.reserve(Lnz + n * prm.p); U->nrows = U->ncols = n; U->ptr.reserve(n+1); U->ptr.push_back(0); U->col.reserve(Unz + n * prm.p); U->val.reserve(Unz + n * prm.p); std::vector<value_type> D; D.reserve(n); sparse_vector w(n); for(ptrdiff_t i = 0; i < static_cast<ptrdiff_t>(n); ++i) { w.dia = i; int lenL = 0; int lenU = 0; scalar_type tol = math::zero<scalar_type>(); for(row_iterator a = backend::row_begin(A, i); a; ++a) { w[a.col()] = a.value(); tol += math::norm(a.value()); if (a.col() < i) ++lenL; if (a.col() >= i) ++lenU; } tol *= prm.tau / (lenL + lenU); while(!w.q.empty()) { ptrdiff_t k = w.next_nonzero(); w[k] = D[k] * w[k]; value_type wk = w[k]; if (math::norm(wk) > tol) { for(ptrdiff_t j = U->ptr[k]; j < U->ptr[k+1]; ++j) w[U->col[j]] -= wk * U->val[j]; } } w.move_to(lenL + prm.p, lenU + prm.p, tol, *L, *U, D); } this->D = Backend::copy_vector(D, bprm); this->L = Backend::copy_matrix(L, bprm); this->U = Backend::copy_matrix(U, bprm); if (!serial_backend::value) { t1 = Backend::create_vector(n, bprm); t2 = Backend::create_vector(n, bprm); } } /// \copydoc amgcl::relaxation::damped_jacobi::apply_pre template <class Matrix, class VectorRHS, class VectorX, class VectorTMP> void apply_pre( const Matrix &A, const VectorRHS &rhs, VectorX &x, VectorTMP &tmp, const params &prm ) const { backend::residual(rhs, A, x, tmp); solve(tmp, prm, serial_backend()); backend::axpby(prm.damping, tmp, math::identity<scalar_type>(), x); } /// \copydoc amgcl::relaxation::damped_jacobi::apply_post template <class Matrix, class VectorRHS, class VectorX, class VectorTMP> void apply_post( const Matrix &A, const VectorRHS &rhs, VectorX &x, VectorTMP &tmp, const params &prm ) const { backend::residual(rhs, A, x, tmp); solve(tmp, prm, serial_backend()); backend::axpby(prm.damping, tmp, math::identity<scalar_type>(), x); } template <class Matrix, class VectorRHS, class VectorX> void apply(const Matrix &A, const VectorRHS &rhs, VectorX &x, const params &prm) const { backend::copy(rhs, x); solve(x, prm, serial_backend()); } private: typedef typename boost::is_same< Backend, backend::builtin<value_type> >::type serial_backend; typedef typename backend::builtin<value_type>::matrix build_matrix; boost::shared_ptr<matrix> L, U; boost::shared_ptr<matrix_diagonal> D; boost::shared_ptr<vector> t1, t2; struct sparse_vector { struct nonzero { ptrdiff_t col; value_type val; nonzero() : col(-1) {} nonzero(ptrdiff_t col, value_type val = value_type()) : col(col), val(val) {} }; struct comp_indices { const std::vector<nonzero> &nz; comp_indices(const std::vector<nonzero> &nz) : nz(nz) {} bool operator()(int a, int b) const { return nz[a].col > nz[b].col; } }; typedef std::priority_queue<int, std::vector<int>, comp_indices> priority_queue; std::vector<nonzero> nz; std::vector<ptrdiff_t> idx; priority_queue q; ptrdiff_t dia; sparse_vector(size_t n) : idx(n, -1), q(comp_indices(nz)), dia(0) { nz.reserve(16); } value_type operator[](ptrdiff_t i) const { if (idx[i] >= 0) return nz[idx[i]].val; return value_type(); } value_type& operator[](ptrdiff_t i) { if (idx[i] == -1) { int p = nz.size(); idx[i] = p; nz.push_back(nonzero(i)); if (i < dia) q.push(p); } return nz[idx[i]].val; } typename std::vector<nonzero>::iterator begin() { return nz.begin(); } typename std::vector<nonzero>::iterator end() { return nz.end(); } ptrdiff_t next_nonzero() { int p = q.top(); q.pop(); return nz[p].col; } struct higher_than { scalar_type tol; ptrdiff_t dia; higher_than(scalar_type tol, ptrdiff_t dia) : tol(tol), dia(dia) {} bool operator()(const nonzero &v) const { return v.col == dia || math::norm(v.val) > tol; } }; struct L_first { ptrdiff_t dia; L_first(ptrdiff_t dia) : dia(dia) {} bool operator()(const nonzero &v) const { return v.col < dia; } }; struct by_abs_val { ptrdiff_t dia; by_abs_val(ptrdiff_t dia) : dia(dia) {} bool operator()(const nonzero &a, const nonzero &b) const { if (a.col == dia) return true; if (b.col == dia) return false; return math::norm(a.val) > math::norm(b.val); } }; struct by_col { bool operator()(const nonzero &a, const nonzero &b) const { return a.col < b.col; } }; void move_to( int lp, int up, scalar_type tol, build_matrix &L, build_matrix &U, std::vector<value_type> &D ) { typedef typename std::vector<nonzero>::iterator ptr; ptr b = nz.begin(); ptr e = nz.end(); // Move zeros to back: e = std::partition(b, e, higher_than(tol, dia)); // Split L and U: ptr m = std::partition(b, e, L_first(dia)); // Get largest p elements in L and U. ptr lend = std::min(b + lp, m); ptr uend = std::min(m + up, e); if (lend != m) std::nth_element(b, lend, m, by_abs_val(dia)); if (uend != e) std::nth_element(m, uend, e, by_abs_val(dia)); // Sort entries by column number std::sort(b, lend, by_col()); std::sort(m, uend, by_col()); // copy L to the output matrix. for(ptr a = b; a != lend; ++a) { L.col.push_back(a->col); L.val.push_back(a->val); } L.ptr.push_back(L.val.size()); // Store inverted diagonal. D.push_back(math::inverse(m->val)); ++m; // copy U to the output matrix. for(ptr a = m; a != uend; ++a) { U.col.push_back(a->col); U.val.push_back(a->val); } U.ptr.push_back(U.val.size()); BOOST_FOREACH(const nonzero &e, nz) idx[e.col] = -1; nz.clear(); } }; template <class VectorX> void solve(VectorX &x, const params &prm, boost::true_type) const { relaxation::detail::serial_ilu_solve(*L, *U, *D, x); } template <class VectorX> void solve(VectorX &x, const params &prm, boost::false_type) const { relaxation::detail::parallel_ilu_solve( *L, *U, *D, x, *t1, *t2, prm.jacobi_iters ); } }; } // namespace relaxation } // namespace amgcl #endif <|endoftext|>
<commit_before>// RUN: %clangxx -O0 %s -o %t // RUN: %env_tool_opts=strip_path_prefix=/TestCases/ %run %t 2>&1 | FileCheck %s // UNSUPPORTED: i386-darwin // // Tests __sanitizer_symbolize_pc. #include <stdio.h> #include <sanitizer/common_interface_defs.h> int GLOBAL_VAR_ABC; void SymbolizeCaller() { char data[100]; __sanitizer_symbolize_pc(__builtin_return_address(0), "%p %F %L", data, sizeof(data)); printf("FIRST_FORMAT %s\n", data); __sanitizer_symbolize_pc(__builtin_return_address(0), "FUNC:%f LINE:%l FILE:%s", data, sizeof(data)); printf("SECOND_FORMAT %s\n", data); __sanitizer_symbolize_pc(__builtin_return_address(0), "LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO" "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO" "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO" "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO" "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG" "FUNC:%f LINE:%l FILE:%s", data, sizeof(data)); printf("LONG_FORMAT %s\n", data); } void SymbolizeData() { char data[100]; __sanitizer_symbolize_global(&GLOBAL_VAR_ABC, "%g %s:%l", data, sizeof(data)); printf("GLOBAL: %s\n", data); } // CHECK: FIRST_FORMAT 0x{{.*}} in main symbolize_pc.cc:[[@LINE+3]] // CHECK: SECOND_FORMAT FUNC:main LINE:[[@LINE+2]] FILE:symbolize_pc.cc int main() { SymbolizeCaller(); SymbolizeData(); } // CHECK: GLOBAL: GLOBAL_VAR_ABC <commit_msg>[asan] Re-enable a test on i386-darwin.<commit_after>// RUN: %clangxx -O0 %s -o %t // RUN: %env_tool_opts=strip_path_prefix=/TestCases/ %run %t 2>&1 | FileCheck %s // // Tests __sanitizer_symbolize_pc. #include <stdio.h> #include <sanitizer/common_interface_defs.h> int GLOBAL_VAR_ABC; void SymbolizeCaller() { char data[100]; __sanitizer_symbolize_pc(__builtin_return_address(0), "%p %F %L", data, sizeof(data)); printf("FIRST_FORMAT %s\n", data); __sanitizer_symbolize_pc(__builtin_return_address(0), "FUNC:%f LINE:%l FILE:%s", data, sizeof(data)); printf("SECOND_FORMAT %s\n", data); __sanitizer_symbolize_pc(__builtin_return_address(0), "LOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO" "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO" "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO" "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO" "OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONG" "FUNC:%f LINE:%l FILE:%s", data, sizeof(data)); printf("LONG_FORMAT %s\n", data); } void SymbolizeData() { char data[100]; __sanitizer_symbolize_global(&GLOBAL_VAR_ABC, "%g %s:%l", data, sizeof(data)); printf("GLOBAL: %s\n", data); } // CHECK: FIRST_FORMAT 0x{{.*}} in main symbolize_pc.cc:[[@LINE+3]] // CHECK: SECOND_FORMAT FUNC:main LINE:[[@LINE+2]] FILE:symbolize_pc.cc int main() { SymbolizeCaller(); SymbolizeData(); } // CHECK: GLOBAL: GLOBAL_VAR_ABC <|endoftext|>
<commit_before>/******************************************************************************\ * File: tool.cpp * Purpose: Implementation of wxExTool class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/file.h> #include <wx/stdpaths.h> #include <wx/textfile.h> #include <wx/extension/tool.h> #include <wx/extension/statistics.h> #include <wx/extension/vcs.h> wxExTool* wxExTool::m_Self = NULL; wxExTool::wxExTool(int type) : m_Id(type) { } wxExTool* wxExTool::Get(bool createOnDemand) { if (m_Self == NULL && createOnDemand) { m_Self = new wxExTool(0); m_Self->AddInfo(ID_TOOL_REVISION_RECENT, _("Recent revision from")); m_Self->AddInfo(ID_TOOL_REPORT_REVISION, _("Reported %ld revisions in"), _("Report &Revision")); m_Self->AddInfo(ID_TOOL_REPORT_COUNT, _("Counted"), _("Report &Count")); m_Self->AddInfo(ID_TOOL_REPORT_FIND, _("Found %ld matches in")); m_Self->AddInfo(ID_TOOL_REPORT_REPLACE, _("Replaced %ld matches in")); m_Self->AddInfo(ID_TOOL_REPORT_KEYWORD, _("Reported %ld keywords in"), _("Report &Keyword")); } return m_Self; } const wxString wxExTool::Info() const { if (m_Self == NULL) { return "No info available"; } const auto it = m_Self->m_ToolInfo.find(m_Id); if (it != m_Self->m_ToolInfo.end()) { return it->second.GetInfo(); } wxFAIL; return wxEmptyString; } void wxExTool::Log(const wxExStatistics<long>* stat) const { wxString logtext(Info()); if (logtext.Contains("%ld")) { logtext = logtext.Format(logtext, stat->Get(_("Actions Completed"))); } logtext << " " << stat->Get(_("Files")) << " " << _("file(s)"); if (stat->Get(_("Files")) != 0) { if (IsCount()) { wxLogMessage(stat->Get()); } } wxLogStatus(logtext); } wxExTool* wxExTool::Set(wxExTool* tool) { wxExTool* old = m_Self; m_Self = tool; return old; } <commit_msg>removed no longer needed include files<commit_after>/******************************************************************************\ * File: tool.cpp * Purpose: Implementation of wxExTool class * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/extension/tool.h> #include <wx/extension/statistics.h> wxExTool* wxExTool::m_Self = NULL; wxExTool::wxExTool(int type) : m_Id(type) { } wxExTool* wxExTool::Get(bool createOnDemand) { if (m_Self == NULL && createOnDemand) { m_Self = new wxExTool(0); m_Self->AddInfo(ID_TOOL_REVISION_RECENT, _("Recent revision from")); m_Self->AddInfo(ID_TOOL_REPORT_REVISION, _("Reported %ld revisions in"), _("Report &Revision")); m_Self->AddInfo(ID_TOOL_REPORT_COUNT, _("Counted"), _("Report &Count")); m_Self->AddInfo(ID_TOOL_REPORT_FIND, _("Found %ld matches in")); m_Self->AddInfo(ID_TOOL_REPORT_REPLACE, _("Replaced %ld matches in")); m_Self->AddInfo(ID_TOOL_REPORT_KEYWORD, _("Reported %ld keywords in"), _("Report &Keyword")); } return m_Self; } const wxString wxExTool::Info() const { if (m_Self == NULL) { return "No info available"; } const auto it = m_Self->m_ToolInfo.find(m_Id); if (it != m_Self->m_ToolInfo.end()) { return it->second.GetInfo(); } wxFAIL; return wxEmptyString; } void wxExTool::Log(const wxExStatistics<long>* stat) const { wxString logtext(Info()); if (logtext.Contains("%ld")) { logtext = logtext.Format(logtext, stat->Get(_("Actions Completed"))); } logtext << " " << stat->Get(_("Files")) << " " << _("file(s)"); if (stat->Get(_("Files")) != 0) { if (IsCount()) { wxLogMessage(stat->Get()); } } wxLogStatus(logtext); } wxExTool* wxExTool::Set(wxExTool* tool) { wxExTool* old = m_Self; m_Self = tool; return old; } <|endoftext|>
<commit_before>#include "errors.hpp" #include <boost/make_shared.hpp> #include "buffer_cache/buffer_cache.hpp" #include "containers/iterators.hpp" #include "rdb_protocol/protocol.hpp" #include "serializer/config.hpp" #include "serializer/translator.hpp" #include "unittest/gtest.hpp" #include "unittest/dummy_namespace_interface.hpp" namespace unittest { namespace { void run_with_namespace_interface(boost::function<void(namespace_interface_t<rdb_protocol_t> *)> fun) { /* Pick shards */ std::vector<rdb_protocol_t::region_t> shards; shards.push_back(rdb_protocol_t::region_t(key_range_t(key_range_t::none, store_key_t(""), key_range_t::open, store_key_t("n")))); shards.push_back(rdb_protocol_t::region_t(key_range_t(key_range_t::closed, store_key_t("n"), key_range_t::none, store_key_t("") ))); boost::ptr_vector<mock::temp_file_t> temp_files; for (int i = 0; i < (int)shards.size(); i++) { temp_files.push_back(new mock::temp_file_t("/tmp/rdb_unittest.XXXXXX")); } boost::ptr_vector<rdb_protocol_t::store_t> underlying_stores; scoped_ptr_t<io_backender_t> io_backender; make_io_backender(aio_default, &io_backender); for (int i = 0; i < (int)shards.size(); i++) { underlying_stores.push_back(new rdb_protocol_t::store_t(io_backender.get(), temp_files[i].name(), true, &get_global_perfmon_collection())); } boost::ptr_vector<store_view_t<rdb_protocol_t> > stores; for (int i = 0; i < (int)shards.size(); i++) { stores.push_back(new store_subview_t<rdb_protocol_t>(&underlying_stores[i], shards[i])); } /* Set up namespace interface */ dummy_namespace_interface_t<rdb_protocol_t> nsi(shards, stores.c_array()); fun(&nsi); } void run_in_thread_pool_with_namespace_interface(boost::function<void(namespace_interface_t<rdb_protocol_t> *)> fun) { mock::run_in_thread_pool(boost::bind(&run_with_namespace_interface, fun)); } } /* anonymous namespace */ /* `SetupTeardown` makes sure that it can start and stop without anything going horribly wrong */ void run_setup_teardown_test(UNUSED namespace_interface_t<rdb_protocol_t> *nsi) { /* Do nothing */ } TEST(RDBProtocol, SetupTeardown) { run_in_thread_pool_with_namespace_interface(&run_setup_teardown_test); } /* `GetSet` tests basic get and set operations */ void run_get_set_test(namespace_interface_t<rdb_protocol_t> *nsi) { order_source_t osource; boost::shared_ptr<scoped_cJSON_t> data(new scoped_cJSON_t(cJSON_CreateNull())); { rdb_protocol_t::write_t write(rdb_protocol_t::point_write_t(store_key_t("a"), data)); cond_t interruptor; rdb_protocol_t::write_response_t response = nsi->write(write, osource.check_in("unittest::run_get_set_test(rdb_protocol.cc-A)"), &interruptor); if (rdb_protocol_t::point_write_response_t *maybe_point_write_response_t = boost::get<rdb_protocol_t::point_write_response_t>(&response.response)) { EXPECT_EQ(maybe_point_write_response_t->result, STORED); } else { ADD_FAILURE() << "got wrong type of result back"; } } { rdb_protocol_t::read_t read(rdb_protocol_t::point_read_t(store_key_t("a"))); cond_t interruptor; rdb_protocol_t::read_response_t response = nsi->read(read, osource.check_in("unittest::run_get_set_test(rdb_protocol.cc-B)"), &interruptor); if (rdb_protocol_t::point_read_response_t *maybe_point_read_response = boost::get<rdb_protocol_t::point_read_response_t>(&response.response)) { EXPECT_TRUE(maybe_point_read_response->data->get() != NULL); EXPECT_TRUE(cJSON_Equal(data->get(), maybe_point_read_response->data->get())); } else { ADD_FAILURE() << "got wrong result back"; } } } TEST(RDBProtocol, GetSet) { run_in_thread_pool_with_namespace_interface(&run_get_set_test); } } /* namespace unittest */ <commit_msg>Make rdb_protocol use order sources correctly.<commit_after>#include "errors.hpp" #include <boost/make_shared.hpp> #include "buffer_cache/buffer_cache.hpp" #include "containers/iterators.hpp" #include "rdb_protocol/protocol.hpp" #include "serializer/config.hpp" #include "serializer/translator.hpp" #include "unittest/gtest.hpp" #include "unittest/dummy_namespace_interface.hpp" namespace unittest { namespace { void run_with_namespace_interface(boost::function<void(namespace_interface_t<rdb_protocol_t> *, order_source_t *)> fun) { order_source_t order_source; /* Pick shards */ std::vector<rdb_protocol_t::region_t> shards; shards.push_back(rdb_protocol_t::region_t(key_range_t(key_range_t::none, store_key_t(""), key_range_t::open, store_key_t("n")))); shards.push_back(rdb_protocol_t::region_t(key_range_t(key_range_t::closed, store_key_t("n"), key_range_t::none, store_key_t("") ))); boost::ptr_vector<mock::temp_file_t> temp_files; for (int i = 0; i < (int)shards.size(); i++) { temp_files.push_back(new mock::temp_file_t("/tmp/rdb_unittest.XXXXXX")); } boost::ptr_vector<rdb_protocol_t::store_t> underlying_stores; scoped_ptr_t<io_backender_t> io_backender; make_io_backender(aio_default, &io_backender); for (int i = 0; i < (int)shards.size(); i++) { underlying_stores.push_back(new rdb_protocol_t::store_t(io_backender.get(), temp_files[i].name(), true, &get_global_perfmon_collection())); } boost::ptr_vector<store_view_t<rdb_protocol_t> > stores; for (int i = 0; i < (int)shards.size(); i++) { stores.push_back(new store_subview_t<rdb_protocol_t>(&underlying_stores[i], shards[i])); } /* Set up namespace interface */ dummy_namespace_interface_t<rdb_protocol_t> nsi(shards, stores.c_array(), &order_source); fun(&nsi, &order_source); } void run_in_thread_pool_with_namespace_interface(boost::function<void(namespace_interface_t<rdb_protocol_t> *, order_source_t*)> fun) { mock::run_in_thread_pool(boost::bind(&run_with_namespace_interface, fun)); } } /* anonymous namespace */ /* `SetupTeardown` makes sure that it can start and stop without anything going horribly wrong */ void run_setup_teardown_test(UNUSED namespace_interface_t<rdb_protocol_t> *nsi, order_source_t *) { /* Do nothing */ } TEST(RDBProtocol, SetupTeardown) { run_in_thread_pool_with_namespace_interface(&run_setup_teardown_test); } /* `GetSet` tests basic get and set operations */ void run_get_set_test(namespace_interface_t<rdb_protocol_t> *nsi, order_source_t *osource) { boost::shared_ptr<scoped_cJSON_t> data(new scoped_cJSON_t(cJSON_CreateNull())); { rdb_protocol_t::write_t write(rdb_protocol_t::point_write_t(store_key_t("a"), data)); cond_t interruptor; rdb_protocol_t::write_response_t response = nsi->write(write, osource->check_in("unittest::run_get_set_test(rdb_protocol.cc-A)"), &interruptor); if (rdb_protocol_t::point_write_response_t *maybe_point_write_response_t = boost::get<rdb_protocol_t::point_write_response_t>(&response.response)) { EXPECT_EQ(maybe_point_write_response_t->result, STORED); } else { ADD_FAILURE() << "got wrong type of result back"; } } { rdb_protocol_t::read_t read(rdb_protocol_t::point_read_t(store_key_t("a"))); cond_t interruptor; rdb_protocol_t::read_response_t response = nsi->read(read, osource->check_in("unittest::run_get_set_test(rdb_protocol.cc-B)"), &interruptor); if (rdb_protocol_t::point_read_response_t *maybe_point_read_response = boost::get<rdb_protocol_t::point_read_response_t>(&response.response)) { EXPECT_TRUE(maybe_point_read_response->data->get() != NULL); EXPECT_TRUE(cJSON_Equal(data->get(), maybe_point_read_response->data->get())); } else { ADD_FAILURE() << "got wrong result back"; } } } TEST(RDBProtocol, GetSet) { run_in_thread_pool_with_namespace_interface(&run_get_set_test); } } /* namespace unittest */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: accessibleselectionhelper.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2003-03-19 15:58:36 $ * * 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 EXPRESS 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 COMPHELPER_ACCESSIBLE_SELECTION_HELPER_HXX #include <comphelper/accessibleselectionhelper.hxx> #endif //......................................................................... namespace comphelper { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::awt; using namespace ::com::sun::star::lang; using namespace ::drafts::com::sun::star::accessibility; //===================================================================== //= OCommonAccessibleSelection //===================================================================== //--------------------------------------------------------------------- OCommonAccessibleSelection::OCommonAccessibleSelection( ) { } //-------------------------------------------------------------------- void SAL_CALL OCommonAccessibleSelection::selectAccessibleChild( sal_Int32 nChildIndex ) throw (IndexOutOfBoundsException, RuntimeException) { implSelect( nChildIndex, sal_True ); } //-------------------------------------------------------------------- sal_Bool SAL_CALL OCommonAccessibleSelection::isAccessibleChildSelected( sal_Int32 nChildIndex ) throw (IndexOutOfBoundsException, RuntimeException) { return( implIsSelected( nChildIndex ) ); } //-------------------------------------------------------------------- void SAL_CALL OCommonAccessibleSelection::clearAccessibleSelection( ) throw (RuntimeException) { implSelect( ACCESSIBLE_SELECTION_CHILD_ALL, sal_False ); } //-------------------------------------------------------------------- void SAL_CALL OCommonAccessibleSelection::selectAllAccessible( ) throw (RuntimeException) { implSelect( ACCESSIBLE_SELECTION_CHILD_ALL, sal_True ); } //-------------------------------------------------------------------- sal_Int32 SAL_CALL OCommonAccessibleSelection::getSelectedAccessibleChildCount( ) throw (RuntimeException) { sal_Int32 nRet = 0; Reference< XAccessibleContext > xParentContext( implGetAccessibleContext() ); OSL_ENSURE( xParentContext.is(), "OCommonAccessibleSelection::getSelectedAccessibleChildCount: no parent context!" ); if( xParentContext.is() ) { for( sal_Int32 i = 0, nChildCount = xParentContext->getAccessibleChildCount(); i < nChildCount; i++ ) if( implIsSelected( i ) ) ++nRet; } return( nRet ); } //-------------------------------------------------------------------- Reference< XAccessible > SAL_CALL OCommonAccessibleSelection::getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (IndexOutOfBoundsException, RuntimeException) { Reference< XAccessible > xRet; Reference< XAccessibleContext > xParentContext( implGetAccessibleContext() ); OSL_ENSURE( xParentContext.is(), "OCommonAccessibleSelection::getSelectedAccessibleChildCount: no parent context!" ); if( xParentContext.is() ) { for( sal_Int32 i = 0, nChildCount = xParentContext->getAccessibleChildCount(), nPos = 0; ( i < nChildCount ) && !xRet.is(); i++ ) if( implIsSelected( i ) && ( nPos++ == nSelectedChildIndex ) ) xRet = xParentContext->getAccessibleChild( i ); } return( xRet ); } //-------------------------------------------------------------------- void SAL_CALL OCommonAccessibleSelection::deselectSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (IndexOutOfBoundsException, RuntimeException) { implSelect( nSelectedChildIndex, sal_False ); } //===================================================================== //= OAccessibleSelectionHelper //===================================================================== //--------------------------------------------------------------------- OAccessibleSelectionHelper::OAccessibleSelectionHelper( ) { } //-------------------------------------------------------------------- OAccessibleSelectionHelper::OAccessibleSelectionHelper( IMutex* _pExternalLock ) : OAccessibleComponentHelper(_pExternalLock) { } //-------------------------------------------------------------------- IMPLEMENT_FORWARD_XINTERFACE2( OAccessibleSelectionHelper, OAccessibleComponentHelper, OAccessibleSelectionHelper_Base ) IMPLEMENT_FORWARD_XTYPEPROVIDER2( OAccessibleSelectionHelper, OAccessibleComponentHelper, OAccessibleSelectionHelper_Base ) // (order matters: the first is the class name, the second is the class doing the ref counting) //-------------------------------------------------------------------- Reference< XAccessibleContext > OAccessibleSelectionHelper::implGetAccessibleContext() throw ( RuntimeException ) { return( this ); } //-------------------------------------------------------------------- void SAL_CALL OAccessibleSelectionHelper::selectAccessibleChild( sal_Int32 nChildIndex ) throw (IndexOutOfBoundsException, RuntimeException) { OExternalLockGuard aGuard( this ); OCommonAccessibleSelection::selectAccessibleChild( nChildIndex ); } //-------------------------------------------------------------------- sal_Bool SAL_CALL OAccessibleSelectionHelper::isAccessibleChildSelected( sal_Int32 nChildIndex ) throw (IndexOutOfBoundsException, RuntimeException) { OExternalLockGuard aGuard( this ); return( OCommonAccessibleSelection::isAccessibleChildSelected( nChildIndex ) ); } //-------------------------------------------------------------------- void SAL_CALL OAccessibleSelectionHelper::clearAccessibleSelection( ) throw (RuntimeException) { OExternalLockGuard aGuard( this ); OCommonAccessibleSelection::clearAccessibleSelection(); } //-------------------------------------------------------------------- void SAL_CALL OAccessibleSelectionHelper::selectAllAccessible( ) throw (RuntimeException) { OExternalLockGuard aGuard( this ); OCommonAccessibleSelection::selectAllAccessible(); } //-------------------------------------------------------------------- sal_Int32 SAL_CALL OAccessibleSelectionHelper::getSelectedAccessibleChildCount( ) throw (RuntimeException) { OExternalLockGuard aGuard( this ); return( OCommonAccessibleSelection::getSelectedAccessibleChildCount() ); } //-------------------------------------------------------------------- Reference< XAccessible > SAL_CALL OAccessibleSelectionHelper::getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (IndexOutOfBoundsException, RuntimeException) { OExternalLockGuard aGuard( this ); return( OCommonAccessibleSelection::getSelectedAccessibleChild( nSelectedChildIndex ) ); } //-------------------------------------------------------------------- void SAL_CALL OAccessibleSelectionHelper::deselectSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (IndexOutOfBoundsException, RuntimeException) { OExternalLockGuard aGuard( this ); OCommonAccessibleSelection::deselectSelectedAccessibleChild( nSelectedChildIndex ); } //......................................................................... } // namespace comphelper //......................................................................... <commit_msg>INTEGRATION: CWS uaa02 (1.3.8); FILE MERGED 2003/04/11 15:39:16 mt 1.3.8.2: #108656# Moved accessibility from drafts to final 2003/04/10 11:59:41 mt 1.3.8.1: #108656# Moved Accessibility module from drafts to final<commit_after>/************************************************************************* * * $RCSfile: accessibleselectionhelper.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2003-04-24 17:27:42 $ * * 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 EXPRESS 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 COMPHELPER_ACCESSIBLE_SELECTION_HELPER_HXX #include <comphelper/accessibleselectionhelper.hxx> #endif //......................................................................... namespace comphelper { //......................................................................... using namespace ::com::sun::star::uno; using namespace ::com::sun::star::awt; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::accessibility; //===================================================================== //= OCommonAccessibleSelection //===================================================================== //--------------------------------------------------------------------- OCommonAccessibleSelection::OCommonAccessibleSelection( ) { } //-------------------------------------------------------------------- void SAL_CALL OCommonAccessibleSelection::selectAccessibleChild( sal_Int32 nChildIndex ) throw (IndexOutOfBoundsException, RuntimeException) { implSelect( nChildIndex, sal_True ); } //-------------------------------------------------------------------- sal_Bool SAL_CALL OCommonAccessibleSelection::isAccessibleChildSelected( sal_Int32 nChildIndex ) throw (IndexOutOfBoundsException, RuntimeException) { return( implIsSelected( nChildIndex ) ); } //-------------------------------------------------------------------- void SAL_CALL OCommonAccessibleSelection::clearAccessibleSelection( ) throw (RuntimeException) { implSelect( ACCESSIBLE_SELECTION_CHILD_ALL, sal_False ); } //-------------------------------------------------------------------- void SAL_CALL OCommonAccessibleSelection::selectAllAccessible( ) throw (RuntimeException) { implSelect( ACCESSIBLE_SELECTION_CHILD_ALL, sal_True ); } //-------------------------------------------------------------------- sal_Int32 SAL_CALL OCommonAccessibleSelection::getSelectedAccessibleChildCount( ) throw (RuntimeException) { sal_Int32 nRet = 0; Reference< XAccessibleContext > xParentContext( implGetAccessibleContext() ); OSL_ENSURE( xParentContext.is(), "OCommonAccessibleSelection::getSelectedAccessibleChildCount: no parent context!" ); if( xParentContext.is() ) { for( sal_Int32 i = 0, nChildCount = xParentContext->getAccessibleChildCount(); i < nChildCount; i++ ) if( implIsSelected( i ) ) ++nRet; } return( nRet ); } //-------------------------------------------------------------------- Reference< XAccessible > SAL_CALL OCommonAccessibleSelection::getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (IndexOutOfBoundsException, RuntimeException) { Reference< XAccessible > xRet; Reference< XAccessibleContext > xParentContext( implGetAccessibleContext() ); OSL_ENSURE( xParentContext.is(), "OCommonAccessibleSelection::getSelectedAccessibleChildCount: no parent context!" ); if( xParentContext.is() ) { for( sal_Int32 i = 0, nChildCount = xParentContext->getAccessibleChildCount(), nPos = 0; ( i < nChildCount ) && !xRet.is(); i++ ) if( implIsSelected( i ) && ( nPos++ == nSelectedChildIndex ) ) xRet = xParentContext->getAccessibleChild( i ); } return( xRet ); } //-------------------------------------------------------------------- void SAL_CALL OCommonAccessibleSelection::deselectAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (IndexOutOfBoundsException, RuntimeException) { implSelect( nSelectedChildIndex, sal_False ); } //===================================================================== //= OAccessibleSelectionHelper //===================================================================== //--------------------------------------------------------------------- OAccessibleSelectionHelper::OAccessibleSelectionHelper( ) { } //-------------------------------------------------------------------- OAccessibleSelectionHelper::OAccessibleSelectionHelper( IMutex* _pExternalLock ) : OAccessibleComponentHelper(_pExternalLock) { } //-------------------------------------------------------------------- IMPLEMENT_FORWARD_XINTERFACE2( OAccessibleSelectionHelper, OAccessibleComponentHelper, OAccessibleSelectionHelper_Base ) IMPLEMENT_FORWARD_XTYPEPROVIDER2( OAccessibleSelectionHelper, OAccessibleComponentHelper, OAccessibleSelectionHelper_Base ) // (order matters: the first is the class name, the second is the class doing the ref counting) //-------------------------------------------------------------------- Reference< XAccessibleContext > OAccessibleSelectionHelper::implGetAccessibleContext() throw ( RuntimeException ) { return( this ); } //-------------------------------------------------------------------- void SAL_CALL OAccessibleSelectionHelper::selectAccessibleChild( sal_Int32 nChildIndex ) throw (IndexOutOfBoundsException, RuntimeException) { OExternalLockGuard aGuard( this ); OCommonAccessibleSelection::selectAccessibleChild( nChildIndex ); } //-------------------------------------------------------------------- sal_Bool SAL_CALL OAccessibleSelectionHelper::isAccessibleChildSelected( sal_Int32 nChildIndex ) throw (IndexOutOfBoundsException, RuntimeException) { OExternalLockGuard aGuard( this ); return( OCommonAccessibleSelection::isAccessibleChildSelected( nChildIndex ) ); } //-------------------------------------------------------------------- void SAL_CALL OAccessibleSelectionHelper::clearAccessibleSelection( ) throw (RuntimeException) { OExternalLockGuard aGuard( this ); OCommonAccessibleSelection::clearAccessibleSelection(); } //-------------------------------------------------------------------- void SAL_CALL OAccessibleSelectionHelper::selectAllAccessible( ) throw (RuntimeException) { OExternalLockGuard aGuard( this ); OCommonAccessibleSelection::selectAllAccessible(); } //-------------------------------------------------------------------- sal_Int32 SAL_CALL OAccessibleSelectionHelper::getSelectedAccessibleChildCount( ) throw (RuntimeException) { OExternalLockGuard aGuard( this ); return( OCommonAccessibleSelection::getSelectedAccessibleChildCount() ); } //-------------------------------------------------------------------- Reference< XAccessible > SAL_CALL OAccessibleSelectionHelper::getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (IndexOutOfBoundsException, RuntimeException) { OExternalLockGuard aGuard( this ); return( OCommonAccessibleSelection::getSelectedAccessibleChild( nSelectedChildIndex ) ); } //-------------------------------------------------------------------- void SAL_CALL OAccessibleSelectionHelper::deselectAccessibleChild( sal_Int32 nSelectedChildIndex ) throw (IndexOutOfBoundsException, RuntimeException) { OExternalLockGuard aGuard( this ); OCommonAccessibleSelection::deselectAccessibleChild( nSelectedChildIndex ); } //......................................................................... } // namespace comphelper //......................................................................... <|endoftext|>
<commit_before>/* * Copyright (C) 2006 Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <tntdb/librarymanager.h> #include <cxxtools/log.h> #include <cxxtools/systemerror.h> #include <cxxtools/directory.h> #ifndef DRIVERDIR #define DRIVERDIR "tntdb" #endif #define TNTDB_STRINGIFY(x) #x #define TNTDB_TOSTRING(x) TNTDB_STRINGIFY(x) log_define("tntdb.librarymanager") namespace tntdb { static const std::string libraryPrefix = "tntdb" ABI_CURRENT "-"; LibraryManager::LibraryManager(const std::string& driverName) { try { log_debug("loading library \"" << libraryPrefix << driverName << '"'); lib = cxxtools::Library(libraryPrefix + driverName); } catch (const cxxtools::FileNotFound& e) { log_debug("library \"" << libraryPrefix << driverName << "\" not found: " << e.what()); } catch (const cxxtools::OpenLibraryFailed& e) { log_debug("opening library \"" << libraryPrefix << driverName << "\" failed: " << e.what()); } if (!lib) { std::string d = DRIVERDIR + cxxtools::Directory::sep() + libraryPrefix + driverName; log_debug("loading library \"" << d << '"'); lib = cxxtools::Library(d); } std::string symbolName = TNTDB_TOSTRING(TNTDB_DRIVER_PRAEFIX) + driverName; void* sym = lib.getSymbol(symbolName.c_str()); connectionManager = static_cast<IConnectionManager*>(sym); log_debug("driver " << driverName << " successfully loaded"); } } <commit_msg>better error message when loading driver library fails<commit_after>/* * Copyright (C) 2006 Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <tntdb/librarymanager.h> #include <tntdb/error.h> #include <cxxtools/log.h> #include <cxxtools/systemerror.h> #include <cxxtools/directory.h> #ifndef DRIVERDIR #define DRIVERDIR "tntdb" #endif #define TNTDB_STRINGIFY(x) #x #define TNTDB_TOSTRING(x) TNTDB_STRINGIFY(x) log_define("tntdb.librarymanager") namespace tntdb { static const std::string libraryPrefix = "tntdb" ABI_CURRENT "-"; LibraryManager::LibraryManager(const std::string& driverName) { try { log_debug("loading library \"" << libraryPrefix << driverName << '"'); lib = cxxtools::Library(libraryPrefix + driverName); } catch (const cxxtools::FileNotFound& e) { log_debug("library \"" << libraryPrefix << driverName << "\" not found: " << e.what()); } catch (const cxxtools::OpenLibraryFailed& e) { log_debug("opening library \"" << libraryPrefix << driverName << "\" failed: " << e.what()); } try { if (!lib) { std::string d = DRIVERDIR + cxxtools::Directory::sep() + libraryPrefix + driverName; log_debug("loading library \"" << d << '"'); lib = cxxtools::Library(d); } } catch (const std::exception& e) { std::ostringstream msg; msg << "failed to load driver \"" << libraryPrefix << driverName << '"'; log_warn(msg.str() << ": " << e.what()); throw Error(msg.str()); } std::string symbolName = TNTDB_TOSTRING(TNTDB_DRIVER_PRAEFIX) + driverName; void* sym = lib.getSymbol(symbolName.c_str()); connectionManager = static_cast<IConnectionManager*>(sym); log_debug("driver " << driverName << " successfully loaded"); } } <|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2013, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file GridConnectHub.cxx * Gridconnect parser/renderer pipe components. * * @author Balazs Racz * @date 20 May 2013 */ //#define LOGLEVEL VERBOSE #include "utils/GridConnectHub.hxx" #include "executor/StateFlow.hxx" #include "can_frame.h" #include "utils/Buffer.hxx" #include "utils/HubDevice.hxx" #include "utils/Hub.hxx" #include "utils/gc_format.h" /// Actual implementation for the gridconnect bridge between a string-typed Hub /// and a CAN-frame-typed Hub. class GCAdapter : public GCAdapterBase { public: GCAdapter(HubFlow *gc_side, CanHubFlow *can_side, bool double_bytes) : parser_(can_side->service(), can_side, &formatter_) , formatter_(can_side->service(), gc_side, &parser_, double_bytes) { gc_side->register_port(&parser_); can_side->register_port(&formatter_); isRegistered_ = 1; } GCAdapter(HubFlow *gc_side_read, HubFlow *gc_side_write, CanHubFlow *can_side, bool double_bytes) : parser_(can_side->service(), can_side, &formatter_) , formatter_(can_side->service(), gc_side_write, &parser_, double_bytes) { gc_side_read->register_port(&parser_); can_side->register_port(&formatter_); isRegistered_ = 1; } virtual ~GCAdapter() { unregister(); } void unregister() { if (isRegistered_) { parser_.destination()->unregister_port(&formatter_); /// @TODO(balazs.racz) This is incorrect if the 3-pipe constructor /// is /// used. formatter_.destination()->unregister_port(&parser_); isRegistered_ = 0; } } bool shutdown() OVERRIDE { unregister(); return parser_.is_waiting() && formatter_.is_waiting(); } /// HubPort (on a CAN-typed hub) that turns a binary CAN packet into a /// string-formatted CAN packet, and sends it off to the HubFlow (of type /// string). class BinaryToGCMember : public CanHubPort { public: BinaryToGCMember(Service *service, HubFlow *destination, HubPort *skip_member, int double_bytes) : CanHubPort(service) , destination_(destination) , skipMember_(skip_member) , double_bytes_(double_bytes) { } HubFlow *destination() { return destination_; } Action entry() { LOG(VERBOSE, "can packet arrived: %" PRIx32, GET_CAN_FRAME_ID_EFF(*message()->data())); char *end = gc_format_generate(message()->data(), dbuf_, double_bytes_); size_t size = (end - dbuf_); if (size) { Buffer<HubData> *target_buffer; /// @todo(balazs.racz) switch to asynchronous allocation here. mainBufferPool->alloc(&target_buffer); target_buffer->data()->skipMember_ = skipMember_; /// @todo(balazs.racz) try to use an assign function for better /// performance. target_buffer->data()->resize(size); memcpy((char *)target_buffer->data()->data(), dbuf_, size); destination_->send(target_buffer, 0); } else { LOG(INFO, "gc generate failed."); } return release_and_exit(); } private: /// Destination buffer (characters). char dbuf_[56]; /// Pipe to send data to. HubFlow *destination_; /// The pipe member that should be sent as "source". HubPort *skipMember_; /// Non-zero if doubling was requested. int double_bytes_; }; /// HubPort (on a string hub) that turns a gridconnect-formatted CAN packet /// into a binary CAN packet, and sends them off to the HubFlow (of CAN /// frame). class GCToBinaryMember : public HubPort { public: GCToBinaryMember(Service *service, CanHubFlow *destination, CanHubPort *skip_member) : HubPort(service) , offset_(-1) , destination_(destination) , skipMember_(skip_member) { } CanHubFlow *destination() { return destination_; } /** Takes more characters from the pending incoming buffer. */ Action entry() { inBuf_ = message()->data()->data(); inBufSize_ = message()->data()->size(); return call_immediately(STATE(parse_more_data)); } Action parse_more_data() { while (inBufSize_--) { char c = *inBuf_++; if (consume_byte(c)) { // End of frame. Allocate an output buffer and parse the // frame. /// @todo(balazs.racz) use a configurable buffer pool mainBufferPool->alloc(&outBuf_); return call_immediately(STATE(parse_to_output_frame)); } } // Will notify the caller. return release_and_exit(); } /** Takes the completed frame in cbuf_, parses it into the allocation * result (a can pipe buffer) and sends off frame. Then comes back to * process buffer. */ Action parse_to_output_frame() { // CanPipeBuffer *pbuf = GetTypedAllocationResult(&g_can_alloc); // pbuf->Reset(); LOG(VERBOSE, "gc packet arrived: %s", cbuf_); int ret = gc_format_parse(cbuf_, outBuf_->data()); if (!ret) { outBuf_->data()->skipMember_ = skipMember_; destination_->send(outBuf_); } else { // Releases the buffer. outBuf_->unref(); } return call_immediately(STATE(parse_more_data)); } /** Adds the next character from the source stream. Returns true if * cbuf_ contains a complete frame. */ bool consume_byte(char c) { if (c == ':') { // Frame is starting here. offset_ = 0; return false; } if (c == ';') { if (offset_ < 0) { return false; } // Frame ends here. cbuf_[offset_] = 0; offset_ = -1; return true; } if (offset_ >= static_cast<int>(sizeof(cbuf_) - 1)) { // We overran the buffer, so this can't be a valid frame. // Reset and look for sync byte again. offset_ = -1; return false; } if (offset_ >= 0) { cbuf_[offset_++] = c; } else { // Drop byte to the floor -- we're not in the middle of a // packet. } return false; } private: /// Collects data from a partial GC packet. char cbuf_[32]; /// offset of next byte in cbuf to write. int offset_; /// The incoming characters. const char *inBuf_; /// The remaining number of characters in inBuf_. size_t inBufSize_; /// The buffer to send to the destination hub. Buffer<CanHubData> *outBuf_; // ==== static data ==== /// Pipe to send data to. CanHubFlow *destination_; /// The pipe member that should be sent as "source". CanHubPortInterface *skipMember_; }; private: /// PipeMember doing the parsing. GCToBinaryMember parser_; /// PipeMember doing the formatting. BinaryToGCMember formatter_; unsigned isRegistered_ : 1; //< 1 if the flows are registered. }; GCAdapterBase *GCAdapterBase::CreateGridConnectAdapter(HubFlow *gc_side, CanHubFlow *can_side, bool double_bytes) { return new GCAdapter(gc_side, can_side, double_bytes); } GCAdapterBase *GCAdapterBase::CreateGridConnectAdapter(HubFlow *gc_side_read, HubFlow *gc_side_write, CanHubFlow *can_side, bool double_bytes) { return new GCAdapter(gc_side_read, gc_side_write, can_side, double_bytes); } /// Implementation for the gridconnect bridge. Owns all necessary structures, /// and is responsible for the initialization, registering, unregistering and /// destruction of these structures. struct GcPacketPrinter::Impl { Impl(CanHubFlow *can_hub, bool timestamped) : canHub_(can_hub) , gcHub_(canHub_->service()) , displayPort_(canHub_->service(), timestamped) , formatter_(canHub_->service(), &gcHub_, nullptr, false) { gcHub_.register_port(&displayPort_); canHub_->register_port(&formatter_); } ~Impl() { canHub_->unregister_port(&formatter_); gcHub_.unregister_port(&displayPort_); } CanHubFlow *canHub_; HubFlow gcHub_; DisplayPort displayPort_; GCAdapter::BinaryToGCMember formatter_; }; GcPacketPrinter::GcPacketPrinter(CanHubFlow *can_hub, bool timestamped) : impl_(new Impl(can_hub, timestamped)) { } GcPacketPrinter::~GcPacketPrinter() { } /// Implementation class that adds a device to a CAN hub with dynamic /// translation of the packets to/from GridConnect format. /// /// Sends a notification to the application level when there is an error on the /// device and the connection is closed. struct GcHubPort : public Executable { GcHubPort(CanHubFlow *can_hub, int fd, Notifiable *on_exit) : gcHub_(can_hub->service()) , bridge_( GCAdapterBase::CreateGridConnectAdapter(&gcHub_, can_hub, false)) , gcWrite_(&gcHub_, fd, this) , onExit_(on_exit) { LOG(VERBOSE, "gchub port %p", (Executable *)this); } virtual ~GcHubPort() { } /** This hub sees the character-based representation of the packets. The * members of it are: the bridge and the physical device (fd). * * Destruction requirement: HubFlow should be empty. This means after the * disconnection of the bridge (write side) and the FdHubport (read side) * we need to wait for the executor until this flow drains. */ HubFlow gcHub_; /** Translates packets between the can-hub of the device and the char-hub * of this port. * * Destruction requirement: Call shutdown() on the can-side executor (and * yield) until it returns true. */ std::unique_ptr<GCAdapterBase> bridge_; /** Reads the characters from the char-hub and sends them to the * fd. Similarly, listens to the fd and sends the read charcters to the * char-hub. */ FdHubPort<HubFlow> gcWrite_; /** If not null, this notifiable will be called when the device is * closed. */ Notifiable* onExit_; /** Callback in case the connection is closed due to error. */ void notify() OVERRIDE { /* We would like to delete *this but we cannot do that in this * callback, because we don't know what executor we are running * on. Deleting on the write executor would cause a deadlock for * example. */ gcHub_.service()->executor()->add(this); } void run() OVERRIDE { if (!bridge_->shutdown() || !gcHub_.is_waiting()) { // Yield. gcHub_.service()->executor()->add(this); return; } LOG(INFO, "GCHubPort: Shutting down gridconnect port %d. (%p)", gcWrite_.fd(), bridge_.get()); if (onExit_) { onExit_->notify(); onExit_ = nullptr; } /* We get this call when something is wrong with the FDs and we need to * close the connection. It is guaranteed that by the time we got this * call the device is unregistered from the char bridge, and the * service thread is ready to be stopped. */ delete this; } }; void create_gc_port_for_can_hub(CanHubFlow *can_hub, int fd, Notifiable* on_exit) { new GcHubPort(can_hub, fd, on_exit); } <commit_msg>Makes timestamped printing of HUB traffic be more user-friendly: - timestamps are printed in human readable form - also prints the skipMember_ field which allows determining where the packet came from.<commit_after>/** \copyright * Copyright (c) 2013, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file GridConnectHub.cxx * Gridconnect parser/renderer pipe components. * * @author Balazs Racz * @date 20 May 2013 */ //#define LOGLEVEL VERBOSE #include "utils/GridConnectHub.hxx" #include "executor/StateFlow.hxx" #include "can_frame.h" #include "utils/Buffer.hxx" #include "utils/HubDevice.hxx" #include "utils/Hub.hxx" #include "utils/gc_format.h" /// Actual implementation for the gridconnect bridge between a string-typed Hub /// and a CAN-frame-typed Hub. class GCAdapter : public GCAdapterBase { public: GCAdapter(HubFlow *gc_side, CanHubFlow *can_side, bool double_bytes) : parser_(can_side->service(), can_side, &formatter_) , formatter_(can_side->service(), gc_side, &parser_, double_bytes) { gc_side->register_port(&parser_); can_side->register_port(&formatter_); isRegistered_ = 1; } GCAdapter(HubFlow *gc_side_read, HubFlow *gc_side_write, CanHubFlow *can_side, bool double_bytes) : parser_(can_side->service(), can_side, &formatter_) , formatter_(can_side->service(), gc_side_write, &parser_, double_bytes) { gc_side_read->register_port(&parser_); can_side->register_port(&formatter_); isRegistered_ = 1; } virtual ~GCAdapter() { unregister(); } void unregister() { if (isRegistered_) { parser_.destination()->unregister_port(&formatter_); /// @TODO(balazs.racz) This is incorrect if the 3-pipe constructor /// is /// used. formatter_.destination()->unregister_port(&parser_); isRegistered_ = 0; } } bool shutdown() OVERRIDE { unregister(); return parser_.is_waiting() && formatter_.is_waiting(); } /// HubPort (on a CAN-typed hub) that turns a binary CAN packet into a /// string-formatted CAN packet, and sends it off to the HubFlow (of type /// string). class BinaryToGCMember : public CanHubPort { public: BinaryToGCMember(Service *service, HubFlow *destination, HubPort *skip_member, int double_bytes) : CanHubPort(service) , destination_(destination) , skipMember_(skip_member) , double_bytes_(double_bytes) { } HubFlow *destination() { return destination_; } Action entry() { LOG(VERBOSE, "can packet arrived: %" PRIx32, GET_CAN_FRAME_ID_EFF(*message()->data())); char *end = gc_format_generate(message()->data(), dbuf_, double_bytes_); size_t size = (end - dbuf_); if (size) { Buffer<HubData> *target_buffer; /// @todo(balazs.racz) switch to asynchronous allocation here. mainBufferPool->alloc(&target_buffer); target_buffer->data()->skipMember_ = skipMember_; /// @todo(balazs.racz) try to use an assign function for better /// performance. target_buffer->data()->resize(size); memcpy((char *)target_buffer->data()->data(), dbuf_, size); destination_->send(target_buffer, 0); } else { LOG(INFO, "gc generate failed."); } return release_and_exit(); } private: /// Destination buffer (characters). char dbuf_[56]; /// Pipe to send data to. HubFlow *destination_; /// The pipe member that should be sent as "source". HubPort *skipMember_; /// Non-zero if doubling was requested. int double_bytes_; }; /// HubPort (on a string hub) that turns a gridconnect-formatted CAN packet /// into a binary CAN packet, and sends them off to the HubFlow (of CAN /// frame). class GCToBinaryMember : public HubPort { public: GCToBinaryMember(Service *service, CanHubFlow *destination, CanHubPort *skip_member) : HubPort(service) , offset_(-1) , destination_(destination) , skipMember_(skip_member) { } CanHubFlow *destination() { return destination_; } /** Takes more characters from the pending incoming buffer. */ Action entry() { inBuf_ = message()->data()->data(); inBufSize_ = message()->data()->size(); return call_immediately(STATE(parse_more_data)); } Action parse_more_data() { while (inBufSize_--) { char c = *inBuf_++; if (consume_byte(c)) { // End of frame. Allocate an output buffer and parse the // frame. /// @todo(balazs.racz) use a configurable buffer pool mainBufferPool->alloc(&outBuf_); return call_immediately(STATE(parse_to_output_frame)); } } // Will notify the caller. return release_and_exit(); } /** Takes the completed frame in cbuf_, parses it into the allocation * result (a can pipe buffer) and sends off frame. Then comes back to * process buffer. */ Action parse_to_output_frame() { // CanPipeBuffer *pbuf = GetTypedAllocationResult(&g_can_alloc); // pbuf->Reset(); LOG(VERBOSE, "gc packet arrived: %s", cbuf_); int ret = gc_format_parse(cbuf_, outBuf_->data()); if (!ret) { outBuf_->data()->skipMember_ = skipMember_; destination_->send(outBuf_); } else { // Releases the buffer. outBuf_->unref(); } return call_immediately(STATE(parse_more_data)); } /** Adds the next character from the source stream. Returns true if * cbuf_ contains a complete frame. */ bool consume_byte(char c) { if (c == ':') { // Frame is starting here. offset_ = 0; return false; } if (c == ';') { if (offset_ < 0) { return false; } // Frame ends here. cbuf_[offset_] = 0; offset_ = -1; return true; } if (offset_ >= static_cast<int>(sizeof(cbuf_) - 1)) { // We overran the buffer, so this can't be a valid frame. // Reset and look for sync byte again. offset_ = -1; return false; } if (offset_ >= 0) { cbuf_[offset_++] = c; } else { // Drop byte to the floor -- we're not in the middle of a // packet. } return false; } private: /// Collects data from a partial GC packet. char cbuf_[32]; /// offset of next byte in cbuf to write. int offset_; /// The incoming characters. const char *inBuf_; /// The remaining number of characters in inBuf_. size_t inBufSize_; /// The buffer to send to the destination hub. Buffer<CanHubData> *outBuf_; // ==== static data ==== /// Pipe to send data to. CanHubFlow *destination_; /// The pipe member that should be sent as "source". CanHubPortInterface *skipMember_; }; private: /// PipeMember doing the parsing. GCToBinaryMember parser_; /// PipeMember doing the formatting. BinaryToGCMember formatter_; unsigned isRegistered_ : 1; //< 1 if the flows are registered. }; GCAdapterBase *GCAdapterBase::CreateGridConnectAdapter(HubFlow *gc_side, CanHubFlow *can_side, bool double_bytes) { return new GCAdapter(gc_side, can_side, double_bytes); } GCAdapterBase *GCAdapterBase::CreateGridConnectAdapter(HubFlow *gc_side_read, HubFlow *gc_side_write, CanHubFlow *can_side, bool double_bytes) { return new GCAdapter(gc_side_read, gc_side_write, can_side, double_bytes); } /// Implementation for the gridconnect bridge. Owns all necessary structures, /// and is responsible for the initialization, registering, unregistering and /// destruction of these structures. struct GcPacketPrinter::Impl : public CanHubPortInterface { Impl(CanHubFlow *can_hub, bool timestamped) : canHub_(can_hub) , timestamped_(timestamped) { canHub_->register_port(this); } ~Impl() { canHub_->unregister_port(this); } void send(Buffer<CanHubData> *message, unsigned priority) OVERRIDE { AutoReleaseBuffer<CanHubData> b(message); char str[40]; char* p = gc_format_generate(message->data(), str, false); *p = 0; if (timestamped_) { #if defined(__linux__) || defined(__MACH__) struct timeval tv; gettimeofday(&tv, nullptr); struct tm t; localtime_r(&tv.tv_sec, &t); printf("%04d-%02d-%02d %02d:%02d:%02d:%06ld [%p] ", t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, tv.tv_usec, message->data()->skipMember_); #endif } printf("%s\n", str); } CanHubFlow* canHub_; bool timestamped_; }; GcPacketPrinter::GcPacketPrinter(CanHubFlow *can_hub, bool timestamped) : impl_(new Impl(can_hub, timestamped)) { } GcPacketPrinter::~GcPacketPrinter() { } /// Implementation class that adds a device to a CAN hub with dynamic /// translation of the packets to/from GridConnect format. /// /// Sends a notification to the application level when there is an error on the /// device and the connection is closed. struct GcHubPort : public Executable { GcHubPort(CanHubFlow *can_hub, int fd, Notifiable *on_exit) : gcHub_(can_hub->service()) , bridge_( GCAdapterBase::CreateGridConnectAdapter(&gcHub_, can_hub, false)) , gcWrite_(&gcHub_, fd, this) , onExit_(on_exit) { LOG(VERBOSE, "gchub port %p", (Executable *)this); } virtual ~GcHubPort() { } /** This hub sees the character-based representation of the packets. The * members of it are: the bridge and the physical device (fd). * * Destruction requirement: HubFlow should be empty. This means after the * disconnection of the bridge (write side) and the FdHubport (read side) * we need to wait for the executor until this flow drains. */ HubFlow gcHub_; /** Translates packets between the can-hub of the device and the char-hub * of this port. * * Destruction requirement: Call shutdown() on the can-side executor (and * yield) until it returns true. */ std::unique_ptr<GCAdapterBase> bridge_; /** Reads the characters from the char-hub and sends them to the * fd. Similarly, listens to the fd and sends the read charcters to the * char-hub. */ FdHubPort<HubFlow> gcWrite_; /** If not null, this notifiable will be called when the device is * closed. */ Notifiable* onExit_; /** Callback in case the connection is closed due to error. */ void notify() OVERRIDE { /* We would like to delete *this but we cannot do that in this * callback, because we don't know what executor we are running * on. Deleting on the write executor would cause a deadlock for * example. */ gcHub_.service()->executor()->add(this); } void run() OVERRIDE { if (!bridge_->shutdown() || !gcHub_.is_waiting()) { // Yield. gcHub_.service()->executor()->add(this); return; } LOG(INFO, "GCHubPort: Shutting down gridconnect port %d. (%p)", gcWrite_.fd(), bridge_.get()); if (onExit_) { onExit_->notify(); onExit_ = nullptr; } /* We get this call when something is wrong with the FDs and we need to * close the connection. It is guaranteed that by the time we got this * call the device is unregistered from the char bridge, and the * service thread is ready to be stopped. */ delete this; } }; void create_gc_port_for_can_hub(CanHubFlow *can_hub, int fd, Notifiable* on_exit) { new GcHubPort(can_hub, fd, on_exit); } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2007 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 * *****************************************************************************/ #include <mapnik/libxml2_loader.hpp> #include <mapnik/config_error.hpp> #include <boost/utility.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/filesystem/operations.hpp> #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/parserInternals.h> #include <iostream> using boost::property_tree::ptree; using namespace std; #define DEFAULT_OPTIONS (XML_PARSE_NOERROR | XML_PARSE_NOENT | XML_PARSE_NOBLANKS | XML_PARSE_DTDLOAD) namespace mapnik { class libxml2_loader : boost::noncopyable { public: libxml2_loader(const char *encoding = NULL, int options = DEFAULT_OPTIONS, const char *url = NULL) : ctx_( 0 ), encoding_( encoding ), options_( options ), url_( url ) { LIBXML_TEST_VERSION; ctx_ = xmlNewParserCtxt(); if ( ! ctx_ ) { throw std::runtime_error("Failed to create parser context."); } } ~libxml2_loader() { if (ctx_) { xmlFreeParserCtxt(ctx_); } } void load( const std::string & filename, ptree & pt ) { boost::filesystem::path path(filename); if ( ! boost::filesystem::exists( path ) ) { throw config_error(string("Could not load map file '") + filename + "': File does not exist"); } xmlDocPtr doc = xmlCtxtReadFile(ctx_, filename.c_str(), encoding_, options_); if ( !doc ) { xmlError * error = xmlCtxtGetLastError( ctx_ ); std::ostringstream os; os << "XML document not well formed"; if (error) { os << ": " << std::endl << error->message; // remove CR std::string msg = os.str().substr(0, os.str().size() - 1); config_error ex( msg ); os.str(""); os << "in file '" << error->file << "' at line " << error->line; ex.append_context( os.str() ); throw ex; } } /* if ( ! ctx->valid ) { std::clog << "### ERROR: Failed to validate DTD." << std::endl; } */ load(doc, pt); } void load( const int fd, ptree & pt ) { xmlDocPtr doc = xmlCtxtReadFd(ctx_, fd, url_, encoding_, options_); load(doc, pt); } void load_string( const std::string & buffer, ptree & pt ) { xmlDocPtr doc = xmlCtxtReadMemory(ctx_, buffer.data(), buffer.length(), url_, encoding_, options_); load(doc, pt); } void load( const xmlDocPtr doc, ptree & pt ) { if ( !doc ) { xmlError * error = xmlCtxtGetLastError( ctx_ ); std::ostringstream os; os << "XML document not well formed"; if (error) { os << ": " << std::endl << error->message; } throw config_error(os.str()); } xmlNode * root = xmlDocGetRootElement( doc ); if ( ! root ) { throw config_error("XML document is empty."); } populate_tree( root, pt ); } private: void append_attributes( xmlAttr * attributes, ptree & pt) { if (attributes) { ptree::iterator it = pt.push_back( ptree::value_type( "<xmlattr>", ptree() )); ptree & attr_list = it->second; xmlAttr * cur_attr = attributes; for (; cur_attr; cur_attr = cur_attr->next ) { ptree::iterator it = attr_list.push_back( ptree::value_type( (char*)cur_attr->name, ptree() )); it->second.put_own( (char*) cur_attr->children->content ); } } } void populate_tree( xmlNode * node, ptree & pt ) { xmlNode * cur_node = node; for (; cur_node; cur_node = cur_node->next ) { switch (cur_node->type) { case XML_ELEMENT_NODE: { ptree::iterator it = pt.push_back( ptree::value_type( (char*)cur_node->name, ptree() )); append_attributes( cur_node->properties, it->second); populate_tree( cur_node->children, it->second ); } break; case XML_TEXT_NODE: pt.put_own( (char*) cur_node->content ); break; case XML_COMMENT_NODE: { ptree::iterator it = pt.push_back( ptree::value_type( "<xmlcomment>", ptree() )); it->second.put_own( (char*) cur_node->content ); } break; default: break; } } } xmlParserCtxtPtr ctx_; const char *encoding_; int options_; const char *url_; }; void read_xml2( std::string const & filename, boost::property_tree::ptree & pt) { libxml2_loader loader; loader.load( filename, pt ); } void read_xml2_string( std::string const & str, boost::property_tree::ptree & pt) { libxml2_loader loader; loader.load_string( str, pt ); } } // end of namespace mapnik <commit_msg>improve formatting of error message during xml loading if document is not well formed<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2007 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 * *****************************************************************************/ #include <mapnik/libxml2_loader.hpp> #include <mapnik/config_error.hpp> #include <boost/utility.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/filesystem/operations.hpp> #include <libxml/parser.h> #include <libxml/tree.h> #include <libxml/parserInternals.h> #include <iostream> using boost::property_tree::ptree; using namespace std; #define DEFAULT_OPTIONS (XML_PARSE_NOERROR | XML_PARSE_NOENT | XML_PARSE_NOBLANKS | XML_PARSE_DTDLOAD) namespace mapnik { class libxml2_loader : boost::noncopyable { public: libxml2_loader(const char *encoding = NULL, int options = DEFAULT_OPTIONS, const char *url = NULL) : ctx_( 0 ), encoding_( encoding ), options_( options ), url_( url ) { LIBXML_TEST_VERSION; ctx_ = xmlNewParserCtxt(); if ( ! ctx_ ) { throw std::runtime_error("Failed to create parser context."); } } ~libxml2_loader() { if (ctx_) { xmlFreeParserCtxt(ctx_); } } void load( const std::string & filename, ptree & pt ) { boost::filesystem::path path(filename); if ( ! boost::filesystem::exists( path ) ) { throw config_error(string("Could not load map file '") + filename + "': File does not exist"); } xmlDocPtr doc = xmlCtxtReadFile(ctx_, filename.c_str(), encoding_, options_); if ( !doc ) { xmlError * error = xmlCtxtGetLastError( ctx_ ); std::ostringstream os; os << "XML document not well formed"; if (error) { os << ": " << std::endl << error->message; // remove CR std::string msg = os.str().substr(0, os.str().size() - 1); config_error ex( msg ); os.str(""); os << "(encountered in file '" << error->file << "' at line " << error->line << ")"; ex.append_context( os.str() ); throw ex; } } /* if ( ! ctx->valid ) { std::clog << "### ERROR: Failed to validate DTD." << std::endl; } */ load(doc, pt); } void load( const int fd, ptree & pt ) { xmlDocPtr doc = xmlCtxtReadFd(ctx_, fd, url_, encoding_, options_); load(doc, pt); } void load_string( const std::string & buffer, ptree & pt ) { xmlDocPtr doc = xmlCtxtReadMemory(ctx_, buffer.data(), buffer.length(), url_, encoding_, options_); load(doc, pt); } void load( const xmlDocPtr doc, ptree & pt ) { if ( !doc ) { xmlError * error = xmlCtxtGetLastError( ctx_ ); std::ostringstream os; os << "XML document not well formed"; if (error) { os << ": " << std::endl << error->message; } throw config_error(os.str()); } xmlNode * root = xmlDocGetRootElement( doc ); if ( ! root ) { throw config_error("XML document is empty."); } populate_tree( root, pt ); } private: void append_attributes( xmlAttr * attributes, ptree & pt) { if (attributes) { ptree::iterator it = pt.push_back( ptree::value_type( "<xmlattr>", ptree() )); ptree & attr_list = it->second; xmlAttr * cur_attr = attributes; for (; cur_attr; cur_attr = cur_attr->next ) { ptree::iterator it = attr_list.push_back( ptree::value_type( (char*)cur_attr->name, ptree() )); it->second.put_own( (char*) cur_attr->children->content ); } } } void populate_tree( xmlNode * node, ptree & pt ) { xmlNode * cur_node = node; for (; cur_node; cur_node = cur_node->next ) { switch (cur_node->type) { case XML_ELEMENT_NODE: { ptree::iterator it = pt.push_back( ptree::value_type( (char*)cur_node->name, ptree() )); append_attributes( cur_node->properties, it->second); populate_tree( cur_node->children, it->second ); } break; case XML_TEXT_NODE: pt.put_own( (char*) cur_node->content ); break; case XML_COMMENT_NODE: { ptree::iterator it = pt.push_back( ptree::value_type( "<xmlcomment>", ptree() )); it->second.put_own( (char*) cur_node->content ); } break; default: break; } } } xmlParserCtxtPtr ctx_; const char *encoding_; int options_; const char *url_; }; void read_xml2( std::string const & filename, boost::property_tree::ptree & pt) { libxml2_loader loader; loader.load( filename, pt ); } void read_xml2_string( std::string const & str, boost::property_tree::ptree & pt) { libxml2_loader loader; loader.load_string( str, pt ); } } // end of namespace mapnik <|endoftext|>
<commit_before>// Copyright 2016 Chirstopher Torres (Raven), L3nn0x // // 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 <cxxopts.hpp> #include "cloginserver.h" #include "config.h" #include "logconsole.h" #include "version.h" namespace { void DisplayTitle() { auto console = Core::CLog::GetLogger(Core::log_type::GENERAL); if(auto log = console.lock()) { log->notice( "--------------------------------" ); log->notice( " osIROSE 2 Alpha " ); log->notice( " http://forum.dev-osrose.com/ " ); log->notice( "--------------------------------" ); log->notice( "Git Branch/Revision: {}/{}", GIT_BRANCH, GIT_COMMIT_HASH ); } } void CheckUser() { #ifndef _WIN32 auto console = Core::CLog::GetLogger(Core::log_type::GENERAL); if(auto log = console.lock()) { if ((getuid() == 0) && (getgid() == 0)) { log->warn( "You are running as the root superuser." ); log->warn( "It is unnecessary and unsafe to run with root privileges." ); } std::this_thread::sleep_for(std::chrono::milliseconds(2000)); } #endif } } int main(int argc, char* argv[]) { cxxopts::Options options("LoginServer", "OsIROSE Login Server"); options.add_options() ("d,debug", "Enable extra debugging info") ("f,file", "Config file path", cxxopts::value<std::string>(), "server.ini") ("l,level", "Logging level", cxxopts::value<int>()) ("h,help", "Print this help text") ; try { options.parse(argc, argv); if (options.count("help")) { std::cout << options.help({"", "Group"}) << std::endl; exit(0); } auto console = Core::CLog::GetLogger(Core::log_type::GENERAL); if(auto log = console.lock()) log->notice( "Starting up server..." ); Core::Config& config = Core::Config::getInstance(); if( options.count("level") != 0 ) Core::CLog::SetLevel((spdlog::level::level_enum)options["level"].as<int>()); else Core::CLog::SetLevel((spdlog::level::level_enum)config.login_server().log_level()); DisplayTitle(); CheckUser(); if(auto log = console.lock()) { if( options.count("level") != 0 ) log->set_level((spdlog::level::level_enum)options["level"].as<int>()); else log->set_level((spdlog::level::level_enum)config.login_server().log_level()); log->trace("Trace logs are enabled."); log->debug("Debug logs are enabled."); log->info("Info logs are enabled."); } Core::NetworkThreadPool::GetInstance(config.serverdata().maxthreads()); CLoginServer clientServer; CLoginServer iscServer(true); clientServer.Init(config.serverdata().ip(), config.login_server().clientport()); clientServer.Listen(); iscServer.Init(config.serverdata().ip(), config.login_server().iscport()); iscServer.Listen(); while (clientServer.IsActive()) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } if(auto log = console.lock()) log->notice( "Server shutting down..." ); Core::NetworkThreadPool::DeleteInstance(); spdlog::drop_all(); } catch (const cxxopts::option_not_exists_exception& ex) { std::cout << options.help({"", "Group"}) << std::endl; return 1; } catch (const spdlog::spdlog_ex& ex) { std::cout << "Log failed: " << ex.what() << std::endl; } return 0; } <commit_msg>Moved command line options into its own function. Added new command line options to override the config file<commit_after>// Copyright 2016 Chirstopher Torres (Raven), L3nn0x // // 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 <cxxopts.hpp> #include "cloginserver.h" #include "config.h" #include "logconsole.h" #include "version.h" namespace { void DisplayTitle() { auto console = Core::CLog::GetLogger(Core::log_type::GENERAL); if(auto log = console.lock()) { log->notice( "--------------------------------" ); log->notice( " osIROSE 2 Alpha " ); log->notice( " http://forum.dev-osrose.com/ " ); log->notice( "--------------------------------" ); log->notice( "Git Branch/Revision: {}/{}", GIT_BRANCH, GIT_COMMIT_HASH ); } } void CheckUser() { #ifndef _WIN32 auto console = Core::CLog::GetLogger(Core::log_type::GENERAL); if(auto log = console.lock()) { if ((getuid() == 0) && (getgid() == 0)) { log->warn( "You are running as the root superuser." ); log->warn( "It is unnecessary and unsafe to run with root privileges." ); } std::this_thread::sleep_for(std::chrono::milliseconds(2000)); } #endif } void ParseCommandLine(int argc, char** argv) { cxxopts::Options options(argv[0], "osIROSE login server"); try { std::string config_file_path = ""; options.add_options() ("f,file", "Config file path", cxxopts::value<std::string>(config_file_path) ->default_value("server.ini"), "FILE_PATH") ("l,level", "Logging level (0-9)", cxxopts::value<int>() ->default_value("3"), "LEVEL") ("ip", "Client listen IP Address", cxxopts::value<std::string>() ->default_value("0.0.0.0"), "IP") ("port", "Client listen port", cxxopts::value<int>() ->default_value("29000"), "PORT") ("iscip", "ISC listen IP Address", cxxopts::value<std::string>() ->default_value("127.0.0.1"), "IP") ("iscport", "ISC listen port", cxxopts::value<int>() ->default_value("29010"), "PORT") ("t,maxthreads", "Max thread count", cxxopts::value<int>() ->default_value("512"), "COUNT") ("h,help", "Print this help text") ; options.parse(argc, argv); // Check to see if the user wants to see the help text if (options.count("help")) { std::cout << options.help({"", "Group"}) << std::endl; exit(0); } Core::Config& config = Core::Config::getInstance(config_file_path); // We are using if checks here because we only want to override the config file if the option was supplied // Since this is a login server startup function we can get away with a little bit of overhead if( options.count("level") ) config.mutable_login_server()->set_log_level( options["level"].as<int>() ); if( options.count("ip") ) config.mutable_serverdata()->set_ip( options["ip"].as<std::string>() ); if( options.count("maxthreads") ) config.mutable_serverdata()->set_maxthreads( options["maxthreads"].as<int>() ); } catch (const cxxopts::OptionException& ex) { std::cout << ex.what() << std::endl; std::cout << options.help({"", "Group"}) << std::endl; exit(1); } } } int main(int argc, char* argv[]) { try { ParseCommandLine(argc, argv); auto console = Core::CLog::GetLogger(Core::log_type::GENERAL); if(auto log = console.lock()) log->notice( "Starting up server..." ); Core::Config& config = Core::Config::getInstance(); Core::CLog::SetLevel((spdlog::level::level_enum)config.login_server().log_level()); DisplayTitle(); CheckUser(); if(auto log = console.lock()) { log->set_level((spdlog::level::level_enum)config.login_server().log_level()); log->trace("Trace logs are enabled."); log->debug("Debug logs are enabled."); log->info("Info logs are enabled."); } Core::NetworkThreadPool::GetInstance(config.serverdata().maxthreads()); CLoginServer clientServer; CLoginServer iscServer(true); clientServer.Init(config.serverdata().ip(), config.login_server().clientport()); clientServer.Listen(); iscServer.Init(config.serverdata().ip(), config.login_server().iscport()); iscServer.Listen(); while (clientServer.IsActive()) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } if(auto log = console.lock()) log->notice( "Server shutting down..." ); Core::NetworkThreadPool::DeleteInstance(); spdlog::drop_all(); } catch (const spdlog::spdlog_ex& ex) { std::cout << "Log failed: " << ex.what() << std::endl; } return 0; } <|endoftext|>
<commit_before>// SCOUT Navigation and Logic #include <Adafruit_GPS.h> #include <SoftwareSerial.h> // Pass data to USB serial via digital 3,2 SoftwareSerial mySerial(3, 2); // Assign names to analog 0-3 for relay int POS1 = A0; int NEG1 = A1; int POS2 = A2; int NEG2 = A3; int delayValue = 5000; Adafruit_GPS GPS(&mySerial); // Set GPSECHO to 'false' to turn off echoing the GPS data to the Serial console // Set to 'true' if you want to debug and listen to the raw GPS sentences. #define GPSECHO true // this keeps track of whether we're using the interrupt // off by default! boolean usingInterrupt = false; void useInterrupt(boolean); // Func prototype keeps Arduino 0023 happy void setup() { // connect at 115200 baud to read GPS quickly // also spit it out Serial.begin(115200); Serial.println("GPS Initializing"); // Initialize analog pins pinMode(POS1, OUTPUT); pinMode(NEG1, OUTPUT); pinMode(POS2, OUTPUT); pinMode(NEG2, OUTPUT); // With this relay, HIGH is OFF digitalWrite(POS1, HIGH); digitalWrite(NEG1, HIGH); digitalWrite(POS2, HIGH); digitalWrite(NEG2, HIGH); Serial.println("Initialized With High."); Serial.println("Turning Clockwise"); digitalWrite(POS1, LOW); digitalWrite(NEG1, HIGH); digitalWrite(POS2, HIGH); digitalWrite(NEG2, LOW); delay(delayValue); Serial.println("Turning OFF"); digitalWrite(POS1, HIGH); digitalWrite(NEG1, HIGH); digitalWrite(POS2, HIGH); digitalWrite(NEG2, HIGH); delay(delayValue); Serial.println("Turning Counter Clockwise"); digitalWrite(POS1, HIGH); digitalWrite(NEG1, LOW); digitalWrite(POS2, LOW); digitalWrite(NEG2, HIGH); delay(delayValue); Serial.println("Turning OFF"); digitalWrite(POS1, HIGH); digitalWrite(NEG1, HIGH); digitalWrite(POS2, HIGH); digitalWrite(NEG2, HIGH); delay(delayValue); // 9600 NMEA is the default baud rate for Adafruit MTK GPS's- some use 4800 GPS.begin(9600); // uncomment this line to turn on RMC (recommended minimum) and GGA (fix data) including altitude GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA); // Set the update rate GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ); // 1 Hz update rate // Request updates on antenna status, comment out to keep quiet GPS.sendCommand(PGCMD_ANTENNA); // 1 ms interrupt useInterrupt(true); delay(1000); // Ask for firmware version //mySerial.println(PMTK_Q_RELEASE); } // Interrupt is called once a millisecond, looks for any new GPS data, and stores it SIGNAL(TIMER0_COMPA_vect) { char c = GPS.read(); // if you want to debug, this is a good time to do it! #ifdef UDR0 if (GPSECHO) if (c) UDR0 = c; // writing direct to UDR0 is much much faster than Serial.print // but only one character can be written at a time. #endif } void useInterrupt(boolean v) { if (v) { // Timer0 is already used for millis() - we'll just interrupt somewhere // in the middle and call the "Compare A" function above OCR0A = 0xAF; TIMSK0 |= _BV(OCIE0A); usingInterrupt = true; } else { // do not call the interrupt function COMPA anymore TIMSK0 &= ~_BV(OCIE0A); usingInterrupt = false; } } uint32_t timer = millis(); void loop() // run over and over again { // in case you are not using the interrupt above, you'll if (! usingInterrupt) { // read data from the GPS in the 'main loop' char c = GPS.read(); // if you want to debug, this is a good time to do it! } // if a sentence is received, we can check the checksum, parse it... if (GPS.newNMEAreceived()) { // a tricky thing here is if we print the NMEA sentence, or data // we end up not listening and catching other sentences! // so be very wary if using OUTPUT_ALLDATA and trytng to print out data //Serial.println(GPS.lastNMEA()); // this also sets the newNMEAreceived() flag to false if (!GPS.parse(GPS.lastNMEA())) // this also sets the newNMEAreceived() flag to false return; // we can fail to parse a sentence in which case we should just wait for another } // if millis() or timer wraps around, we'll just reset it if (timer > millis()) timer = millis(); // approximately every 2 seconds or so, print out the current stats if (millis() - timer > 2000) { timer = millis(); // reset the timer Serial.print("Fix: "); Serial.print((int)GPS.fix); Serial.print(" quality: "); Serial.println((int)GPS.fixquality); if (GPS.fix) { Serial.print("Location: "); Serial.print(GPS.latitude, 4); Serial.print(GPS.lat); Serial.print(", "); Serial.print(GPS.longitude, 4); Serial.println(GPS.lon); Serial.print("Speed (knots): "); Serial.println(GPS.speed); Serial.print("Angle: "); Serial.println(GPS.angle); Serial.print("Altitude: "); Serial.println(GPS.altitude); Serial.print("Satellites: "); Serial.println((int)GPS.satellites); } } }<commit_msg>Clean up instrument code<commit_after>// SCOUT Navigation and Logic #include <Adafruit_GPS.h> #include <SoftwareSerial.h> // Pass data to USB serial via digital 3,2 SoftwareSerial mySerial(3, 2); // Assign names to analog 0-3 for relay int POS1 = A0; int NEG1 = A1; int POS2 = A2; int NEG2 = A3; int delayValue = 5000; Adafruit_GPS GPS(&mySerial); // Set GPSECHO to 'false' to turn off echoing the GPS data to the Serial console // Set to 'true' if you want to debug and listen to the raw GPS sentences. #define GPSECHO true // this keeps track of whether we're using the interrupt // off by default! boolean usingInterrupt = false; void useInterrupt(boolean); // Func prototype keeps Arduino 0023 happy void setup() { // connect at 115200 baud to read GPS quickly // also spit it out Serial.begin(115200); Serial.println("GPS Initializing"); // Initialize analog pins pinMode(POS1, OUTPUT); pinMode(NEG1, OUTPUT); pinMode(POS2, OUTPUT); pinMode(NEG2, OUTPUT); // With this relay, HIGH is OFF digitalWrite(POS1, HIGH); digitalWrite(NEG1, HIGH); digitalWrite(POS2, HIGH); digitalWrite(NEG2, HIGH); Serial.println("Initialized With High."); Serial.println("Turning Clockwise"); digitalWrite(POS1, LOW); digitalWrite(NEG1, HIGH); digitalWrite(POS2, HIGH); digitalWrite(NEG2, LOW); delay(delayValue); Serial.println("Turning OFF"); digitalWrite(POS1, HIGH); digitalWrite(NEG1, HIGH); digitalWrite(POS2, HIGH); digitalWrite(NEG2, HIGH); delay(delayValue); Serial.println("Turning Counter Clockwise"); digitalWrite(POS1, HIGH); digitalWrite(NEG1, LOW); digitalWrite(POS2, LOW); digitalWrite(NEG2, HIGH); delay(delayValue); Serial.println("Turning OFF"); digitalWrite(POS1, HIGH); digitalWrite(NEG1, HIGH); digitalWrite(POS2, HIGH); digitalWrite(NEG2, HIGH); delay(delayValue); // 9600 NMEA is the default baud rate for Adafruit MTK GPS's- some use 4800 GPS.begin(9600); // uncomment this line to turn on RMC (recommended minimum) and GGA (fix data) including altitude GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA); // Set the update rate GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ); // 1 Hz update rate // Request updates on antenna status, comment out to keep quiet GPS.sendCommand(PGCMD_ANTENNA); // 1 ms interrupt useInterrupt(true); delay(1000); // Ask for firmware version //mySerial.println(PMTK_Q_RELEASE); } // Interrupt is called once a millisecond, looks for any new GPS data, and stores it SIGNAL(TIMER0_COMPA_vect) { char c = GPS.read(); // if you want to debug, this is a good time to do it! #ifdef UDR0 if (GPSECHO) if (c) UDR0 = c; // writing direct to UDR0 #endif } void useInterrupt(boolean v) { if (v) { // Timer0 is already used for millis() - we'll just interrupt somewhere // in the middle and call the "Compare A" function above OCR0A = 0xAF; TIMSK0 |= _BV(OCIE0A); usingInterrupt = true; } else { // do not call the interrupt function COMPA anymore TIMSK0 &= ~_BV(OCIE0A); usingInterrupt = false; } } uint32_t timer = millis(); void loop() { if (! usingInterrupt) { // read data from the GPS in the 'main loop' char c = GPS.read(); } // Determine if new statement received, if so, check the checksum, parse if (GPS.newNMEAreceived()) { if (!GPS.parse(GPS.lastNMEA())) // this sets the newNMEAreceived() flag to false return; // if miss statement, wait for } // if millis() or timer wraps around, reset it if (timer > millis()) timer = millis(); // Every 2 seconds, print out the current stats if (millis() - timer > 2000) { timer = millis(); // reset the timer Serial.print("Fix: "); Serial.print((int)GPS.fix); Serial.print(" quality: "); Serial.println((int)GPS.fixquality); if (GPS.fix) { Serial.print("Location: "); Serial.print(GPS.latitude, 4); Serial.print(GPS.lat); Serial.print(", "); Serial.print(GPS.longitude, 4); Serial.println(GPS.lon); Serial.print("Speed (knots): "); Serial.println(GPS.speed); Serial.print("Angle: "); Serial.println(GPS.angle); Serial.print("Altitude: "); Serial.println(GPS.altitude); Serial.print("Satellites: "); Serial.println((int)GPS.satellites); } } }<|endoftext|>
<commit_before>// // MessagePack for C++ static resolution routine // // Copyright (C) 2008-2009 FURUHASHI Sadayuki // // 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 MSGPACK_TYPE_INT_HPP #define MSGPACK_TYPE_INT_HPP #include "msgpack/object.hpp" #include <limits> namespace msgpack { namespace type { namespace detail { template <typename T, bool Signed> struct convert_integer_sign; template <typename T> struct convert_integer_sign<T, true> { static inline T convert(object const& o) { if(o.type == type::POSITIVE_INTEGER) { if(o.via.u64 > (uint64_t)std::numeric_limits<T>::max()) { throw type_error(); } return (T)o.via.u64; } else if(o.type == type::NEGATIVE_INTEGER) { if(o.via.i64 < (int64_t)std::numeric_limits<T>::min()) { throw type_error(); } return (T)o.via.i64; } throw type_error(); } }; template <typename T> struct convert_integer_sign<T, false> { static inline T convert(object const& o) { if(o.type == type::POSITIVE_INTEGER) { if(o.via.u64 > (uint64_t)std::numeric_limits<T>::max()) { throw type_error(); } return (T)o.via.u64; } throw type_error(); } }; template <typename T> struct is_signed { static const bool value = std::numeric_limits<T>::is_signed; }; template <typename T> static inline T convert_integer(object o) { return detail::convert_integer_sign<T, is_signed<T>::value>::convert(o); } template <bool Signed> struct pack_char_sign; template <> struct pack_char_sign<true> { template <typename Stream> static inline packer<Stream>& pack(packer<Stream>& o, char v) { o.pack_int8(v); return o; } }; template <> struct pack_char_sign<false> { template <typename Stream> static inline packer<Stream>& pack(packer<Stream>& o, char v) { o.pack_uint8(v); return o; } }; template <typename Stream> static inline packer<Stream>& pack_char(packer<Stream>& o, char v) { return pack_char_sign<is_signed<char>::value>::pack(o, v); } template <bool Signed> struct object_char_sign; template <> struct object_char_sign<true> { static inline void make(object& o, char v) { v < 0 ? o.type = type::NEGATIVE_INTEGER, o.via.i64 = v : o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } }; template <> struct object_char_sign<false> { static inline void make(object& o, char v) { o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } }; static inline void object_char(object& o, char v) { return object_char_sign<is_signed<char>::value>::make(o, v); } } // namespace detail } // namespace type inline char& operator>> (object const& o, char& v) { v = type::detail::convert_integer<char>(o); return v; } inline signed char& operator>> (object const& o, signed char& v) { v = type::detail::convert_integer<signed char>(o); return v; } inline signed short& operator>> (object const& o, signed short& v) { v = type::detail::convert_integer<signed short>(o); return v; } inline signed int& operator>> (object const& o, signed int& v) { v = type::detail::convert_integer<signed int>(o); return v; } inline signed long& operator>> (object const& o, signed long& v) { v = type::detail::convert_integer<signed long>(o); return v; } inline signed long long& operator>> (object const& o, signed long long& v) { v = type::detail::convert_integer<signed long long>(o); return v; } inline unsigned char& operator>> (object const& o, unsigned char& v) { v = type::detail::convert_integer<unsigned char>(o); return v; } inline unsigned short& operator>> (object const& o, unsigned short& v) { v = type::detail::convert_integer<unsigned short>(o); return v; } inline unsigned int& operator>> (object const& o, unsigned int& v) { v = type::detail::convert_integer<unsigned int>(o); return v; } inline unsigned long& operator>> (object const& o, unsigned long& v) { v = type::detail::convert_integer<unsigned long>(o); return v; } inline unsigned long long& operator>> (object const& o, unsigned long long& v) { v = type::detail::convert_integer<unsigned long long>(o); return v; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, char v) { return type::detail::pack_char(o, v); } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, signed char v) { o.pack_int8(v); return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, signed short v) { o.pack_short(v); return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, signed int v) { o.pack_int(v); return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, signed long v) { o.pack_long(v); return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, signed long long v) { o.pack_long_long(v); return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, unsigned char v) { o.pack_uint8(v); return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, unsigned short v) { o.pack_unsigned_short(v); return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, unsigned int v) { o.pack_unsigned_int(v); return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, unsigned long v) { o.pack_unsigned_long(v); return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, unsigned long long v) { o.pack_unsigned_long_long(v); return o; } inline void operator<< (object& o, char v) { type::detail::object_char(o, v); } inline void operator<< (object& o, signed char v) { v < 0 ? o.type = type::NEGATIVE_INTEGER, o.via.i64 = v : o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object& o, signed short v) { v < 0 ? o.type = type::NEGATIVE_INTEGER, o.via.i64 = v : o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object& o, signed int v) { v < 0 ? o.type = type::NEGATIVE_INTEGER, o.via.i64 = v : o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object& o, signed long v) { v < 0 ? o.type = type::NEGATIVE_INTEGER, o.via.i64 = v : o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object& o, signed long long v) { v < 0 ? o.type = type::NEGATIVE_INTEGER, o.via.i64 = v : o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object& o, unsigned char v) { o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object& o, unsigned short v) { o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object& o, unsigned int v) { o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object& o, unsigned long v) { o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object& o, unsigned long long v) { o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object::with_zone& o, char v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, signed char v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, signed short v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, signed int v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, signed long v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, const signed long long& v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, unsigned char v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, unsigned short v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, unsigned int v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, unsigned long v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, const unsigned long long& v) { static_cast<object&>(o) << v; } } // namespace msgpack #endif /* msgpack/type/int.hpp */ <commit_msg>Supported 'plain' char. msgpack used to only support signed char and unsigned char.<commit_after>// // MessagePack for C++ static resolution routine // // Copyright (C) 2008-2009 FURUHASHI Sadayuki // // 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 MSGPACK_TYPE_INT_HPP #define MSGPACK_TYPE_INT_HPP #include "msgpack/object.hpp" #include <limits> namespace msgpack { namespace type { namespace detail { template <typename T, bool Signed> struct convert_integer_sign; template <typename T> struct convert_integer_sign<T, true> { static inline T convert(object const& o) { if(o.type == type::POSITIVE_INTEGER) { if(o.via.u64 > (uint64_t)std::numeric_limits<T>::max()) { throw type_error(); } return (T)o.via.u64; } else if(o.type == type::NEGATIVE_INTEGER) { if(o.via.i64 < (int64_t)std::numeric_limits<T>::min()) { throw type_error(); } return (T)o.via.i64; } throw type_error(); } }; template <typename T> struct convert_integer_sign<T, false> { static inline T convert(object const& o) { if(o.type == type::POSITIVE_INTEGER) { if(o.via.u64 > (uint64_t)std::numeric_limits<T>::max()) { throw type_error(); } return (T)o.via.u64; } throw type_error(); } }; template <typename T> struct is_signed { static const bool value = std::numeric_limits<T>::is_signed; }; template <typename T> static inline T convert_integer(object const& o) { return detail::convert_integer_sign<T, is_signed<T>::value>::convert(o); } template <bool Signed> struct pack_char_sign; template <> struct pack_char_sign<true> { template <typename Stream> static inline packer<Stream>& pack(packer<Stream>& o, char v) { o.pack_int8(v); return o; } }; template <> struct pack_char_sign<false> { template <typename Stream> static inline packer<Stream>& pack(packer<Stream>& o, char v) { o.pack_uint8(v); return o; } }; template <typename Stream> static inline packer<Stream>& pack_char(packer<Stream>& o, char v) { return pack_char_sign<is_signed<char>::value>::pack(o, v); } template <bool Signed> struct object_char_sign; template <> struct object_char_sign<true> { static inline void make(object& o, char v) { v < 0 ? o.type = type::NEGATIVE_INTEGER, o.via.i64 = v : o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } }; template <> struct object_char_sign<false> { static inline void make(object& o, char v) { o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } }; static inline void object_char(object& o, char v) { return object_char_sign<is_signed<char>::value>::make(o, v); } } // namespace detail } // namespace type inline char& operator>> (object const& o, char& v) { v = type::detail::convert_integer<char>(o); return v; } inline signed char& operator>> (object const& o, signed char& v) { v = type::detail::convert_integer<signed char>(o); return v; } inline signed short& operator>> (object const& o, signed short& v) { v = type::detail::convert_integer<signed short>(o); return v; } inline signed int& operator>> (object const& o, signed int& v) { v = type::detail::convert_integer<signed int>(o); return v; } inline signed long& operator>> (object const& o, signed long& v) { v = type::detail::convert_integer<signed long>(o); return v; } inline signed long long& operator>> (object const& o, signed long long& v) { v = type::detail::convert_integer<signed long long>(o); return v; } inline unsigned char& operator>> (object const& o, unsigned char& v) { v = type::detail::convert_integer<unsigned char>(o); return v; } inline unsigned short& operator>> (object const& o, unsigned short& v) { v = type::detail::convert_integer<unsigned short>(o); return v; } inline unsigned int& operator>> (object const& o, unsigned int& v) { v = type::detail::convert_integer<unsigned int>(o); return v; } inline unsigned long& operator>> (object const& o, unsigned long& v) { v = type::detail::convert_integer<unsigned long>(o); return v; } inline unsigned long long& operator>> (object const& o, unsigned long long& v) { v = type::detail::convert_integer<unsigned long long>(o); return v; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, char v) { return type::detail::pack_char(o, v); } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, signed char v) { o.pack_int8(v); return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, signed short v) { o.pack_short(v); return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, signed int v) { o.pack_int(v); return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, signed long v) { o.pack_long(v); return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, signed long long v) { o.pack_long_long(v); return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, unsigned char v) { o.pack_uint8(v); return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, unsigned short v) { o.pack_unsigned_short(v); return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, unsigned int v) { o.pack_unsigned_int(v); return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, unsigned long v) { o.pack_unsigned_long(v); return o; } template <typename Stream> inline packer<Stream>& operator<< (packer<Stream>& o, unsigned long long v) { o.pack_unsigned_long_long(v); return o; } inline void operator<< (object& o, char v) { type::detail::object_char(o, v); } inline void operator<< (object& o, signed char v) { v < 0 ? o.type = type::NEGATIVE_INTEGER, o.via.i64 = v : o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object& o, signed short v) { v < 0 ? o.type = type::NEGATIVE_INTEGER, o.via.i64 = v : o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object& o, signed int v) { v < 0 ? o.type = type::NEGATIVE_INTEGER, o.via.i64 = v : o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object& o, signed long v) { v < 0 ? o.type = type::NEGATIVE_INTEGER, o.via.i64 = v : o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object& o, signed long long v) { v < 0 ? o.type = type::NEGATIVE_INTEGER, o.via.i64 = v : o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object& o, unsigned char v) { o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object& o, unsigned short v) { o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object& o, unsigned int v) { o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object& o, unsigned long v) { o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object& o, unsigned long long v) { o.type = type::POSITIVE_INTEGER, o.via.u64 = v; } inline void operator<< (object::with_zone& o, char v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, signed char v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, signed short v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, signed int v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, signed long v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, const signed long long& v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, unsigned char v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, unsigned short v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, unsigned int v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, unsigned long v) { static_cast<object&>(o) << v; } inline void operator<< (object::with_zone& o, const unsigned long long& v) { static_cast<object&>(o) << v; } } // namespace msgpack #endif /* msgpack/type/int.hpp */ <|endoftext|>
<commit_before>#include "pd_host.h" #include <foundation/array.h> #include <foundation/string.h> /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct ServiceData { void* funcs; const char* identifer; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static ServiceData* s_serviceData; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Service_create() { array_clear(s_serviceData); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Service_destroy() { array_clear(s_serviceData); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Service_register(void* serviceFuncs, const char* ident) { ServiceData data = { serviceFuncs, ident }; int count = array_size(s_serviceData); for (int i = 0; i < count; ++i) { if (string_equal(s_serviceData[i].identifer, ident)) return; } array_push(s_serviceData, data); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void* Service_getService(const char* ident) { int count = array_size(s_serviceData); for (int i = 0; i < count; ++i) { if (string_equal(s_serviceData[i].identifer, ident)) return s_serviceData[i].funcs; } return 0; } <commit_msg>Print error if service can't be found.<commit_after>#include "pd_host.h" #include "log.h" #include <foundation/array.h> #include <foundation/string.h> /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct ServiceData { void* funcs; const char* identifer; }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static ServiceData* s_serviceData; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Service_create() { array_clear(s_serviceData); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Service_destroy() { array_clear(s_serviceData); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Service_register(void* serviceFuncs, const char* ident) { ServiceData data = { serviceFuncs, ident }; int count = array_size(s_serviceData); for (int i = 0; i < count; ++i) { if (string_equal(s_serviceData[i].identifer, ident)) return; } array_push(s_serviceData, data); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void* Service_getService(const char* ident) { int count = array_size(s_serviceData); for (int i = 0; i < count; ++i) { if (string_equal(s_serviceData[i].identifer, ident)) return s_serviceData[i].funcs; } pd_error("Unable to get service %s\n", ident); return 0; } <|endoftext|>
<commit_before>/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2014 Steven Lovegrove * * 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 <pangolin/video/drivers/thread.h> #ifdef DEBUGTHREAD #include <pangolin/utils/timer.h> #define TSTART() pangolin::basetime start,last,now; start = pangolin::TimeNow(); last = start; #define TGRABANDPRINT(...) now = pangolin::TimeNow(); fprintf(stderr,"THREAD: "); fprintf(stderr, __VA_ARGS__); fprintf(stderr, " %fms.\n",1000*pangolin::TimeDiff_s(last, now)); last = now; #define DBGPRINT(...) fprintf(stderr,"THREAD: "); fprintf(stderr, __VA_ARGS__); fprintf(stderr,"\n"); #else #define TSTART() #define TGRABANDPRINT(...) #define DBGPRINT(...) #endif namespace pangolin { ThreadVideo::ThreadVideo(VideoInterface* src, unsigned int num_buffers): quit_grab_thread(true), num_buffers(num_buffers) { if(!src) { throw VideoException("ThreadVideo: VideoInterface in must not be null"); } videoin.push_back(src); // queue init allocates buffers. queue.init(num_buffers, videoin[0]->SizeBytes()); Start(); } ThreadVideo::~ThreadVideo() { Stop(); delete videoin[0]; // queue destructor will take care of deallocating buffers. } //! Implement VideoInput::Start() void ThreadVideo::Start() { videoin[0]->Start(); quit_grab_thread = false; grab_thread = boostd::thread(boostd::ref(*this)); } //! Implement VideoInput::Stop() void ThreadVideo::Stop() { quit_grab_thread = true; if(grab_thread.joinable()) { grab_thread.join(); } videoin[0]->Stop(); } //! Implement VideoInput::SizeBytes() size_t ThreadVideo::SizeBytes() const { return videoin[0]->SizeBytes(); } //! Implement VideoInput::Streams() const std::vector<StreamInfo>& ThreadVideo::Streams() const { return videoin[0]->Streams(); } const json::value& ThreadVideo::DeviceProperties() const { VideoPropertiesInterface* in_prop = dynamic_cast<VideoPropertiesInterface*>(videoin[0]); if(!in_prop) throw std::runtime_error("ThreadVideo: video in interface does not implement VideoPropertiesInterface."); else return in_prop->FrameProperties(); } const json::value& ThreadVideo::FrameProperties() const { VideoPropertiesInterface* in_prop = dynamic_cast<VideoPropertiesInterface*>(videoin[0]); if(!in_prop) throw std::runtime_error("ThreadVideo: video in interface does not implement VideoPropertiesInterface."); else return in_prop->FrameProperties(); } unsigned int ThreadVideo::AvailableFrames() const { return queue.AvailableFrames(); } bool ThreadVideo::DropNFrames(uint32_t n) { return queue.DropNFrames(n); } //! Implement VideoInput::GrabNext() bool ThreadVideo::GrabNext( unsigned char* image, bool wait ) { if(queue.AvailableFrames() > 0) { // At least one valid frame in queue, return it. DBGPRINT("GrabNext at least one frame available."); unsigned char* i = queue.getNext(); std::memcpy(image, i, queue.BufferSizeBytes()); queue.returnUsedBuffer(i); return true; } else { if(wait) { // Must return a frame so block on notification from grab thread. std::unique_lock<std::mutex> lk(cvMtx); DBGPRINT("GrabNext no available frames wait for notification."); if(cv.wait_for(lk, boostd::chrono::seconds(5)) == boostd::cv_status::timeout) throw std::runtime_error("ThreadVideo: GrabNext blocking read for frames reached timeout."); DBGPRINT("GrabNext got notification."); unsigned char* i = queue.getNext(); std::memcpy(image, i, queue.BufferSizeBytes()); queue.returnUsedBuffer(i); return true; } else { DBGPRINT("GrabNext no available frames no wait."); // No frames available, no wait, simply return false. return false; } } } //! Implement VideoInput::GrabNewest() bool ThreadVideo::GrabNewest( unsigned char* image, bool wait ) { if(queue.AvailableFrames() > 0) { // At least one valid frame in queue, call grabNewest to drop old frame and return the newest. DBGPRINT("GrabNewest at least one frame available."); unsigned char* i = queue.getNewest(); std::memcpy(image, i, queue.BufferSizeBytes()); queue.returnUsedBuffer(i); return true; } else { if(wait) { // Must return a frame so block on notification from grab thread. DBGPRINT("GrabNewest no available frames wait for notification."); std::unique_lock<std::mutex> lk(cvMtx); if(cv.wait_for(lk, boostd::chrono::seconds(5)) == boostd::cv_status::timeout) throw std::runtime_error("ThreadVideo: GrabNewest blocking read for frames reached timeout."); DBGPRINT("GrabNewest got notification."); unsigned char* i = queue.getNext(); std::memcpy(image, i, queue.BufferSizeBytes()); queue.returnUsedBuffer(i); return true; } else { DBGPRINT("GrabNewest no available frames no wait."); // No frames available, no wait, simply return false. return false; } } } void ThreadVideo::operator()() { DBGPRINT("Grab thread Started.") // Spinning thread attempting to read from videoin[0] as fast as possible // relying on the videoin[0] blocking grab. while(!quit_grab_thread) { // Get a buffer from the queue; unsigned char* i = queue.getFreeBuffer(); // Blocking grab (i.e. GrabNext with wait = true). if(videoin[0]->GrabNext(i, true)){ queue.addValidBuffer(i); DBGPRINT("Grab thread got frame. valid:%d free:%d",queue.AvailableFrames(),queue.EmptyBuffers()) // Let listening threads know we got a frame in case they are waiting. cv.notify_all(); } else { // Grabbing frames failed, requeue the buffer. queue.returnUsedBuffer(i); } boostd::this_thread::yield(); } DBGPRINT("Grab thread Stopped.") return; } } #undef TSTART #undef TGRABANDPRINT #undef DBGPRINT <commit_msg>Add time printout to thread debug info.<commit_after>/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2014 Steven Lovegrove * * 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 <pangolin/video/drivers/thread.h> #ifdef DEBUGTHREAD #include <pangolin/utils/timer.h> #define TSTART() pangolin::basetime start,last,now; start = pangolin::TimeNow(); last = start; #define TGRABANDPRINT(...) now = pangolin::TimeNow(); fprintf(stderr,"THREAD: "); fprintf(stderr, __VA_ARGS__); fprintf(stderr, " %fms.\n",1000*pangolin::TimeDiff_s(last, now)); last = now; #define DBGPRINT(...) fprintf(stderr,"THREAD: "); fprintf(stderr, __VA_ARGS__); fprintf(stderr,"\n"); #else #define TSTART() #define TGRABANDPRINT(...) #define DBGPRINT(...) #endif namespace pangolin { ThreadVideo::ThreadVideo(VideoInterface* src, unsigned int num_buffers): quit_grab_thread(true), num_buffers(num_buffers) { if(!src) { throw VideoException("ThreadVideo: VideoInterface in must not be null"); } videoin.push_back(src); // queue init allocates buffers. queue.init(num_buffers, videoin[0]->SizeBytes()); Start(); } ThreadVideo::~ThreadVideo() { Stop(); delete videoin[0]; // queue destructor will take care of deallocating buffers. } //! Implement VideoInput::Start() void ThreadVideo::Start() { videoin[0]->Start(); quit_grab_thread = false; grab_thread = boostd::thread(boostd::ref(*this)); } //! Implement VideoInput::Stop() void ThreadVideo::Stop() { quit_grab_thread = true; if(grab_thread.joinable()) { grab_thread.join(); } videoin[0]->Stop(); } //! Implement VideoInput::SizeBytes() size_t ThreadVideo::SizeBytes() const { return videoin[0]->SizeBytes(); } //! Implement VideoInput::Streams() const std::vector<StreamInfo>& ThreadVideo::Streams() const { return videoin[0]->Streams(); } const json::value& ThreadVideo::DeviceProperties() const { VideoPropertiesInterface* in_prop = dynamic_cast<VideoPropertiesInterface*>(videoin[0]); if(!in_prop) throw std::runtime_error("ThreadVideo: video in interface does not implement VideoPropertiesInterface."); else return in_prop->FrameProperties(); } const json::value& ThreadVideo::FrameProperties() const { VideoPropertiesInterface* in_prop = dynamic_cast<VideoPropertiesInterface*>(videoin[0]); if(!in_prop) throw std::runtime_error("ThreadVideo: video in interface does not implement VideoPropertiesInterface."); else return in_prop->FrameProperties(); } unsigned int ThreadVideo::AvailableFrames() const { return queue.AvailableFrames(); } bool ThreadVideo::DropNFrames(uint32_t n) { return queue.DropNFrames(n); } //! Implement VideoInput::GrabNext() bool ThreadVideo::GrabNext( unsigned char* image, bool wait ) { TSTART() if(queue.AvailableFrames() > 0) { // At least one valid frame in queue, return it. DBGPRINT("GrabNext at least one frame available."); unsigned char* i = queue.getNext(); std::memcpy(image, i, queue.BufferSizeBytes()); queue.returnUsedBuffer(i); TGRABANDPRINT("GrabNext memcpy of available frame took") return true; } else { if(wait) { // Must return a frame so block on notification from grab thread. std::unique_lock<std::mutex> lk(cvMtx); DBGPRINT("GrabNext no available frames wait for notification."); if(cv.wait_for(lk, boostd::chrono::seconds(5)) == boostd::cv_status::timeout) throw std::runtime_error("ThreadVideo: GrabNext blocking read for frames reached timeout."); DBGPRINT("GrabNext got notification."); unsigned char* i = queue.getNext(); std::memcpy(image, i, queue.BufferSizeBytes()); queue.returnUsedBuffer(i); TGRABANDPRINT("GrabNext wait for lock and memcpy of available frame took") return true; } else { DBGPRINT("GrabNext no available frames no wait."); // No frames available, no wait, simply return false. return false; } } } //! Implement VideoInput::GrabNewest() bool ThreadVideo::GrabNewest( unsigned char* image, bool wait ) { TSTART() if(queue.AvailableFrames() > 0) { // At least one valid frame in queue, call grabNewest to drop old frame and return the newest. DBGPRINT("GrabNewest at least one frame available."); unsigned char* i = queue.getNewest(); std::memcpy(image, i, queue.BufferSizeBytes()); queue.returnUsedBuffer(i); TGRABANDPRINT("GrabNewest memcpy of available frame took") return true; } else { if(wait) { // Must return a frame so block on notification from grab thread. DBGPRINT("GrabNewest no available frames wait for notification."); std::unique_lock<std::mutex> lk(cvMtx); if(cv.wait_for(lk, boostd::chrono::seconds(5)) == boostd::cv_status::timeout) throw std::runtime_error("ThreadVideo: GrabNewest blocking read for frames reached timeout."); DBGPRINT("GrabNewest got notification."); unsigned char* i = queue.getNext(); std::memcpy(image, i, queue.BufferSizeBytes()); queue.returnUsedBuffer(i); TGRABANDPRINT("GrabNwest wait for lock and memcpy of available frame took") return true; } else { DBGPRINT("GrabNewest no available frames no wait."); // No frames available, no wait, simply return false. return false; } } } void ThreadVideo::operator()() { DBGPRINT("Grab thread Started.") // Spinning thread attempting to read from videoin[0] as fast as possible // relying on the videoin[0] blocking grab. while(!quit_grab_thread) { // Get a buffer from the queue; unsigned char* i = queue.getFreeBuffer(); // Blocking grab (i.e. GrabNext with wait = true). if(videoin[0]->GrabNext(i, true)){ queue.addValidBuffer(i); DBGPRINT("Grab thread got frame. valid:%d free:%d",queue.AvailableFrames(),queue.EmptyBuffers()) // Let listening threads know we got a frame in case they are waiting. cv.notify_all(); } else { // Grabbing frames failed, requeue the buffer. queue.returnUsedBuffer(i); } boostd::this_thread::yield(); } DBGPRINT("Grab thread Stopped.") return; } } #undef TSTART #undef TGRABANDPRINT #undef DBGPRINT <|endoftext|>
<commit_before>/* Copyright © 2010, 2011, 2012 Vladimír Vondruš <[email protected]> This file is part of Magnum. Magnum 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. Magnum 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. */ #include <iostream> #include <chrono> #include <memory> #include <unordered_map> #include "PluginManager/PluginManager.h" #include "Scene.h" #include "Camera.h" #include "Trade/AbstractImporter.h" #include "Trade/MeshData.h" #include "Trade/MeshObjectData.h" #include "Trade/SceneData.h" #include "MeshTools/Tipsify.h" #include "MeshTools/Interleave.h" #include "MeshTools/CompressIndices.h" #include "Shaders/PhongShader.h" #include "AbstractExample.h" #include "ViewedObject.h" #include "configure.h" using namespace std; using namespace Corrade::PluginManager; using namespace Corrade::Utility; using namespace Magnum; using namespace Magnum::Shaders; using namespace Magnum::Trade; using namespace Magnum::Examples; namespace Magnum { namespace Examples { class ViewerExample: public AbstractExample { public: ViewerExample(int& argc, char** argv); ~ViewerExample() { for(auto i: meshes) delete i.second; } protected: inline void viewportEvent(const Math::Vector2<GLsizei>& size) { camera->setViewport(size); } void drawEvent() { if(fps) { chrono::high_resolution_clock::time_point now = chrono::high_resolution_clock::now(); double duration = chrono::duration<double>(now-before).count(); if(duration > 3.5) { cout << frames << " frames in " << duration << " sec: " << frames/duration << " FPS \r"; cout.flush(); totalfps += frames/duration; before = now; frames = 0; ++totalmeasurecount; } } camera->draw(); swapBuffers(); if(fps) { ++frames; redraw(); } } void keyEvent(Key key, const Math::Vector2<int>& position) { switch(key) { case Key::Up: o->rotate(deg(10.0f), Vector3::xAxis(-1)); break; case Key::Down: o->rotate(deg(10.0f), Vector3::xAxis(1)); break; case Key::Left: o->rotate(deg(10.0f), Vector3::yAxis(-1), false); break; case Key::Right: o->rotate(deg(10.0f), Vector3::yAxis(1), false); break; case Key::PageUp: camera->translate(Vector3::zAxis(-0.5), false); break; case Key::PageDown: camera->translate(Vector3::zAxis(0.5), false); break; case Key::Home: glPolygonMode(GL_FRONT_AND_BACK, wireframe ? GL_FILL : GL_LINE); wireframe = !wireframe; break; case Key::End: if(fps) cout << "Average FPS on " << camera->viewport().x() << 'x' << camera->viewport().y() << " from " << totalmeasurecount << " measures: " << totalfps/totalmeasurecount << " " << endl; else before = chrono::high_resolution_clock::now(); fps = !fps; frames = totalmeasurecount = 0; totalfps = 0; break; } redraw(); } void mouseEvent(MouseButton button, MouseState state, const Math::Vector2<int>& position) { switch(button) { case MouseButton::Left: if(state == MouseState::Down) previousPosition = positionOnSphere(position); else previousPosition = Vector3(); break; case MouseButton::WheelUp: case MouseButton::WheelDown: { if(state == MouseState::Up) return; /* Distance between origin and near camera clipping plane */ GLfloat distance = camera->transformation().at(3).z()-0-camera->near(); /* Move 15% of the distance back or forward */ if(button == MouseButton::WheelUp) distance *= 1 - 1/0.85f; else distance *= 1 - 0.85f; camera->translate(Vector3::zAxis(distance), false); redraw(); break; } default: ; } } void mouseMoveEvent(const Math::Vector2<int>& position) { Vector3 currentPosition = positionOnSphere(position); Vector3 axis = Vector3::cross(previousPosition, currentPosition); if(previousPosition.length() < 0.001f || axis.length() < 0.001f) return; GLfloat angle = acos(previousPosition*currentPosition); o->rotate(angle, axis); previousPosition = currentPosition; redraw(); } private: Vector3 positionOnSphere(const Math::Vector2<int>& _position) const { Math::Vector2<GLsizei> viewport = camera->viewport(); Vector2 position(_position.x()*2.0f/viewport.x() - 1.0f, _position.y()*2.0f/viewport.y() - 1.0f); GLfloat length = position.length(); Vector3 result(length > 1.0f ? position : Vector3(position, 1.0f - length)); result.setY(-result.y()); return result.normalized(); } void addObject(AbstractImporter* colladaImporter, Object* parent, unordered_map<size_t, PhongMaterialData*>& materials, size_t objectId); Scene scene; Camera* camera; PhongShader shader; Object* o; unordered_map<size_t, IndexedMesh*> meshes; chrono::high_resolution_clock::time_point before; bool wireframe, fps; size_t frames; double totalfps; size_t totalmeasurecount; Vector3 previousPosition; }; ViewerExample::ViewerExample(int& argc, char** argv): AbstractExample(argc, argv, "Magnum Viewer"), wireframe(false), fps(false) { if(argc != 2) { cout << "Usage: " << argv[0] << " file.dae" << endl; exit(0); } /* Instance ColladaImporter plugin */ PluginManager<AbstractImporter> manager(PLUGIN_IMPORTER_DIR); if(manager.load("ColladaImporter") != AbstractPluginManager::LoadOk) { Error() << "Could not load ColladaImporter plugin"; exit(1); } unique_ptr<AbstractImporter> colladaImporter(manager.instance("ColladaImporter")); if(!colladaImporter) { Error() << "Could not instance ColladaImporter plugin"; exit(2); } if(!(colladaImporter->features() & AbstractImporter::OpenFile)) { Error() << "ColladaImporter cannot open files"; exit(3); } scene.setFeature(Scene::DepthTest, true); /* Every scene needs a camera */ camera = new Camera(&scene); camera->setPerspective(deg(35.0f), 0.001f, 100); camera->translate(Vector3::zAxis(5)); /* Load file */ if(!colladaImporter->open(argv[1])) exit(4); if(colladaImporter->sceneCount() == 0) exit(5); /* Map with materials */ unordered_map<size_t, PhongMaterialData*> materials; /* Default object, parent of all (for manipulation) */ o = new Object(&scene); /* Load the scene */ SceneData* scene = colladaImporter->scene(colladaImporter->defaultScene()); /* Add all children */ for(size_t objectId: scene->children()) addObject(colladaImporter.get(), o, materials, objectId); /* Delete materials, as they are now unused */ for(auto i: materials) delete i.second; colladaImporter->close(); delete colladaImporter.release(); } void ViewerExample::addObject(AbstractImporter* colladaImporter, Object* parent, unordered_map<size_t, PhongMaterialData*>& materials, size_t objectId) { ObjectData* object = colladaImporter->object(objectId); /* Only meshes for now */ if(object->instanceType() == ObjectData::InstanceType::Mesh) { /* Use already processed mesh, if exists */ IndexedMesh* mesh; auto found = meshes.find(object->instanceId()); if(found != meshes.end()) mesh = found->second; /* Or create a new one */ else { mesh = new IndexedMesh; meshes.insert(make_pair(object->instanceId(), mesh)); MeshData* data = colladaImporter->mesh(object->instanceId()); if(!data || !data->indices() || !data->vertexArrayCount() || !data->normalArrayCount()) exit(6); /* Optimize vertices */ Debug() << "Optimizing vertices of mesh" << object->instanceId() << "using Tipsify algorithm (cache size 24)..."; MeshTools::tipsify(*data->indices(), data->vertices(0)->size(), 24); /* Interleave mesh data */ Buffer* buffer = mesh->addBuffer(true); mesh->bindAttribute<PhongShader::Vertex>(buffer); mesh->bindAttribute<PhongShader::Normal>(buffer); MeshTools::interleave(mesh, buffer, Buffer::Usage::StaticDraw, *data->vertices(0), *data->normals(0)); /* Compress indices */ MeshTools::compressIndices(mesh, Buffer::Usage::StaticDraw, *data->indices()); } /* Use already processed material, if exists */ PhongMaterialData* material; auto materialFound = materials.find(static_cast<MeshObjectData*>(object)->material()); if(materialFound != materials.end()) material = materialFound->second; /* Else get material or create default one */ else { material = static_cast<PhongMaterialData*>(colladaImporter->material(static_cast<MeshObjectData*>(object)->material())); if(!material) material = new PhongMaterialData({0.0f, 0.0f, 0.0f}, {0.9f, 0.9f, 0.9f}, {1.0f, 1.0f, 1.0f}, 50.0f); } /* Add object */ Object* o = new ViewedObject(mesh, material, &shader, parent); o->setTransformation(object->transformation()); } /* Recursively add children */ for(size_t id: object->children()) addObject(colladaImporter, o, materials, id); } }} MAGNUM_EXAMPLE_MAIN(Magnum::Examples::ViewerExample) <commit_msg>Using Corrade::Debug instead of std::cout.<commit_after>/* Copyright © 2010, 2011, 2012 Vladimír Vondruš <[email protected]> This file is part of Magnum. Magnum 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. Magnum 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. */ #include <iostream> #include <chrono> #include <memory> #include <unordered_map> #include "PluginManager/PluginManager.h" #include "Scene.h" #include "Camera.h" #include "Trade/AbstractImporter.h" #include "Trade/MeshData.h" #include "Trade/MeshObjectData.h" #include "Trade/SceneData.h" #include "MeshTools/Tipsify.h" #include "MeshTools/Interleave.h" #include "MeshTools/CompressIndices.h" #include "Shaders/PhongShader.h" #include "AbstractExample.h" #include "ViewedObject.h" #include "configure.h" using namespace std; using namespace Corrade::PluginManager; using namespace Corrade::Utility; using namespace Magnum; using namespace Magnum::Shaders; using namespace Magnum::Trade; using namespace Magnum::Examples; namespace Magnum { namespace Examples { class ViewerExample: public AbstractExample { public: ViewerExample(int& argc, char** argv); ~ViewerExample() { for(auto i: meshes) delete i.second; } protected: inline void viewportEvent(const Math::Vector2<GLsizei>& size) { camera->setViewport(size); } void drawEvent() { if(fps) { chrono::high_resolution_clock::time_point now = chrono::high_resolution_clock::now(); double duration = chrono::duration<double>(now-before).count(); if(duration > 3.5) { cout << frames << " frames in " << duration << " sec: " << frames/duration << " FPS \r"; cout.flush(); totalfps += frames/duration; before = now; frames = 0; ++totalmeasurecount; } } camera->draw(); swapBuffers(); if(fps) { ++frames; redraw(); } } void keyEvent(Key key, const Math::Vector2<int>& position) { switch(key) { case Key::Up: o->rotate(deg(10.0f), Vector3::xAxis(-1)); break; case Key::Down: o->rotate(deg(10.0f), Vector3::xAxis(1)); break; case Key::Left: o->rotate(deg(10.0f), Vector3::yAxis(-1), false); break; case Key::Right: o->rotate(deg(10.0f), Vector3::yAxis(1), false); break; case Key::PageUp: camera->translate(Vector3::zAxis(-0.5), false); break; case Key::PageDown: camera->translate(Vector3::zAxis(0.5), false); break; case Key::Home: glPolygonMode(GL_FRONT_AND_BACK, wireframe ? GL_FILL : GL_LINE); wireframe = !wireframe; break; case Key::End: if(fps) cout << "Average FPS on " << camera->viewport().x() << 'x' << camera->viewport().y() << " from " << totalmeasurecount << " measures: " << totalfps/totalmeasurecount << " " << endl; else before = chrono::high_resolution_clock::now(); fps = !fps; frames = totalmeasurecount = 0; totalfps = 0; break; } redraw(); } void mouseEvent(MouseButton button, MouseState state, const Math::Vector2<int>& position) { switch(button) { case MouseButton::Left: if(state == MouseState::Down) previousPosition = positionOnSphere(position); else previousPosition = Vector3(); break; case MouseButton::WheelUp: case MouseButton::WheelDown: { if(state == MouseState::Up) return; /* Distance between origin and near camera clipping plane */ GLfloat distance = camera->transformation().at(3).z()-0-camera->near(); /* Move 15% of the distance back or forward */ if(button == MouseButton::WheelUp) distance *= 1 - 1/0.85f; else distance *= 1 - 0.85f; camera->translate(Vector3::zAxis(distance), false); redraw(); break; } default: ; } } void mouseMoveEvent(const Math::Vector2<int>& position) { Vector3 currentPosition = positionOnSphere(position); Vector3 axis = Vector3::cross(previousPosition, currentPosition); if(previousPosition.length() < 0.001f || axis.length() < 0.001f) return; GLfloat angle = acos(previousPosition*currentPosition); o->rotate(angle, axis); previousPosition = currentPosition; redraw(); } private: Vector3 positionOnSphere(const Math::Vector2<int>& _position) const { Math::Vector2<GLsizei> viewport = camera->viewport(); Vector2 position(_position.x()*2.0f/viewport.x() - 1.0f, _position.y()*2.0f/viewport.y() - 1.0f); GLfloat length = position.length(); Vector3 result(length > 1.0f ? position : Vector3(position, 1.0f - length)); result.setY(-result.y()); return result.normalized(); } void addObject(AbstractImporter* colladaImporter, Object* parent, unordered_map<size_t, PhongMaterialData*>& materials, size_t objectId); Scene scene; Camera* camera; PhongShader shader; Object* o; unordered_map<size_t, IndexedMesh*> meshes; chrono::high_resolution_clock::time_point before; bool wireframe, fps; size_t frames; double totalfps; size_t totalmeasurecount; Vector3 previousPosition; }; ViewerExample::ViewerExample(int& argc, char** argv): AbstractExample(argc, argv, "Magnum Viewer"), wireframe(false), fps(false) { if(argc != 2) { Debug() << "Usage:" << argv[0] << "file.dae"; exit(0); } /* Instance ColladaImporter plugin */ PluginManager<AbstractImporter> manager(PLUGIN_IMPORTER_DIR); if(manager.load("ColladaImporter") != AbstractPluginManager::LoadOk) { Error() << "Could not load ColladaImporter plugin"; exit(1); } unique_ptr<AbstractImporter> colladaImporter(manager.instance("ColladaImporter")); if(!colladaImporter) { Error() << "Could not instance ColladaImporter plugin"; exit(2); } if(!(colladaImporter->features() & AbstractImporter::OpenFile)) { Error() << "ColladaImporter cannot open files"; exit(3); } scene.setFeature(Scene::DepthTest, true); /* Every scene needs a camera */ camera = new Camera(&scene); camera->setPerspective(deg(35.0f), 0.001f, 100); camera->translate(Vector3::zAxis(5)); /* Load file */ if(!colladaImporter->open(argv[1])) exit(4); if(colladaImporter->sceneCount() == 0) exit(5); /* Map with materials */ unordered_map<size_t, PhongMaterialData*> materials; /* Default object, parent of all (for manipulation) */ o = new Object(&scene); /* Load the scene */ SceneData* scene = colladaImporter->scene(colladaImporter->defaultScene()); /* Add all children */ for(size_t objectId: scene->children()) addObject(colladaImporter.get(), o, materials, objectId); /* Delete materials, as they are now unused */ for(auto i: materials) delete i.second; colladaImporter->close(); delete colladaImporter.release(); } void ViewerExample::addObject(AbstractImporter* colladaImporter, Object* parent, unordered_map<size_t, PhongMaterialData*>& materials, size_t objectId) { ObjectData* object = colladaImporter->object(objectId); /* Only meshes for now */ if(object->instanceType() == ObjectData::InstanceType::Mesh) { /* Use already processed mesh, if exists */ IndexedMesh* mesh; auto found = meshes.find(object->instanceId()); if(found != meshes.end()) mesh = found->second; /* Or create a new one */ else { mesh = new IndexedMesh; meshes.insert(make_pair(object->instanceId(), mesh)); MeshData* data = colladaImporter->mesh(object->instanceId()); if(!data || !data->indices() || !data->vertexArrayCount() || !data->normalArrayCount()) exit(6); /* Optimize vertices */ Debug() << "Optimizing vertices of mesh" << object->instanceId() << "using Tipsify algorithm (cache size 24)..."; MeshTools::tipsify(*data->indices(), data->vertices(0)->size(), 24); /* Interleave mesh data */ Buffer* buffer = mesh->addBuffer(true); mesh->bindAttribute<PhongShader::Vertex>(buffer); mesh->bindAttribute<PhongShader::Normal>(buffer); MeshTools::interleave(mesh, buffer, Buffer::Usage::StaticDraw, *data->vertices(0), *data->normals(0)); /* Compress indices */ MeshTools::compressIndices(mesh, Buffer::Usage::StaticDraw, *data->indices()); } /* Use already processed material, if exists */ PhongMaterialData* material; auto materialFound = materials.find(static_cast<MeshObjectData*>(object)->material()); if(materialFound != materials.end()) material = materialFound->second; /* Else get material or create default one */ else { material = static_cast<PhongMaterialData*>(colladaImporter->material(static_cast<MeshObjectData*>(object)->material())); if(!material) material = new PhongMaterialData({0.0f, 0.0f, 0.0f}, {0.9f, 0.9f, 0.9f}, {1.0f, 1.0f, 1.0f}, 50.0f); } /* Add object */ Object* o = new ViewedObject(mesh, material, &shader, parent); o->setTransformation(object->transformation()); } /* Recursively add children */ for(size_t id: object->children()) addObject(colladaImporter, o, materials, id); } }} MAGNUM_EXAMPLE_MAIN(Magnum::Examples::ViewerExample) <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * Effective License of whole file: * * 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 * * Parts "Copyright by Sun Microsystems, Inc" prior to August 2011: * * The Contents of this file are made available subject to the terms of * the GNU Lesser General Public License Version 2.1 * * Copyright: 2000 by Sun Microsystems, Inc. * * Contributor(s): Joerg Budischewski * * All parts contributed on or after August 2011: * * Version: MPL 1.1 / GPLv3+ / LGPLv2.1+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * [ Copyright (C) 2011 Lionel Elie Mamane <[email protected]> ] * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPLv2.1+"), * in which case the provisions of the GPLv3+ or the LGPLv2.1+ are applicable * instead of those above. * ************************************************************************/ #include <stdio.h> #include <cppuhelper/factory.hxx> #include <cppuhelper/compbase1.hxx> #include <cppuhelper/compbase2.hxx> #include <cppuhelper/implementationentry.hxx> #include <com/sun/star/beans/XPropertySet.hpp> #include "pq_driver.hxx" using rtl::OUString; using rtl::OUStringToOString; using osl::MutexGuard; using cppu::WeakComponentImplHelper2; using com::sun::star::lang::XSingleComponentFactory; using com::sun::star::lang::XServiceInfo; using com::sun::star::lang::XComponent; using com::sun::star::uno::RuntimeException; using com::sun::star::uno::Exception; using com::sun::star::uno::Sequence; using com::sun::star::uno::Reference; using com::sun::star::uno::XInterface; using com::sun::star::uno::UNO_QUERY; using com::sun::star::uno::XComponentContext; using com::sun::star::uno::Any; using com::sun::star::beans::PropertyValue; using com::sun::star::beans::XPropertySet; using com::sun::star::sdbc::XConnection; using com::sun::star::sdbc::SQLException; using com::sun::star::sdbc::DriverPropertyInfo; using com::sun::star::sdbcx::XTablesSupplier; namespace pq_sdbc_driver { #define ASCII_STR(x) OUString( RTL_CONSTASCII_USTRINGPARAM( x ) ) OUString DriverGetImplementationName() { static OUString *p; if (! p ) { MutexGuard guard( osl::Mutex::getGlobalMutex() ); static OUString instance( RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.comp.connectivity.pq.Driver" ) ); p = &instance; } return *p; } Sequence< OUString > DriverGetSupportedServiceNames() { static Sequence< OUString > *p; if( ! p ) { MutexGuard guard( osl::Mutex::getGlobalMutex() ); OUString tmp( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.sdbc.Driver" ) ); static Sequence< OUString > instance( &tmp,1 ); p = &instance; } return *p; } Reference< XConnection > Driver::connect( const OUString& url,const Sequence< PropertyValue >& info ) throw (SQLException, RuntimeException) { if( ! acceptsURL( url ) ) // XDriver spec tells me to do so ... return Reference< XConnection > (); Sequence< Any > seq ( 2 ); seq[0] <<= url; seq[1] <<= info; return Reference< XConnection> ( m_smgr->createInstanceWithArgumentsAndContext( OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.comp.connectivity.pq.Connection" ) ), seq, m_ctx ), UNO_QUERY ); } sal_Bool Driver::acceptsURL( const ::rtl::OUString& url ) throw (SQLException, RuntimeException) { return url.matchAsciiL( RTL_CONSTASCII_STRINGPARAM( "sdbc:postgresql:" ) ); } Sequence< DriverPropertyInfo > Driver::getPropertyInfo( const OUString& url,const Sequence< PropertyValue >& info ) throw (SQLException, RuntimeException) { (void)url; (void)info; return Sequence< DriverPropertyInfo > (); } sal_Int32 Driver::getMajorVersion( ) throw (RuntimeException) { return PQ_SDBC_MAJOR; } sal_Int32 Driver::getMinorVersion( ) throw (RuntimeException) { return PQ_SDBC_MINOR; } // XServiceInfo OUString SAL_CALL Driver::getImplementationName() throw(::com::sun::star::uno::RuntimeException) { return DriverGetImplementationName(); } sal_Bool Driver::supportsService(const OUString& ServiceName) throw(::com::sun::star::uno::RuntimeException) { Sequence< OUString > serviceNames = DriverGetSupportedServiceNames(); for( int i = 0 ; i < serviceNames.getLength() ; i ++ ) if( serviceNames[i] == ServiceName ) return sal_True; return sal_False; } Sequence< OUString > Driver::getSupportedServiceNames(void) throw(::com::sun::star::uno::RuntimeException) { return DriverGetSupportedServiceNames(); } // XComponent void Driver::disposing() { } Reference< XTablesSupplier > Driver::getDataDefinitionByConnection( const Reference< XConnection >& connection ) throw (SQLException, RuntimeException) { return Reference< XTablesSupplier >( connection , UNO_QUERY ); } Reference< XTablesSupplier > Driver::getDataDefinitionByURL( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw (SQLException, RuntimeException) { return Reference< XTablesSupplier > ( connect( url, info ), UNO_QUERY ); } Reference< XInterface > DriverCreateInstance( const Reference < XComponentContext > & ctx ) { Reference< XInterface > ret = * new Driver( ctx ); return ret; } class OOneInstanceComponentFactory : public MutexHolder, public WeakComponentImplHelper2< XSingleComponentFactory, XServiceInfo > { public: OOneInstanceComponentFactory( const OUString & rImplementationName_, cppu::ComponentFactoryFunc fptr, const Sequence< OUString > & serviceNames, const Reference< XComponentContext > & defaultContext) : WeakComponentImplHelper2< XSingleComponentFactory, XServiceInfo >( this->m_mutex ), m_create( fptr ), m_serviceNames( serviceNames ), m_implName( rImplementationName_ ), m_defaultContext( defaultContext ) { } // XSingleComponentFactory virtual Reference< XInterface > SAL_CALL createInstanceWithContext( Reference< XComponentContext > const & xContext ) throw (Exception, RuntimeException); virtual Reference< XInterface > SAL_CALL createInstanceWithArgumentsAndContext( Sequence< Any > const & rArguments, Reference< XComponentContext > const & xContext ) throw (Exception, RuntimeException); // XServiceInfo OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException) { return m_implName; } sal_Bool SAL_CALL supportsService(const OUString& ServiceName) throw(::com::sun::star::uno::RuntimeException) { for( int i = 0 ; i < m_serviceNames.getLength() ; i ++ ) if( m_serviceNames[i] == ServiceName ) return sal_True; return sal_False; } Sequence< OUString > SAL_CALL getSupportedServiceNames(void) throw(::com::sun::star::uno::RuntimeException) { return m_serviceNames; } // XComponent virtual void SAL_CALL disposing(); private: cppu::ComponentFactoryFunc m_create; Sequence< OUString > m_serviceNames; OUString m_implName; Reference< XInterface > m_theInstance; Reference< XComponentContext > m_defaultContext; }; Reference< XInterface > OOneInstanceComponentFactory::createInstanceWithArgumentsAndContext( Sequence< Any > const &rArguments, const Reference< XComponentContext > & ctx ) throw( RuntimeException, Exception ) { (void)rArguments; return createInstanceWithContext( ctx ); } Reference< XInterface > OOneInstanceComponentFactory::createInstanceWithContext( const Reference< XComponentContext > & ctx ) throw( RuntimeException, Exception ) { if( ! m_theInstance.is() ) { // work around the problem in sdbc Reference< XComponentContext > useCtx = ctx; if( ! useCtx.is() ) useCtx = m_defaultContext; Reference< XInterface > theInstance = m_create( useCtx ); MutexGuard guard( osl::Mutex::getGlobalMutex() ); if( ! m_theInstance.is () ) { m_theInstance = theInstance; } } return m_theInstance; } void OOneInstanceComponentFactory::disposing() { Reference< XComponent > rComp; { MutexGuard guard( osl::Mutex::getGlobalMutex() ); rComp = Reference< XComponent >( m_theInstance, UNO_QUERY ); m_theInstance.clear(); } if( rComp.is() ) rComp->dispose(); } // Reference< XSingleComponentFactory > createOneInstanceComponentFactory( // cppu::ComponentFactoryFunc fptr, // ::rtl::OUString const & rImplementationName, // ::com::sun::star::uno::Sequence< ::rtl::OUString > const & rServiceNames, // rtl_ModuleCount * pModCount = 0 ) // SAL_THROW(()) // { // return new OOneInstanceComponentFactory( rImplementationName, fptr , rServiceNames); // } } static struct cppu::ImplementationEntry g_entries[] = { { pq_sdbc_driver::DriverCreateInstance, pq_sdbc_driver::DriverGetImplementationName, pq_sdbc_driver::DriverGetSupportedServiceNames, 0, 0 , 0 }, { 0, 0, 0, 0, 0, 0 } }; extern "C" { void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * ) { // need to extract the defaultcontext, because the way, sdbc // bypasses the servicemanager, does not allow to use the // XSingleComponentFactory interface ... void * pRet = 0; Reference< XSingleComponentFactory > xFactory; Reference< XInterface > xSmgr( (XInterface * ) pServiceManager ); for( sal_Int32 i = 0 ; g_entries[i].create ; i ++ ) { OUString implName = g_entries[i].getImplementationName(); if( 0 == implName.compareToAscii( pImplName ) ) { Reference< XComponentContext > defaultContext; Reference< XPropertySet > propSet( xSmgr, UNO_QUERY ); if( propSet.is() ) { try { propSet->getPropertyValue( ASCII_STR( "DefaultContext" ) ) >>= defaultContext; } catch( com::sun::star::uno::Exception &e ) { // if there is no default context, ignore it } } xFactory = new pq_sdbc_driver::OOneInstanceComponentFactory( implName, g_entries[i].create, g_entries[i].getSupportedServiceNames(), defaultContext ); } } if( xFactory.is() ) { xFactory->acquire(); pRet = xFactory.get(); } return pRet; } } <commit_msg>WaE: unreferenced local variable<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * Effective License of whole file: * * 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 * * Parts "Copyright by Sun Microsystems, Inc" prior to August 2011: * * The Contents of this file are made available subject to the terms of * the GNU Lesser General Public License Version 2.1 * * Copyright: 2000 by Sun Microsystems, Inc. * * Contributor(s): Joerg Budischewski * * All parts contributed on or after August 2011: * * Version: MPL 1.1 / GPLv3+ / LGPLv2.1+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * [ Copyright (C) 2011 Lionel Elie Mamane <[email protected]> ] * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPLv2.1+"), * in which case the provisions of the GPLv3+ or the LGPLv2.1+ are applicable * instead of those above. * ************************************************************************/ #include <stdio.h> #include <cppuhelper/factory.hxx> #include <cppuhelper/compbase1.hxx> #include <cppuhelper/compbase2.hxx> #include <cppuhelper/implementationentry.hxx> #include <com/sun/star/beans/XPropertySet.hpp> #include "pq_driver.hxx" using rtl::OUString; using rtl::OUStringToOString; using osl::MutexGuard; using cppu::WeakComponentImplHelper2; using com::sun::star::lang::XSingleComponentFactory; using com::sun::star::lang::XServiceInfo; using com::sun::star::lang::XComponent; using com::sun::star::uno::RuntimeException; using com::sun::star::uno::Exception; using com::sun::star::uno::Sequence; using com::sun::star::uno::Reference; using com::sun::star::uno::XInterface; using com::sun::star::uno::UNO_QUERY; using com::sun::star::uno::XComponentContext; using com::sun::star::uno::Any; using com::sun::star::beans::PropertyValue; using com::sun::star::beans::XPropertySet; using com::sun::star::sdbc::XConnection; using com::sun::star::sdbc::SQLException; using com::sun::star::sdbc::DriverPropertyInfo; using com::sun::star::sdbcx::XTablesSupplier; namespace pq_sdbc_driver { #define ASCII_STR(x) OUString( RTL_CONSTASCII_USTRINGPARAM( x ) ) OUString DriverGetImplementationName() { static OUString *p; if (! p ) { MutexGuard guard( osl::Mutex::getGlobalMutex() ); static OUString instance( RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.comp.connectivity.pq.Driver" ) ); p = &instance; } return *p; } Sequence< OUString > DriverGetSupportedServiceNames() { static Sequence< OUString > *p; if( ! p ) { MutexGuard guard( osl::Mutex::getGlobalMutex() ); OUString tmp( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.sdbc.Driver" ) ); static Sequence< OUString > instance( &tmp,1 ); p = &instance; } return *p; } Reference< XConnection > Driver::connect( const OUString& url,const Sequence< PropertyValue >& info ) throw (SQLException, RuntimeException) { if( ! acceptsURL( url ) ) // XDriver spec tells me to do so ... return Reference< XConnection > (); Sequence< Any > seq ( 2 ); seq[0] <<= url; seq[1] <<= info; return Reference< XConnection> ( m_smgr->createInstanceWithArgumentsAndContext( OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.comp.connectivity.pq.Connection" ) ), seq, m_ctx ), UNO_QUERY ); } sal_Bool Driver::acceptsURL( const ::rtl::OUString& url ) throw (SQLException, RuntimeException) { return url.matchAsciiL( RTL_CONSTASCII_STRINGPARAM( "sdbc:postgresql:" ) ); } Sequence< DriverPropertyInfo > Driver::getPropertyInfo( const OUString& url,const Sequence< PropertyValue >& info ) throw (SQLException, RuntimeException) { (void)url; (void)info; return Sequence< DriverPropertyInfo > (); } sal_Int32 Driver::getMajorVersion( ) throw (RuntimeException) { return PQ_SDBC_MAJOR; } sal_Int32 Driver::getMinorVersion( ) throw (RuntimeException) { return PQ_SDBC_MINOR; } // XServiceInfo OUString SAL_CALL Driver::getImplementationName() throw(::com::sun::star::uno::RuntimeException) { return DriverGetImplementationName(); } sal_Bool Driver::supportsService(const OUString& ServiceName) throw(::com::sun::star::uno::RuntimeException) { Sequence< OUString > serviceNames = DriverGetSupportedServiceNames(); for( int i = 0 ; i < serviceNames.getLength() ; i ++ ) if( serviceNames[i] == ServiceName ) return sal_True; return sal_False; } Sequence< OUString > Driver::getSupportedServiceNames(void) throw(::com::sun::star::uno::RuntimeException) { return DriverGetSupportedServiceNames(); } // XComponent void Driver::disposing() { } Reference< XTablesSupplier > Driver::getDataDefinitionByConnection( const Reference< XConnection >& connection ) throw (SQLException, RuntimeException) { return Reference< XTablesSupplier >( connection , UNO_QUERY ); } Reference< XTablesSupplier > Driver::getDataDefinitionByURL( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw (SQLException, RuntimeException) { return Reference< XTablesSupplier > ( connect( url, info ), UNO_QUERY ); } Reference< XInterface > DriverCreateInstance( const Reference < XComponentContext > & ctx ) { Reference< XInterface > ret = * new Driver( ctx ); return ret; } class OOneInstanceComponentFactory : public MutexHolder, public WeakComponentImplHelper2< XSingleComponentFactory, XServiceInfo > { public: OOneInstanceComponentFactory( const OUString & rImplementationName_, cppu::ComponentFactoryFunc fptr, const Sequence< OUString > & serviceNames, const Reference< XComponentContext > & defaultContext) : WeakComponentImplHelper2< XSingleComponentFactory, XServiceInfo >( this->m_mutex ), m_create( fptr ), m_serviceNames( serviceNames ), m_implName( rImplementationName_ ), m_defaultContext( defaultContext ) { } // XSingleComponentFactory virtual Reference< XInterface > SAL_CALL createInstanceWithContext( Reference< XComponentContext > const & xContext ) throw (Exception, RuntimeException); virtual Reference< XInterface > SAL_CALL createInstanceWithArgumentsAndContext( Sequence< Any > const & rArguments, Reference< XComponentContext > const & xContext ) throw (Exception, RuntimeException); // XServiceInfo OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException) { return m_implName; } sal_Bool SAL_CALL supportsService(const OUString& ServiceName) throw(::com::sun::star::uno::RuntimeException) { for( int i = 0 ; i < m_serviceNames.getLength() ; i ++ ) if( m_serviceNames[i] == ServiceName ) return sal_True; return sal_False; } Sequence< OUString > SAL_CALL getSupportedServiceNames(void) throw(::com::sun::star::uno::RuntimeException) { return m_serviceNames; } // XComponent virtual void SAL_CALL disposing(); private: cppu::ComponentFactoryFunc m_create; Sequence< OUString > m_serviceNames; OUString m_implName; Reference< XInterface > m_theInstance; Reference< XComponentContext > m_defaultContext; }; Reference< XInterface > OOneInstanceComponentFactory::createInstanceWithArgumentsAndContext( Sequence< Any > const &rArguments, const Reference< XComponentContext > & ctx ) throw( RuntimeException, Exception ) { (void)rArguments; return createInstanceWithContext( ctx ); } Reference< XInterface > OOneInstanceComponentFactory::createInstanceWithContext( const Reference< XComponentContext > & ctx ) throw( RuntimeException, Exception ) { if( ! m_theInstance.is() ) { // work around the problem in sdbc Reference< XComponentContext > useCtx = ctx; if( ! useCtx.is() ) useCtx = m_defaultContext; Reference< XInterface > theInstance = m_create( useCtx ); MutexGuard guard( osl::Mutex::getGlobalMutex() ); if( ! m_theInstance.is () ) { m_theInstance = theInstance; } } return m_theInstance; } void OOneInstanceComponentFactory::disposing() { Reference< XComponent > rComp; { MutexGuard guard( osl::Mutex::getGlobalMutex() ); rComp = Reference< XComponent >( m_theInstance, UNO_QUERY ); m_theInstance.clear(); } if( rComp.is() ) rComp->dispose(); } // Reference< XSingleComponentFactory > createOneInstanceComponentFactory( // cppu::ComponentFactoryFunc fptr, // ::rtl::OUString const & rImplementationName, // ::com::sun::star::uno::Sequence< ::rtl::OUString > const & rServiceNames, // rtl_ModuleCount * pModCount = 0 ) // SAL_THROW(()) // { // return new OOneInstanceComponentFactory( rImplementationName, fptr , rServiceNames); // } } static struct cppu::ImplementationEntry g_entries[] = { { pq_sdbc_driver::DriverCreateInstance, pq_sdbc_driver::DriverGetImplementationName, pq_sdbc_driver::DriverGetSupportedServiceNames, 0, 0 , 0 }, { 0, 0, 0, 0, 0, 0 } }; extern "C" { void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * ) { // need to extract the defaultcontext, because the way, sdbc // bypasses the servicemanager, does not allow to use the // XSingleComponentFactory interface ... void * pRet = 0; Reference< XSingleComponentFactory > xFactory; Reference< XInterface > xSmgr( (XInterface * ) pServiceManager ); for( sal_Int32 i = 0 ; g_entries[i].create ; i ++ ) { OUString implName = g_entries[i].getImplementationName(); if( 0 == implName.compareToAscii( pImplName ) ) { Reference< XComponentContext > defaultContext; Reference< XPropertySet > propSet( xSmgr, UNO_QUERY ); if( propSet.is() ) { try { propSet->getPropertyValue( ASCII_STR( "DefaultContext" ) ) >>= defaultContext; } catch( com::sun::star::uno::Exception & ) { // if there is no default context, ignore it } } xFactory = new pq_sdbc_driver::OOneInstanceComponentFactory( implName, g_entries[i].create, g_entries[i].getSupportedServiceNames(), defaultContext ); } } if( xFactory.is() ) { xFactory->acquire(); pRet = xFactory.get(); } return pRet; } } <|endoftext|>
<commit_before>#include "vlc_video_source.h" #include <cstdio> #include <cstdlib> #include <chrono> #include <thread> namespace gg { VideoSourceVLC::VideoSourceVLC(const std::string path) : _vlc_inst(nullptr) , _vlc_mp(nullptr) , _video_buffer(nullptr) , _data_length(0) , _cols(0) , _rows(0) , _sub(nullptr) , _path(path) { this->init_vlc(); this->run_vlc(); } VideoSourceVLC::~VideoSourceVLC() { stop_vlc(); release_vlc(); } bool VideoSourceVLC::get_frame_dimensions(int & width, int & height) { ///\todo mutex if(this->_cols == 0 || this->_rows == 0) return false; width = this->_cols; height = this->_rows; return true; } bool VideoSourceVLC::get_frame(VideoFrame_BGRA & frame) { throw VideoSourceError("VLC video source supports only I420 colour space"); // TODO ///\todo mutex if (_cols == 0 || _rows == 0 || _video_buffer == nullptr) return false; // allocate and fill the image if (_cols * _rows * 4 == this->_data_length) frame = VideoFrame_BGRA(this->_video_buffer, this->_cols, this->_rows); else throw VideoSourceError("VLC video source does not support padded images"); return true; } bool VideoSourceVLC::get_frame(VideoFrame_I420 & frame) { if (_data_length > 0) { // TODO manage data? frame = VideoFrame_I420(_video_buffer, _data_length, _cols, _rows, false); return true; } else return false; // TODO #86 } double VideoSourceVLC::get_frame_rate() { //return libvlc_media_player_get_rate( m_mp ); return libvlc_media_player_get_fps(_vlc_mp); //throw std::runtime_error("get_frame_rate to be implemented"); //return 0.0; } void VideoSourceVLC::set_sub_frame(int x, int y, int width, int height) { // TODO mutex? if (x >= _full.x and x + width <= _full.x + _full.width and y >= _full.y and y + height <= _full.y + _full.height) { stop_vlc(); release_vlc(); if (_sub == nullptr) _sub = new FrameBox; _sub->x = x; _sub->y = y; _sub->width = width; _sub->height = height; init_vlc(); run_vlc(); } } void VideoSourceVLC::get_full_frame() { // TODO mutex? stop_vlc(); release_vlc(); init_vlc(); run_vlc(); } void VideoSourceVLC::init_vlc() { // VLC pointers libvlc_media_t * vlc_media = nullptr; // VLC options char smem_options[512]; sprintf(smem_options, "#"); if (_sub != nullptr) { unsigned int croptop = _sub->y, cropbottom = _full.height - (_sub->y + _sub->height), cropleft = _sub->x, cropright = _full.width - (_sub->x + _sub->width); sprintf(smem_options, "%stranscode{vcodec=I420,vfilter=croppadd{", smem_options); sprintf(smem_options, "%scroptop=%u,cropbottom=%u,cropleft=%u,cropright=%u}}:", smem_options, croptop, cropbottom, cropleft, cropright); } sprintf(smem_options, "%ssmem{video-data=%lld,video-prerender-callback=%lld,video-postrender-callback=%lld}", smem_options, (long long int)(intptr_t)(void*) this, (long long int)(intptr_t)(void*) &VideoSourceVLC::prepareRender, (long long int)(intptr_t)(void*) &VideoSourceVLC::handleStream ); const char * const vlc_args[] = { "-I", "dummy", // Don't use any interface "--ignore-config", // Don't use VLC's config "--extraintf=logger", // Log anything // TODO - what about the options below? //"--verbose=2", // Be much more verbose then normal for debugging purpose //"--clock-jitter=0", //"--file-caching=150", "--no-audio", "--sout", smem_options // Stream to memory }; // We launch VLC _vlc_inst = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args); if (_vlc_inst == nullptr) throw VideoSourceError("Could not create VLC engine"); // If path contains a colon (:), it will be treated as a // URL. Else, it will be considered as a local path. if (_path.find(":") == std::string::npos) vlc_media = libvlc_media_new_path(_vlc_inst, _path.c_str()); else vlc_media = libvlc_media_new_location(_vlc_inst, _path.c_str()); if (vlc_media == nullptr) throw VideoSourceError(std::string("Could not open ").append(_path)); libvlc_media_add_option(vlc_media, ":noaudio"); libvlc_media_add_option(vlc_media, ":no-video-title-show"); // Create a media player playing environement _vlc_mp = libvlc_media_player_new_from_media(vlc_media); if (_vlc_mp == nullptr) throw VideoSourceError("Could not create VLC media player"); // No need to keep the media now libvlc_media_release( vlc_media ); } void VideoSourceVLC::run_vlc() { // play the media_player if (libvlc_media_player_play(_vlc_mp) != 0) throw VideoSourceError("Could not start VLC media player"); // empirically determined value that allows for initialisation // to succeed before any API functions are called on this object std::this_thread::sleep_for(std::chrono::milliseconds(350)); unsigned int width, height; if (libvlc_video_get_size(_vlc_mp, 0, &width, &height) != 0) throw VideoSourceError("Could not get video dimensions"); _full.x = 0; _full.y = 0; _full.width = width; _full.height = height; } void VideoSourceVLC::stop_vlc() { if (libvlc_media_player_is_playing(_vlc_mp) == 1) // stop playing libvlc_media_player_stop(_vlc_mp); } void VideoSourceVLC::release_vlc() { // free media player libvlc_media_player_release(_vlc_mp); // free engine libvlc_release(_vlc_inst); // free buffer if (_video_buffer != nullptr) delete[] _video_buffer; _data_length = 0; _cols = 0; _rows = 0; // free sub-frame if (_sub != nullptr) { delete _sub; _sub = nullptr; } } void VideoSourceVLC::prepareRender(VideoSourceVLC * p_video_data, uint8_t ** pp_pixel_buffer, size_t size) { ///\todo create mutex guard unsigned int width, height; if (libvlc_video_get_size(p_video_data->_vlc_mp, 0, &width, &height) != 0) return; p_video_data->_cols = width; p_video_data->_rows = height; if (size > p_video_data->_data_length) p_video_data->_video_buffer = reinterpret_cast<uint8_t *>( realloc(p_video_data->_video_buffer, size * sizeof(uint8_t)) ); p_video_data->_data_length = size; *pp_pixel_buffer = p_video_data->_video_buffer; } void VideoSourceVLC::handleStream(VideoSourceVLC * p_video_data, uint8_t * p_pixel_buffer, size_t cols, size_t rows, size_t colour_depth, size_t size) { // TODO: explain how data should be handled (see #86) // TODO: Unlock the mutex } std::string VideoSourceVLC::encode_psz_geometry(int x, int y, int width, int height) { std::string psz_geometry; psz_geometry.append(std::to_string(width)).append("x") .append(std::to_string(height)) .append("+").append(std::to_string(x)) .append("+").append(std::to_string(y)); return psz_geometry; } } <commit_msg>Issue #83: removed is-playing check on VLC player in stop_vlc function<commit_after>#include "vlc_video_source.h" #include <cstdio> #include <cstdlib> #include <chrono> #include <thread> namespace gg { VideoSourceVLC::VideoSourceVLC(const std::string path) : _vlc_inst(nullptr) , _vlc_mp(nullptr) , _video_buffer(nullptr) , _data_length(0) , _cols(0) , _rows(0) , _sub(nullptr) , _path(path) { this->init_vlc(); this->run_vlc(); } VideoSourceVLC::~VideoSourceVLC() { stop_vlc(); release_vlc(); } bool VideoSourceVLC::get_frame_dimensions(int & width, int & height) { ///\todo mutex if(this->_cols == 0 || this->_rows == 0) return false; width = this->_cols; height = this->_rows; return true; } bool VideoSourceVLC::get_frame(VideoFrame_BGRA & frame) { throw VideoSourceError("VLC video source supports only I420 colour space"); // TODO ///\todo mutex if (_cols == 0 || _rows == 0 || _video_buffer == nullptr) return false; // allocate and fill the image if (_cols * _rows * 4 == this->_data_length) frame = VideoFrame_BGRA(this->_video_buffer, this->_cols, this->_rows); else throw VideoSourceError("VLC video source does not support padded images"); return true; } bool VideoSourceVLC::get_frame(VideoFrame_I420 & frame) { if (_data_length > 0) { // TODO manage data? frame = VideoFrame_I420(_video_buffer, _data_length, _cols, _rows, false); return true; } else return false; // TODO #86 } double VideoSourceVLC::get_frame_rate() { //return libvlc_media_player_get_rate( m_mp ); return libvlc_media_player_get_fps(_vlc_mp); //throw std::runtime_error("get_frame_rate to be implemented"); //return 0.0; } void VideoSourceVLC::set_sub_frame(int x, int y, int width, int height) { // TODO mutex? if (x >= _full.x and x + width <= _full.x + _full.width and y >= _full.y and y + height <= _full.y + _full.height) { stop_vlc(); release_vlc(); if (_sub == nullptr) _sub = new FrameBox; _sub->x = x; _sub->y = y; _sub->width = width; _sub->height = height; init_vlc(); run_vlc(); } } void VideoSourceVLC::get_full_frame() { // TODO mutex? stop_vlc(); release_vlc(); init_vlc(); run_vlc(); } void VideoSourceVLC::init_vlc() { // VLC pointers libvlc_media_t * vlc_media = nullptr; // VLC options char smem_options[512]; sprintf(smem_options, "#"); if (_sub != nullptr) { unsigned int croptop = _sub->y, cropbottom = _full.height - (_sub->y + _sub->height), cropleft = _sub->x, cropright = _full.width - (_sub->x + _sub->width); sprintf(smem_options, "%stranscode{vcodec=I420,vfilter=croppadd{", smem_options); sprintf(smem_options, "%scroptop=%u,cropbottom=%u,cropleft=%u,cropright=%u}}:", smem_options, croptop, cropbottom, cropleft, cropright); } sprintf(smem_options, "%ssmem{video-data=%lld,video-prerender-callback=%lld,video-postrender-callback=%lld}", smem_options, (long long int)(intptr_t)(void*) this, (long long int)(intptr_t)(void*) &VideoSourceVLC::prepareRender, (long long int)(intptr_t)(void*) &VideoSourceVLC::handleStream ); const char * const vlc_args[] = { "-I", "dummy", // Don't use any interface "--ignore-config", // Don't use VLC's config "--extraintf=logger", // Log anything // TODO - what about the options below? //"--verbose=2", // Be much more verbose then normal for debugging purpose //"--clock-jitter=0", //"--file-caching=150", "--no-audio", "--sout", smem_options // Stream to memory }; // We launch VLC _vlc_inst = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args); if (_vlc_inst == nullptr) throw VideoSourceError("Could not create VLC engine"); // If path contains a colon (:), it will be treated as a // URL. Else, it will be considered as a local path. if (_path.find(":") == std::string::npos) vlc_media = libvlc_media_new_path(_vlc_inst, _path.c_str()); else vlc_media = libvlc_media_new_location(_vlc_inst, _path.c_str()); if (vlc_media == nullptr) throw VideoSourceError(std::string("Could not open ").append(_path)); libvlc_media_add_option(vlc_media, ":noaudio"); libvlc_media_add_option(vlc_media, ":no-video-title-show"); // Create a media player playing environement _vlc_mp = libvlc_media_player_new_from_media(vlc_media); if (_vlc_mp == nullptr) throw VideoSourceError("Could not create VLC media player"); // No need to keep the media now libvlc_media_release( vlc_media ); } void VideoSourceVLC::run_vlc() { // play the media_player if (libvlc_media_player_play(_vlc_mp) != 0) throw VideoSourceError("Could not start VLC media player"); // empirically determined value that allows for initialisation // to succeed before any API functions are called on this object std::this_thread::sleep_for(std::chrono::milliseconds(350)); unsigned int width, height; if (libvlc_video_get_size(_vlc_mp, 0, &width, &height) != 0) throw VideoSourceError("Could not get video dimensions"); _full.x = 0; _full.y = 0; _full.width = width; _full.height = height; } void VideoSourceVLC::stop_vlc() { // stop playing libvlc_media_player_stop(_vlc_mp); } void VideoSourceVLC::release_vlc() { // free media player libvlc_media_player_release(_vlc_mp); // free engine libvlc_release(_vlc_inst); // free buffer if (_video_buffer != nullptr) delete[] _video_buffer; _data_length = 0; _cols = 0; _rows = 0; // free sub-frame if (_sub != nullptr) { delete _sub; _sub = nullptr; } } void VideoSourceVLC::prepareRender(VideoSourceVLC * p_video_data, uint8_t ** pp_pixel_buffer, size_t size) { ///\todo create mutex guard unsigned int width, height; if (libvlc_video_get_size(p_video_data->_vlc_mp, 0, &width, &height) != 0) return; p_video_data->_cols = width; p_video_data->_rows = height; if (size > p_video_data->_data_length) p_video_data->_video_buffer = reinterpret_cast<uint8_t *>( realloc(p_video_data->_video_buffer, size * sizeof(uint8_t)) ); p_video_data->_data_length = size; *pp_pixel_buffer = p_video_data->_video_buffer; } void VideoSourceVLC::handleStream(VideoSourceVLC * p_video_data, uint8_t * p_pixel_buffer, size_t cols, size_t rows, size_t colour_depth, size_t size) { // TODO: explain how data should be handled (see #86) // TODO: Unlock the mutex } std::string VideoSourceVLC::encode_psz_geometry(int x, int y, int width, int height) { std::string psz_geometry; psz_geometry.append(std::to_string(width)).append("x") .append(std::to_string(height)) .append("+").append(std::to_string(x)) .append("+").append(std::to_string(y)); return psz_geometry; } } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs */ /* */ /* 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 "VirtualMachinePool.h" #include "VirtualMachineHook.h" #include "NebulaLog.h" #include <sstream> /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ time_t VirtualMachinePool::_monitor_expiration; bool VirtualMachinePool::_submit_on_hold; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ VirtualMachinePool::VirtualMachinePool( SqlDB * db, vector<const Attribute *> hook_mads, const string& hook_location, const string& remotes_location, vector<const Attribute *>& restricted_attrs, time_t expire_time, bool on_hold) : PoolSQL(db, VirtualMachine::table, false) { const VectorAttribute * vattr; string name; string on; string cmd; string arg; bool remote; bool state_hook = false; _monitor_expiration = expire_time; _submit_on_hold = on_hold; if ( _monitor_expiration == 0 ) { clean_all_monitoring(); } for (unsigned int i = 0 ; i < hook_mads.size() ; i++ ) { vattr = static_cast<const VectorAttribute *>(hook_mads[i]); name = vattr->vector_value("NAME"); on = vattr->vector_value("ON"); cmd = vattr->vector_value("COMMAND"); arg = vattr->vector_value("ARGUMENTS"); vattr->vector_value("REMOTE", remote); transform (on.begin(),on.end(),on.begin(),(int(*)(int))toupper); if ( on.empty() || cmd.empty() ) { ostringstream oss; oss << "Empty ON or COMMAND attribute in VM_HOOK. Hook " << "not registered!"; NebulaLog::log("VM",Log::WARNING,oss); continue; } if ( name.empty() ) { name = cmd; } if (cmd[0] != '/') { ostringstream cmd_os; if ( remote ) { cmd_os << hook_location << "/" << cmd; } else { cmd_os << remotes_location << "/hooks/" << cmd; } cmd = cmd_os.str(); } if ( on == "CREATE" ) { AllocateHook * hook; hook = new AllocateHook(name, cmd, arg, false); add_hook(hook); } else if ( on == "PROLOG" ) { VirtualMachineStateHook * hook; hook = new VirtualMachineStateHook(name, cmd, arg, remote, VirtualMachine::PROLOG, VirtualMachine::ACTIVE); add_hook(hook); state_hook = true; } else if ( on == "RUNNING" ) { VirtualMachineStateHook * hook; hook = new VirtualMachineStateHook(name, cmd, arg, remote, VirtualMachine::RUNNING, VirtualMachine::ACTIVE); add_hook(hook); state_hook = true; } else if ( on == "SHUTDOWN" ) { VirtualMachineStateHook * hook; hook = new VirtualMachineStateHook(name, cmd, arg, remote, VirtualMachine::EPILOG, VirtualMachine::ACTIVE); add_hook(hook); state_hook = true; } else if ( on == "STOP" ) { VirtualMachineStateHook * hook; hook = new VirtualMachineStateHook(name, cmd, arg, remote, VirtualMachine::LCM_INIT, VirtualMachine::STOPPED); add_hook(hook); state_hook = true; } else if ( on == "DONE" ) { VirtualMachineStateHook * hook; hook = new VirtualMachineStateHook(name, cmd, arg, remote, VirtualMachine::LCM_INIT, VirtualMachine::DONE); add_hook(hook); state_hook = true; } else if ( on == "FAILED" ) { VirtualMachineStateHook * hook; hook = new VirtualMachineStateHook(name, cmd, arg, remote, VirtualMachine::LCM_INIT, VirtualMachine::FAILED); add_hook(hook); state_hook = true; } else if ( on == "UNKNOWN" ) { VirtualMachineStateHook * hook; hook = new VirtualMachineStateHook(name, cmd, arg, remote, VirtualMachine::UNKNOWN, VirtualMachine::ACTIVE); add_hook(hook); state_hook = true; } else if ( on == "CUSTOM" ) { VirtualMachineStateHook * hook; string lcm_str = vattr->vector_value("LCM_STATE"); string vm_str = vattr->vector_value("STATE"); VirtualMachine::LcmState lcm_state; VirtualMachine::VmState vm_state; if ( VirtualMachine::lcm_state_from_str(lcm_str, lcm_state) != 0 ) { ostringstream oss; oss << "Wrong LCM_STATE: "<< lcm_str <<". Hook not registered!"; NebulaLog::log("VM",Log::WARNING,oss); continue; } if ( VirtualMachine::vm_state_from_str(vm_str, vm_state) != 0 ) { ostringstream oss; oss << "Wrong STATE: "<< vm_str <<". Hook not registered!"; NebulaLog::log("VM",Log::WARNING,oss); continue; } hook = new VirtualMachineStateHook(name, cmd, arg, remote, lcm_state, vm_state); add_hook(hook); state_hook = true; } else { ostringstream oss; oss << "Unknown VM_HOOK " << on << ". Hook not registered!"; NebulaLog::log("VM",Log::WARNING,oss); } } if ( state_hook ) { VirtualMachineUpdateStateHook * hook; hook = new VirtualMachineUpdateStateHook(); add_hook(hook); } // Set restricted attributes VirtualMachineTemplate::set_restricted_attributes(restricted_attrs); } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int VirtualMachinePool::allocate ( int uid, int gid, const string& uname, const string& gname, int umask, VirtualMachineTemplate * vm_template, int * oid, string& error_str, bool on_hold) { VirtualMachine * vm; // ------------------------------------------------------------------------ // Build a new Virtual Machine object // ------------------------------------------------------------------------ vm = new VirtualMachine(-1, uid, gid, uname, gname, umask, vm_template); if ( _submit_on_hold == true || on_hold ) { vm->state = VirtualMachine::HOLD; } else { vm->state = VirtualMachine::PENDING; } // ------------------------------------------------------------------------ // Insert the Object in the pool // ------------------------------------------------------------------------ *oid = PoolSQL::allocate(vm, error_str); return *oid; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int VirtualMachinePool::get_running( vector<int>& oids, int vm_limit, time_t last_poll) { ostringstream os; string where; os << "last_poll <= " << last_poll << " and" << " state = " << VirtualMachine::ACTIVE << " and ( lcm_state = " << VirtualMachine::RUNNING << " or lcm_state = " << VirtualMachine::UNKNOWN << " )" << " ORDER BY last_poll ASC LIMIT " << vm_limit; where = os.str(); return PoolSQL::search(oids,VirtualMachine::table,where); }; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int VirtualMachinePool::get_pending( vector<int>& oids) { ostringstream os; string where; os << "state = " << VirtualMachine::PENDING; where = os.str(); return PoolSQL::search(oids,VirtualMachine::table,where); }; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int VirtualMachinePool::dump_acct(ostringstream& oss, const string& where, int time_start, int time_end) { ostringstream cmd; cmd << "SELECT " << History::table << ".body FROM " << History::table << " INNER JOIN " << VirtualMachine::table << " WHERE vid=oid"; if ( !where.empty() ) { cmd << " AND " << where; } if ( time_start != -1 || time_end != -1 ) { if ( time_start != -1 ) { cmd << " AND (etime > " << time_start << " OR etime = 0)"; } if ( time_end != -1 ) { cmd << " AND stime < " << time_end; } } cmd << " GROUP BY vid,seq"; return PoolSQL::dump(oss, "HISTORY_RECORDS", cmd); }; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int VirtualMachinePool::clean_expired_monitoring() { if ( _monitor_expiration == 0 ) { return 0; } time_t max_last_poll; int rc; ostringstream oss; max_last_poll = time(0) - _monitor_expiration; oss << "DELETE FROM " << VirtualMachine::monit_table << " WHERE last_poll < " << max_last_poll; rc = db->exec(oss); return rc; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int VirtualMachinePool::clean_all_monitoring() { ostringstream oss; int rc; oss << "DELETE FROM " << VirtualMachine::monit_table; rc = db->exec(oss); return rc; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int VirtualMachinePool::dump_monitoring( ostringstream& oss, const string& where) { ostringstream cmd; cmd << "SELECT " << VirtualMachine::monit_table << ".body FROM " << VirtualMachine::monit_table << " INNER JOIN " << VirtualMachine::table << " WHERE vmid = oid"; if ( !where.empty() ) { cmd << " AND " << where; } cmd << " ORDER BY vmid, " << VirtualMachine::monit_table << ".last_poll;"; return PoolSQL::dump(oss, "MONITORING_DATA", cmd); } <commit_msg>Bug #2700: SQL query for VirtualMachinePool accounting now has ORDER BY instead of GROUP BY (which was a typo)<commit_after>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs */ /* */ /* 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 "VirtualMachinePool.h" #include "VirtualMachineHook.h" #include "NebulaLog.h" #include <sstream> /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ time_t VirtualMachinePool::_monitor_expiration; bool VirtualMachinePool::_submit_on_hold; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ VirtualMachinePool::VirtualMachinePool( SqlDB * db, vector<const Attribute *> hook_mads, const string& hook_location, const string& remotes_location, vector<const Attribute *>& restricted_attrs, time_t expire_time, bool on_hold) : PoolSQL(db, VirtualMachine::table, false) { const VectorAttribute * vattr; string name; string on; string cmd; string arg; bool remote; bool state_hook = false; _monitor_expiration = expire_time; _submit_on_hold = on_hold; if ( _monitor_expiration == 0 ) { clean_all_monitoring(); } for (unsigned int i = 0 ; i < hook_mads.size() ; i++ ) { vattr = static_cast<const VectorAttribute *>(hook_mads[i]); name = vattr->vector_value("NAME"); on = vattr->vector_value("ON"); cmd = vattr->vector_value("COMMAND"); arg = vattr->vector_value("ARGUMENTS"); vattr->vector_value("REMOTE", remote); transform (on.begin(),on.end(),on.begin(),(int(*)(int))toupper); if ( on.empty() || cmd.empty() ) { ostringstream oss; oss << "Empty ON or COMMAND attribute in VM_HOOK. Hook " << "not registered!"; NebulaLog::log("VM",Log::WARNING,oss); continue; } if ( name.empty() ) { name = cmd; } if (cmd[0] != '/') { ostringstream cmd_os; if ( remote ) { cmd_os << hook_location << "/" << cmd; } else { cmd_os << remotes_location << "/hooks/" << cmd; } cmd = cmd_os.str(); } if ( on == "CREATE" ) { AllocateHook * hook; hook = new AllocateHook(name, cmd, arg, false); add_hook(hook); } else if ( on == "PROLOG" ) { VirtualMachineStateHook * hook; hook = new VirtualMachineStateHook(name, cmd, arg, remote, VirtualMachine::PROLOG, VirtualMachine::ACTIVE); add_hook(hook); state_hook = true; } else if ( on == "RUNNING" ) { VirtualMachineStateHook * hook; hook = new VirtualMachineStateHook(name, cmd, arg, remote, VirtualMachine::RUNNING, VirtualMachine::ACTIVE); add_hook(hook); state_hook = true; } else if ( on == "SHUTDOWN" ) { VirtualMachineStateHook * hook; hook = new VirtualMachineStateHook(name, cmd, arg, remote, VirtualMachine::EPILOG, VirtualMachine::ACTIVE); add_hook(hook); state_hook = true; } else if ( on == "STOP" ) { VirtualMachineStateHook * hook; hook = new VirtualMachineStateHook(name, cmd, arg, remote, VirtualMachine::LCM_INIT, VirtualMachine::STOPPED); add_hook(hook); state_hook = true; } else if ( on == "DONE" ) { VirtualMachineStateHook * hook; hook = new VirtualMachineStateHook(name, cmd, arg, remote, VirtualMachine::LCM_INIT, VirtualMachine::DONE); add_hook(hook); state_hook = true; } else if ( on == "FAILED" ) { VirtualMachineStateHook * hook; hook = new VirtualMachineStateHook(name, cmd, arg, remote, VirtualMachine::LCM_INIT, VirtualMachine::FAILED); add_hook(hook); state_hook = true; } else if ( on == "UNKNOWN" ) { VirtualMachineStateHook * hook; hook = new VirtualMachineStateHook(name, cmd, arg, remote, VirtualMachine::UNKNOWN, VirtualMachine::ACTIVE); add_hook(hook); state_hook = true; } else if ( on == "CUSTOM" ) { VirtualMachineStateHook * hook; string lcm_str = vattr->vector_value("LCM_STATE"); string vm_str = vattr->vector_value("STATE"); VirtualMachine::LcmState lcm_state; VirtualMachine::VmState vm_state; if ( VirtualMachine::lcm_state_from_str(lcm_str, lcm_state) != 0 ) { ostringstream oss; oss << "Wrong LCM_STATE: "<< lcm_str <<". Hook not registered!"; NebulaLog::log("VM",Log::WARNING,oss); continue; } if ( VirtualMachine::vm_state_from_str(vm_str, vm_state) != 0 ) { ostringstream oss; oss << "Wrong STATE: "<< vm_str <<". Hook not registered!"; NebulaLog::log("VM",Log::WARNING,oss); continue; } hook = new VirtualMachineStateHook(name, cmd, arg, remote, lcm_state, vm_state); add_hook(hook); state_hook = true; } else { ostringstream oss; oss << "Unknown VM_HOOK " << on << ". Hook not registered!"; NebulaLog::log("VM",Log::WARNING,oss); } } if ( state_hook ) { VirtualMachineUpdateStateHook * hook; hook = new VirtualMachineUpdateStateHook(); add_hook(hook); } // Set restricted attributes VirtualMachineTemplate::set_restricted_attributes(restricted_attrs); } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int VirtualMachinePool::allocate ( int uid, int gid, const string& uname, const string& gname, int umask, VirtualMachineTemplate * vm_template, int * oid, string& error_str, bool on_hold) { VirtualMachine * vm; // ------------------------------------------------------------------------ // Build a new Virtual Machine object // ------------------------------------------------------------------------ vm = new VirtualMachine(-1, uid, gid, uname, gname, umask, vm_template); if ( _submit_on_hold == true || on_hold ) { vm->state = VirtualMachine::HOLD; } else { vm->state = VirtualMachine::PENDING; } // ------------------------------------------------------------------------ // Insert the Object in the pool // ------------------------------------------------------------------------ *oid = PoolSQL::allocate(vm, error_str); return *oid; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int VirtualMachinePool::get_running( vector<int>& oids, int vm_limit, time_t last_poll) { ostringstream os; string where; os << "last_poll <= " << last_poll << " and" << " state = " << VirtualMachine::ACTIVE << " and ( lcm_state = " << VirtualMachine::RUNNING << " or lcm_state = " << VirtualMachine::UNKNOWN << " )" << " ORDER BY last_poll ASC LIMIT " << vm_limit; where = os.str(); return PoolSQL::search(oids,VirtualMachine::table,where); }; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int VirtualMachinePool::get_pending( vector<int>& oids) { ostringstream os; string where; os << "state = " << VirtualMachine::PENDING; where = os.str(); return PoolSQL::search(oids,VirtualMachine::table,where); }; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int VirtualMachinePool::dump_acct(ostringstream& oss, const string& where, int time_start, int time_end) { ostringstream cmd; cmd << "SELECT " << History::table << ".body FROM " << History::table << " INNER JOIN " << VirtualMachine::table << " WHERE vid=oid"; if ( !where.empty() ) { cmd << " AND " << where; } if ( time_start != -1 || time_end != -1 ) { if ( time_start != -1 ) { cmd << " AND (etime > " << time_start << " OR etime = 0)"; } if ( time_end != -1 ) { cmd << " AND stime < " << time_end; } } cmd << " ORDER BY vid,seq"; return PoolSQL::dump(oss, "HISTORY_RECORDS", cmd); }; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int VirtualMachinePool::clean_expired_monitoring() { if ( _monitor_expiration == 0 ) { return 0; } time_t max_last_poll; int rc; ostringstream oss; max_last_poll = time(0) - _monitor_expiration; oss << "DELETE FROM " << VirtualMachine::monit_table << " WHERE last_poll < " << max_last_poll; rc = db->exec(oss); return rc; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int VirtualMachinePool::clean_all_monitoring() { ostringstream oss; int rc; oss << "DELETE FROM " << VirtualMachine::monit_table; rc = db->exec(oss); return rc; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ int VirtualMachinePool::dump_monitoring( ostringstream& oss, const string& where) { ostringstream cmd; cmd << "SELECT " << VirtualMachine::monit_table << ".body FROM " << VirtualMachine::monit_table << " INNER JOIN " << VirtualMachine::table << " WHERE vmid = oid"; if ( !where.empty() ) { cmd << " AND " << where; } cmd << " ORDER BY vmid, " << VirtualMachine::monit_table << ".last_poll;"; return PoolSQL::dump(oss, "MONITORING_DATA", cmd); } <|endoftext|>
<commit_before><commit_msg>Prediction: extract trajectory from semantic_LSTM<commit_after><|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (C) 2006-2010 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <vw/Core/Stopwatch.h> #include <vw/Plate/Index.h> #include <vw/Plate/Amqp.h> #include <vw/Plate/ProtoBuffers.pb.h> #include <vw/Plate/common.h> #include <vw/Plate/RpcServices.h> #include <vw/Plate/IndexService.h> #include <signal.h> #include <google/protobuf/descriptor.h> #ifdef VW_HAVE_PKG_TCMALLOC #include <google/heap-checker.h> #else class HeapLeakChecker { public: explicit HeapLeakChecker(const char* name) {std::cerr << "Using fake leak checker: " << name << std::endl;} bool NoLeaks() {return true;} ssize_t BytesLeaked() const {return 0;} }; #endif #include <boost/program_options.hpp> namespace po = boost::program_options; using namespace vw::platefile; using namespace vw; // Global variable. (Makes signal handling a lot easier...) boost::shared_ptr<IndexServiceImpl> g_service; // ------------------------------ SIGNAL HANDLER ------------------------------- volatile bool process_messages = true; volatile bool force_sync = false; void sig_unexpected_shutdown(int sig_num) { signal(sig_num, SIG_IGN); process_messages = false; signal(sig_num, sig_unexpected_shutdown); } void sig_sync(int sig_num) { signal(sig_num, SIG_IGN); force_sync = true; signal(sig_num, sig_sync); } // ------------------------------ MAIN LOOP ------------------------------- class ServerTask { boost::shared_ptr<AmqpRpcServer> m_server; public: ServerTask(boost::shared_ptr<AmqpRpcServer> server) : m_server(server) {} void operator()() { std::cout << "\t--> Listening for messages.\n"; m_server->run(); } void kill() { m_server->shutdown(); } }; // ------------------------------ MAIN ------------------------------- int main(int argc, char** argv) { std::string queue_name, root_directory; std::string hostname; int port; po::options_description general_options("Runs a mosaicking daemon that listens for mosaicking requests coming in over the AMQP bus..\n\nGeneral Options:"); general_options.add_options() ("queue_name,q", po::value<std::string>(&queue_name)->default_value("index"), "Specify the name of the AMQP queue to create and listen to for mosaicking requests. (Defaults to the \"ngt_mosaic_worker\" queue.") ("hostname,h", po::value<std::string>(&hostname)->default_value("localhost"), "Specify the hostname of the AMQP server to use for remote procedure calls (RPCs).") ("port,p", po::value<int>(&port)->default_value(5672), "Specify the port of the AMQP server to use for remote procedure calls (RPCs).") ("debug", "Output debug messages.") ("help", "Display this help message"); po::options_description hidden_options(""); hidden_options.add_options() ("root-directory", po::value<std::string>(&root_directory)); po::options_description options("Allowed Options"); options.add(general_options).add(hidden_options); po::positional_options_description p; p.add("root-directory", -1); po::variables_map vm; po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm ); po::notify( vm ); std::ostringstream usage; usage << "Usage: " << argv[0] << " [-q <queue name>] root_directory" <<std::endl << std::endl; usage << general_options << std::endl; if( vm.count("help") ) { std::cout << usage.str(); return 0; } if( vm.count("root-directory") != 1 ) { std::cerr << "Error: must specify a root directory that contains plate files!" << std::endl << std::endl; std::cout << usage.str(); return 1; } boost::shared_ptr<AmqpConnection> connection( new AmqpConnection(hostname, port) ); boost::shared_ptr<AmqpRpcServer> server( new AmqpRpcServer(connection, INDEX_EXCHANGE, queue_name, vm.count("debug")) ); g_service.reset( new IndexServiceImpl(root_directory) ); server->bind_service(g_service, "index"); // Start the server task in another thread boost::shared_ptr<ServerTask> server_task( new ServerTask(server) ); Thread server_thread( server_task ); // Install Unix Signal Handlers. These will help us to gracefully // recover and salvage the index under most unexpected error // conditions. signal(SIGINT, sig_unexpected_shutdown); signal(SIGUSR1, sig_sync); std::cout << "\n\n"; long long t0 = Stopwatch::microtime(); HeapLeakChecker checker_end("testing_at_end"); { HeapLeakChecker checker_sync("testing_force_sync"); while(process_messages) { if (force_sync) { std::cout << "Syncing." << std::endl; g_service->sync(); if (!checker_sync.NoLeaks()) std::cout << "Leaked " << checker_sync.BytesLeaked() << " bytes" << std::endl; force_sync = false; } int queries = server->queries_processed(); size_t bytes = server->bytes_processed(); int n_outstanding_messages = server->incoming_message_queue_size(); server->reset_stats(); float dt = float(Stopwatch::microtime() - t0) / 1e6; t0 = Stopwatch::microtime(); std::cout << "[index_server] : " << float(queries/dt) << " qps " << float(bytes/dt)/1000.0 << " kB/sec " << n_outstanding_messages << " outstanding messages \r" << std::flush; sleep(1.0); } } std::cout << "\nShutting down the index service safely.\n"; g_service->sync(); if (!checker_end.NoLeaks()) std::cout << "Leaked " << checker_end.BytesLeaked() << " bytes at end" << std::endl; return 0; } <commit_msg>NoLeaks does its own printing.<commit_after>// __BEGIN_LICENSE__ // Copyright (C) 2006-2010 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <vw/Core/Stopwatch.h> #include <vw/Plate/Index.h> #include <vw/Plate/Amqp.h> #include <vw/Plate/ProtoBuffers.pb.h> #include <vw/Plate/common.h> #include <vw/Plate/RpcServices.h> #include <vw/Plate/IndexService.h> #include <signal.h> #include <google/protobuf/descriptor.h> #ifdef VW_HAVE_PKG_TCMALLOC #include <google/heap-checker.h> #else class HeapLeakChecker { public: explicit HeapLeakChecker(const char* name) {std::cerr << "Using fake leak checker: " << name << std::endl;} bool NoLeaks() {return true;} ssize_t BytesLeaked() const {return 0;} }; #endif #include <boost/program_options.hpp> namespace po = boost::program_options; using namespace vw::platefile; using namespace vw; // Global variable. (Makes signal handling a lot easier...) boost::shared_ptr<IndexServiceImpl> g_service; // ------------------------------ SIGNAL HANDLER ------------------------------- volatile bool process_messages = true; volatile bool force_sync = false; void sig_unexpected_shutdown(int sig_num) { signal(sig_num, SIG_IGN); process_messages = false; signal(sig_num, sig_unexpected_shutdown); } void sig_sync(int sig_num) { signal(sig_num, SIG_IGN); force_sync = true; signal(sig_num, sig_sync); } // ------------------------------ MAIN LOOP ------------------------------- class ServerTask { boost::shared_ptr<AmqpRpcServer> m_server; public: ServerTask(boost::shared_ptr<AmqpRpcServer> server) : m_server(server) {} void operator()() { std::cout << "\t--> Listening for messages.\n"; m_server->run(); } void kill() { m_server->shutdown(); } }; // ------------------------------ MAIN ------------------------------- int main(int argc, char** argv) { std::string queue_name, root_directory; std::string hostname; int port; po::options_description general_options("Runs a mosaicking daemon that listens for mosaicking requests coming in over the AMQP bus..\n\nGeneral Options:"); general_options.add_options() ("queue_name,q", po::value<std::string>(&queue_name)->default_value("index"), "Specify the name of the AMQP queue to create and listen to for mosaicking requests. (Defaults to the \"ngt_mosaic_worker\" queue.") ("hostname,h", po::value<std::string>(&hostname)->default_value("localhost"), "Specify the hostname of the AMQP server to use for remote procedure calls (RPCs).") ("port,p", po::value<int>(&port)->default_value(5672), "Specify the port of the AMQP server to use for remote procedure calls (RPCs).") ("debug", "Output debug messages.") ("help", "Display this help message"); po::options_description hidden_options(""); hidden_options.add_options() ("root-directory", po::value<std::string>(&root_directory)); po::options_description options("Allowed Options"); options.add(general_options).add(hidden_options); po::positional_options_description p; p.add("root-directory", -1); po::variables_map vm; po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm ); po::notify( vm ); std::ostringstream usage; usage << "Usage: " << argv[0] << " [-q <queue name>] root_directory" <<std::endl << std::endl; usage << general_options << std::endl; if( vm.count("help") ) { std::cout << usage.str(); return 0; } if( vm.count("root-directory") != 1 ) { std::cerr << "Error: must specify a root directory that contains plate files!" << std::endl << std::endl; std::cout << usage.str(); return 1; } boost::shared_ptr<AmqpConnection> connection( new AmqpConnection(hostname, port) ); boost::shared_ptr<AmqpRpcServer> server( new AmqpRpcServer(connection, INDEX_EXCHANGE, queue_name, vm.count("debug")) ); g_service.reset( new IndexServiceImpl(root_directory) ); server->bind_service(g_service, "index"); // Start the server task in another thread boost::shared_ptr<ServerTask> server_task( new ServerTask(server) ); Thread server_thread( server_task ); // Install Unix Signal Handlers. These will help us to gracefully // recover and salvage the index under most unexpected error // conditions. signal(SIGINT, sig_unexpected_shutdown); signal(SIGUSR1, sig_sync); std::cout << "\n\n"; long long t0 = Stopwatch::microtime(); HeapLeakChecker checker_end("testing_at_end"); { HeapLeakChecker checker_sync("testing_force_sync"); while(process_messages) { if (force_sync) { std::cout << "Syncing." << std::endl; g_service->sync(); checker_sync.NoLeaks(); force_sync = false; } int queries = server->queries_processed(); size_t bytes = server->bytes_processed(); int n_outstanding_messages = server->incoming_message_queue_size(); server->reset_stats(); float dt = float(Stopwatch::microtime() - t0) / 1e6; t0 = Stopwatch::microtime(); std::cout << "[index_server] : " << float(queries/dt) << " qps " << float(bytes/dt)/1000.0 << " kB/sec " << n_outstanding_messages << " outstanding messages \r" << std::flush; sleep(1.0); } } std::cout << "\nShutting down the index service safely.\n"; g_service->sync(); checker_end.NoLeaks(); return 0; } <|endoftext|>
<commit_before>/********************************************************************* * * Copyright (C) 2007, Simon Kagstrom * * Filename: emit.hh * Author: Simon Kagstrom <[email protected]> * Description: Emitter * * $Id:$ * ********************************************************************/ #ifndef __EMIT_HH__ #define __EMIT_HH__ #include <stdint.h> #include <registerallocator.hh> class Emit { public: Emit(); void bc_comment(const char *what) { this->output("; "); this->write((char*)what); } void bc_generic(const char *what, ...); void bc_generic_insn(const char *what) { this->writeIndent(what); } void bc_label(const char *what, ...); void bc_goto(uint32_t dst) { this->writeIndent("goto L_%x", dst); } void bc_goto(const char *where) { this->writeIndent("goto %s", where); } void bc_condbranch(const char *what, ...); void bc_pushconst(int32_t nr); void bc_pushconst_u(uint32_t nr); void bc_pushregister(MIPS_register_t reg); void bc_popregister(MIPS_register_t reg); void bc_pushindex(MIPS_register_t reg, int32_t extra); void bc_pushaddress(MIPS_register_t reg, int32_t extra); void bc_getstatic(const char *what) { this->writeIndent("getstatic %s", what); } void bc_putstatic(const char *what) { this->writeIndent("putstatic %s", what); } void bc_iload(int n); void bc_istore(int n); void bc_ldc(char *str) { this->writeIndent("ldc \"%s\"", str); } void bc_iadd() { this->writeIndent("iadd"); } void bc_iinc(MIPS_register_t reg, int extra); void bc_isub() { this->writeIndent("isub"); } void bc_invokestatic(const char *what, ...); void bc_lookupswitch(int n, uint32_t *table, const char *def); void bc_iushr() { this->writeIndent("iushr"); } void bc_lushr() { this->writeIndent("lushr"); } void bc_imul() { this->writeIndent("imul"); } void bc_idiv() { this->writeIndent("idiv"); } void bc_irem() { this->writeIndent("irem"); } void bc_ineg() { this->writeIndent("ineg"); } void bc_ior() { this->writeIndent("ior"); } void bc_ixor() { this->writeIndent("ixor"); } void bc_lmul() { this->writeIndent("lmul"); } void bc_dup() { this->writeIndent("dup"); } void bc_dup2() { this->writeIndent("dup2"); } void bc_pop() { this->writeIndent("pop"); } void bc_pop2() { this->writeIndent("pop2"); } void bc_i2l() { this->writeIndent("i2l"); } void bc_l2i() { this->writeIndent("l2i"); } void bc_swap() { this->writeIndent("swap"); } void bc_iaload() { this->writeIndent("iaload"); } void bc_iastore() { this->writeIndent("iastore"); } void bc_ireturn() { this->writeIndent("ireturn"); } void bc_return() { this->writeIndent("return"); } void error(const char *dst, ...); void warning(const char *dst, ...); void setOutputFile(FILE *fp); private: void bc_load_store_helper(const char *type, int nr); void write(const char *dst, ...); void writeIndent(const char *dst, ...); void output(char *what); FILE *fp; }; extern Emit *emit; #endif /* !__EMIT_HH__ */ <commit_msg>include stdio.h<commit_after>/********************************************************************* * * Copyright (C) 2007, Simon Kagstrom * * Filename: emit.hh * Author: Simon Kagstrom <[email protected]> * Description: Emitter * * $Id:$ * ********************************************************************/ #ifndef __EMIT_HH__ #define __EMIT_HH__ #include <stdio.h> #include <stdint.h> #include <registerallocator.hh> class Emit { public: Emit(); void bc_comment(const char *what) { this->output("; "); this->write((char*)what); } void bc_generic(const char *what, ...); void bc_generic_insn(const char *what) { this->writeIndent(what); } void bc_label(const char *what, ...); void bc_goto(uint32_t dst) { this->writeIndent("goto L_%x", dst); } void bc_goto(const char *where) { this->writeIndent("goto %s", where); } void bc_condbranch(const char *what, ...); void bc_pushconst(int32_t nr); void bc_pushconst_u(uint32_t nr); void bc_pushregister(MIPS_register_t reg); void bc_popregister(MIPS_register_t reg); void bc_pushindex(MIPS_register_t reg, int32_t extra); void bc_pushaddress(MIPS_register_t reg, int32_t extra); void bc_getstatic(const char *what) { this->writeIndent("getstatic %s", what); } void bc_putstatic(const char *what) { this->writeIndent("putstatic %s", what); } void bc_iload(int n); void bc_istore(int n); void bc_ldc(char *str) { this->writeIndent("ldc \"%s\"", str); } void bc_iadd() { this->writeIndent("iadd"); } void bc_iinc(MIPS_register_t reg, int extra); void bc_isub() { this->writeIndent("isub"); } void bc_invokestatic(const char *what, ...); void bc_lookupswitch(int n, uint32_t *table, const char *def); void bc_iushr() { this->writeIndent("iushr"); } void bc_lushr() { this->writeIndent("lushr"); } void bc_imul() { this->writeIndent("imul"); } void bc_idiv() { this->writeIndent("idiv"); } void bc_irem() { this->writeIndent("irem"); } void bc_ineg() { this->writeIndent("ineg"); } void bc_ior() { this->writeIndent("ior"); } void bc_ixor() { this->writeIndent("ixor"); } void bc_lmul() { this->writeIndent("lmul"); } void bc_dup() { this->writeIndent("dup"); } void bc_dup2() { this->writeIndent("dup2"); } void bc_pop() { this->writeIndent("pop"); } void bc_pop2() { this->writeIndent("pop2"); } void bc_i2l() { this->writeIndent("i2l"); } void bc_l2i() { this->writeIndent("l2i"); } void bc_swap() { this->writeIndent("swap"); } void bc_iaload() { this->writeIndent("iaload"); } void bc_iastore() { this->writeIndent("iastore"); } void bc_ireturn() { this->writeIndent("ireturn"); } void bc_return() { this->writeIndent("return"); } void error(const char *dst, ...); void warning(const char *dst, ...); void setOutputFile(FILE *fp); private: void bc_load_store_helper(const char *type, int nr); void write(const char *dst, ...); void writeIndent(const char *dst, ...); void output(char *what); FILE *fp; }; extern Emit *emit; #endif /* !__EMIT_HH__ */ <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/ime_adapter_android.h" #include <android/input.h> #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/strings/utf_string_conversions.h" #include "base/time.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/browser/renderer_host/render_widget_host_view_android.h" #include "content/common/view_messages.h" #include "content/public/browser/native_web_keyboard_event.h" #include "jni/ImeAdapter_jni.h" #include "third_party/WebKit/public/web/WebCompositionUnderline.h" #include "third_party/WebKit/public/web/WebInputEvent.h" using base::android::AttachCurrentThread; using base::android::ConvertJavaStringToUTF16; namespace content { namespace { // Maps a java KeyEvent into a NativeWebKeyboardEvent. // |java_key_event| is used to maintain a globalref for KeyEvent. // |action| will help determine the WebInputEvent type. // type, |modifiers|, |time_ms|, |key_code|, |unicode_char| is used to create // WebKeyboardEvent. |key_code| is also needed ad need to treat the enter key // as a key press of character \r. NativeWebKeyboardEvent NativeWebKeyboardEventFromKeyEvent( JNIEnv* env, jobject java_key_event, int action, int modifiers, long time_ms, int key_code, bool is_system_key, int unicode_char) { WebKit::WebInputEvent::Type type = WebKit::WebInputEvent::Undefined; if (action == AKEY_EVENT_ACTION_DOWN) type = WebKit::WebInputEvent::RawKeyDown; else if (action == AKEY_EVENT_ACTION_UP) type = WebKit::WebInputEvent::KeyUp; return NativeWebKeyboardEvent(java_key_event, type, modifiers, time_ms, key_code, unicode_char, is_system_key); } } // anonymous namespace bool RegisterImeAdapter(JNIEnv* env) { if (!RegisterNativesImpl(env)) return false; Java_ImeAdapter_initializeWebInputEvents(env, WebKit::WebInputEvent::RawKeyDown, WebKit::WebInputEvent::KeyUp, WebKit::WebInputEvent::Char, WebKit::WebInputEvent::ShiftKey, WebKit::WebInputEvent::AltKey, WebKit::WebInputEvent::ControlKey, WebKit::WebInputEvent::CapsLockOn, WebKit::WebInputEvent::NumLockOn); // TODO(miguelg): remove date time related enums after // https://bugs.webkit.org/show_bug.cgi?id=100935. Java_ImeAdapter_initializeTextInputTypes( env, ui::TEXT_INPUT_TYPE_NONE, ui::TEXT_INPUT_TYPE_TEXT, ui::TEXT_INPUT_TYPE_TEXT_AREA, ui::TEXT_INPUT_TYPE_PASSWORD, ui::TEXT_INPUT_TYPE_SEARCH, ui::TEXT_INPUT_TYPE_URL, ui::TEXT_INPUT_TYPE_EMAIL, ui::TEXT_INPUT_TYPE_TELEPHONE, ui::TEXT_INPUT_TYPE_NUMBER, ui::TEXT_INPUT_TYPE_DATE, ui::TEXT_INPUT_TYPE_DATE_TIME, ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL, ui::TEXT_INPUT_TYPE_MONTH, ui::TEXT_INPUT_TYPE_TIME, ui::TEXT_INPUT_TYPE_WEEK, ui::TEXT_INPUT_TYPE_CONTENT_EDITABLE); return true; } ImeAdapterAndroid::ImeAdapterAndroid(RenderWidgetHostViewAndroid* rwhva) : rwhva_(rwhva) { } ImeAdapterAndroid::~ImeAdapterAndroid() { JNIEnv* env = AttachCurrentThread(); base::android::ScopedJavaLocalRef<jobject> obj = java_ime_adapter_.get(env); if (!obj.is_null()) Java_ImeAdapter_detach(env, obj.obj()); } bool ImeAdapterAndroid::SendSyntheticKeyEvent(JNIEnv*, jobject, int type, long time_ms, int key_code, int text) { NativeWebKeyboardEvent event(static_cast<WebKit::WebInputEvent::Type>(type), 0 /* modifiers */, time_ms / 1000.0, key_code, text, false /* is_system_key */); rwhva_->SendKeyEvent(event); return true; } bool ImeAdapterAndroid::SendKeyEvent(JNIEnv* env, jobject, jobject original_key_event, int action, int modifiers, long time_ms, int key_code, bool is_system_key, int unicode_char) { NativeWebKeyboardEvent event = NativeWebKeyboardEventFromKeyEvent( env, original_key_event, action, modifiers, time_ms, key_code, is_system_key, unicode_char); rwhva_->SendKeyEvent(event); if (event.type == WebKit::WebInputEvent::RawKeyDown && event.text[0]) { // Send a Char event, but without an os_event since we don't want to // roundtrip back to java such synthetic event. NativeWebKeyboardEvent char_event(event); char_event.os_event = NULL; event.type = WebKit::WebInputEvent::Char; rwhva_->SendKeyEvent(event); } return true; } void ImeAdapterAndroid::SetComposingText(JNIEnv* env, jobject, jstring text, int new_cursor_pos) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; string16 text16 = ConvertJavaStringToUTF16(env, text); std::vector<WebKit::WebCompositionUnderline> underlines; underlines.push_back( WebKit::WebCompositionUnderline(0, text16.length(), SK_ColorBLACK, false)); // new_cursor_position is as described in the Android API for // InputConnection#setComposingText, whereas the parameters for // ImeSetComposition are relative to the start of the composition. if (new_cursor_pos > 0) new_cursor_pos = text16.length() + new_cursor_pos - 1; rwhi->ImeSetComposition(text16, underlines, new_cursor_pos, new_cursor_pos); } void ImeAdapterAndroid::ImeBatchStateChanged(JNIEnv* env, jobject, jboolean is_begin) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; rwhi->Send(new ViewMsg_ImeBatchStateChanged(rwhi->GetRoutingID(), is_begin)); } void ImeAdapterAndroid::CommitText(JNIEnv* env, jobject, jstring text) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; string16 text16 = ConvertJavaStringToUTF16(env, text); rwhi->ImeConfirmComposition(text16); } void ImeAdapterAndroid::AttachImeAdapter(JNIEnv* env, jobject java_object) { java_ime_adapter_ = JavaObjectWeakGlobalRef(env, java_object); } void ImeAdapterAndroid::CancelComposition() { base::android::ScopedJavaLocalRef<jobject> obj = java_ime_adapter_.get(AttachCurrentThread()); if (!obj.is_null()) Java_ImeAdapter_cancelComposition(AttachCurrentThread(), obj.obj()); } void ImeAdapterAndroid::SetEditableSelectionOffsets(JNIEnv*, jobject, int start, int end) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; rwhi->Send(new ViewMsg_SetEditableSelectionOffsets(rwhi->GetRoutingID(), start, end)); } void ImeAdapterAndroid::SetComposingRegion(JNIEnv*, jobject, int start, int end) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; std::vector<WebKit::WebCompositionUnderline> underlines; underlines.push_back( WebKit::WebCompositionUnderline(0, end - start, SK_ColorBLACK, false)); rwhi->Send(new ViewMsg_SetCompositionFromExistingText( rwhi->GetRoutingID(), start, end, underlines)); } void ImeAdapterAndroid::DeleteSurroundingText(JNIEnv*, jobject, int before, int after) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; rwhi->Send(new ViewMsg_ExtendSelectionAndDelete(rwhi->GetRoutingID(), before, after)); } void ImeAdapterAndroid::Unselect(JNIEnv* env, jobject) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; rwhi->Unselect(); } void ImeAdapterAndroid::SelectAll(JNIEnv* env, jobject) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; rwhi->SelectAll(); } void ImeAdapterAndroid::Cut(JNIEnv* env, jobject) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; rwhi->Cut(); } void ImeAdapterAndroid::Copy(JNIEnv* env, jobject) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; rwhi->Copy(); } void ImeAdapterAndroid::Paste(JNIEnv* env, jobject) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; rwhi->Paste(); } void ImeAdapterAndroid::ResetImeAdapter(JNIEnv* env, jobject) { java_ime_adapter_.reset(); } } // namespace content <commit_msg>[Android] Change "handling" of unhandled key events. When we receive an IME Key Down event in Android, we forward it to WebKit for processing as RawKeyDown, followed by a WebInputEvent::Char if it had a character associated with it. When typing into a text field or textarea, if the RawKeyDown triggers an editing event it will go unhandled by WebKit, and it's the subsequent Char event that WebKit handles. The unhandled RawKeyDown is propogated back down to the Browser and out to the embedder. In the Android WebView where we then propogate the unhandled event to the WebView embedder. However - as the Char event is going to be handled by the textarea later, informing the embedder that the KeyDown wasn't handled isn't what it expects and we shouldn't do so. We should only propogate an unhandled Char event to the WebView embedder. This CL fixes this by using the NativeWebKeyboardEvent.skip_in_browser flag to prevent browser side handling of the RawKeyDown. It also fixes a bug in the propogation of the synthetic Char event.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/renderer_host/ime_adapter_android.h" #include <android/input.h> #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/strings/utf_string_conversions.h" #include "base/time.h" #include "content/browser/renderer_host/render_widget_host_impl.h" #include "content/browser/renderer_host/render_widget_host_view_android.h" #include "content/common/view_messages.h" #include "content/public/browser/native_web_keyboard_event.h" #include "jni/ImeAdapter_jni.h" #include "third_party/WebKit/public/web/WebCompositionUnderline.h" #include "third_party/WebKit/public/web/WebInputEvent.h" using base::android::AttachCurrentThread; using base::android::ConvertJavaStringToUTF16; namespace content { namespace { // Maps a java KeyEvent into a NativeWebKeyboardEvent. // |java_key_event| is used to maintain a globalref for KeyEvent. // |action| will help determine the WebInputEvent type. // type, |modifiers|, |time_ms|, |key_code|, |unicode_char| is used to create // WebKeyboardEvent. |key_code| is also needed ad need to treat the enter key // as a key press of character \r. NativeWebKeyboardEvent NativeWebKeyboardEventFromKeyEvent( JNIEnv* env, jobject java_key_event, int action, int modifiers, long time_ms, int key_code, bool is_system_key, int unicode_char) { WebKit::WebInputEvent::Type type = WebKit::WebInputEvent::Undefined; if (action == AKEY_EVENT_ACTION_DOWN) type = WebKit::WebInputEvent::RawKeyDown; else if (action == AKEY_EVENT_ACTION_UP) type = WebKit::WebInputEvent::KeyUp; return NativeWebKeyboardEvent(java_key_event, type, modifiers, time_ms, key_code, unicode_char, is_system_key); } } // anonymous namespace bool RegisterImeAdapter(JNIEnv* env) { if (!RegisterNativesImpl(env)) return false; Java_ImeAdapter_initializeWebInputEvents(env, WebKit::WebInputEvent::RawKeyDown, WebKit::WebInputEvent::KeyUp, WebKit::WebInputEvent::Char, WebKit::WebInputEvent::ShiftKey, WebKit::WebInputEvent::AltKey, WebKit::WebInputEvent::ControlKey, WebKit::WebInputEvent::CapsLockOn, WebKit::WebInputEvent::NumLockOn); // TODO(miguelg): remove date time related enums after // https://bugs.webkit.org/show_bug.cgi?id=100935. Java_ImeAdapter_initializeTextInputTypes( env, ui::TEXT_INPUT_TYPE_NONE, ui::TEXT_INPUT_TYPE_TEXT, ui::TEXT_INPUT_TYPE_TEXT_AREA, ui::TEXT_INPUT_TYPE_PASSWORD, ui::TEXT_INPUT_TYPE_SEARCH, ui::TEXT_INPUT_TYPE_URL, ui::TEXT_INPUT_TYPE_EMAIL, ui::TEXT_INPUT_TYPE_TELEPHONE, ui::TEXT_INPUT_TYPE_NUMBER, ui::TEXT_INPUT_TYPE_DATE, ui::TEXT_INPUT_TYPE_DATE_TIME, ui::TEXT_INPUT_TYPE_DATE_TIME_LOCAL, ui::TEXT_INPUT_TYPE_MONTH, ui::TEXT_INPUT_TYPE_TIME, ui::TEXT_INPUT_TYPE_WEEK, ui::TEXT_INPUT_TYPE_CONTENT_EDITABLE); return true; } ImeAdapterAndroid::ImeAdapterAndroid(RenderWidgetHostViewAndroid* rwhva) : rwhva_(rwhva) { } ImeAdapterAndroid::~ImeAdapterAndroid() { JNIEnv* env = AttachCurrentThread(); base::android::ScopedJavaLocalRef<jobject> obj = java_ime_adapter_.get(env); if (!obj.is_null()) Java_ImeAdapter_detach(env, obj.obj()); } bool ImeAdapterAndroid::SendSyntheticKeyEvent(JNIEnv*, jobject, int type, long time_ms, int key_code, int text) { NativeWebKeyboardEvent event(static_cast<WebKit::WebInputEvent::Type>(type), 0 /* modifiers */, time_ms / 1000.0, key_code, text, false /* is_system_key */); rwhva_->SendKeyEvent(event); return true; } bool ImeAdapterAndroid::SendKeyEvent(JNIEnv* env, jobject, jobject original_key_event, int action, int modifiers, long time_ms, int key_code, bool is_system_key, int unicode_char) { NativeWebKeyboardEvent event = NativeWebKeyboardEventFromKeyEvent( env, original_key_event, action, modifiers, time_ms, key_code, is_system_key, unicode_char); bool key_down_text_insertion = event.type == WebKit::WebInputEvent::RawKeyDown && event.text[0]; // If we are going to follow up with a synthetic Char event, then that's the // one we expect to test if it's handled or unhandled, so skip handling the // "real" event in the browser. event.skip_in_browser = key_down_text_insertion; rwhva_->SendKeyEvent(event); if (key_down_text_insertion) { // Send a Char event, but without an os_event since we don't want to // roundtrip back to java such synthetic event. NativeWebKeyboardEvent char_event(event); char_event.os_event = NULL; char_event.type = WebKit::WebInputEvent::Char; rwhva_->SendKeyEvent(char_event); } return true; } void ImeAdapterAndroid::SetComposingText(JNIEnv* env, jobject, jstring text, int new_cursor_pos) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; string16 text16 = ConvertJavaStringToUTF16(env, text); std::vector<WebKit::WebCompositionUnderline> underlines; underlines.push_back( WebKit::WebCompositionUnderline(0, text16.length(), SK_ColorBLACK, false)); // new_cursor_position is as described in the Android API for // InputConnection#setComposingText, whereas the parameters for // ImeSetComposition are relative to the start of the composition. if (new_cursor_pos > 0) new_cursor_pos = text16.length() + new_cursor_pos - 1; rwhi->ImeSetComposition(text16, underlines, new_cursor_pos, new_cursor_pos); } void ImeAdapterAndroid::ImeBatchStateChanged(JNIEnv* env, jobject, jboolean is_begin) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; rwhi->Send(new ViewMsg_ImeBatchStateChanged(rwhi->GetRoutingID(), is_begin)); } void ImeAdapterAndroid::CommitText(JNIEnv* env, jobject, jstring text) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; string16 text16 = ConvertJavaStringToUTF16(env, text); rwhi->ImeConfirmComposition(text16); } void ImeAdapterAndroid::AttachImeAdapter(JNIEnv* env, jobject java_object) { java_ime_adapter_ = JavaObjectWeakGlobalRef(env, java_object); } void ImeAdapterAndroid::CancelComposition() { base::android::ScopedJavaLocalRef<jobject> obj = java_ime_adapter_.get(AttachCurrentThread()); if (!obj.is_null()) Java_ImeAdapter_cancelComposition(AttachCurrentThread(), obj.obj()); } void ImeAdapterAndroid::SetEditableSelectionOffsets(JNIEnv*, jobject, int start, int end) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; rwhi->Send(new ViewMsg_SetEditableSelectionOffsets(rwhi->GetRoutingID(), start, end)); } void ImeAdapterAndroid::SetComposingRegion(JNIEnv*, jobject, int start, int end) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; std::vector<WebKit::WebCompositionUnderline> underlines; underlines.push_back( WebKit::WebCompositionUnderline(0, end - start, SK_ColorBLACK, false)); rwhi->Send(new ViewMsg_SetCompositionFromExistingText( rwhi->GetRoutingID(), start, end, underlines)); } void ImeAdapterAndroid::DeleteSurroundingText(JNIEnv*, jobject, int before, int after) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; rwhi->Send(new ViewMsg_ExtendSelectionAndDelete(rwhi->GetRoutingID(), before, after)); } void ImeAdapterAndroid::Unselect(JNIEnv* env, jobject) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; rwhi->Unselect(); } void ImeAdapterAndroid::SelectAll(JNIEnv* env, jobject) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; rwhi->SelectAll(); } void ImeAdapterAndroid::Cut(JNIEnv* env, jobject) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; rwhi->Cut(); } void ImeAdapterAndroid::Copy(JNIEnv* env, jobject) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; rwhi->Copy(); } void ImeAdapterAndroid::Paste(JNIEnv* env, jobject) { RenderWidgetHostImpl* rwhi = RenderWidgetHostImpl::From( rwhva_->GetRenderWidgetHost()); if (!rwhi) return; rwhi->Paste(); } void ImeAdapterAndroid::ResetImeAdapter(JNIEnv* env, jobject) { java_ime_adapter_.reset(); } } // namespace content <|endoftext|>
<commit_before>#ifndef ITER_POWERSET_HPP_ #define ITER_POWERSET_HPP_ #include "combinations.hpp" #include "internal/iterbase.hpp" #include <cassert> #include <initializer_list> #include <iterator> #include <memory> #include <type_traits> #include <utility> namespace iter { namespace impl { template <typename Container> class Powersetter; using PowersetFn = IterToolFn<Powersetter>; } constexpr impl::PowersetFn powerset{}; } template <typename Container> class iter::impl::Powersetter { private: Container container_; using CombinatorType = decltype(combinations(std::declval<Container&>(), 0)); friend PowersetFn; Powersetter(Container&& container) : container_(std::forward<Container>(container)) {} public: Powersetter(Powersetter&&) = default; class Iterator : public std::iterator<std::input_iterator_tag, CombinatorType> { private: std::remove_reference_t<Container>* container_p_; std::size_t set_size_{}; std::shared_ptr<CombinatorType> comb_; iterator_type<CombinatorType> comb_iter_; iterator_type<CombinatorType> comb_end_; public: Iterator(Container& container, std::size_t sz) : container_p_{&container}, set_size_{sz}, comb_{std::make_shared<CombinatorType>(combinations(container, sz))}, comb_iter_{get_begin(*comb_)}, comb_end_{get_end(*comb_)} {} Iterator& operator++() { ++comb_iter_; if (comb_iter_ == comb_end_) { ++set_size_; comb_ = std::make_shared<CombinatorType>( combinations(*container_p_, set_size_)); comb_iter_ = get_begin(*comb_); comb_end_ = get_end(*comb_); } return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } iterator_deref<CombinatorType> operator*() { return *comb_iter_; } iterator_arrow<CombinatorType> operator->() { apply_arrow(comb_iter_); } bool operator!=(const Iterator& other) const { return !(*this == other); } bool operator==(const Iterator& other) const { return set_size_ == other.set_size_ && comb_iter_ == other.comb_iter_; } }; Iterator begin() { return {container_, 0}; } Iterator end() { return {container_, dumb_size(container_) + 1}; } }; #endif <commit_msg>Adds support for const iteration to powerset<commit_after>#ifndef ITER_POWERSET_HPP_ #define ITER_POWERSET_HPP_ #include "combinations.hpp" #include "internal/iterbase.hpp" #include <cassert> #include <initializer_list> #include <iterator> #include <memory> #include <type_traits> #include <utility> namespace iter { namespace impl { template <typename Container> class Powersetter; using PowersetFn = IterToolFn<Powersetter>; } constexpr impl::PowersetFn powerset{}; } template <typename Container> class iter::impl::Powersetter { private: Container container_; template <typename T> using CombinatorType = decltype(combinations(std::declval<T&>(), 0)); friend PowersetFn; Powersetter(Container&& container) : container_(std::forward<Container>(container)) {} public: Powersetter(Powersetter&&) = default; template <typename ContainerT> class Iterator : public std::iterator<std::input_iterator_tag, CombinatorType<ContainerT>> { private: #if 0 template <typename> friend class Iterator; #endif std::remove_reference_t<ContainerT>* container_p_; std::size_t set_size_{}; std::shared_ptr<CombinatorType<ContainerT>> comb_; iterator_type<CombinatorType<ContainerT>> comb_iter_; iterator_type<CombinatorType<ContainerT>> comb_end_; public: Iterator(ContainerT& container, std::size_t sz) : container_p_{&container}, set_size_{sz}, comb_{std::make_shared<CombinatorType<ContainerT>>( combinations(container, sz))}, comb_iter_{get_begin(*comb_)}, comb_end_{get_end(*comb_)} {} Iterator& operator++() { ++comb_iter_; if (comb_iter_ == comb_end_) { ++set_size_; comb_ = std::make_shared<CombinatorType<ContainerT>>( combinations(*container_p_, set_size_)); comb_iter_ = get_begin(*comb_); comb_end_ = get_end(*comb_); } return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } iterator_deref<CombinatorType<ContainerT>> operator*() { return *comb_iter_; } iterator_arrow<CombinatorType<ContainerT>> operator->() { apply_arrow(comb_iter_); } bool operator!=(const Iterator& other) const { return !(*this == other); } bool operator==(const Iterator& other) const { return set_size_ == other.set_size_ && comb_iter_ == other.comb_iter_; } #if 0 template <typename T> bool operator!=(const Iterator<T>& other) const { return !(*this == other); } template <typename T> bool operator==(const Iterator<T>& other) const { return set_size_ == other.set_size_ && comb_iter_ == other.comb_iter_; } #endif }; Iterator<Container> begin() { return {container_, 0}; } Iterator<Container> end() { return {container_, dumb_size(container_) + 1}; } Iterator<AsConst<Container>> begin() const { return {as_const(container_), 0}; } Iterator<AsConst<Container>> end() const { return {as_const(container_), dumb_size(as_const(container_)) + 1}; } }; #endif <|endoftext|>
<commit_before>#include <xzero/raft/ServerUtil.h> #include <xzero/Random.h> namespace xzero { namespace raft { Duration ServerUtil::alleviatedDuration(Duration base) { static Random rng_; auto emin = base.milliseconds() / 2; auto emax = base.milliseconds(); auto e = emin + rng_.random64() % (emax - emin); return Duration::fromMilliseconds(e); } Duration ServerUtil::cumulativeDuration(Duration base) { static Random rng_; auto emin = base.milliseconds(); auto emax = base.milliseconds() / 2 + emin; auto e = emin + rng_.random64() % (emax - emin); return Duration::fromMilliseconds(e); } Index ServerUtil::majorityIndexOf(const ServerIndexMap& set) { const auto compFn = [](std::pair<Id, Index> a, std::pair<Id, Index> b) { return a.second < b.second; }; const Index low = std::min_element(set.begin(), set.end(), compFn)->second; const Index high = std::max_element(set.begin(), set.end(), compFn)->second; const size_t quorum = set.size() / 2 + 1; Index result = low; // logDebug("raft.Server", "computeCommitIndex: min=$0, max=$1, quorum=$2", // low, high, quorum); for (Index N = low; N <= high; N++) { size_t ok = 0; for (const auto& element: set) { if (element.second >= N) { ok++; } } if (ok >= quorum && N > result) { result = N; } } return result; } } // namespace raft } // namespace xzero <commit_msg>[xzero] raft: adds missing include<commit_after>#include <xzero/raft/ServerUtil.h> #include <xzero/Random.h> #include <algorithm> namespace xzero { namespace raft { Duration ServerUtil::alleviatedDuration(Duration base) { static Random rng_; auto emin = base.milliseconds() / 2; auto emax = base.milliseconds(); auto e = emin + rng_.random64() % (emax - emin); return Duration::fromMilliseconds(e); } Duration ServerUtil::cumulativeDuration(Duration base) { static Random rng_; auto emin = base.milliseconds(); auto emax = base.milliseconds() / 2 + emin; auto e = emin + rng_.random64() % (emax - emin); return Duration::fromMilliseconds(e); } Index ServerUtil::majorityIndexOf(const ServerIndexMap& set) { const auto compFn = [](std::pair<Id, Index> a, std::pair<Id, Index> b) { return a.second < b.second; }; const Index low = std::min_element(set.begin(), set.end(), compFn)->second; const Index high = std::max_element(set.begin(), set.end(), compFn)->second; const size_t quorum = set.size() / 2 + 1; Index result = low; // logDebug("raft.Server", "computeCommitIndex: min=$0, max=$1, quorum=$2", // low, high, quorum); for (Index N = low; N <= high; N++) { size_t ok = 0; for (const auto& element: set) { if (element.second >= N) { ok++; } } if (ok >= quorum && N > result) { result = N; } } return result; } } // namespace raft } // namespace xzero <|endoftext|>
<commit_before>#include <QTimer> #include <QDateTime> #include "utils/utils.h" #include "utils/translate-commit-desc.h" #include "utils/json-utils.h" #include "utils/file-utils.h" #include "seafile-applet.h" #include "daemon-mgr.h" #include "settings-mgr.h" #include "rpc/rpc-client.h" #include "rpc/sync-error.h" #include "ui/tray-icon.h" #include "message-poller.h" #include "seafile/seafile-error.h" namespace { const int kCheckNotificationIntervalMSecs = 1000; } // namespace struct SyncNotification { QString type; QString content; static SyncNotification fromJson(const json_t* json); }; MessagePoller::MessagePoller(QObject *parent): QObject(parent) { rpc_client_ = new SeafileRpcClient(); check_notification_timer_ = new QTimer(this); connect(check_notification_timer_, SIGNAL(timeout()), this, SLOT(checkNotification())); } MessagePoller::~MessagePoller() { delete check_notification_timer_; delete rpc_client_; } void MessagePoller::start() { rpc_client_->tryConnectDaemon(); check_notification_timer_->start(kCheckNotificationIntervalMSecs); connect(seafApplet->daemonManager(), SIGNAL(daemonDead()), this, SLOT(onDaemonDead())); connect(seafApplet->daemonManager(), SIGNAL(daemonRestarted()), this, SLOT(onDaemonRestarted())); } void MessagePoller::onDaemonDead() { qDebug("pausing message poller when daemon is dead"); check_notification_timer_->stop(); } void MessagePoller::onDaemonRestarted() { qDebug("reviving message poller when daemon is restarted"); if (rpc_client_) { delete rpc_client_; } rpc_client_ = new SeafileRpcClient(); rpc_client_->tryConnectDaemon(); check_notification_timer_->start(kCheckNotificationIntervalMSecs); } void MessagePoller::checkNotification() { json_t *ret; if (!rpc_client_->getSyncNotification(&ret)) { return; } SyncNotification notification = SyncNotification::fromJson(ret); json_decref(ret); processNotification(notification); } SyncNotification SyncNotification::fromJson(const json_t *root) { SyncNotification notification; Json json(root); // char *s = json_dumps(root, 0); // printf ("[%s] %s\n", QDateTime::currentDateTime().toString().toUtf8().data(), s); // qWarning ("[%s] %s\n", QDateTime::currentDateTime().toString().toUtf8().data(), s); // free (s); notification.type = json.getString("type"); notification.content = json.getString("content"); return notification; } void MessagePoller::processNotification(const SyncNotification& notification) { const QString& type = notification.type; const QString& content = notification.content; if (type == "transfer") { // empty } else if (type == "sync.done" || type == "sync.multipart_upload") { /* format: a concatenation of (repo_name, repo_id, commmit_id, * previous_commit_id, description), separated by tabs */ QStringList slist = content.split("\t"); if (slist.count() != 5) { qWarning("Bad sync.done message format"); return; } QString title; if (type == "sync.done") title = tr("\"%1\" is synchronized").arg(slist.at(0)); else title = tr("Files uploaded to \"%1\"").arg(slist.at(0)); QString repo_id = slist.at(1).trimmed(); QString commit_id = slist.at(2).trimmed(); QString previous_commit_id = slist.at(3).trimmed(); QString desc = slist.at(4).trimmed(); seafApplet->trayIcon()->showMessage(title, translateCommitDesc(desc), repo_id, commit_id, previous_commit_id); } else if (type == "sync.error") { json_error_t error; json_t *object = json_loads(toCStr(content), 0, &error); if (!object) { qWarning("Failed to parse json: %s", error.text); return; } QString repo_id = QString::fromUtf8(json_string_value(json_object_get(object, "repo_id"))); QString title = QString::fromUtf8(json_string_value(json_object_get(object, "repo_name"))); QString path = QString::fromUtf8(json_string_value(json_object_get(object, "path"))); int err_id = json_integer_value(json_object_get(object, "err_id")); QString msg; switch (err_id) { case SYNC_ERROR_ID_FILE_LOCKED_BY_APP: msg = tr("Failed to sync file %1\nFile is locked by other application. This file will be updated when you close the application.").arg(path); break; case SYNC_ERROR_ID_FOLDER_LOCKED_BY_APP: msg = tr("Failed to sync folder %1\nSome file in this folder is locked by other application. This folder will be updated when you close the application.").arg(path); break; case SYNC_ERROR_ID_FILE_LOCKED: msg = tr("Failed to sync file %1\nFile is locked by another user. Update to this file is not uploaded.").arg(path); break; case SYNC_ERROR_ID_INVALID_PATH: msg = tr("Failed to sync %1\nFile path contains invalid characters. It is not synced to this computer.").arg(path); break; case SYNC_ERROR_ID_INDEX_ERROR: msg = tr("Failed to index file %1\nPlease check file permission and disk space.").arg(path); break; case SYNC_ERROR_ID_PATH_END_SPACE_PERIOD: msg = tr("Failed to sync %1\nFile path is ended with space or period and cannot be created on Windows.").arg(path); break; case SYNC_ERROR_ID_PATH_INVALID_CHARACTER: msg = tr("Failed to sync %1\nFile path contains invalid characters. It is not synced to this computer.").arg(path); break; case SYNC_ERROR_ID_FOLDER_PERM_DENIED: msg = tr("Update to file %1 is denied by folder permission setting.").arg(path); break; case SYNC_ERROR_ID_PERM_NOT_SYNCABLE: msg = tr("No permission to sync folder %1.").arg(path); break; case SYNC_ERROR_ID_UPDATE_TO_READ_ONLY_REPO: msg = tr("Updates in read-only library %1 will not be uploaded.").arg(path); break; case SYNC_ERROR_ID_CONFLICT: msg = tr("Concurrent updates to file. File %1 is saved as conflict file").arg(path); break; default: qWarning("Unknown sync error id %d", err_id); json_decref(object); return; } seafApplet->trayIcon()->showMessage(title, msg, repo_id); json_decref(object); } else if (type == "repo.remove") { /* format : <repo_name> */ QString repo_name = content; QString buf = tr("Folder for library %1 is removed or moved. The library is unsynced.").arg(repo_name); seafApplet->trayIcon()->showMessage(getBrand(), buf); } } <commit_msg>add error code for uncommited folder<commit_after>#include <QTimer> #include <QDateTime> #include "utils/utils.h" #include "utils/translate-commit-desc.h" #include "utils/json-utils.h" #include "utils/file-utils.h" #include "seafile-applet.h" #include "daemon-mgr.h" #include "settings-mgr.h" #include "rpc/rpc-client.h" #include "rpc/sync-error.h" #include "ui/tray-icon.h" #include "message-poller.h" #include "seafile/seafile-error.h" namespace { const int kCheckNotificationIntervalMSecs = 1000; } // namespace struct SyncNotification { QString type; QString content; static SyncNotification fromJson(const json_t* json); }; MessagePoller::MessagePoller(QObject *parent): QObject(parent) { rpc_client_ = new SeafileRpcClient(); check_notification_timer_ = new QTimer(this); connect(check_notification_timer_, SIGNAL(timeout()), this, SLOT(checkNotification())); } MessagePoller::~MessagePoller() { delete check_notification_timer_; delete rpc_client_; } void MessagePoller::start() { rpc_client_->tryConnectDaemon(); check_notification_timer_->start(kCheckNotificationIntervalMSecs); connect(seafApplet->daemonManager(), SIGNAL(daemonDead()), this, SLOT(onDaemonDead())); connect(seafApplet->daemonManager(), SIGNAL(daemonRestarted()), this, SLOT(onDaemonRestarted())); } void MessagePoller::onDaemonDead() { qDebug("pausing message poller when daemon is dead"); check_notification_timer_->stop(); } void MessagePoller::onDaemonRestarted() { qDebug("reviving message poller when daemon is restarted"); if (rpc_client_) { delete rpc_client_; } rpc_client_ = new SeafileRpcClient(); rpc_client_->tryConnectDaemon(); check_notification_timer_->start(kCheckNotificationIntervalMSecs); } void MessagePoller::checkNotification() { json_t *ret; if (!rpc_client_->getSyncNotification(&ret)) { return; } SyncNotification notification = SyncNotification::fromJson(ret); json_decref(ret); processNotification(notification); } SyncNotification SyncNotification::fromJson(const json_t *root) { SyncNotification notification; Json json(root); // char *s = json_dumps(root, 0); // printf ("[%s] %s\n", QDateTime::currentDateTime().toString().toUtf8().data(), s); // qWarning ("[%s] %s\n", QDateTime::currentDateTime().toString().toUtf8().data(), s); // free (s); notification.type = json.getString("type"); notification.content = json.getString("content"); return notification; } void MessagePoller::processNotification(const SyncNotification& notification) { const QString& type = notification.type; const QString& content = notification.content; if (type == "transfer") { // empty } else if (type == "sync.done" || type == "sync.multipart_upload") { /* format: a concatenation of (repo_name, repo_id, commmit_id, * previous_commit_id, description), separated by tabs */ QStringList slist = content.split("\t"); if (slist.count() != 5) { qWarning("Bad sync.done message format"); return; } QString title; if (type == "sync.done") title = tr("\"%1\" is synchronized").arg(slist.at(0)); else title = tr("Files uploaded to \"%1\"").arg(slist.at(0)); QString repo_id = slist.at(1).trimmed(); QString commit_id = slist.at(2).trimmed(); QString previous_commit_id = slist.at(3).trimmed(); QString desc = slist.at(4).trimmed(); seafApplet->trayIcon()->showMessage(title, translateCommitDesc(desc), repo_id, commit_id, previous_commit_id); } else if (type == "sync.error") { json_error_t error; json_t *object = json_loads(toCStr(content), 0, &error); if (!object) { qWarning("Failed to parse json: %s", error.text); return; } QString repo_id = QString::fromUtf8(json_string_value(json_object_get(object, "repo_id"))); QString title = QString::fromUtf8(json_string_value(json_object_get(object, "repo_name"))); QString path = QString::fromUtf8(json_string_value(json_object_get(object, "path"))); int err_id = json_integer_value(json_object_get(object, "err_id")); QString msg; switch (err_id) { case SYNC_ERROR_ID_FILE_LOCKED_BY_APP: msg = tr("Failed to sync file %1\nFile is locked by other application. This file will be updated when you close the application.").arg(path); break; case SYNC_ERROR_ID_FOLDER_LOCKED_BY_APP: msg = tr("Failed to sync folder %1\nSome file in this folder is locked by other application. This folder will be updated when you close the application.").arg(path); break; case SYNC_ERROR_ID_FILE_LOCKED: msg = tr("Failed to sync file %1\nFile is locked by another user. Update to this file is not uploaded.").arg(path); break; case SYNC_ERROR_ID_INVALID_PATH: msg = tr("Failed to sync %1\nFile path contains invalid characters. It is not synced to this computer.").arg(path); break; case SYNC_ERROR_ID_INDEX_ERROR: msg = tr("Failed to index file %1\nPlease check file permission and disk space.").arg(path); break; case SYNC_ERROR_ID_PATH_END_SPACE_PERIOD: msg = tr("Failed to sync %1\nFile path is ended with space or period and cannot be created on Windows.").arg(path); break; case SYNC_ERROR_ID_PATH_INVALID_CHARACTER: msg = tr("Failed to sync %1\nFile path contains invalid characters. It is not synced to this computer.").arg(path); break; case SYNC_ERROR_ID_FOLDER_PERM_DENIED: msg = tr("Update to file %1 is denied by folder permission setting.").arg(path); break; case SYNC_ERROR_ID_PERM_NOT_SYNCABLE: msg = tr("No permission to sync folder %1.").arg(path); break; case SYNC_ERROR_ID_UPDATE_TO_READ_ONLY_REPO: msg = tr("Updates in read-only library %1 will not be uploaded.").arg(path); break; case SYNC_ERROR_ID_CONFLICT: msg = tr("Concurrent updates to file. File %1 is saved as conflict file").arg(path); break; case SYNC_ERROR_ID_REMOVE_UNCOMMITTED_FOLDER: msg = tr("Failed to remove uncommited folder %1.").arg(path); break; default: qWarning("Unknown sync error id %d", err_id); json_decref(object); return; } seafApplet->trayIcon()->showMessage(title, msg, repo_id); json_decref(object); } else if (type == "repo.remove") { /* format : <repo_name> */ QString repo_name = content; QString buf = tr("Folder for library %1 is removed or moved. The library is unsynced.").arg(repo_name); seafApplet->trayIcon()->showMessage(getBrand(), buf); } } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage 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. *********************************************************************/ /* Author Ioan Sucan */ #include "collision_detection_fcl/collision_world.h" #include <fcl/geometric_shape_to_BVH_model.h> #include <fcl/traversal_node_bvhs.h> #include <fcl/simple_setup.h> #include <fcl/collision_node.h> #include <ros/console.h> collision_detection::CollisionWorldFCL::CollisionWorldFCL(void) : CollisionWorld() { fcl::DynamicAABBTreeCollisionManager* m = new fcl::DynamicAABBTreeCollisionManager(); // m->tree_init_level = 2; manager_.reset(m); } collision_detection::CollisionWorldFCL::CollisionWorldFCL(const CollisionWorldFCL &other) : CollisionWorld(other) { fcl::DynamicAABBTreeCollisionManager* m = new fcl::DynamicAABBTreeCollisionManager(); // m->tree_init_level = 2; manager_.reset(m); fcl_objs_ = other.fcl_objs_; for (std::map<std::string, FCLObject>::iterator it = fcl_objs_.begin() ; it != fcl_objs_.end() ; ++it) it->second.registerTo(manager_.get()); // manager_->update(); } collision_detection::CollisionWorldFCL::~CollisionWorldFCL(void) { } void collision_detection::CollisionWorldFCL::checkRobotCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state) const { checkRobotCollisionHelper(req, res, robot, state, NULL); } void collision_detection::CollisionWorldFCL::checkRobotCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state, const AllowedCollisionMatrix &acm) const { checkRobotCollisionHelper(req, res, robot, state, &acm); } void collision_detection::CollisionWorldFCL::checkRobotCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state1, const planning_models::KinematicState &state2) const { ROS_ERROR("FCL continuous collision checking not yet implemented"); } void collision_detection::CollisionWorldFCL::checkRobotCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state1, const planning_models::KinematicState &state2, const AllowedCollisionMatrix &acm) const { ROS_ERROR("FCL continuous collision checking not yet implemented"); } void collision_detection::CollisionWorldFCL::checkRobotCollisionHelper(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state, const AllowedCollisionMatrix *acm) const { const CollisionRobotFCL &robot_fcl = dynamic_cast<const CollisionRobotFCL&>(robot); FCLObject fcl_obj; robot_fcl.constructFCLObject(state, fcl_obj); CollisionData cd(&req, &res, acm); cd.enableGroup(robot.getKinematicModel()); for (std::size_t i = 0 ; !cd.done_ && i < fcl_obj.collision_objects_.size() ; ++i) manager_->collide(fcl_obj.collision_objects_[i].get(), &cd, &collisionCallback); if (req.distance) res.distance = distanceRobotHelper(robot, state, acm); } void collision_detection::CollisionWorldFCL::checkWorldCollision(const CollisionRequest &req, CollisionResult &res, const CollisionWorld &other_world) const { checkWorldCollisionHelper(req, res, other_world, NULL); } void collision_detection::CollisionWorldFCL::checkWorldCollision(const CollisionRequest &req, CollisionResult &res, const CollisionWorld &other_world, const AllowedCollisionMatrix &acm) const { checkWorldCollisionHelper(req, res, other_world, &acm); } void collision_detection::CollisionWorldFCL::checkWorldCollisionHelper(const CollisionRequest &req, CollisionResult &res, const CollisionWorld &other_world, const AllowedCollisionMatrix *acm) const { const CollisionWorldFCL &other_fcl_world = dynamic_cast<const CollisionWorldFCL&>(other_world); CollisionData cd(&req, &res, acm); manager_->collide(other_fcl_world.manager_.get(), &cd, &collisionCallback); if (req.distance) res.distance = distanceWorldHelper(other_world, acm); } void collision_detection::CollisionWorldFCL::constructFCLObject(const Object *obj, FCLObject &fcl_obj) const { for (std::size_t i = 0 ; i < obj->shapes_.size() ; ++i) { FCLGeometryConstPtr g = createCollisionGeometry(obj->shapes_[i], obj); if (g) { fcl::CollisionObject *co = new fcl::CollisionObject(g->collision_geometry_, transform2fcl(obj->shape_poses_[i])); fcl_obj.collision_objects_.push_back(boost::shared_ptr<fcl::CollisionObject>(co)); fcl_obj.collision_geometry_.push_back(g); } } } void collision_detection::CollisionWorldFCL::updateFCLObject(const std::string &id) { // remove FCL objects that correspond to this object std::map<std::string, FCLObject>::iterator jt = fcl_objs_.find(id); if (jt != fcl_objs_.end()) { jt->second.unregisterFrom(manager_.get()); jt->second.clear(); } // check to see if we have this object std::map<std::string, ObjectPtr>::iterator it = objects_.find(id); if (it != objects_.end()) { // construct FCL objects that correspond to this object if (jt != fcl_objs_.end()) { constructFCLObject(it->second.get(), jt->second); jt->second.registerTo(manager_.get()); } else { constructFCLObject(it->second.get(), fcl_objs_[id]); fcl_objs_[id].registerTo(manager_.get()); } } else { if (jt != fcl_objs_.end()) fcl_objs_.erase(jt); } // manager_->update(); } void collision_detection::CollisionWorldFCL::addToObject(const std::string &id, const std::vector<shapes::ShapeConstPtr> &shapes, const std::vector<Eigen::Affine3d> &poses) { CollisionWorld::addToObject(id, shapes, poses); updateFCLObject(id); } void collision_detection::CollisionWorldFCL::addToObject(const std::string &id, const shapes::ShapeConstPtr &shape, const Eigen::Affine3d &pose) { CollisionWorld::addToObject(id, shape, pose); updateFCLObject(id); } bool collision_detection::CollisionWorldFCL::moveShapeInObject(const std::string &id, const shapes::ShapeConstPtr &shape, const Eigen::Affine3d &pose) { if (CollisionWorld::moveShapeInObject(id, shape, pose)) { updateFCLObject(id); return true; } else return false; } bool collision_detection::CollisionWorldFCL::removeShapeFromObject(const std::string &id, const shapes::ShapeConstPtr &shape) { if (CollisionWorld::removeShapeFromObject(id, shape)) { updateFCLObject(id); return true; } else return false; } void collision_detection::CollisionWorldFCL::removeObject(const std::string &id) { CollisionWorld::removeObject(id); std::map<std::string, FCLObject>::iterator it = fcl_objs_.find(id); if (it != fcl_objs_.end()) { it->second.unregisterFrom(manager_.get()); it->second.clear(); fcl_objs_.erase(it); // manager_->update(); } } void collision_detection::CollisionWorldFCL::clearObjects(void) { CollisionWorld::clearObjects(); manager_->clear(); fcl_objs_.clear(); } double collision_detection::CollisionWorldFCL::distanceRobotHelper(const CollisionRobot &robot, const planning_models::KinematicState &state, const AllowedCollisionMatrix *acm) const { const CollisionRobotFCL& robot_fcl = dynamic_cast<const CollisionRobotFCL&>(robot); FCLObject fcl_obj; robot_fcl.constructFCLObject(state, fcl_obj); CollisionRequest req; CollisionResult res; CollisionData cd(&req, &res, acm); cd.enableGroup(robot.getKinematicModel()); for(std::size_t i = 0; !cd.done_ && i < fcl_obj.collision_objects_.size(); ++i) manager_->distance(fcl_obj.collision_objects_[i].get(), &cd, &distanceCallback); return res.distance; } double collision_detection::CollisionWorldFCL::distanceRobot(const CollisionRobot &robot, const planning_models::KinematicState &state) const { return distanceRobotHelper(robot, state, NULL); } double collision_detection::CollisionWorldFCL::distanceRobot(const CollisionRobot &robot, const planning_models::KinematicState &state, const AllowedCollisionMatrix &acm) const { return distanceRobotHelper(robot, state, &acm); } double collision_detection::CollisionWorldFCL::distanceWorld(const CollisionWorld &world) const { return distanceWorldHelper(world, NULL); } double collision_detection::CollisionWorldFCL::distanceWorld(const CollisionWorld &world, const AllowedCollisionMatrix &acm) const { return distanceWorldHelper(world, &acm); } double collision_detection::CollisionWorldFCL::distanceWorldHelper(const CollisionWorld &other_world, const AllowedCollisionMatrix *acm) const { const CollisionWorldFCL& other_fcl_world = dynamic_cast<const CollisionWorldFCL&>(other_world); CollisionRequest req; CollisionResult res; CollisionData cd(&req, &res, acm); manager_->distance(other_fcl_world.manager_.get(), &cd, &distanceCallback); return res.distance; } <commit_msg>change according to change in fcl's change of file name<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage 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. *********************************************************************/ /* Author Ioan Sucan */ #include "collision_detection_fcl/collision_world.h" #include <fcl/geometric_shape_to_BVH_model.h> #include <fcl/traversal_node_bvhs.h> #include <fcl/traversal_node_setup.h> #include <fcl/collision_node.h> #include <ros/console.h> collision_detection::CollisionWorldFCL::CollisionWorldFCL(void) : CollisionWorld() { fcl::DynamicAABBTreeCollisionManager* m = new fcl::DynamicAABBTreeCollisionManager(); // m->tree_init_level = 2; manager_.reset(m); } collision_detection::CollisionWorldFCL::CollisionWorldFCL(const CollisionWorldFCL &other) : CollisionWorld(other) { fcl::DynamicAABBTreeCollisionManager* m = new fcl::DynamicAABBTreeCollisionManager(); // m->tree_init_level = 2; manager_.reset(m); fcl_objs_ = other.fcl_objs_; for (std::map<std::string, FCLObject>::iterator it = fcl_objs_.begin() ; it != fcl_objs_.end() ; ++it) it->second.registerTo(manager_.get()); // manager_->update(); } collision_detection::CollisionWorldFCL::~CollisionWorldFCL(void) { } void collision_detection::CollisionWorldFCL::checkRobotCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state) const { checkRobotCollisionHelper(req, res, robot, state, NULL); } void collision_detection::CollisionWorldFCL::checkRobotCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state, const AllowedCollisionMatrix &acm) const { checkRobotCollisionHelper(req, res, robot, state, &acm); } void collision_detection::CollisionWorldFCL::checkRobotCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state1, const planning_models::KinematicState &state2) const { ROS_ERROR("FCL continuous collision checking not yet implemented"); } void collision_detection::CollisionWorldFCL::checkRobotCollision(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state1, const planning_models::KinematicState &state2, const AllowedCollisionMatrix &acm) const { ROS_ERROR("FCL continuous collision checking not yet implemented"); } void collision_detection::CollisionWorldFCL::checkRobotCollisionHelper(const CollisionRequest &req, CollisionResult &res, const CollisionRobot &robot, const planning_models::KinematicState &state, const AllowedCollisionMatrix *acm) const { const CollisionRobotFCL &robot_fcl = dynamic_cast<const CollisionRobotFCL&>(robot); FCLObject fcl_obj; robot_fcl.constructFCLObject(state, fcl_obj); CollisionData cd(&req, &res, acm); cd.enableGroup(robot.getKinematicModel()); for (std::size_t i = 0 ; !cd.done_ && i < fcl_obj.collision_objects_.size() ; ++i) manager_->collide(fcl_obj.collision_objects_[i].get(), &cd, &collisionCallback); if (req.distance) res.distance = distanceRobotHelper(robot, state, acm); } void collision_detection::CollisionWorldFCL::checkWorldCollision(const CollisionRequest &req, CollisionResult &res, const CollisionWorld &other_world) const { checkWorldCollisionHelper(req, res, other_world, NULL); } void collision_detection::CollisionWorldFCL::checkWorldCollision(const CollisionRequest &req, CollisionResult &res, const CollisionWorld &other_world, const AllowedCollisionMatrix &acm) const { checkWorldCollisionHelper(req, res, other_world, &acm); } void collision_detection::CollisionWorldFCL::checkWorldCollisionHelper(const CollisionRequest &req, CollisionResult &res, const CollisionWorld &other_world, const AllowedCollisionMatrix *acm) const { const CollisionWorldFCL &other_fcl_world = dynamic_cast<const CollisionWorldFCL&>(other_world); CollisionData cd(&req, &res, acm); manager_->collide(other_fcl_world.manager_.get(), &cd, &collisionCallback); if (req.distance) res.distance = distanceWorldHelper(other_world, acm); } void collision_detection::CollisionWorldFCL::constructFCLObject(const Object *obj, FCLObject &fcl_obj) const { for (std::size_t i = 0 ; i < obj->shapes_.size() ; ++i) { FCLGeometryConstPtr g = createCollisionGeometry(obj->shapes_[i], obj); if (g) { fcl::CollisionObject *co = new fcl::CollisionObject(g->collision_geometry_, transform2fcl(obj->shape_poses_[i])); fcl_obj.collision_objects_.push_back(boost::shared_ptr<fcl::CollisionObject>(co)); fcl_obj.collision_geometry_.push_back(g); } } } void collision_detection::CollisionWorldFCL::updateFCLObject(const std::string &id) { // remove FCL objects that correspond to this object std::map<std::string, FCLObject>::iterator jt = fcl_objs_.find(id); if (jt != fcl_objs_.end()) { jt->second.unregisterFrom(manager_.get()); jt->second.clear(); } // check to see if we have this object std::map<std::string, ObjectPtr>::iterator it = objects_.find(id); if (it != objects_.end()) { // construct FCL objects that correspond to this object if (jt != fcl_objs_.end()) { constructFCLObject(it->second.get(), jt->second); jt->second.registerTo(manager_.get()); } else { constructFCLObject(it->second.get(), fcl_objs_[id]); fcl_objs_[id].registerTo(manager_.get()); } } else { if (jt != fcl_objs_.end()) fcl_objs_.erase(jt); } // manager_->update(); } void collision_detection::CollisionWorldFCL::addToObject(const std::string &id, const std::vector<shapes::ShapeConstPtr> &shapes, const std::vector<Eigen::Affine3d> &poses) { CollisionWorld::addToObject(id, shapes, poses); updateFCLObject(id); } void collision_detection::CollisionWorldFCL::addToObject(const std::string &id, const shapes::ShapeConstPtr &shape, const Eigen::Affine3d &pose) { CollisionWorld::addToObject(id, shape, pose); updateFCLObject(id); } bool collision_detection::CollisionWorldFCL::moveShapeInObject(const std::string &id, const shapes::ShapeConstPtr &shape, const Eigen::Affine3d &pose) { if (CollisionWorld::moveShapeInObject(id, shape, pose)) { updateFCLObject(id); return true; } else return false; } bool collision_detection::CollisionWorldFCL::removeShapeFromObject(const std::string &id, const shapes::ShapeConstPtr &shape) { if (CollisionWorld::removeShapeFromObject(id, shape)) { updateFCLObject(id); return true; } else return false; } void collision_detection::CollisionWorldFCL::removeObject(const std::string &id) { CollisionWorld::removeObject(id); std::map<std::string, FCLObject>::iterator it = fcl_objs_.find(id); if (it != fcl_objs_.end()) { it->second.unregisterFrom(manager_.get()); it->second.clear(); fcl_objs_.erase(it); // manager_->update(); } } void collision_detection::CollisionWorldFCL::clearObjects(void) { CollisionWorld::clearObjects(); manager_->clear(); fcl_objs_.clear(); } double collision_detection::CollisionWorldFCL::distanceRobotHelper(const CollisionRobot &robot, const planning_models::KinematicState &state, const AllowedCollisionMatrix *acm) const { const CollisionRobotFCL& robot_fcl = dynamic_cast<const CollisionRobotFCL&>(robot); FCLObject fcl_obj; robot_fcl.constructFCLObject(state, fcl_obj); CollisionRequest req; CollisionResult res; CollisionData cd(&req, &res, acm); cd.enableGroup(robot.getKinematicModel()); for(std::size_t i = 0; !cd.done_ && i < fcl_obj.collision_objects_.size(); ++i) manager_->distance(fcl_obj.collision_objects_[i].get(), &cd, &distanceCallback); return res.distance; } double collision_detection::CollisionWorldFCL::distanceRobot(const CollisionRobot &robot, const planning_models::KinematicState &state) const { return distanceRobotHelper(robot, state, NULL); } double collision_detection::CollisionWorldFCL::distanceRobot(const CollisionRobot &robot, const planning_models::KinematicState &state, const AllowedCollisionMatrix &acm) const { return distanceRobotHelper(robot, state, &acm); } double collision_detection::CollisionWorldFCL::distanceWorld(const CollisionWorld &world) const { return distanceWorldHelper(world, NULL); } double collision_detection::CollisionWorldFCL::distanceWorld(const CollisionWorld &world, const AllowedCollisionMatrix &acm) const { return distanceWorldHelper(world, &acm); } double collision_detection::CollisionWorldFCL::distanceWorldHelper(const CollisionWorld &other_world, const AllowedCollisionMatrix *acm) const { const CollisionWorldFCL& other_fcl_world = dynamic_cast<const CollisionWorldFCL&>(other_world); CollisionRequest req; CollisionResult res; CollisionData cd(&req, &res, acm); manager_->distance(other_fcl_world.manager_.get(), &cd, &distanceCallback); return res.distance; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: sjapplet.cxx,v $ * * $Revision: 1.15 $ * * last change: $Author: obo $ $Date: 2007-03-12 10:46:26 $ * * 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 "sal/config.h" #include "sjapplet.hxx" #include "osl/diagnose.h" #include "rtl/string.hxx" #include "rtl/ustring.hxx" #include "sjapplet_impl.hxx" using namespace ::rtl; using namespace ::com::sun::star::uno; SjApplet2::SjApplet2() : _pImpl(new SjApplet2_Impl()) { } SjApplet2::~SjApplet2() { delete _pImpl; } //========================================================================= void SjApplet2::Init( com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > const & context, Window * pParentWin, const INetURLObject & rDocBase, const SvCommandList & rCmdList) { try { if(_pImpl) _pImpl->init(pParentWin, context, rDocBase, rCmdList); } catch(RuntimeException & runtimeException) { #if OSL_DEBUG_LEVEL > 1 OString message = OUStringToOString(runtimeException.Message, RTL_TEXTENCODING_ASCII_US); OSL_TRACE("sjapplet.cxx: SjApplet2::Init - exception occurred: %s\n", message.getStr()); #else (void) runtimeException; // avoid warning #endif delete _pImpl; _pImpl = 0; } } //========================================================================= void SjApplet2::setSizePixel( const Size & rSize ) { if(_pImpl) _pImpl->setSize(rSize); } void SjApplet2::appletRestart() { if(_pImpl) _pImpl->restart(); } void SjApplet2::appletReload() { if(_pImpl) _pImpl->reload(); } void SjApplet2::appletStart() { if(_pImpl) _pImpl->start(); } void SjApplet2::appletStop() { if(_pImpl) _pImpl->stop(); } void SjApplet2::appletClose() { if(_pImpl) _pImpl->close(); } // Fuer SO3, Wrapper fuer Applet liefern SjJScriptAppletObject * SjApplet2::GetJScriptApplet() { OSL_TRACE("SjApplet2::GetJScriptApplet\n"); return NULL; } // Settings are detected by the JavaVM service // This function is not necessary anymore void SjApplet2::settingsChanged(void) {} <commit_msg>INTEGRATION: CWS changefileheader (1.15.20); FILE MERGED 2008/03/31 15:27:22 rt 1.15.20.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: sjapplet.cxx,v $ * $Revision: 1.16 $ * * 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. * ************************************************************************/ #include "sal/config.h" #include "sjapplet.hxx" #include "osl/diagnose.h" #include "rtl/string.hxx" #include "rtl/ustring.hxx" #include "sjapplet_impl.hxx" using namespace ::rtl; using namespace ::com::sun::star::uno; SjApplet2::SjApplet2() : _pImpl(new SjApplet2_Impl()) { } SjApplet2::~SjApplet2() { delete _pImpl; } //========================================================================= void SjApplet2::Init( com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > const & context, Window * pParentWin, const INetURLObject & rDocBase, const SvCommandList & rCmdList) { try { if(_pImpl) _pImpl->init(pParentWin, context, rDocBase, rCmdList); } catch(RuntimeException & runtimeException) { #if OSL_DEBUG_LEVEL > 1 OString message = OUStringToOString(runtimeException.Message, RTL_TEXTENCODING_ASCII_US); OSL_TRACE("sjapplet.cxx: SjApplet2::Init - exception occurred: %s\n", message.getStr()); #else (void) runtimeException; // avoid warning #endif delete _pImpl; _pImpl = 0; } } //========================================================================= void SjApplet2::setSizePixel( const Size & rSize ) { if(_pImpl) _pImpl->setSize(rSize); } void SjApplet2::appletRestart() { if(_pImpl) _pImpl->restart(); } void SjApplet2::appletReload() { if(_pImpl) _pImpl->reload(); } void SjApplet2::appletStart() { if(_pImpl) _pImpl->start(); } void SjApplet2::appletStop() { if(_pImpl) _pImpl->stop(); } void SjApplet2::appletClose() { if(_pImpl) _pImpl->close(); } // Fuer SO3, Wrapper fuer Applet liefern SjJScriptAppletObject * SjApplet2::GetJScriptApplet() { OSL_TRACE("SjApplet2::GetJScriptApplet\n"); return NULL; } // Settings are detected by the JavaVM service // This function is not necessary anymore void SjApplet2::settingsChanged(void) {} <|endoftext|>
<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_LA_BACKEND_EIGEN_HH #define DUNE_DETAILED_DISCRETIZATIONS_LA_BACKEND_EIGEN_HH #ifdef HAVE_EIGEN // eigen #include <Eigen/Core> #include <Eigen/Sparse> // dune-common #include <dune/common/shared_ptr.hh> namespace Dune { namespace Detailed { namespace Discretizations { namespace LA { namespace Backend { namespace Container { namespace Eigen { template <class EntryImp> class SparseMatrix { public: typedef EntryImp EntryType; typedef SparseMatrix<EntryType> ThisType; typedef ::Eigen::SparseMatrix<EntryType> StorageType; SparseMatrix(unsigned int rows, unsigned int cols) : rows_(rows) , cols_(cols) , storage_(new StorageType(rows_, cols_)) { } SparseMatrix(Dune::shared_ptr<StorageType> storage) : rows_(storage->rows()) , cols_(storage->cols()) , storage_(storage) { } SparseMatrix(const ThisType& other) : rows_(other.rows()) , cols_(other.cols()) , storage_(other.storage()) { } ThisType& operator=(const ThisType& other) { rows_ = other.rows(); cols_ = other.cols(); storage_ = other.storage(); return *this; } unsigned int rows() const { return rows_; } unsigned int cols() const { return cols_; } Dune::shared_ptr<StorageType> storage() { return storage_; } const Dune::shared_ptr<StorageType> storage() const { return storage_; } void reserve(unsigned int nnz) { storage_->reserve(nnz); } void add(unsigned int i, unsigned int j, const EntryType& val) { storage_->coeffRef(i, j) += val; } void set(unsigned int i, unsigned int j, const EntryType& val) { storage_->coeffRef(i, j) = val; } const EntryType get(unsigned int i, unsigned int j) const { return storage_->coeff(i, j); } private: unsigned int rows_; unsigned int cols_; Dune::shared_ptr<StorageType> storage_; }; // class SparseMatrix template <class EntryImp> class DenseMatrix; template <> class DenseMatrix<double> { public: typedef double EntryType; typedef DenseMatrix<EntryType> ThisType; typedef ::Eigen::MatrixXd StorageType; DenseMatrix(unsigned int rows, unsigned int cols) : rows_(rows) , cols_(cols) , storage_(new StorageType(rows_, cols_)) { } DenseMatrix(Dune::shared_ptr<StorageType> storage) : rows_(storage->rows()) , cols_(storage->cols()) , storage_(storage) { } DenseMatrix(const ThisType& other) : rows_(other.rows()) , cols_(other.cols()) , storage_(other.storage()) { } ThisType& operator=(const ThisType& other) { rows_ = other.rows(); cols_ = other.cols(); storage_ = other.storage(); return *this; } unsigned int rows() const { return rows_; } unsigned int cols() const { return cols_; } Dune::shared_ptr<StorageType> storage() { return storage_; } const Dune::shared_ptr<StorageType> storage() const { return storage_; } void reserve() { storage_->operator=(StorageType::Zero(rows(), cols())); } void add(unsigned int i, unsigned int j, const EntryType& val) { storage_->operator()(i, j) += val; } void set(unsigned int i, unsigned int j, const EntryType& val) { storage_->operator()(i, j) = val; } const EntryType get(unsigned int i, unsigned int j) const { return storage_->operator()(i, j); } private: unsigned int rows_; unsigned int cols_; Dune::shared_ptr<StorageType> storage_; }; // class DenseMatrix template <class EntryImp> class DenseVector; template <> class DenseVector<double> { public: typedef double EntryType; typedef DenseVector<EntryType> ThisType; typedef ::Eigen::VectorXd StorageType; DenseVector(unsigned int size) : size_(size) , storage_(new StorageType(size_)) { } DenseVector(Dune::shared_ptr<StorageType> storage) : size_(storage->rows()) , storage_(storage) { } DenseVector(const ThisType& other) : size_(other.size()) , storage_(other.storage()) { } ThisType& operator=(const ThisType& other) { size_ = other.size(); storage_ = other.storage(); return *this; } unsigned int size() const { return size_; } Dune::shared_ptr<StorageType> storage() { return storage_; } const Dune::shared_ptr<StorageType> storage() const { return storage_; } void reserve() { storage_->operator=(StorageType::Zero(size())); } void add(unsigned int i, const EntryType& val) { storage_->operator()(i) += val; } void set(unsigned int i, const EntryType& val) { storage_->operator()(i) = val; } const EntryType get(unsigned int i) const { return storage_->operator()(i); } const EntryType& operator[](unsigned int i) const { return storage_->coeff(i); } EntryType& operator[](unsigned int i) { return storage_->coeffRef(i); } private: unsigned int size_; Dune::shared_ptr<StorageType> storage_; }; // class DenseVector } // namespace Container } // namespace Eigen } // namespace Backend } // namespace LA } // namespace Discretizations } // namespace Detailed } // namespace Dune #endif // HAVE_EIGEN #endif // DUNE_DETAILED_DISCRETIZATIONS_LA_BACKEND_EIGEN_HH <commit_msg>[la.backend.container.eigen] minor change<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_LA_BACKEND_EIGEN_HH #define DUNE_DETAILED_DISCRETIZATIONS_LA_BACKEND_EIGEN_HH #ifdef HAVE_EIGEN // eigen #include <Eigen/Core> #include <Eigen/Sparse> // dune-common #include <dune/common/shared_ptr.hh> namespace Dune { namespace Detailed { namespace Discretizations { namespace LA { namespace Backend { namespace Container { namespace Eigen { template <class EntryImp> class SparseMatrix { public: typedef EntryImp EntryType; typedef SparseMatrix<EntryType> ThisType; typedef ::Eigen::SparseMatrix<EntryType> StorageType; SparseMatrix(unsigned int rows, unsigned int cols) : rows_(rows) , cols_(cols) , storage_(new StorageType(rows_, cols_)) { } SparseMatrix(Dune::shared_ptr<StorageType> storage) : rows_(storage->rows()) , cols_(storage->cols()) , storage_(storage) { } SparseMatrix(const ThisType& other) : rows_(other.rows_) , cols_(other.cols_) , storage_(other.storage_) { } ThisType& operator=(const ThisType& other) { rows_ = other.rows(); cols_ = other.cols(); storage_ = other.storage(); return *this; } unsigned int rows() const { return rows_; } unsigned int cols() const { return cols_; } Dune::shared_ptr<StorageType> storage() { return storage_; } const Dune::shared_ptr<StorageType> storage() const { return storage_; } void reserve(unsigned int nnz) { storage_->reserve(nnz); } void add(unsigned int i, unsigned int j, const EntryType& val) { storage_->coeffRef(i, j) += val; } void set(unsigned int i, unsigned int j, const EntryType& val) { storage_->coeffRef(i, j) = val; } const EntryType get(unsigned int i, unsigned int j) const { return storage_->coeff(i, j); } private: unsigned int rows_; unsigned int cols_; Dune::shared_ptr<StorageType> storage_; }; // class SparseMatrix template <class EntryImp> class DenseMatrix; template <> class DenseMatrix<double> { public: typedef double EntryType; typedef DenseMatrix<EntryType> ThisType; typedef ::Eigen::MatrixXd StorageType; DenseMatrix(unsigned int rows, unsigned int cols) : rows_(rows) , cols_(cols) , storage_(new StorageType(rows_, cols_)) { } DenseMatrix(Dune::shared_ptr<StorageType> storage) : rows_(storage->rows()) , cols_(storage->cols()) , storage_(storage) { } DenseMatrix(const ThisType& other) : rows_(other.rows()) , cols_(other.cols()) , storage_(other.storage()) { } ThisType& operator=(const ThisType& other) { rows_ = other.rows(); cols_ = other.cols(); storage_ = other.storage(); return *this; } unsigned int rows() const { return rows_; } unsigned int cols() const { return cols_; } Dune::shared_ptr<StorageType> storage() { return storage_; } const Dune::shared_ptr<StorageType> storage() const { return storage_; } void reserve() { storage_->operator=(StorageType::Zero(rows(), cols())); } void add(unsigned int i, unsigned int j, const EntryType& val) { storage_->operator()(i, j) += val; } void set(unsigned int i, unsigned int j, const EntryType& val) { storage_->operator()(i, j) = val; } const EntryType get(unsigned int i, unsigned int j) const { return storage_->operator()(i, j); } private: unsigned int rows_; unsigned int cols_; Dune::shared_ptr<StorageType> storage_; }; // class DenseMatrix template <class EntryImp> class DenseVector; template <> class DenseVector<double> { public: typedef double EntryType; typedef DenseVector<EntryType> ThisType; typedef ::Eigen::VectorXd StorageType; DenseVector(unsigned int size) : size_(size) , storage_(new StorageType(size_)) { } DenseVector(Dune::shared_ptr<StorageType> storage) : size_(storage->rows()) , storage_(storage) { } DenseVector(const ThisType& other) : size_(other.size()) , storage_(other.storage()) { } ThisType& operator=(const ThisType& other) { size_ = other.size(); storage_ = other.storage(); return *this; } unsigned int size() const { return size_; } Dune::shared_ptr<StorageType> storage() { return storage_; } const Dune::shared_ptr<StorageType> storage() const { return storage_; } void reserve() { storage_->operator=(StorageType::Zero(size())); } void add(unsigned int i, const EntryType& val) { storage_->operator()(i) += val; } void set(unsigned int i, const EntryType& val) { storage_->operator()(i) = val; } const EntryType get(unsigned int i) const { return storage_->operator()(i); } const EntryType& operator[](unsigned int i) const { return storage_->coeff(i); } EntryType& operator[](unsigned int i) { return storage_->coeffRef(i); } private: unsigned int size_; Dune::shared_ptr<StorageType> storage_; }; // class DenseVector } // namespace Container } // namespace Eigen } // namespace Backend } // namespace LA } // namespace Discretizations } // namespace Detailed } // namespace Dune #endif // HAVE_EIGEN #endif // DUNE_DETAILED_DISCRETIZATIONS_LA_BACKEND_EIGEN_HH <|endoftext|>
<commit_before><commit_msg>update comment<commit_after><|endoftext|>
<commit_before> #include <yafraycore/tiledintegrator.h> #include <core_api/imagefilm.h> #include <core_api/camera.h> #include <yafraycore/timer.h> #include <yafraycore/scr_halton.h> #include <utilities/mcqmc.h> #include <utilities/sample_utils.h> #include <sstream> __BEGIN_YAFRAY #ifdef USING_THREADS class renderWorker_t: public yafthreads::thread_t { public: renderWorker_t(tiledIntegrator_t *it, scene_t *s, imageFilm_t *f, threadControl_t *c, int id, int smpls, int offs=0, bool adptv=false): integrator(it), scene(s), imageFilm(f), control(c), samples(smpls), offset(offs), threadID(id), adaptive(adptv) { /* std::cout << "renderWorker_t::renderWorker_t(): *this="<<(void*)this<<std::endl; */ }; virtual void body(); protected: tiledIntegrator_t *integrator; scene_t *scene; imageFilm_t *imageFilm; threadControl_t *control; int samples, offset; int threadID; bool adaptive; }; void renderWorker_t::body() { renderArea_t a; while(imageFilm->nextArea(a)) { if(scene->getSignals() & Y_SIG_ABORT) break; integrator->renderTile(a, samples, offset, adaptive, threadID); // imageFilm->finishArea(a); control->countCV.lock(); control->areas.push_back(a); control->countCV.signal(); control->countCV.unlock(); } control->countCV.lock(); ++(control->finishedThreads); control->countCV.signal(); control->countCV.unlock(); } #endif bool tiledIntegrator_t::render(imageFilm_t *image) { std::stringstream passString; imageFilm = image; scene->getAAParameters(AA_samples, AA_passes, AA_inc_samples, AA_threshold); Y_INFO << integratorName << ": Rendering "<<AA_passes<<" passes\n"; Y_INFO << integratorName << ": Min. " << AA_samples << " samples\n"; Y_INFO << integratorName << ": "<< AA_inc_samples << " per additional pass\n"; Y_INFO << integratorName << ": Max. "<<AA_samples + std::max(0,AA_passes-1)*AA_inc_samples<<" total samples\n"; passString << "Rendering pass 1 of " << std::max(1, AA_passes) << "..."; if(intpb) intpb->setTag(passString.str().c_str()); gTimer.addEvent("rendert"); gTimer.start("rendert"); imageFilm->init(AA_passes); renderPass(AA_samples, 0, false); for(int i=1; i<AA_passes; ++i) { if(scene->getSignals() & Y_SIG_ABORT) break; imageFilm->setAAThreshold(AA_threshold); imageFilm->nextPass(true); renderPass(AA_inc_samples, AA_samples + (i-1)*AA_inc_samples, true); } gTimer.stop("rendert"); Y_INFO << integratorName << ": Overall rendertime: "<< gTimer.getTime("rendert")<<"s\n"; return true; } bool tiledIntegrator_t::renderPass(int samples, int offset, bool adaptive) { int nthreads = scene->getNumThreads(); #ifdef USING_THREADS if(nthreads>1) { threadControl_t tc; std::vector<renderWorker_t *> workers; for(int i=0;i<nthreads;++i) workers.push_back(new renderWorker_t(this, scene, imageFilm, &tc, i, samples, offset, adaptive)); for(int i=0;i<nthreads;++i) { workers[i]->run(); } //update finished tiles tc.countCV.lock(); while(tc.finishedThreads < nthreads) { tc.countCV.wait(); for(size_t i=0; i<tc.areas.size(); ++i) imageFilm->finishArea(tc.areas[i]); tc.areas.clear(); } tc.countCV.unlock(); //join all threads (although they probably have exited already, but not necessarily): for(int i=0;i<nthreads;++i) delete workers[i]; } else { #endif renderArea_t a; while(imageFilm->nextArea(a)) { if(scene->getSignals() & Y_SIG_ABORT) break; renderTile(a, samples, offset, adaptive,0); imageFilm->finishArea(a); } #ifdef USING_THREADS } #endif return true; //hm...quite useless the return value :) } bool tiledIntegrator_t::renderTile(renderArea_t &a, int n_samples, int offset, bool adaptive, int threadID) { int x, y; const camera_t* camera = scene->getCamera(); bool do_depth = scene->doDepth(); x=camera->resX(); y=camera->resY(); diffRay_t c_ray; ray_t d_ray; PFLOAT dx=0.5, dy=0.5, d1=1.0/(PFLOAT)n_samples; float lens_u=0.5f, lens_v=0.5f; PFLOAT wt, wt_dummy; random_t prng(offset*(x*a.Y+a.X)+123); renderState_t rstate(&prng); rstate.threadID = threadID; rstate.cam = camera; bool sampleLns = camera->sampleLense(); int pass_offs=offset, end_x=a.X+a.W, end_y=a.Y+a.H; for(int i=a.Y; i<end_y; ++i) { for(int j=a.X; j<end_x; ++j) { if(scene->getSignals() & Y_SIG_ABORT) break; if(adaptive) { if(!imageFilm->doMoreSamples(j, i)) continue; } rstate.pixelNumber = x*i+j; //rstate.screenpos = point3d_t(2.0f * j / x - 1.0f, -2.0f * i / y + 1.0f, 0.f); // screen position in -1..1 coordinates rstate.samplingOffs = fnv_32a_buf(i*fnv_32a_buf(j));//fnv_32a_buf(rstate.pixelNumber); float toff = scrHalton(5, pass_offs+rstate.samplingOffs); // **shall be just the pass number...** for(int sample=0; sample<n_samples; ++sample) { rstate.setDefaults(); rstate.pixelSample = pass_offs+sample; rstate.time = addMod1((PFLOAT)sample*d1, toff);//(0.5+(PFLOAT)sample)*d1; // the (1/n, Larcher&Pillichshammer-Seq.) only gives good coverage when total sample count is known // hence we use scrambled (Sobol, van-der-Corput) for multipass AA if(AA_passes>1) { dx = RI_S(rstate.pixelSample, rstate.samplingOffs); dy = RI_vdC(rstate.pixelSample, rstate.samplingOffs); } else if(n_samples > 1) { dx = (0.5+(PFLOAT)sample)*d1; dy = RI_LP(sample+rstate.samplingOffs); } if(sampleLns) { lens_u = scrHalton(3, rstate.pixelSample+rstate.samplingOffs); lens_v = scrHalton(4, rstate.pixelSample+rstate.samplingOffs); } c_ray = camera->shootRay(j+dx, i+dy, lens_u, lens_v, wt); if(wt==0.0) continue; //setup ray differentials d_ray = camera->shootRay(j+1+dx, i+dy, lens_u, lens_v, wt_dummy); c_ray.xfrom = d_ray.from; c_ray.xdir = d_ray.dir; d_ray = camera->shootRay(j+dx, i+1+dy, lens_u, lens_v, wt_dummy); c_ray.yfrom = d_ray.from; c_ray.ydir = d_ray.dir; c_ray.time = rstate.time; c_ray.hasDifferentials = true; // col = T * L_o + L_v colorA_t col = integrate(rstate, c_ray); // L_o // I really don't like this here, bert... col *= scene->volIntegrator->transmittance(rstate, c_ray); // T col += scene->volIntegrator->integrate(rstate, c_ray); // L_v imageFilm->addSample(wt * col, j, i, dx, dy,/*.5f, .5f,*/ &a); } if(do_depth) imageFilm->setChanPixel(c_ray.tmax, 0, j, i); } } return true; } __END_YAFRAY <commit_msg>- Core: integrator now adds a black sample when camera wt == 0 instead of ommiting sampling, this allows for angular camera circular mask to be antialiased (needs thorough testing)<commit_after> #include <yafraycore/tiledintegrator.h> #include <core_api/imagefilm.h> #include <core_api/camera.h> #include <yafraycore/timer.h> #include <yafraycore/scr_halton.h> #include <utilities/mcqmc.h> #include <utilities/sample_utils.h> #include <sstream> __BEGIN_YAFRAY #ifdef USING_THREADS class renderWorker_t: public yafthreads::thread_t { public: renderWorker_t(tiledIntegrator_t *it, scene_t *s, imageFilm_t *f, threadControl_t *c, int id, int smpls, int offs=0, bool adptv=false): integrator(it), scene(s), imageFilm(f), control(c), samples(smpls), offset(offs), threadID(id), adaptive(adptv) { /* std::cout << "renderWorker_t::renderWorker_t(): *this="<<(void*)this<<std::endl; */ }; virtual void body(); protected: tiledIntegrator_t *integrator; scene_t *scene; imageFilm_t *imageFilm; threadControl_t *control; int samples, offset; int threadID; bool adaptive; }; void renderWorker_t::body() { renderArea_t a; while(imageFilm->nextArea(a)) { if(scene->getSignals() & Y_SIG_ABORT) break; integrator->renderTile(a, samples, offset, adaptive, threadID); // imageFilm->finishArea(a); control->countCV.lock(); control->areas.push_back(a); control->countCV.signal(); control->countCV.unlock(); } control->countCV.lock(); ++(control->finishedThreads); control->countCV.signal(); control->countCV.unlock(); } #endif bool tiledIntegrator_t::render(imageFilm_t *image) { std::stringstream passString; imageFilm = image; scene->getAAParameters(AA_samples, AA_passes, AA_inc_samples, AA_threshold); Y_INFO << integratorName << ": Rendering "<<AA_passes<<" passes\n"; Y_INFO << integratorName << ": Min. " << AA_samples << " samples\n"; Y_INFO << integratorName << ": "<< AA_inc_samples << " per additional pass\n"; Y_INFO << integratorName << ": Max. "<<AA_samples + std::max(0,AA_passes-1)*AA_inc_samples<<" total samples\n"; passString << "Rendering pass 1 of " << std::max(1, AA_passes) << "..."; if(intpb) intpb->setTag(passString.str().c_str()); gTimer.addEvent("rendert"); gTimer.start("rendert"); imageFilm->init(AA_passes); renderPass(AA_samples, 0, false); for(int i=1; i<AA_passes; ++i) { if(scene->getSignals() & Y_SIG_ABORT) break; imageFilm->setAAThreshold(AA_threshold); imageFilm->nextPass(true); renderPass(AA_inc_samples, AA_samples + (i-1)*AA_inc_samples, true); } gTimer.stop("rendert"); Y_INFO << integratorName << ": Overall rendertime: "<< gTimer.getTime("rendert")<<"s\n"; return true; } bool tiledIntegrator_t::renderPass(int samples, int offset, bool adaptive) { int nthreads = scene->getNumThreads(); #ifdef USING_THREADS if(nthreads>1) { threadControl_t tc; std::vector<renderWorker_t *> workers; for(int i=0;i<nthreads;++i) workers.push_back(new renderWorker_t(this, scene, imageFilm, &tc, i, samples, offset, adaptive)); for(int i=0;i<nthreads;++i) { workers[i]->run(); } //update finished tiles tc.countCV.lock(); while(tc.finishedThreads < nthreads) { tc.countCV.wait(); for(size_t i=0; i<tc.areas.size(); ++i) imageFilm->finishArea(tc.areas[i]); tc.areas.clear(); } tc.countCV.unlock(); //join all threads (although they probably have exited already, but not necessarily): for(int i=0;i<nthreads;++i) delete workers[i]; } else { #endif renderArea_t a; while(imageFilm->nextArea(a)) { if(scene->getSignals() & Y_SIG_ABORT) break; renderTile(a, samples, offset, adaptive,0); imageFilm->finishArea(a); } #ifdef USING_THREADS } #endif return true; //hm...quite useless the return value :) } bool tiledIntegrator_t::renderTile(renderArea_t &a, int n_samples, int offset, bool adaptive, int threadID) { int x, y; const camera_t* camera = scene->getCamera(); bool do_depth = scene->doDepth(); x=camera->resX(); y=camera->resY(); diffRay_t c_ray; ray_t d_ray; PFLOAT dx=0.5, dy=0.5, d1=1.0/(PFLOAT)n_samples; float lens_u=0.5f, lens_v=0.5f; PFLOAT wt, wt_dummy; random_t prng(offset*(x*a.Y+a.X)+123); renderState_t rstate(&prng); rstate.threadID = threadID; rstate.cam = camera; bool sampleLns = camera->sampleLense(); int pass_offs=offset, end_x=a.X+a.W, end_y=a.Y+a.H; for(int i=a.Y; i<end_y; ++i) { for(int j=a.X; j<end_x; ++j) { if(scene->getSignals() & Y_SIG_ABORT) break; if(adaptive) { if(!imageFilm->doMoreSamples(j, i)) continue; } rstate.pixelNumber = x*i+j; //rstate.screenpos = point3d_t(2.0f * j / x - 1.0f, -2.0f * i / y + 1.0f, 0.f); // screen position in -1..1 coordinates rstate.samplingOffs = fnv_32a_buf(i*fnv_32a_buf(j));//fnv_32a_buf(rstate.pixelNumber); float toff = scrHalton(5, pass_offs+rstate.samplingOffs); // **shall be just the pass number...** for(int sample=0; sample<n_samples; ++sample) { rstate.setDefaults(); rstate.pixelSample = pass_offs+sample; rstate.time = addMod1((PFLOAT)sample*d1, toff);//(0.5+(PFLOAT)sample)*d1; // the (1/n, Larcher&Pillichshammer-Seq.) only gives good coverage when total sample count is known // hence we use scrambled (Sobol, van-der-Corput) for multipass AA if(AA_passes>1) { dx = RI_S(rstate.pixelSample, rstate.samplingOffs); dy = RI_vdC(rstate.pixelSample, rstate.samplingOffs); } else if(n_samples > 1) { dx = (0.5+(PFLOAT)sample)*d1; dy = RI_LP(sample+rstate.samplingOffs); } if(sampleLns) { lens_u = scrHalton(3, rstate.pixelSample+rstate.samplingOffs); lens_v = scrHalton(4, rstate.pixelSample+rstate.samplingOffs); } c_ray = camera->shootRay(j+dx, i+dy, lens_u, lens_v, wt); if(wt==0.0) { imageFilm->addSample(colorA_t(0.f), j, i, dx, dy, &a); continue; } //setup ray differentials d_ray = camera->shootRay(j+1+dx, i+dy, lens_u, lens_v, wt_dummy); c_ray.xfrom = d_ray.from; c_ray.xdir = d_ray.dir; d_ray = camera->shootRay(j+dx, i+1+dy, lens_u, lens_v, wt_dummy); c_ray.yfrom = d_ray.from; c_ray.ydir = d_ray.dir; c_ray.time = rstate.time; c_ray.hasDifferentials = true; // col = T * L_o + L_v colorA_t col = integrate(rstate, c_ray); // L_o // I really don't like this here, bert... col *= scene->volIntegrator->transmittance(rstate, c_ray); // T col += scene->volIntegrator->integrate(rstate, c_ray); // L_v imageFilm->addSample(wt * col, j, i, dx, dy,/*.5f, .5f,*/ &a); } if(do_depth) imageFilm->setChanPixel(c_ray.tmax, 0, j, i); } } return true; } __END_YAFRAY <|endoftext|>
<commit_before>#include "migrate/migrate.hpp" #include <getopt.h> #include "help.hpp" #include "string.h" #include <boost/algorithm/string/join.hpp> #include <boost/algorithm/string/replace.hpp> namespace migrate { void usage(UNUSED const char *name) { Help_Pager *help = Help_Pager::instance(); help->pagef("Usage:\n" " rethinkdb migrate --in -f <file_1> [-f <file_2> ...] --out -f <file_1> [-f <file_2>] [--intermediate file]\n"); help->pagef("\n" "Migrate from one version of RethinkDB to another\n" "\n" "Options:\n" " -f, --file Path to file or block device where database goes.\n" " --in Specify input files, -f (or --file) flags following\n" " this command will be used to extract data from.\n" " --out Specify output files, -f (or --file) flags following\n" " this command is where the new database will go.\n" " --intermediate File to store intermediate raw memcached commands" " in. It defaults to: %s.\n", TEMP_MIGRATION_FILE); help->pagef(" --force Allow migrate to overwrite an existing database file.\n"); help->pagef("\n" "Migration extracts data from the old database into a portable format of raw\n" "memcached commands and then reinserts the data into a new file version being\n" "migrated to.\n" "Migration can done from a set of files to themselves. Effectively migrating\n" "in place. This requires a --force flag.\n" "Note: if migration in place is interrupted it has the potential to leave the\n" "target files with missing data. Should this happen the intermediate file will\n" "be the only remaining copy of the data. Please consult support for help getting\n" "this data back in to a database.\n"); exit(0); } void parse_cmd_args(int argc, char **argv, config_t *config) { // TODO disallow rogue options. //Grab the exec-name config->exec_name = argv[0]; argc--; argv++; enum reading_list_t { in = 0, out, unset } reading_list; reading_list = unset; optind = 1; // reinit getopt. if (argc >= 2) { if (!strncmp("help", argv[1], 4)) { usage(argv[0]); } } for (;;) { int do_help = 0; /* Which list a -f argument goes into */ int switch_to_reading_in_files = 0; int switch_to_reading_out_files = 0; static const struct option long_options[] = { {"in", no_argument, &switch_to_reading_in_files, 1}, {"out", no_argument, &switch_to_reading_out_files, 1}, {"file", required_argument, 0, 'f'}, {"intermediate", required_argument, 0, 'i'}, {"force", no_argument, (int *) &(config->force), 1}, {"help", no_argument, &do_help, 1}, {0, 0, 0, 0} }; int option_index = 0; int c = getopt_long(argc, argv, "f:i:", long_options, &option_index); if (do_help) { c = 'h'; } if (switch_to_reading_in_files) { reading_list = in; } if (switch_to_reading_out_files) { reading_list = out; } // Detect the end of the options. if (c == -1) break; switch (c) { case 0: break; case 'f': if (reading_list == in) config->input_filenames.push_back(optarg); else if (reading_list == out) config->output_filenames.push_back(optarg); else fail_due_to_user_error("-f argument must follow either a --in or a --out flag\n"); break; case 'i': config->intermediate_file = optarg; break; default: // getopt_long already printed an error message. usage(argv[0]); } } if (optind < argc) { fail_due_to_user_error("Unexpected extra argument: \"%s\"", argv[optind]); } // Sanity checks if (config->input_filenames.empty()) { fprintf(stderr, "At least one input file must be specified.\n"); usage(argv[0]); } { std::vector<std::string> names = config->input_filenames; std::sort(names.begin(), names.end()); if (std::unique(names.begin(), names.end()) != names.end()) { fail_due_to_user_error("Duplicate file names provided."); } } } } // namespace migrate //convert spaces to command line safe '\ ' space escapes Truly sucks that I //have to write this, but the documentation for boost just wasn't explaining //things to me, if anyone knows how to use replace all, please rewrite this std::string escape_spaces(std::string str) { for (std::string::iterator it = str.begin(); it != str.end(); it++) { if (*it == ' ') { it = str.insert(it, '\\') + 1; } } return str; } int run_migrate(int argc, char **argv) { migrate::config_t cfg; migrate::parse_cmd_args(argc, argv, &cfg); //BREAKPOINT; std::vector<std::string> command_line; command_line.push_back("rdb_migrate"); command_line.push_back("-r"); command_line.push_back(cfg.exec_name); for (std::vector<std::string>::iterator it = cfg.input_filenames.begin(); it != cfg.input_filenames.end(); it++) { command_line.push_back("-i"); command_line.push_back(escape_spaces(*it)); } for (std::vector<std::string>::iterator it = cfg.output_filenames.begin(); it != cfg.output_filenames.end(); it++) { command_line.push_back("-o"); command_line.push_back(escape_spaces(*it)); } command_line.push_back("-s"); command_line.push_back(cfg.intermediate_file); if (cfg.force) command_line.push_back("-f"); int res = system(boost::algorithm::join(command_line, " ").c_str()); if (res != 0) fprintf(stderr, "Migration failed.\n"); return res; } <commit_msg>Polish and clarify migrate help output. (affects #359)<commit_after>#include "migrate/migrate.hpp" #include <getopt.h> #include "help.hpp" #include "string.h" #include <boost/algorithm/string/join.hpp> #include <boost/algorithm/string/replace.hpp> namespace migrate { void usage(UNUSED const char *name) { Help_Pager *help = Help_Pager::instance(); help->pagef("Usage:\n" " rethinkdb migrate --in -f <file_1> [-f <file_2> ...] --out -f <file_1> [-f <file_2>] [--intermediate file]\n"); help->pagef("\n" "Migrate from one version of RethinkDB to another\n" "\n" "Options:\n" " --in Specify input files, -f (or --file) flags following\n" " this command will be used to extract data from.\n" " --out Specify output files, -f (or --file) flags following\n" " this command is where the new database will go.\n" " -f, --file Path to a file or block device that constitutes to\n" " either the input or output database.\n" " --intermediate File to store intermediate raw memcached commands\n" " in. It defaults to: %s.\n", TEMP_MIGRATION_FILE); help->pagef(" --force Allow migrate to overwrite an existing database file.\n"); help->pagef("\n" "Migration extracts data from the old database into a portable format of raw\n" "memcached commands and then reinserts the data into a new file version being\n" "migrated to.\n" "Migration can be done from a set of files to themselves. Effectively migrating\n" "in place. This requires a --force flag.\n" "Note: if migration in place is interrupted it has the potential to leave the\n" "target files with missing data. Should this happen the intermediate file will\n" "be the only remaining copy of the data. Please consult support for help getting\n" "this data back in to a database.\n"); exit(0); } void parse_cmd_args(int argc, char **argv, config_t *config) { // TODO disallow rogue options. //Grab the exec-name config->exec_name = argv[0]; argc--; argv++; enum reading_list_t { in = 0, out, unset } reading_list; reading_list = unset; optind = 1; // reinit getopt. if (argc >= 2) { if (!strncmp("help", argv[1], 4)) { usage(argv[0]); } } for (;;) { int do_help = 0; /* Which list a -f argument goes into */ int switch_to_reading_in_files = 0; int switch_to_reading_out_files = 0; static const struct option long_options[] = { {"in", no_argument, &switch_to_reading_in_files, 1}, {"out", no_argument, &switch_to_reading_out_files, 1}, {"file", required_argument, 0, 'f'}, {"intermediate", required_argument, 0, 'i'}, {"force", no_argument, (int *) &(config->force), 1}, {"help", no_argument, &do_help, 1}, {0, 0, 0, 0} }; int option_index = 0; int c = getopt_long(argc, argv, "f:i:", long_options, &option_index); if (do_help) { c = 'h'; } if (switch_to_reading_in_files) { reading_list = in; } if (switch_to_reading_out_files) { reading_list = out; } // Detect the end of the options. if (c == -1) break; switch (c) { case 0: break; case 'f': if (reading_list == in) config->input_filenames.push_back(optarg); else if (reading_list == out) config->output_filenames.push_back(optarg); else fail_due_to_user_error("-f argument must follow either a --in or a --out flag\n"); break; case 'i': config->intermediate_file = optarg; break; default: // getopt_long already printed an error message. usage(argv[0]); } } if (optind < argc) { fail_due_to_user_error("Unexpected extra argument: \"%s\"", argv[optind]); } // Sanity checks if (config->input_filenames.empty()) { fprintf(stderr, "At least one input file must be specified.\n"); usage(argv[0]); } { std::vector<std::string> names = config->input_filenames; std::sort(names.begin(), names.end()); if (std::unique(names.begin(), names.end()) != names.end()) { fail_due_to_user_error("Duplicate file names provided."); } } } } // namespace migrate //convert spaces to command line safe '\ ' space escapes Truly sucks that I //have to write this, but the documentation for boost just wasn't explaining //things to me, if anyone knows how to use replace all, please rewrite this std::string escape_spaces(std::string str) { for (std::string::iterator it = str.begin(); it != str.end(); it++) { if (*it == ' ') { it = str.insert(it, '\\') + 1; } } return str; } int run_migrate(int argc, char **argv) { migrate::config_t cfg; migrate::parse_cmd_args(argc, argv, &cfg); //BREAKPOINT; std::vector<std::string> command_line; command_line.push_back("rdb_migrate"); command_line.push_back("-r"); command_line.push_back(cfg.exec_name); for (std::vector<std::string>::iterator it = cfg.input_filenames.begin(); it != cfg.input_filenames.end(); it++) { command_line.push_back("-i"); command_line.push_back(escape_spaces(*it)); } for (std::vector<std::string>::iterator it = cfg.output_filenames.begin(); it != cfg.output_filenames.end(); it++) { command_line.push_back("-o"); command_line.push_back(escape_spaces(*it)); } command_line.push_back("-s"); command_line.push_back(cfg.intermediate_file); if (cfg.force) command_line.push_back("-f"); int res = system(boost::algorithm::join(command_line, " ").c_str()); if (res != 0) fprintf(stderr, "Migration failed.\n"); return res; } <|endoftext|>
<commit_before>#ifndef DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH #define DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH //#ifdef HAVE_EIGEN #include <dune/common/shared_ptr.hh> #include <dune/stuff/la/container/pattern.hh> #include <dune/stuff/la/container/eigen.hh> namespace Dune { namespace Detailed { namespace Discretizations { namespace LA { namespace Container { namespace Factory { template< class ElementType > class Eigen { public: typedef Dune::Stuff::LA::Container::EigenRowMajorSparseMatrix< ElementType > RowMajorSparseMatrixType; typedef Dune::Stuff::LA::Container::EigenDenseMatrix< ElementType > DenseMatrixType; typedef Dune::Stuff::LA::Container::EigenDenseVector< ElementType > DenseVectorType; typedef Dune::Stuff::LA::Container::SparsityPatternDefault PatternType; template< class TestSpaceType, class AnsatzSpaceType > static Dune::shared_ptr< RowMajorSparseMatrixType > createRowMajorSparseMatrix(const TestSpaceType& testSpace, const AnsatzSpaceType& ansatzSpace) { typedef Dune::Stuff::LA::Container::SparsityPatternDefault PatternType; const Dune::shared_ptr< const PatternType > pattern = testSpace.computePattern(ansatzSpace); return createRowMajorSparseMatrix(testSpace, ansatzSpace, *pattern); } // static ... createRowMajorSparseMatrix(...) template< class TestSpaceType, class AnsatzSpaceType > static Dune::shared_ptr< RowMajorSparseMatrixType > createRowMajorSparseMatrix(const TestSpaceType& testSpace, const AnsatzSpaceType& ansatzSpace, const PatternType& pattern) { return Dune::make_shared< RowMajorSparseMatrixType >(testSpace.map().size(), ansatzSpace.map().size(), pattern); } // static ... createRowMajorSparseMatrix(...) template< class TestSpaceType, class AnsatzSpaceType > static Dune::shared_ptr< DenseMatrixType > createDenseMatrix(const TestSpaceType& testSpace, const AnsatzSpaceType& ansatzSpace) { return Dune::make_shared< DenseMatrixType >(testSpace.map().size(), ansatzSpace.map().size()); } // static ... createDenseMatrix(...) template< class SpaceType > static Dune::shared_ptr< DenseVectorType > createDenseVector(const SpaceType& space) { return Dune::make_shared< DenseVectorType >(space.map().size()); } // static Dune::shared_ptr< DenseVectorType > createDenseVector(const SpaceType& space) }; // class Eigen } // namespace Factory } // namespace Conatiner } // namespace LA } // namespace Discretizations } // namespace Detailed } // namespace Dune //#endif // HAVE_EIGEN #endif // DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH <commit_msg>[la.container.factory.eigen] reenabled HAVE_EIGEN guard<commit_after>#ifndef DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH #define DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH #ifdef HAVE_EIGEN #include <dune/common/shared_ptr.hh> #include <dune/stuff/la/container/pattern.hh> #include <dune/stuff/la/container/eigen.hh> namespace Dune { namespace Detailed { namespace Discretizations { namespace LA { namespace Container { namespace Factory { template< class ElementType > class Eigen { public: typedef Dune::Stuff::LA::Container::EigenRowMajorSparseMatrix< ElementType > RowMajorSparseMatrixType; typedef Dune::Stuff::LA::Container::EigenDenseMatrix< ElementType > DenseMatrixType; typedef Dune::Stuff::LA::Container::EigenDenseVector< ElementType > DenseVectorType; typedef Dune::Stuff::LA::Container::SparsityPatternDefault PatternType; template< class TestSpaceType, class AnsatzSpaceType > static Dune::shared_ptr< RowMajorSparseMatrixType > createRowMajorSparseMatrix(const TestSpaceType& testSpace, const AnsatzSpaceType& ansatzSpace) { typedef Dune::Stuff::LA::Container::SparsityPatternDefault PatternType; const Dune::shared_ptr< const PatternType > pattern = testSpace.computePattern(ansatzSpace); return createRowMajorSparseMatrix(testSpace, ansatzSpace, *pattern); } // static ... createRowMajorSparseMatrix(...) template< class TestSpaceType, class AnsatzSpaceType > static Dune::shared_ptr< RowMajorSparseMatrixType > createRowMajorSparseMatrix(const TestSpaceType& testSpace, const AnsatzSpaceType& ansatzSpace, const PatternType& pattern) { return Dune::make_shared< RowMajorSparseMatrixType >(testSpace.map().size(), ansatzSpace.map().size(), pattern); } // static ... createRowMajorSparseMatrix(...) template< class TestSpaceType, class AnsatzSpaceType > static Dune::shared_ptr< DenseMatrixType > createDenseMatrix(const TestSpaceType& testSpace, const AnsatzSpaceType& ansatzSpace) { return Dune::make_shared< DenseMatrixType >(testSpace.map().size(), ansatzSpace.map().size()); } // static ... createDenseMatrix(...) template< class SpaceType > static Dune::shared_ptr< DenseVectorType > createDenseVector(const SpaceType& space) { return Dune::make_shared< DenseVectorType >(space.map().size()); } // static Dune::shared_ptr< DenseVectorType > createDenseVector(const SpaceType& space) }; // class Eigen } // namespace Factory } // namespace Conatiner } // namespace LA } // namespace Discretizations } // namespace Detailed } // namespace Dune #endif // HAVE_EIGEN #endif // DUNE_DETAILED_DISCRETIZATIONS_LA_CONTAINER_FACTORY_EIGEN_HH <|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "stdafx.h" #include <limits> #include <string> #include <stdlib.h> #include "common/common.h" #include "util/ascii_util.h" #include "decimal.h" #include "floatimpl.h" #include "integer.h" #include "zorbaserialization/serialize_zorba_types.h" #include "zorbaserialization/serialize_template_types.h" /////////////////////////////////////////////////////////////////////////////// namespace zorba { zstring const& nan_str() { static zstring const value( "NaN" ); return value; } zstring const& pos_inf_str() { static zstring const value( "INF" ); return value; } zstring const& neg_inf_str() { static zstring const value( "-INF" ); return value; } //////////////////////////////////////////////////////////////////////////////// static void count_significant_digits( char digit, int *significant_digits, int *trailing_zeros ) { if ( digit == '0' ) ++*trailing_zeros; else { if ( (*significant_digits)++ ) *significant_digits += *trailing_zeros; *trailing_zeros = 0; } } template<typename F> void FloatImpl<F>::parse( char const *s ) { if ( !*s ) throw std::invalid_argument( "empty string" ); int significant_digits = 0; s = ascii::trim_start_space( s ); if ( !parse_etc( s ) ) { char const *const first_non_ws = s; int trailing_zeros = 0; // // We need got_digit to know that we're potentially parsing a floating // point value comprised of at least one digit -- which means the value // can't be one of the special values of INF, -INF, or NaN. // // We need to know this to prevent aton() from parsing the special values // since it (via strtod() that it uses) allows them regardless of case // whereas XQuery insists on a specific case. // bool got_digit = false; if ( *s == '+' || *s == '-' ) ++s; if ( ascii::is_digit( *s ) ) { got_digit = true; do { count_significant_digits( *s, &significant_digits, &trailing_zeros ); } while ( ascii::is_digit( *++s ) ); } if ( *s == '.' && ascii::is_digit( *++s ) ) { got_digit = true; do { count_significant_digits( *s, &significant_digits, &trailing_zeros ); } while ( ascii::is_digit( *++s ) ); } if ( *s == 'e' || *s == 'E' ) { ++s; if ( *s == '+' || *s == '-' ) ++s; if ( ascii::is_digit( *s ) ) { got_digit = true; while ( ascii::is_digit( *++s ) ) ; } } if ( !got_digit ) throw std::invalid_argument( BUILD_STRING( '"', first_non_ws, "\": invalid floating-point literal" ) ); value_ = ztd::aton<value_type>( first_non_ws ); } precision_ = significant_digits < max_precision() ? significant_digits : max_precision(); } template<typename FloatType> bool FloatImpl<FloatType>::parse_etc( char const *s ) { if ( strncmp( s, "INF", 3 ) == 0 ) { value_ = FloatImpl<FloatType>::pos_inf().value_; s += 3; } else if ( strncmp( s, "-INF", 4 ) == 0 ) { value_ = FloatImpl<FloatType>::neg_inf().value_; s += 4; } else if ( strncmp( s, "NaN", 3 ) == 0 ) { value_ = FloatImpl<FloatType>::nan().value_; s += 3; } else if ( strncmp( s, "+INF", 4 ) == 0 ) { value_ = FloatImpl<FloatType>::pos_inf().value_; s += 4; } else return false; return !*ascii::trim_start_space( s ); } ////////// constructors /////////////////////////////////////////////////////// template<typename F> FloatImpl<F>::FloatImpl( Decimal const &d ) { zstring const temp( d.toString() ); parse( temp.c_str() ); } template<typename F> template<class T> FloatImpl<F>::FloatImpl( IntegerImpl<T> const &i ) { zstring const temp( i.toString() ); parse( temp.c_str() ); } template FloatImpl<float>::FloatImpl( Integer const& ); template FloatImpl<float>::FloatImpl( NegativeInteger const& ); template FloatImpl<float>::FloatImpl( NonNegativeInteger const& ); template FloatImpl<float>::FloatImpl( NonPositiveInteger const& ); template FloatImpl<float>::FloatImpl( PositiveInteger const& ); template FloatImpl<double>::FloatImpl( Integer const& ); template FloatImpl<double>::FloatImpl( NegativeInteger const& ); template FloatImpl<double>::FloatImpl( NonNegativeInteger const& ); template FloatImpl<double>::FloatImpl( NonPositiveInteger const& ); template FloatImpl<double>::FloatImpl( PositiveInteger const& ); ////////// assignment operators /////////////////////////////////////////////// template<typename F> FloatImpl<F>& FloatImpl<F>::operator=( Decimal const &d ) { zstring const temp( d.toString() ); parse( temp.c_str() ); return *this; } template<typename F> template<class T> FloatImpl<F>& FloatImpl<F>::operator=( IntegerImpl<T> const &i ) { zstring const temp( i.toString() ); parse( temp.c_str() ); return *this; } #define ZORBA_INSTANTIATE(F,I) \ template FloatImpl<F>& FloatImpl<F>::operator=( I const& ) ZORBA_INSTANTIATE(float,Integer); ZORBA_INSTANTIATE(float,NegativeInteger); ZORBA_INSTANTIATE(float,NonNegativeInteger); ZORBA_INSTANTIATE(float,NonPositiveInteger); ZORBA_INSTANTIATE(float,PositiveInteger); ZORBA_INSTANTIATE(double,Integer); ZORBA_INSTANTIATE(double,NegativeInteger); ZORBA_INSTANTIATE(double,NonNegativeInteger); ZORBA_INSTANTIATE(double,NonPositiveInteger); ZORBA_INSTANTIATE(double,PositiveInteger); #undef ZORBA_INSTANTIATE ////////// math functions ///////////////////////////////////////////////////// template<typename F> FloatImpl<F> FloatImpl<F>::acos() const { if ( *this < numeric_consts<FloatImpl>::neg_one() || *this > numeric_consts<FloatImpl>::one() ) return nan(); return FloatImpl<F>( isNegZero() ? -std::acos( value_ ) : std::acos( value_ ) ); } template<typename F> FloatImpl<F> FloatImpl<F>::asin() const { if ( *this < numeric_consts<FloatImpl>::neg_one() || *this > numeric_consts<FloatImpl>::one() ) return nan(); return FloatImpl<F>( std::asin( value_ ) ); } template<typename F> void FloatImpl<F>::frexp( FloatImpl<F> &out_mantissa, Integer &out_exponent ) const { int expint; out_mantissa = FloatImpl( ::frexp( value_, &expint ) ); out_exponent = Integer( expint ); } template<> void FloatImpl<double>::modf( FloatImpl<double> &out_fraction, FloatImpl<double> &out_integer ) const { double int_part; out_fraction = std::modf( value_, &int_part ); out_integer = int_part; } template<> void FloatImpl<float>::modf( FloatImpl<float> &out_fraction, FloatImpl<float> &out_integer ) const { float int_part; out_fraction = ::modff( value_, &int_part ); out_integer = int_part; } template<typename F> FloatImpl<F> FloatImpl<F>::round() const { return round( numeric_consts<xs_integer>::zero() ); } template<typename F> FloatImpl<F> FloatImpl<F>::round( Integer const &precision ) const { FloatImpl result; if ( isFinite() && !isZero() ) { MAPM m( Decimal::round2( Decimal::value_type( value_ ), Decimal::value_type( precision.itod() ) ) ); if ( value_ < 0 && m.sign() == 0 ) result = neg_zero(); else { char buf[200]; m.toString( buf, ZORBA_FLOAT_POINT_PRECISION ); result.parse( buf ); } } else result.value_ = value_; return result; } template<typename F> FloatImpl<F> FloatImpl<F>::roundHalfToEven( Integer const &precision ) const { FloatImpl result; if ( isFinite() && !isZero() ) { MAPM m( Decimal::roundHalfToEven2( Decimal::value_type( value_ ), Decimal::value_type( precision.itod() ) ) ); if ( value_ < 0 && m.sign() == 0 ) result = neg_zero(); else { char buf[200]; m.toString( buf, ZORBA_FLOAT_POINT_PRECISION ); result.parse( buf ); } } else result.value_ = value_; return result; } ////////// miscellaneous ////////////////////////////////////////////////////// template<> bool FloatImpl<double>::isNegZero() const { if ( !value_ ) { char const *const bytes = reinterpret_cast<char const*>( &value_ ); // test for little endian and big endian return bytes[0] || bytes[7]; // TODO: depends on sizeof(double) } return false; } template<> bool FloatImpl<float>::isNegZero() const { if ( !value_ ) { char const *const bytes = reinterpret_cast<char const*>( &value_ ); // test for little endian and big endian return bytes[0] || bytes[3]; // TODO: depends on sizeof(float) } return false; } template<typename F> FloatImpl<F> const& FloatImpl<F>::nan() { static FloatImpl<F> const value( std::sqrt( -1.0 ) ); return value; } template<typename F> FloatImpl<F> const& FloatImpl<F>::neg_inf() { static FloatImpl<F> const value( -std::numeric_limits<F>::infinity() ); return value; } template<typename F> FloatImpl<F> const& FloatImpl<F>::neg_zero() { static FloatImpl<F> const value( -0.0 ); return value; } template<typename F> FloatImpl<F> const& FloatImpl<F>::pos_inf() { static FloatImpl<F> const value( std::numeric_limits<F>::infinity() ); return value; } template<typename F> zstring FloatImpl<F>::toIntegerString() const { if ( isNaN() ) return nan_str(); if (isPosInf() ) return pos_inf_str(); if ( isNegInf() ) return neg_inf_str(); if ( isPosZero() ) return "0"; if ( isNegZero() ) return "-0"; return ztd::to_string( static_cast<long long>( value_ ) ); } template<typename F> zstring FloatImpl<F>::toString( bool no_scientific_format ) const { if ( isNaN() ) return nan_str(); if ( isPosInf() ) return pos_inf_str(); if ( isNegInf() ) return neg_inf_str(); if ( isPosZero() ) return "0"; if ( isNegZero() ) return "-0"; value_type const abs_val = fabs( value_ ); value_type const lower = 0.000001f, upper = 1000000.0f; if ( no_scientific_format || (abs_val >= lower && abs_val < upper) || abs_val == 0 ) { #if 1 // This is the "spec" implementation, i.e., it is an exact application of // the spec in http://www.w3.org/TR/xpath-functions/#casting MAPM temp( value_ ); temp = temp.round( precision_ ); return Decimal::toString( temp, isNegZero(), precision_ ); #else std::stringstream stream; stream.precision(7); stream.setf(std::ios::fixed); stream << value_; zstring result(stream.str()); // remove non-significant trailing 0's long i = result.size() - 1; while (str[i] == '0') --i; if (i >= 0) { long j = i; while (str[j] != '.') --j; if (j >= 0) if (j == i) result.resize(i); else result.resize(i+1); } return result; #endif } else { char format[15]; sprintf( format, "%%#1.%dE", static_cast<int>( precision_ ) ); char buf[174]; sprintf( buf, format, static_cast<double>( value_ ) ); char *e = strchr( buf, 'E' ); char *zeros = e ? e - 1 : buf + strlen( buf ) - 1; while ( *zeros == '0' ) --zeros; if ( e ) { if ( *zeros == '.' ) ++zeros; zeros[1] = 'E'; ++e; if ( *e == '+' ) ++e; else if ( *e == '-' ) { ++zeros; zeros[1] = '-'; ++e; } while ( *e == '0' ) ++e; memmove( (void*)(zeros + 2), e, strlen( e ) + 1 ); } else { if ( *zeros == '.' ) --zeros; zeros[1] = '\0'; } Decimal::reduce( buf ); return buf; } } /////////////////////////////////////////////////////////////////////////////// template class FloatImpl<double>; template class FloatImpl<float>; #ifdef WIN32 // exported for testing only template class ZORBA_DLL_PUBLIC FloatImpl<double>; template class ZORBA_DLL_PUBLIC FloatImpl<float>; #endif /* WIN32 */ } // namespace zorba /* vim:set et sw=2 ts=2: */ <commit_msg>Put original precision back.<commit_after>/* * Copyright 2006-2008 The FLWOR Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "stdafx.h" #include <limits> #include <string> #include <stdlib.h> #include "common/common.h" #include "util/ascii_util.h" #include "decimal.h" #include "floatimpl.h" #include "integer.h" #include "zorbaserialization/serialize_zorba_types.h" #include "zorbaserialization/serialize_template_types.h" /////////////////////////////////////////////////////////////////////////////// namespace zorba { zstring const& nan_str() { static zstring const value( "NaN" ); return value; } zstring const& pos_inf_str() { static zstring const value( "INF" ); return value; } zstring const& neg_inf_str() { static zstring const value( "-INF" ); return value; } //////////////////////////////////////////////////////////////////////////////// static void count_significant_digits( char digit, int *significant_digits, int *trailing_zeros ) { if ( digit == '0' ) ++*trailing_zeros; else { if ( (*significant_digits)++ ) *significant_digits += *trailing_zeros; *trailing_zeros = 0; } } template<typename F> void FloatImpl<F>::parse( char const *s ) { if ( !*s ) throw std::invalid_argument( "empty string" ); int significant_digits = 0; s = ascii::trim_start_space( s ); if ( !parse_etc( s ) ) { char const *const first_non_ws = s; int trailing_zeros = 0; // // We need got_digit to know that we're potentially parsing a floating // point value comprised of at least one digit -- which means the value // can't be one of the special values of INF, -INF, or NaN. // // We need to know this to prevent aton() from parsing the special values // since it (via strtod() that it uses) allows them regardless of case // whereas XQuery insists on a specific case. // bool got_digit = false; if ( *s == '+' || *s == '-' ) ++s; if ( ascii::is_digit( *s ) ) { got_digit = true; do { count_significant_digits( *s, &significant_digits, &trailing_zeros ); } while ( ascii::is_digit( *++s ) ); } if ( *s == '.' && ascii::is_digit( *++s ) ) { got_digit = true; do { count_significant_digits( *s, &significant_digits, &trailing_zeros ); } while ( ascii::is_digit( *++s ) ); } if ( *s == 'e' || *s == 'E' ) { ++s; if ( *s == '+' || *s == '-' ) ++s; if ( ascii::is_digit( *s ) ) { got_digit = true; while ( ascii::is_digit( *++s ) ) ; } } if ( !got_digit ) throw std::invalid_argument( BUILD_STRING( '"', first_non_ws, "\": invalid floating-point literal" ) ); value_ = ztd::aton<value_type>( first_non_ws ); } precision_ = significant_digits < max_precision() ? significant_digits : max_precision(); } template<typename FloatType> bool FloatImpl<FloatType>::parse_etc( char const *s ) { if ( strncmp( s, "INF", 3 ) == 0 ) { value_ = FloatImpl<FloatType>::pos_inf().value_; s += 3; } else if ( strncmp( s, "-INF", 4 ) == 0 ) { value_ = FloatImpl<FloatType>::neg_inf().value_; s += 4; } else if ( strncmp( s, "NaN", 3 ) == 0 ) { value_ = FloatImpl<FloatType>::nan().value_; s += 3; } else if ( strncmp( s, "+INF", 4 ) == 0 ) { value_ = FloatImpl<FloatType>::pos_inf().value_; s += 4; } else return false; return !*ascii::trim_start_space( s ); } ////////// constructors /////////////////////////////////////////////////////// template<typename F> FloatImpl<F>::FloatImpl( Decimal const &d ) { zstring const temp( d.toString() ); parse( temp.c_str() ); } template<typename F> template<class T> FloatImpl<F>::FloatImpl( IntegerImpl<T> const &i ) { zstring const temp( i.toString() ); parse( temp.c_str() ); } template FloatImpl<float>::FloatImpl( Integer const& ); template FloatImpl<float>::FloatImpl( NegativeInteger const& ); template FloatImpl<float>::FloatImpl( NonNegativeInteger const& ); template FloatImpl<float>::FloatImpl( NonPositiveInteger const& ); template FloatImpl<float>::FloatImpl( PositiveInteger const& ); template FloatImpl<double>::FloatImpl( Integer const& ); template FloatImpl<double>::FloatImpl( NegativeInteger const& ); template FloatImpl<double>::FloatImpl( NonNegativeInteger const& ); template FloatImpl<double>::FloatImpl( NonPositiveInteger const& ); template FloatImpl<double>::FloatImpl( PositiveInteger const& ); ////////// assignment operators /////////////////////////////////////////////// template<typename F> FloatImpl<F>& FloatImpl<F>::operator=( Decimal const &d ) { zstring const temp( d.toString() ); parse( temp.c_str() ); return *this; } template<typename F> template<class T> FloatImpl<F>& FloatImpl<F>::operator=( IntegerImpl<T> const &i ) { zstring const temp( i.toString() ); parse( temp.c_str() ); return *this; } #define ZORBA_INSTANTIATE(F,I) \ template FloatImpl<F>& FloatImpl<F>::operator=( I const& ) ZORBA_INSTANTIATE(float,Integer); ZORBA_INSTANTIATE(float,NegativeInteger); ZORBA_INSTANTIATE(float,NonNegativeInteger); ZORBA_INSTANTIATE(float,NonPositiveInteger); ZORBA_INSTANTIATE(float,PositiveInteger); ZORBA_INSTANTIATE(double,Integer); ZORBA_INSTANTIATE(double,NegativeInteger); ZORBA_INSTANTIATE(double,NonNegativeInteger); ZORBA_INSTANTIATE(double,NonPositiveInteger); ZORBA_INSTANTIATE(double,PositiveInteger); #undef ZORBA_INSTANTIATE ////////// math functions ///////////////////////////////////////////////////// template<typename F> FloatImpl<F> FloatImpl<F>::acos() const { if ( *this < numeric_consts<FloatImpl>::neg_one() || *this > numeric_consts<FloatImpl>::one() ) return nan(); return FloatImpl<F>( isNegZero() ? -std::acos( value_ ) : std::acos( value_ ) ); } template<typename F> FloatImpl<F> FloatImpl<F>::asin() const { if ( *this < numeric_consts<FloatImpl>::neg_one() || *this > numeric_consts<FloatImpl>::one() ) return nan(); return FloatImpl<F>( std::asin( value_ ) ); } template<typename F> void FloatImpl<F>::frexp( FloatImpl<F> &out_mantissa, Integer &out_exponent ) const { int expint; out_mantissa = FloatImpl( ::frexp( value_, &expint ) ); out_exponent = Integer( expint ); } template<> void FloatImpl<double>::modf( FloatImpl<double> &out_fraction, FloatImpl<double> &out_integer ) const { double int_part; out_fraction = std::modf( value_, &int_part ); out_integer = int_part; } template<> void FloatImpl<float>::modf( FloatImpl<float> &out_fraction, FloatImpl<float> &out_integer ) const { float int_part; out_fraction = ::modff( value_, &int_part ); out_integer = int_part; } template<typename F> FloatImpl<F> FloatImpl<F>::round() const { return round( numeric_consts<xs_integer>::zero() ); } template<typename F> FloatImpl<F> FloatImpl<F>::round( Integer const &precision ) const { FloatImpl result; if ( isFinite() && !isZero() ) { MAPM m( Decimal::round2( Decimal::value_type( value_ ), Decimal::value_type( precision.itod() ) ) ); if ( value_ < 0 && m.sign() == 0 ) result = neg_zero(); else { char buf[200]; m.toString( buf, ZORBA_FLOAT_POINT_PRECISION ); result.parse( buf ); } } else result.value_ = value_; return result; } template<typename F> FloatImpl<F> FloatImpl<F>::roundHalfToEven( Integer const &precision ) const { FloatImpl result; if ( isFinite() && !isZero() ) { MAPM m( Decimal::roundHalfToEven2( Decimal::value_type( value_ ), Decimal::value_type( precision.itod() ) ) ); if ( value_ < 0 && m.sign() == 0 ) result = neg_zero(); else { char buf[200]; m.toString( buf, ZORBA_FLOAT_POINT_PRECISION ); result.parse( buf ); } } else result.value_ = value_; return result; } ////////// miscellaneous ////////////////////////////////////////////////////// template<> bool FloatImpl<double>::isNegZero() const { if ( !value_ ) { char const *const bytes = reinterpret_cast<char const*>( &value_ ); // test for little endian and big endian return bytes[0] || bytes[7]; // TODO: depends on sizeof(double) } return false; } template<> bool FloatImpl<float>::isNegZero() const { if ( !value_ ) { char const *const bytes = reinterpret_cast<char const*>( &value_ ); // test for little endian and big endian return bytes[0] || bytes[3]; // TODO: depends on sizeof(float) } return false; } template<typename F> FloatImpl<F> const& FloatImpl<F>::nan() { static FloatImpl<F> const value( std::sqrt( -1.0 ) ); return value; } template<typename F> FloatImpl<F> const& FloatImpl<F>::neg_inf() { static FloatImpl<F> const value( -std::numeric_limits<F>::infinity() ); return value; } template<typename F> FloatImpl<F> const& FloatImpl<F>::neg_zero() { static FloatImpl<F> const value( -0.0 ); return value; } template<typename F> FloatImpl<F> const& FloatImpl<F>::pos_inf() { static FloatImpl<F> const value( std::numeric_limits<F>::infinity() ); return value; } template<typename F> zstring FloatImpl<F>::toIntegerString() const { if ( isNaN() ) return nan_str(); if (isPosInf() ) return pos_inf_str(); if ( isNegInf() ) return neg_inf_str(); if ( isPosZero() ) return "0"; if ( isNegZero() ) return "-0"; return ztd::to_string( static_cast<long long>( value_ ) ); } template<typename F> zstring FloatImpl<F>::toString( bool no_scientific_format ) const { if ( isNaN() ) return nan_str(); if ( isPosInf() ) return pos_inf_str(); if ( isNegInf() ) return neg_inf_str(); if ( isPosZero() ) return "0"; if ( isNegZero() ) return "-0"; value_type const abs_val = fabs( value_ ); value_type const lower = 0.000001f, upper = 1000000.0f; if ( no_scientific_format || (abs_val >= lower && abs_val < upper) || abs_val == 0 ) { #if 1 // This is the "spec" implementation, i.e., it is an exact application of // the spec in http://www.w3.org/TR/xpath-functions/#casting MAPM temp( value_ ); temp = temp.round( precision_ ); return Decimal::toString( temp, isNegZero(), max_precision() ); #else std::stringstream stream; stream.precision(7); stream.setf(std::ios::fixed); stream << value_; zstring result(stream.str()); // remove non-significant trailing 0's long i = result.size() - 1; while (str[i] == '0') --i; if (i >= 0) { long j = i; while (str[j] != '.') --j; if (j >= 0) if (j == i) result.resize(i); else result.resize(i+1); } return result; #endif } else { char format[15]; sprintf( format, "%%#1.%dE", static_cast<int>( precision_ ) ); char buf[174]; sprintf( buf, format, static_cast<double>( value_ ) ); char *e = strchr( buf, 'E' ); char *zeros = e ? e - 1 : buf + strlen( buf ) - 1; while ( *zeros == '0' ) --zeros; if ( e ) { if ( *zeros == '.' ) ++zeros; zeros[1] = 'E'; ++e; if ( *e == '+' ) ++e; else if ( *e == '-' ) { ++zeros; zeros[1] = '-'; ++e; } while ( *e == '0' ) ++e; memmove( (void*)(zeros + 2), e, strlen( e ) + 1 ); } else { if ( *zeros == '.' ) --zeros; zeros[1] = '\0'; } Decimal::reduce( buf ); return buf; } } /////////////////////////////////////////////////////////////////////////////// template class FloatImpl<double>; template class FloatImpl<float>; #ifdef WIN32 // exported for testing only template class ZORBA_DLL_PUBLIC FloatImpl<double>; template class ZORBA_DLL_PUBLIC FloatImpl<float>; #endif /* WIN32 */ } // namespace zorba /* vim:set et sw=2 ts=2: */ <|endoftext|>
<commit_before><commit_msg>debugged always true condition<commit_after><|endoftext|>