text
stringlengths
54
60.6k
<commit_before>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <vector> #include <iostream> #include <cctype> #include <iomanip> #include <sstream> #include "zlib.h" #include "libtorrent/tracker_manager.hpp" #include "libtorrent/udp_tracker_connection.hpp" #include "libtorrent/io.hpp" namespace { enum { udp_connection_retries = 4, udp_announce_retries = 15, udp_connect_timeout = 15, udp_announce_timeout = 10, udp_buffer_size = 2048 }; } using namespace boost::posix_time; namespace libtorrent { udp_tracker_connection::udp_tracker_connection( tracker_request const& req , std::string const& hostname , unsigned short port , boost::weak_ptr<request_callback> c , const http_settings& stn) : tracker_connection(c) , m_request_time(second_clock::universal_time()) , m_request(req) , m_transaction_id(0) , m_connection_id(0) , m_settings(stn) , m_attempts(0) { // TODO: this is a problem. DNS-lookup is blocking! // (may block up to 5 seconds) address a(hostname.c_str(), port); if (has_requester()) requester().m_tracker_address = a; m_socket.reset(new socket(socket::udp, false)); m_socket->connect(a); send_udp_connect(); } bool udp_tracker_connection::send_finished() const { using namespace boost::posix_time; time_duration d = second_clock::universal_time() - m_request_time; return (m_transaction_id != 0 && m_connection_id != 0) || d > seconds(m_settings.tracker_timeout); } bool udp_tracker_connection::tick() { using namespace boost::posix_time; time_duration d = second_clock::universal_time() - m_request_time; if (m_connection_id == 0 && d > seconds(udp_connect_timeout)) { if (m_attempts >= udp_connection_retries) { if (has_requester()) requester().tracker_request_timed_out(m_request); return true; } send_udp_connect(); return false; } if (m_connection_id != 0 && d > seconds(udp_announce_timeout)) { if (m_attempts >= udp_announce_retries) { if (has_requester()) requester().tracker_request_timed_out(m_request); return true; } if (m_request.kind == tracker_request::announce_request) send_udp_announce(); else if (m_request.kind == tracker_request::scrape_request) send_udp_scrape(); return false; } char buf[udp_buffer_size]; int ret = m_socket->receive(buf, udp_buffer_size); // if there was nothing to receive, return if (ret == 0) return false; if (ret < 0) { socket::error_code err = m_socket->last_error(); if (err == socket::would_block) return false; throw network_error(m_socket->last_error()); } if (ret == udp_buffer_size) { if (has_requester()) requester().tracker_request_error( m_request, -1, "tracker reply too big"); return true; } if (m_connection_id == 0) { return parse_connect_response(buf, ret); } else if (m_request.kind == tracker_request::announce_request) { return parse_announce_response(buf, ret); } else if (m_request.kind == tracker_request::scrape_request) { return parse_scrape_response(buf, ret); } assert(false); return false; } void udp_tracker_connection::send_udp_announce() { if (m_transaction_id == 0) m_transaction_id = rand() ^ (rand() << 16); std::vector<char> buf; std::back_insert_iterator<std::vector<char> > out(buf); // connection_id detail::write_int64(m_connection_id, out); // action (announce) detail::write_int32(announce, out); // transaction_id detail::write_int32(m_transaction_id, out); // info_hash std::copy(m_request.info_hash.begin(), m_request.info_hash.end(), out); // peer_id std::copy(m_request.id.begin(), m_request.id.end(), out); // downloaded detail::write_int64(m_request.downloaded, out); // left detail::write_int64(m_request.left, out); // uploaded detail::write_int64(m_request.uploaded, out); // event detail::write_int32(m_request.event, out); // ip address detail::write_int32(0, out); // key detail::write_int32(m_request.key, out); // num_want detail::write_int32(m_request.num_want, out); // port detail::write_uint16(m_request.listen_port, out); // extensions detail::write_uint16(0, out); m_socket->send(&buf[0], buf.size()); m_request_time = second_clock::universal_time(); ++m_attempts; } void udp_tracker_connection::send_udp_scrape() { if (m_transaction_id == 0) m_transaction_id = rand() ^ (rand() << 16); std::vector<char> buf; std::back_insert_iterator<std::vector<char> > out(buf); // connection_id detail::write_int64(m_connection_id, out); // action (scrape) detail::write_int32(scrape, out); // transaction_id detail::write_int32(m_transaction_id, out); // info_hash std::copy(m_request.info_hash.begin(), m_request.info_hash.end(), out); m_socket->send(&buf[0], buf.size()); m_request_time = second_clock::universal_time(); ++m_attempts; } void udp_tracker_connection::send_udp_connect() { char send_buf[16]; char* ptr = send_buf; if (m_transaction_id == 0) m_transaction_id = rand() ^ (rand() << 16); // connection_id detail::write_int64(0x41727101980, ptr); // action (connect) detail::write_int32(connect, ptr); // transaction_id detail::write_int32(m_transaction_id, ptr); m_socket->send(send_buf, 16); m_request_time = second_clock::universal_time(); ++m_attempts; } bool udp_tracker_connection::parse_announce_response(const char* buf, int len) { assert(buf != 0); assert(len > 0); if (len < 8) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 8, ignoring"); #endif return false; } int action = detail::read_int32(buf); int transaction = detail::read_int32(buf); if (transaction != m_transaction_id) { return false; } if (action == error) { if (has_requester()) requester().tracker_request_error( m_request, -1, std::string(buf, buf + len - 8)); return true; } if (action != announce) return false; if (len < 20) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 20, ignoring"); #endif return false; } int interval = detail::read_int32(buf); int incomplete = detail::read_int32(buf); int complete = detail::read_int32(buf); int num_peers = (len - 20) / 6; if ((len - 20) % 6 != 0) { if (has_requester()) requester().tracker_request_error( m_request, -1, "invalid tracker response"); return true; } if (!has_requester()) return true; std::vector<peer_entry> peer_list; for (int i = 0; i < num_peers; ++i) { peer_entry e; std::stringstream s; s << (int)detail::read_uint8(buf) << "."; s << (int)detail::read_uint8(buf) << "."; s << (int)detail::read_uint8(buf) << "."; s << (int)detail::read_uint8(buf); e.ip = s.str(); e.port = detail::read_uint16(buf); e.id.clear(); peer_list.push_back(e); } requester().tracker_response(m_request, peer_list, interval , complete, incomplete); return true; } bool udp_tracker_connection::parse_scrape_response(const char* buf, int len) { assert(buf != 0); assert(len > 0); if (len < 8) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 8, ignoring"); #endif return false; } int action = detail::read_int32(buf); int transaction = detail::read_int32(buf); if (transaction != m_transaction_id) { return false; } if (action == error) { if (has_requester()) requester().tracker_request_error( m_request, -1, std::string(buf, buf + len - 8)); return true; } if (action != scrape) return false; if (len < 20) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 20, ignoring"); #endif return false; } int complete = detail::read_int32(buf); /*int downloaded = */detail::read_int32(buf); int incomplete = detail::read_int32(buf); if (!has_requester()) return true; std::vector<peer_entry> peer_list; requester().tracker_response(m_request, peer_list, 0 , complete, incomplete); return true; } bool udp_tracker_connection::parse_connect_response(const char* buf, int len) { assert(buf != 0); assert(len > 0); if (len < 8) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 8, ignoring"); #endif return false; } const char* ptr = buf; int action = detail::read_int32(ptr); int transaction = detail::read_int32(ptr); if (action == error) { if (has_requester()) requester().tracker_request_error( m_request, -1, std::string(ptr, buf + len)); return true; } if (action != connect) return false; if (m_transaction_id != transaction) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with incorrect transaction id, ignoring"); #endif return false; } if (len < 16) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a connection message size < 16, ignoring"); #endif return false; } // reset transaction m_transaction_id = 0; m_attempts = 0; m_connection_id = detail::read_int64(ptr); if (m_request.kind == tracker_request::announce_request) send_udp_announce(); else if (m_request.kind == tracker_request::scrape_request) send_udp_scrape(); return false; } } <commit_msg>*** empty log message ***<commit_after>/* Copyright (c) 2003, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <vector> #include <iostream> #include <cctype> #include <iomanip> #include <sstream> #include "zlib.h" #include "libtorrent/tracker_manager.hpp" #include "libtorrent/udp_tracker_connection.hpp" #include "libtorrent/io.hpp" namespace { enum { udp_connection_retries = 4, udp_announce_retries = 15, udp_connect_timeout = 15, udp_announce_timeout = 10, udp_buffer_size = 2048 }; } using namespace boost::posix_time; namespace libtorrent { udp_tracker_connection::udp_tracker_connection( tracker_request const& req , std::string const& hostname , unsigned short port , boost::weak_ptr<request_callback> c , const http_settings& stn) : tracker_connection(c) , m_request_time(second_clock::universal_time()) , m_request(req) , m_transaction_id(0) , m_connection_id(0) , m_settings(stn) , m_attempts(0) { // TODO: this is a problem. DNS-lookup is blocking! // (may block up to 5 seconds) address a(hostname.c_str(), port); if (has_requester()) requester().m_tracker_address = a; m_socket.reset(new socket(socket::udp, false)); m_socket->connect(a); send_udp_connect(); } bool udp_tracker_connection::send_finished() const { using namespace boost::posix_time; time_duration d = second_clock::universal_time() - m_request_time; return (m_transaction_id != 0 && m_connection_id != 0) || d > seconds(m_settings.tracker_timeout); } bool udp_tracker_connection::tick() { using namespace boost::posix_time; time_duration d = second_clock::universal_time() - m_request_time; if (m_connection_id == 0 && d > seconds(udp_connect_timeout)) { if (m_attempts >= udp_connection_retries) { if (has_requester()) requester().tracker_request_timed_out(m_request); return true; } send_udp_connect(); return false; } if (m_connection_id != 0 && d > seconds(udp_announce_timeout)) { if (m_attempts >= udp_announce_retries) { if (has_requester()) requester().tracker_request_timed_out(m_request); return true; } if (m_request.kind == tracker_request::announce_request) send_udp_announce(); else if (m_request.kind == tracker_request::scrape_request) send_udp_scrape(); return false; } char buf[udp_buffer_size]; int ret = m_socket->receive(buf, udp_buffer_size); // if there was nothing to receive, return if (ret == 0) return false; if (ret < 0) { socket::error_code err = m_socket->last_error(); if (err == socket::would_block) return false; throw network_error(m_socket->last_error()); } if (ret == udp_buffer_size) { if (has_requester()) requester().tracker_request_error( m_request, -1, "tracker reply too big"); return true; } if (m_connection_id == 0) { return parse_connect_response(buf, ret); } else if (m_request.kind == tracker_request::announce_request) { return parse_announce_response(buf, ret); } else if (m_request.kind == tracker_request::scrape_request) { return parse_scrape_response(buf, ret); } assert(false); return false; } void udp_tracker_connection::send_udp_announce() { if (m_transaction_id == 0) m_transaction_id = rand() ^ (rand() << 16); std::vector<char> buf; std::back_insert_iterator<std::vector<char> > out(buf); // connection_id detail::write_int64(m_connection_id, out); // action (announce) detail::write_int32(announce, out); // transaction_id detail::write_int32(m_transaction_id, out); // info_hash std::copy(m_request.info_hash.begin(), m_request.info_hash.end(), out); // peer_id std::copy(m_request.id.begin(), m_request.id.end(), out); // downloaded detail::write_int64(m_request.downloaded, out); // left detail::write_int64(m_request.left, out); // uploaded detail::write_int64(m_request.uploaded, out); // event detail::write_int32(m_request.event, out); // ip address detail::write_int32(0, out); // key detail::write_int32(m_request.key, out); // num_want detail::write_int32(m_request.num_want, out); // port detail::write_uint16(m_request.listen_port, out); // extensions detail::write_uint16(0, out); m_socket->send(&buf[0], buf.size()); m_request_time = second_clock::universal_time(); ++m_attempts; } void udp_tracker_connection::send_udp_scrape() { if (m_transaction_id == 0) m_transaction_id = rand() ^ (rand() << 16); std::vector<char> buf; std::back_insert_iterator<std::vector<char> > out(buf); // connection_id detail::write_int64(m_connection_id, out); // action (scrape) detail::write_int32(scrape, out); // transaction_id detail::write_int32(m_transaction_id, out); // info_hash std::copy(m_request.info_hash.begin(), m_request.info_hash.end(), out); m_socket->send(&buf[0], buf.size()); m_request_time = second_clock::universal_time(); ++m_attempts; } void udp_tracker_connection::send_udp_connect() { char send_buf[16]; char* ptr = send_buf; if (m_transaction_id == 0) m_transaction_id = rand() ^ (rand() << 16); // connection_id detail::write_uint32(0x417, ptr); detail::write_uint32(0x27101980, ptr); // action (connect) detail::write_int32(connect, ptr); // transaction_id detail::write_int32(m_transaction_id, ptr); m_socket->send(send_buf, 16); m_request_time = second_clock::universal_time(); ++m_attempts; } bool udp_tracker_connection::parse_announce_response(const char* buf, int len) { assert(buf != 0); assert(len > 0); if (len < 8) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 8, ignoring"); #endif return false; } int action = detail::read_int32(buf); int transaction = detail::read_int32(buf); if (transaction != m_transaction_id) { return false; } if (action == error) { if (has_requester()) requester().tracker_request_error( m_request, -1, std::string(buf, buf + len - 8)); return true; } if (action != announce) return false; if (len < 20) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 20, ignoring"); #endif return false; } int interval = detail::read_int32(buf); int incomplete = detail::read_int32(buf); int complete = detail::read_int32(buf); int num_peers = (len - 20) / 6; if ((len - 20) % 6 != 0) { if (has_requester()) requester().tracker_request_error( m_request, -1, "invalid tracker response"); return true; } if (!has_requester()) return true; std::vector<peer_entry> peer_list; for (int i = 0; i < num_peers; ++i) { peer_entry e; std::stringstream s; s << (int)detail::read_uint8(buf) << "."; s << (int)detail::read_uint8(buf) << "."; s << (int)detail::read_uint8(buf) << "."; s << (int)detail::read_uint8(buf); e.ip = s.str(); e.port = detail::read_uint16(buf); e.id.clear(); peer_list.push_back(e); } requester().tracker_response(m_request, peer_list, interval , complete, incomplete); return true; } bool udp_tracker_connection::parse_scrape_response(const char* buf, int len) { assert(buf != 0); assert(len > 0); if (len < 8) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 8, ignoring"); #endif return false; } int action = detail::read_int32(buf); int transaction = detail::read_int32(buf); if (transaction != m_transaction_id) { return false; } if (action == error) { if (has_requester()) requester().tracker_request_error( m_request, -1, std::string(buf, buf + len - 8)); return true; } if (action != scrape) return false; if (len < 20) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 20, ignoring"); #endif return false; } int complete = detail::read_int32(buf); /*int downloaded = */detail::read_int32(buf); int incomplete = detail::read_int32(buf); if (!has_requester()) return true; std::vector<peer_entry> peer_list; requester().tracker_response(m_request, peer_list, 0 , complete, incomplete); return true; } bool udp_tracker_connection::parse_connect_response(const char* buf, int len) { assert(buf != 0); assert(len > 0); if (len < 8) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with size < 8, ignoring"); #endif return false; } const char* ptr = buf; int action = detail::read_int32(ptr); int transaction = detail::read_int32(ptr); if (action == error) { if (has_requester()) requester().tracker_request_error( m_request, -1, std::string(ptr, buf + len)); return true; } if (action != connect) return false; if (m_transaction_id != transaction) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a message with incorrect transaction id, ignoring"); #endif return false; } if (len < 16) { #ifdef TORRENT_VERBOSE_LOGGING if (has_requester()) requester().debug_log("udp_tracker_connection: " "got a connection message size < 16, ignoring"); #endif return false; } // reset transaction m_transaction_id = 0; m_attempts = 0; m_connection_id = detail::read_int64(ptr); if (m_request.kind == tracker_request::announce_request) send_udp_announce(); else if (m_request.kind == tracker_request::scrape_request) send_udp_scrape(); return false; } } <|endoftext|>
<commit_before>/** * @file DurationString.cpp * @brief DurationString class implementation. * @author zer0 * @date 2019-07-15 */ #include <libtbag/time/DurationString.hpp> #include <libtbag/string/StringUtils.hpp> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace time { template <typename DefaultDurationT> static std::size_t __to_chrono_duration(std::string const & str) { auto const lower_str = libtbag::string::trim(libtbag::string::lower(str)); auto const size = lower_str.size(); std::size_t i = 0; for (; i < size; ++i) { if (!std::isdigit(lower_str[i])) { break; } } // Skip space; for (; i < size; ++i) { if (lower_str[i] != ' ') { break; } } auto const value = libtbag::string::toValue<std::size_t>(lower_str.substr(0, i)); auto const suffix = lower_str.substr(i); auto const suffix_size = suffix.size(); using namespace std::chrono; if (suffix_size <= 0) { return value; } assert(suffix_size >= 1); if (suffix[0] == 'h') { return duration_cast<DefaultDurationT>(hours(value)).count(); } else if (suffix[0] == 's') { return duration_cast<DefaultDurationT>(seconds(value)).count(); } else if (suffix[0] == 'n') { return duration_cast<DefaultDurationT>(nanoseconds(value)).count(); } else if (suffix[0] == 'm') { if (suffix_size >= 2 && suffix[1] == 'i') { if (suffix_size >= 3) { if (suffix[2] == 'c') { // mic return duration_cast<DefaultDurationT>(microseconds(value)).count(); } else if (suffix[2] == 'l') { // mil return duration_cast<DefaultDurationT>(milliseconds(value)).count(); } else if (suffix[2] == 'n') { // min return duration_cast<DefaultDurationT>(minutes(value)).count(); } } } } return value; } std::size_t toNanoseconds(std::string const & str) { return __to_chrono_duration<std::chrono::nanoseconds>(str); } std::size_t toMicroseconds(std::string const & str) { return __to_chrono_duration<std::chrono::microseconds>(str); } std::size_t toMilliseconds(std::string const & str) { return __to_chrono_duration<std::chrono::milliseconds>(str); } std::size_t toSeconds(std::string const & str) { return __to_chrono_duration<std::chrono::seconds>(str); } std::size_t toMinutes(std::string const & str) { return __to_chrono_duration<std::chrono::minutes>(str); } std::size_t toHours(std::string const & str) { return __to_chrono_duration<std::chrono::hours>(str); } } // namespace time // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- <commit_msg>Fixed build error in MSVC.<commit_after>/** * @file DurationString.cpp * @brief DurationString class implementation. * @author zer0 * @date 2019-07-15 */ #include <libtbag/time/DurationString.hpp> #include <libtbag/string/StringUtils.hpp> #include <cctype> #include <cassert> // ------------------- NAMESPACE_LIBTBAG_OPEN // ------------------- namespace time { template <typename DefaultDurationT> static std::size_t __to_chrono_duration(std::string const & str) { auto const lower_str = libtbag::string::trim(libtbag::string::lower(str)); auto const size = lower_str.size(); std::size_t i = 0; for (; i < size; ++i) { if (!std::isdigit(lower_str[i])) { break; } } // Skip space; for (; i < size; ++i) { if (lower_str[i] != ' ') { break; } } auto const value = libtbag::string::toValue<std::size_t>(lower_str.substr(0, i)); auto const suffix = lower_str.substr(i); auto const suffix_size = suffix.size(); using namespace std::chrono; if (suffix_size <= 0) { return value; } assert(suffix_size >= 1); if (suffix[0] == 'h') { return duration_cast<DefaultDurationT>(hours(value)).count(); } else if (suffix[0] == 's') { return duration_cast<DefaultDurationT>(seconds(value)).count(); } else if (suffix[0] == 'n') { return duration_cast<DefaultDurationT>(nanoseconds(value)).count(); } else if (suffix[0] == 'm') { if (suffix_size >= 2 && suffix[1] == 'i') { if (suffix_size >= 3) { if (suffix[2] == 'c') { // mic return duration_cast<DefaultDurationT>(microseconds(value)).count(); } else if (suffix[2] == 'l') { // mil return duration_cast<DefaultDurationT>(milliseconds(value)).count(); } else if (suffix[2] == 'n') { // min return duration_cast<DefaultDurationT>(minutes(value)).count(); } } } } return value; } std::size_t toNanoseconds(std::string const & str) { return __to_chrono_duration<std::chrono::nanoseconds>(str); } std::size_t toMicroseconds(std::string const & str) { return __to_chrono_duration<std::chrono::microseconds>(str); } std::size_t toMilliseconds(std::string const & str) { return __to_chrono_duration<std::chrono::milliseconds>(str); } std::size_t toSeconds(std::string const & str) { return __to_chrono_duration<std::chrono::seconds>(str); } std::size_t toMinutes(std::string const & str) { return __to_chrono_duration<std::chrono::minutes>(str); } std::size_t toHours(std::string const & str) { return __to_chrono_duration<std::chrono::hours>(str); } } // namespace time // -------------------- NAMESPACE_LIBTBAG_CLOSE // -------------------- <|endoftext|>
<commit_before>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2010 Emmanuel Benazera, ebenazer@seeks-project.info * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "db_query_record.h" #include "db_query_record_msg.pb.h" #include "errlog.h" #include "DHTKey.h" // for fixing issue 169. #include "qprocess.h" // idem. #include "query_capture_configuration.h" // idem. using lsh::qprocess; #include <algorithm> #include <iterator> #include <iostream> using sp::errlog; namespace seeks_plugins { /*- query_data -*/ query_data::query_data(const std::string &query, const short &radius) :_query(query),_radius(radius),_hits(1),_visited_urls(NULL) { } query_data::query_data(const std::string &query, const short &radius, const std::string &url) :_query(query),_radius(radius),_hits(1) { _visited_urls = new hash_map<const char*,vurl_data*,hash<const char*>,eqstr>(1); vurl_data *vd = new vurl_data(url); add_vurl(vd); } query_data::query_data(const query_data *qd) :_query(qd->_query),_radius(qd->_radius),_hits(qd->_hits),_visited_urls(NULL) { if (qd->_visited_urls) { create_visited_urls(); hash_map<const char*,vurl_data*,hash<const char*>,eqstr>::const_iterator hit = qd->_visited_urls->begin(); while (hit!=qd->_visited_urls->end()) { vurl_data *vd = new vurl_data((*hit).second); add_vurl(vd); ++hit; } } } query_data::~query_data() { if (_visited_urls) { hash_map<const char*,vurl_data*,hash<const char*>,eqstr>::iterator dhit; hash_map<const char*,vurl_data*,hash<const char*>,eqstr>::iterator hit = _visited_urls->begin(); while (hit!=_visited_urls->end()) { vurl_data *vd = (*hit).second; dhit = hit; ++hit; _visited_urls->erase(dhit); delete vd; } delete _visited_urls; _visited_urls = NULL; } } void query_data::create_visited_urls() { if (!_visited_urls) _visited_urls = new hash_map<const char*,vurl_data*,hash<const char*>,eqstr>(25); else errlog::log_error(LOG_LEVEL_INFO,"query_data::create_visited_urls failed: already exists"); } void query_data::merge(const query_data *qd) { if (qd->_query != _query) { errlog::log_error(LOG_LEVEL_ERROR,"trying to merge query record data for different queries"); return; } assert(qd->_radius == _radius); if (!qd->_visited_urls) return; if (!_visited_urls) create_visited_urls(); hash_map<const char*,vurl_data*,hash<const char*>,eqstr>::iterator fhit; hash_map<const char*,vurl_data*,hash<const char*>,eqstr>::const_iterator hit = qd->_visited_urls->begin(); while (hit!=qd->_visited_urls->end()) { if ((fhit=_visited_urls->find((*hit).first))!=_visited_urls->end()) { (*fhit).second->merge((*hit).second); } else { vurl_data *vd = new vurl_data((*hit).second); add_vurl(vd); } ++hit; } } void query_data::add_vurl(vurl_data *vd) { if (!_visited_urls) return; // safe. _visited_urls->insert(std::pair<const char*,vurl_data*>(vd->_url.c_str(),vd)); } vurl_data* query_data::find_vurl(const std::string &url) const { if (!_visited_urls) return NULL; hash_map<const char*,vurl_data*,hash<const char*>,eqstr>::iterator hit; if ((hit=_visited_urls->find(url.c_str()))!=_visited_urls->end()) return (*hit).second; return NULL; } float query_data::vurls_total_hits() const { if (!_visited_urls) return 0.0; float res = 0.0; hash_map<const char*,vurl_data*,hash<const char*>,eqstr>::iterator hit = _visited_urls->begin(); while (hit!=_visited_urls->end()) { res += (*hit).second->_hits; ++hit; } } /*- db_query_record -*/ db_query_record::db_query_record(const time_t &creation_time, const std::string &plugin_name) :db_record(creation_time,plugin_name) { } db_query_record::db_query_record(const std::string &plugin_name, const std::string &query, const short &radius) :db_record(plugin_name) { query_data *qd = new query_data(query,radius); _related_queries.insert(std::pair<const char*,query_data*>(qd->_query.c_str(),qd)); } db_query_record::db_query_record(const std::string &plugin_name, const std::string &query, const short &radius, const std::string &url) :db_record(plugin_name) { query_data *qd = new query_data(query,radius,url); _related_queries.insert(std::pair<const char*,query_data*>(qd->_query.c_str(),qd)); } db_query_record::db_query_record(const db_query_record &dbr) { hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator hit = dbr._related_queries.begin(); while (hit!=dbr._related_queries.end()) { query_data *rd = (*hit).second; query_data *crd = new query_data(*rd); _related_queries.insert(std::pair<const char*,query_data*>(crd->_query.c_str(),crd)); ++hit; } } db_query_record::db_query_record() :db_record() { } db_query_record::~db_query_record() { hash_map<const char*,query_data*,hash<const char*>,eqstr>::iterator dhit; hash_map<const char*,query_data*,hash<const char*>,eqstr>::iterator hit = _related_queries.begin(); while (hit!=_related_queries.end()) { query_data *qd = (*hit).second; dhit = hit; ++hit; _related_queries.erase(dhit); delete qd; } } int db_query_record::serialize(std::string &msg) const { sp::db::record r; create_query_record(r); if (!r.SerializeToString(&msg)) { errlog::log_error(LOG_LEVEL_ERROR,"Failed serializing db_query_record"); return 1; // error. } else return 0; } int db_query_record::deserialize(const std::string &msg) { sp::db::record r; if (!r.ParseFromString(msg)) { errlog::log_error(LOG_LEVEL_ERROR,"Failed deserializing db_query_record"); return 1; // error. } read_query_record(r); return 0; } int db_query_record::merge_with(const db_record &dbr) { if (dbr._plugin_name != _plugin_name) return -2; const db_query_record &dqr = static_cast<const db_query_record&>(dbr); hash_map<const char*,query_data*,hash<const char*>,eqstr>::iterator fhit; hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator hit = dqr._related_queries.begin(); while (hit!=dqr._related_queries.end()) { if ((fhit = _related_queries.find((*hit).first))!=_related_queries.end()) { // merge. (*fhit).second->merge((*hit).second); } else { // add query. query_data *rd = new query_data((*hit).second); _related_queries.insert(std::pair<const char*,query_data*>(rd->_query.c_str(),rd)); } ++hit; } return 0; } void db_query_record::create_query_record(sp::db::record &r) const { create_base_record(r); sp::db::related_queries *queries = r.MutableExtension(sp::db::queries); hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator hit = _related_queries.begin(); while (hit!=_related_queries.end()) { query_data *rd = (*hit).second; sp::db::related_query* rq = queries->add_rquery(); rq->set_radius(rd->_radius); rq->set_query(rd->_query); rq->set_query_hits((*hit).second->_hits); sp::db::visited_urls *rq_vurls = rq->mutable_vurls(); if (rd->_visited_urls) { hash_map<const char*,vurl_data*,hash<const char*>,eqstr>::const_iterator vhit = rd->_visited_urls->begin(); while (vhit!=rd->_visited_urls->end()) { vurl_data *vd = (*vhit).second; if (vd) // XXX: should not happen. { sp::db::visited_url *rq_vurl = rq_vurls->add_vurl(); rq_vurl->set_url(vd->_url); rq_vurl->set_hits(vd->_hits); } else std::cerr << "[Debug]: null vurl_data element in visited_urls...\n"; ++vhit; } } ++hit; } } void db_query_record::read_query_record(sp::db::record &r) { read_base_record(r); sp::db::related_queries *rqueries = r.MutableExtension(sp::db::queries); int nrq = rqueries->rquery_size(); for (int i=0; i<nrq; i++) { sp::db::related_query *rq = rqueries->mutable_rquery(i); short radius = rq->radius(); std::string query = rq->query(); query_data *rd = new query_data(query,radius); rd->_hits = rq->query_hits(); sp::db::visited_urls *rq_vurls = rq->mutable_vurls(); int nvurls = rq_vurls->vurl_size(); if (nvurls > 0) rd->create_visited_urls(); for (int j=0; j<nvurls; j++) { sp::db::visited_url *rq_vurl = rq_vurls->mutable_vurl(j); std::string url = rq_vurl->url(); short uhits = rq_vurl->hits(); vurl_data *vd = new vurl_data(url,uhits); rd->_visited_urls->insert(std::pair<const char*,vurl_data*>(vd->_url.c_str(),vd)); } _related_queries.insert(std::pair<const char*,query_data*>(rd->_query.c_str(),rd)); } } int db_query_record::fix_issue_169(user_db &cudb) { // lookup a radius 0 query. If one: // - convert the record's key. // - generate 0 to max_radius keys for this query. // - store the newly formed records in to the new DB. // - change their keys and store them into the new DB. // if none, skip. hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator hit = _related_queries.begin(); while (hit!=_related_queries.end()) { query_data *qd = (*hit).second; if (qd->_radius != 0) { ++hit; continue; } // generate query hashes with proper hashing function. hash_multimap<uint32_t,DHTKey,id_hash_uint> features; qprocess::generate_query_hashes(qd->_query,0, query_capture_configuration::_config->_max_radius, features); hash_multimap<uint32_t,DHTKey,id_hash_uint>::const_iterator fhit = features.begin(); while (fhit!=features.end()) { if ((*hit).first == 0) { // copy this record and store it with fixed key in new db. db_query_record cdqr(*this); cdqr._creation_time = _creation_time; // reset creation time to original time. std::string key_str = (*fhit).second.to_rstring(); cudb.add_dbr(key_str,cdqr); } else { // store the query fragment with fixed key. db_query_record ndqr("query-capture",qd->_query,(*fhit).first); ndqr._creation_time = _creation_time; // reset creation time to original time. std::string key_str = (*fhit).second.to_rstring(); cudb.add_dbr(key_str,ndqr); } ++fhit; } ++hit; } return 0; } } /* end of namespace. */ <commit_msg>fixed missing return value in total hits computation<commit_after>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2010 Emmanuel Benazera, ebenazer@seeks-project.info * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "db_query_record.h" #include "db_query_record_msg.pb.h" #include "errlog.h" #include "DHTKey.h" // for fixing issue 169. #include "qprocess.h" // idem. #include "query_capture_configuration.h" // idem. using lsh::qprocess; #include <algorithm> #include <iterator> #include <iostream> using sp::errlog; namespace seeks_plugins { /*- query_data -*/ query_data::query_data(const std::string &query, const short &radius) :_query(query),_radius(radius),_hits(1),_visited_urls(NULL) { } query_data::query_data(const std::string &query, const short &radius, const std::string &url) :_query(query),_radius(radius),_hits(1) { _visited_urls = new hash_map<const char*,vurl_data*,hash<const char*>,eqstr>(1); vurl_data *vd = new vurl_data(url); add_vurl(vd); } query_data::query_data(const query_data *qd) :_query(qd->_query),_radius(qd->_radius),_hits(qd->_hits),_visited_urls(NULL) { if (qd->_visited_urls) { create_visited_urls(); hash_map<const char*,vurl_data*,hash<const char*>,eqstr>::const_iterator hit = qd->_visited_urls->begin(); while (hit!=qd->_visited_urls->end()) { vurl_data *vd = new vurl_data((*hit).second); add_vurl(vd); ++hit; } } } query_data::~query_data() { if (_visited_urls) { hash_map<const char*,vurl_data*,hash<const char*>,eqstr>::iterator dhit; hash_map<const char*,vurl_data*,hash<const char*>,eqstr>::iterator hit = _visited_urls->begin(); while (hit!=_visited_urls->end()) { vurl_data *vd = (*hit).second; dhit = hit; ++hit; _visited_urls->erase(dhit); delete vd; } delete _visited_urls; _visited_urls = NULL; } } void query_data::create_visited_urls() { if (!_visited_urls) _visited_urls = new hash_map<const char*,vurl_data*,hash<const char*>,eqstr>(25); else errlog::log_error(LOG_LEVEL_INFO,"query_data::create_visited_urls failed: already exists"); } void query_data::merge(const query_data *qd) { if (qd->_query != _query) { errlog::log_error(LOG_LEVEL_ERROR,"trying to merge query record data for different queries"); return; } assert(qd->_radius == _radius); if (!qd->_visited_urls) return; if (!_visited_urls) create_visited_urls(); hash_map<const char*,vurl_data*,hash<const char*>,eqstr>::iterator fhit; hash_map<const char*,vurl_data*,hash<const char*>,eqstr>::const_iterator hit = qd->_visited_urls->begin(); while (hit!=qd->_visited_urls->end()) { if ((fhit=_visited_urls->find((*hit).first))!=_visited_urls->end()) { (*fhit).second->merge((*hit).second); } else { vurl_data *vd = new vurl_data((*hit).second); add_vurl(vd); } ++hit; } } void query_data::add_vurl(vurl_data *vd) { if (!_visited_urls) return; // safe. _visited_urls->insert(std::pair<const char*,vurl_data*>(vd->_url.c_str(),vd)); } vurl_data* query_data::find_vurl(const std::string &url) const { if (!_visited_urls) return NULL; hash_map<const char*,vurl_data*,hash<const char*>,eqstr>::iterator hit; if ((hit=_visited_urls->find(url.c_str()))!=_visited_urls->end()) return (*hit).second; return NULL; } float query_data::vurls_total_hits() const { if (!_visited_urls) return 0.0; float res = 0.0; hash_map<const char*,vurl_data*,hash<const char*>,eqstr>::iterator hit = _visited_urls->begin(); while (hit!=_visited_urls->end()) { res += (*hit).second->_hits; ++hit; } return res; } /*- db_query_record -*/ db_query_record::db_query_record(const time_t &creation_time, const std::string &plugin_name) :db_record(creation_time,plugin_name) { } db_query_record::db_query_record(const std::string &plugin_name, const std::string &query, const short &radius) :db_record(plugin_name) { query_data *qd = new query_data(query,radius); _related_queries.insert(std::pair<const char*,query_data*>(qd->_query.c_str(),qd)); } db_query_record::db_query_record(const std::string &plugin_name, const std::string &query, const short &radius, const std::string &url) :db_record(plugin_name) { query_data *qd = new query_data(query,radius,url); _related_queries.insert(std::pair<const char*,query_data*>(qd->_query.c_str(),qd)); } db_query_record::db_query_record(const db_query_record &dbr) { hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator hit = dbr._related_queries.begin(); while (hit!=dbr._related_queries.end()) { query_data *rd = (*hit).second; query_data *crd = new query_data(*rd); _related_queries.insert(std::pair<const char*,query_data*>(crd->_query.c_str(),crd)); ++hit; } } db_query_record::db_query_record() :db_record() { } db_query_record::~db_query_record() { hash_map<const char*,query_data*,hash<const char*>,eqstr>::iterator dhit; hash_map<const char*,query_data*,hash<const char*>,eqstr>::iterator hit = _related_queries.begin(); while (hit!=_related_queries.end()) { query_data *qd = (*hit).second; dhit = hit; ++hit; _related_queries.erase(dhit); delete qd; } } int db_query_record::serialize(std::string &msg) const { sp::db::record r; create_query_record(r); if (!r.SerializeToString(&msg)) { errlog::log_error(LOG_LEVEL_ERROR,"Failed serializing db_query_record"); return 1; // error. } else return 0; } int db_query_record::deserialize(const std::string &msg) { sp::db::record r; if (!r.ParseFromString(msg)) { errlog::log_error(LOG_LEVEL_ERROR,"Failed deserializing db_query_record"); return 1; // error. } read_query_record(r); return 0; } int db_query_record::merge_with(const db_record &dbr) { if (dbr._plugin_name != _plugin_name) return -2; const db_query_record &dqr = static_cast<const db_query_record&>(dbr); hash_map<const char*,query_data*,hash<const char*>,eqstr>::iterator fhit; hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator hit = dqr._related_queries.begin(); while (hit!=dqr._related_queries.end()) { if ((fhit = _related_queries.find((*hit).first))!=_related_queries.end()) { // merge. (*fhit).second->merge((*hit).second); } else { // add query. query_data *rd = new query_data((*hit).second); _related_queries.insert(std::pair<const char*,query_data*>(rd->_query.c_str(),rd)); } ++hit; } return 0; } void db_query_record::create_query_record(sp::db::record &r) const { create_base_record(r); sp::db::related_queries *queries = r.MutableExtension(sp::db::queries); hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator hit = _related_queries.begin(); while (hit!=_related_queries.end()) { query_data *rd = (*hit).second; sp::db::related_query* rq = queries->add_rquery(); rq->set_radius(rd->_radius); rq->set_query(rd->_query); rq->set_query_hits((*hit).second->_hits); sp::db::visited_urls *rq_vurls = rq->mutable_vurls(); if (rd->_visited_urls) { hash_map<const char*,vurl_data*,hash<const char*>,eqstr>::const_iterator vhit = rd->_visited_urls->begin(); while (vhit!=rd->_visited_urls->end()) { vurl_data *vd = (*vhit).second; if (vd) // XXX: should not happen. { sp::db::visited_url *rq_vurl = rq_vurls->add_vurl(); rq_vurl->set_url(vd->_url); rq_vurl->set_hits(vd->_hits); } else std::cerr << "[Debug]: null vurl_data element in visited_urls...\n"; ++vhit; } } ++hit; } } void db_query_record::read_query_record(sp::db::record &r) { read_base_record(r); sp::db::related_queries *rqueries = r.MutableExtension(sp::db::queries); int nrq = rqueries->rquery_size(); for (int i=0; i<nrq; i++) { sp::db::related_query *rq = rqueries->mutable_rquery(i); short radius = rq->radius(); std::string query = rq->query(); query_data *rd = new query_data(query,radius); rd->_hits = rq->query_hits(); sp::db::visited_urls *rq_vurls = rq->mutable_vurls(); int nvurls = rq_vurls->vurl_size(); if (nvurls > 0) rd->create_visited_urls(); for (int j=0; j<nvurls; j++) { sp::db::visited_url *rq_vurl = rq_vurls->mutable_vurl(j); std::string url = rq_vurl->url(); short uhits = rq_vurl->hits(); vurl_data *vd = new vurl_data(url,uhits); rd->_visited_urls->insert(std::pair<const char*,vurl_data*>(vd->_url.c_str(),vd)); } _related_queries.insert(std::pair<const char*,query_data*>(rd->_query.c_str(),rd)); } } int db_query_record::fix_issue_169(user_db &cudb) { // lookup a radius 0 query. If one: // - convert the record's key. // - generate 0 to max_radius keys for this query. // - store the newly formed records in to the new DB. // - change their keys and store them into the new DB. // if none, skip. hash_map<const char*,query_data*,hash<const char*>,eqstr>::const_iterator hit = _related_queries.begin(); while (hit!=_related_queries.end()) { query_data *qd = (*hit).second; if (qd->_radius != 0) { ++hit; continue; } // generate query hashes with proper hashing function. hash_multimap<uint32_t,DHTKey,id_hash_uint> features; qprocess::generate_query_hashes(qd->_query,0, query_capture_configuration::_config->_max_radius, features); hash_multimap<uint32_t,DHTKey,id_hash_uint>::const_iterator fhit = features.begin(); while (fhit!=features.end()) { if ((*hit).first == 0) { // copy this record and store it with fixed key in new db. db_query_record cdqr(*this); cdqr._creation_time = _creation_time; // reset creation time to original time. std::string key_str = (*fhit).second.to_rstring(); cudb.add_dbr(key_str,cdqr); } else { // store the query fragment with fixed key. db_query_record ndqr("query-capture",qd->_query,(*fhit).first); ndqr._creation_time = _creation_time; // reset creation time to original time. std::string key_str = (*fhit).second.to_rstring(); cudb.add_dbr(key_str,ndqr); } ++fhit; } ++hit; } return 0; } } /* end of namespace. */ <|endoftext|>
<commit_before>#include "unittest/dummy_protocol.hpp" #include "concurrency/signal.hpp" #include "arch/timing.hpp" namespace unittest { bool dummy_protocol_t::region_t::contains(const region_t &r) { for (std::set<std::string>::iterator it = r.keys.begin(); it != r.keys.end(); it++) { if (keys.count(*it) == 0) { return false; } } return true; } bool dummy_protocol_t::region_t::overlaps(const region_t &r) { for (std::set<std::string>::iterator it = r.keys.begin(); it != r.keys.end(); it++) { if (keys.count(*it) != 0) { return true; } } return false; } dummy_protocol_t::region_t dummy_protocol_t::region_t::intersection(const region_t &r) { region_t i; for (std::set<std::string>::iterator it = r.keys.begin(); it != r.keys.end(); it++) { if (keys.count(*it) != 0) { i.keys.insert(*it); } } return i; } dummy_protocol_t::region_t dummy_protocol_t::read_t::get_region() { return keys; } std::vector<dummy_protocol_t::read_t> dummy_protocol_t::read_t::shard(std::vector<region_t> regions) { std::vector<read_t> results; for (int i = 0; i < (int)regions.size(); i++) { read_t r; r.keys = regions[i].intersection(keys); results.push_back(r); } return results; } dummy_protocol_t::read_response_t dummy_protocol_t::read_t::unshard(std::vector<read_response_t> resps, temporary_cache_t *cache) { rassert(cache != NULL); read_response_t combined; for (int i = 0; i < (int)resps.size(); i++) { for (std::map<std::string, std::string>::iterator it = resps[i].values.begin(); it != resps[i].values.end(); it++) { rassert(keys.keys.count((*it).first) != 0); rassert(combined.values.count((*it).first) == 0); combined.values[(*it).first] = (*it).second; } } return combined; } dummy_protocol_t::region_t dummy_protocol_t::write_t::get_region() { region_t region; for (std::map<std::string, std::string>::iterator it = values.begin(); it != values.end(); it++) { region.keys.insert((*it).first); } return region; } std::vector<dummy_protocol_t::write_t> dummy_protocol_t::write_t::shard(std::vector<region_t> regions) { std::vector<write_t> results; for (int i = 0; i < (int)regions.size(); i++) { write_t w; for (std::map<std::string, std::string>::iterator it = values.begin(); it != values.end(); it++) { if (regions[i].keys.count((*it).first) != 0) { w.values[(*it).first] = (*it).second; } } results.push_back(w); } return results; } dummy_protocol_t::write_response_t dummy_protocol_t::write_t::unshard(std::vector<write_response_t> resps, temporary_cache_t *cache) { rassert(cache != NULL); write_response_t combined; for (int i = 0; i < (int)resps.size(); i++) { for (std::map<std::string, std::string>::iterator it = resps[i].old_values.begin(); it != resps[i].old_values.end(); it++) { rassert(values.find((*it).first) != values.end()); rassert(combined.old_values.count((*it).first) == 0); combined.old_values[(*it).first] = (*it).second; } } return combined; } dummy_protocol_t::region_t dummy_protocol_t::store_t::get_region() { return region; } bool dummy_protocol_t::store_t::is_coherent() { rassert(!backfilling); return coherent; } repli_timestamp_t dummy_protocol_t::store_t::get_timestamp() { rassert(!backfilling); return latest; } dummy_protocol_t::read_response_t dummy_protocol_t::store_t::read(read_t read, order_token_t otok, signal_t *interruptor) { rassert(!backfilling); rassert(coherent); order_sink.check_out(otok); if (interruptor->is_pulsed() && rand() % 2) throw interrupted_exc_t(); read_response_t resp; for (std::set<std::string>::iterator it = read.keys.keys.begin(); it != read.keys.keys.end(); it++) { rassert(region.keys.count(*it) != 0); resp.values[*it] = values[*it]; } if (rand() % 2 == 0) nap(rand() % 10, interruptor); return resp; } dummy_protocol_t::write_response_t dummy_protocol_t::store_t::write(write_t write, repli_timestamp_t timestamp, order_token_t otok, signal_t *interruptor) { rassert(!backfilling); rassert(coherent); rassert(timestamp >= latest); rassert(earliest == latest); order_sink.check_out(otok); if (interruptor->is_pulsed() && rand() % 2) throw interrupted_exc_t(); earliest = latest = timestamp; if (interruptor->is_pulsed() && rand() % 2) throw interrupted_exc_t(); write_response_t resp; for (std::map<std::string, std::string>::iterator it = write.values.begin(); it != write.values.end(); it++) { resp.old_values[(*it).first] = values[(*it).first]; values[(*it).first] = (*it).second; timestamps[(*it).first] = timestamp; } if (rand() % 2 == 0) nap(rand() % 10, interruptor); return resp; } bool dummy_protocol_t::store_t::is_backfilling() { return backfilling; } dummy_protocol_t::store_t::backfill_request_t dummy_protocol_t::store_t::backfillee_begin() { rassert(!backfilling); backfilling = true; backfill_request_t bfr; bfr.region = region; bfr.earliest = earliest; bfr.latest = latest; return bfr; } void dummy_protocol_t::store_t::backfillee_chunk(backfill_chunk_t chunk) { rassert(backfilling); rassert(region.keys.count(chunk.key) != 0); values[chunk.key] = chunk.value; timestamps[chunk.key] = chunk.timestamp; latest = chunk.timestamp; } void dummy_protocol_t::store_t::backfillee_end(backfill_end_t end) { rassert(backfilling); coherent = true; earliest = latest = end.timestamp; backfilling = false; } void dummy_protocol_t::store_t::backfillee_cancel() { rassert(backfilling); coherent = false; backfilling = false; } dummy_protocol_t::store_t::backfill_end_t dummy_protocol_t::store_t::backfiller(backfill_request_t request, boost::function<void(backfill_chunk_t)> chunk_fun, signal_t *interruptor) { rassert(!backfilling); rassert(coherent); rassert(request.region == region); rassert(request.latest <= latest); /* Make a copy so we can sleep and still have the correct semantics */ std::map<std::string, std::string> snapshot = values; if (rand() % 2 == 0) nap(rand() % 10, interruptor); for (std::map<std::string, std::string>::iterator it = snapshot.begin(); it != snapshot.end(); it++) { if (timestamps[(*it).first] <= request.earliest) { backfill_chunk_t chunk; chunk.key = (*it).first; chunk.value = (*it).second; chunk.timestamp = timestamps[(*it).first]; chunk_fun(chunk); } if (rand() % 2 == 0) nap(rand() % 10, interruptor); } backfill_end_t end; end.timestamp = latest; return end; } dummy_protocol_t::store_t::store_t(region_t r) : region(r), coherent(true), backfilling(false), earliest(repli_timestamp_t::distant_past), latest(earliest) { for (std::set<std::string>::iterator it = region.keys.begin(); it != region.keys.end(); it++) { values[*it] = ""; timestamps[*it] = repli_timestamp_t::distant_past; } } dummy_protocol_t::store_t::~store_t() { rassert(!backfilling); } bool operator==(dummy_protocol_t::region_t a, dummy_protocol_t::region_t b) { return a.keys == b.keys; } bool operator!=(dummy_protocol_t::region_t a, dummy_protocol_t::region_t b) { return !(a == b); } } /* namespace unittest */ <commit_msg>Fixed bug in dummy protocol backfilling.<commit_after>#include "unittest/dummy_protocol.hpp" #include "concurrency/signal.hpp" #include "arch/timing.hpp" namespace unittest { bool dummy_protocol_t::region_t::contains(const region_t &r) { for (std::set<std::string>::iterator it = r.keys.begin(); it != r.keys.end(); it++) { if (keys.count(*it) == 0) { return false; } } return true; } bool dummy_protocol_t::region_t::overlaps(const region_t &r) { for (std::set<std::string>::iterator it = r.keys.begin(); it != r.keys.end(); it++) { if (keys.count(*it) != 0) { return true; } } return false; } dummy_protocol_t::region_t dummy_protocol_t::region_t::intersection(const region_t &r) { region_t i; for (std::set<std::string>::iterator it = r.keys.begin(); it != r.keys.end(); it++) { if (keys.count(*it) != 0) { i.keys.insert(*it); } } return i; } dummy_protocol_t::region_t dummy_protocol_t::read_t::get_region() { return keys; } std::vector<dummy_protocol_t::read_t> dummy_protocol_t::read_t::shard(std::vector<region_t> regions) { std::vector<read_t> results; for (int i = 0; i < (int)regions.size(); i++) { read_t r; r.keys = regions[i].intersection(keys); results.push_back(r); } return results; } dummy_protocol_t::read_response_t dummy_protocol_t::read_t::unshard(std::vector<read_response_t> resps, temporary_cache_t *cache) { rassert(cache != NULL); read_response_t combined; for (int i = 0; i < (int)resps.size(); i++) { for (std::map<std::string, std::string>::iterator it = resps[i].values.begin(); it != resps[i].values.end(); it++) { rassert(keys.keys.count((*it).first) != 0); rassert(combined.values.count((*it).first) == 0); combined.values[(*it).first] = (*it).second; } } return combined; } dummy_protocol_t::region_t dummy_protocol_t::write_t::get_region() { region_t region; for (std::map<std::string, std::string>::iterator it = values.begin(); it != values.end(); it++) { region.keys.insert((*it).first); } return region; } std::vector<dummy_protocol_t::write_t> dummy_protocol_t::write_t::shard(std::vector<region_t> regions) { std::vector<write_t> results; for (int i = 0; i < (int)regions.size(); i++) { write_t w; for (std::map<std::string, std::string>::iterator it = values.begin(); it != values.end(); it++) { if (regions[i].keys.count((*it).first) != 0) { w.values[(*it).first] = (*it).second; } } results.push_back(w); } return results; } dummy_protocol_t::write_response_t dummy_protocol_t::write_t::unshard(std::vector<write_response_t> resps, temporary_cache_t *cache) { rassert(cache != NULL); write_response_t combined; for (int i = 0; i < (int)resps.size(); i++) { for (std::map<std::string, std::string>::iterator it = resps[i].old_values.begin(); it != resps[i].old_values.end(); it++) { rassert(values.find((*it).first) != values.end()); rassert(combined.old_values.count((*it).first) == 0); combined.old_values[(*it).first] = (*it).second; } } return combined; } dummy_protocol_t::region_t dummy_protocol_t::store_t::get_region() { return region; } bool dummy_protocol_t::store_t::is_coherent() { rassert(!backfilling); return coherent; } repli_timestamp_t dummy_protocol_t::store_t::get_timestamp() { rassert(!backfilling); return latest; } dummy_protocol_t::read_response_t dummy_protocol_t::store_t::read(read_t read, order_token_t otok, signal_t *interruptor) { rassert(!backfilling); rassert(coherent); order_sink.check_out(otok); if (interruptor->is_pulsed() && rand() % 2) throw interrupted_exc_t(); read_response_t resp; for (std::set<std::string>::iterator it = read.keys.keys.begin(); it != read.keys.keys.end(); it++) { rassert(region.keys.count(*it) != 0); resp.values[*it] = values[*it]; } if (rand() % 2 == 0) nap(rand() % 10, interruptor); return resp; } dummy_protocol_t::write_response_t dummy_protocol_t::store_t::write(write_t write, repli_timestamp_t timestamp, order_token_t otok, signal_t *interruptor) { rassert(!backfilling); rassert(coherent); rassert(timestamp >= latest); rassert(earliest == latest); order_sink.check_out(otok); if (interruptor->is_pulsed() && rand() % 2) throw interrupted_exc_t(); earliest = latest = timestamp; if (interruptor->is_pulsed() && rand() % 2) throw interrupted_exc_t(); write_response_t resp; for (std::map<std::string, std::string>::iterator it = write.values.begin(); it != write.values.end(); it++) { resp.old_values[(*it).first] = values[(*it).first]; values[(*it).first] = (*it).second; timestamps[(*it).first] = timestamp; } if (rand() % 2 == 0) nap(rand() % 10, interruptor); return resp; } bool dummy_protocol_t::store_t::is_backfilling() { return backfilling; } dummy_protocol_t::store_t::backfill_request_t dummy_protocol_t::store_t::backfillee_begin() { rassert(!backfilling); backfilling = true; backfill_request_t bfr; bfr.region = region; bfr.earliest = earliest; bfr.latest = latest; return bfr; } void dummy_protocol_t::store_t::backfillee_chunk(backfill_chunk_t chunk) { rassert(backfilling); rassert(region.keys.count(chunk.key) != 0); values[chunk.key] = chunk.value; timestamps[chunk.key] = chunk.timestamp; latest = chunk.timestamp; } void dummy_protocol_t::store_t::backfillee_end(backfill_end_t end) { rassert(backfilling); coherent = true; earliest = latest = end.timestamp; backfilling = false; } void dummy_protocol_t::store_t::backfillee_cancel() { rassert(backfilling); coherent = false; backfilling = false; } dummy_protocol_t::store_t::backfill_end_t dummy_protocol_t::store_t::backfiller(backfill_request_t request, boost::function<void(backfill_chunk_t)> chunk_fun, signal_t *interruptor) { rassert(!backfilling); rassert(coherent); rassert(request.region == region); rassert(request.latest <= latest); /* Make a copy so we can sleep and still have the correct semantics */ std::map<std::string, std::string> snapshot = values; if (rand() % 2 == 0) nap(rand() % 10, interruptor); for (std::map<std::string, std::string>::iterator it = snapshot.begin(); it != snapshot.end(); it++) { if (timestamps[(*it).first] >= request.earliest) { backfill_chunk_t chunk; chunk.key = (*it).first; chunk.value = (*it).second; chunk.timestamp = timestamps[(*it).first]; chunk_fun(chunk); } if (rand() % 2 == 0) nap(rand() % 10, interruptor); } backfill_end_t end; end.timestamp = latest; return end; } dummy_protocol_t::store_t::store_t(region_t r) : region(r), coherent(true), backfilling(false), earliest(repli_timestamp_t::distant_past), latest(earliest) { for (std::set<std::string>::iterator it = region.keys.begin(); it != region.keys.end(); it++) { values[*it] = ""; timestamps[*it] = repli_timestamp_t::distant_past; } } dummy_protocol_t::store_t::~store_t() { rassert(!backfilling); } bool operator==(dummy_protocol_t::region_t a, dummy_protocol_t::region_t b) { return a.keys == b.keys; } bool operator!=(dummy_protocol_t::region_t a, dummy_protocol_t::region_t b) { return !(a == b); } } /* namespace unittest */ <|endoftext|>
<commit_before>/* * Copyright (C) 2017~2017 by CSSlayer * wengxt@gmail.com * * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 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; see the file COPYING. If not, * see <http://www.gnu.org/licenses/>. */ #include "unix/fcitx5/mozc_engine.h" #include <fcitx-config/iniparser.h> #include <fcitx-utils/i18n.h> #include <fcitx-utils/log.h> #include <fcitx-utils/standardpath.h> #include <fcitx/inputcontext.h> #include <fcitx/inputcontextmanager.h> #include <fcitx/inputmethodmanager.h> #include <fcitx/userinterfacemanager.h> #include <vector> #include "base/clock.h" #include "base/init_mozc.h" #include "base/process.h" #include "unix/fcitx5/mozc_connection.h" #include "unix/fcitx5/mozc_response_parser.h" namespace fcitx { const struct CompositionModeInfo { const char *name; const char *icon; const char *label; const char *description; mozc::commands::CompositionMode mode; } kPropCompositionModes[] = { { "mozc-mode-direct", "fcitx-mozc-direct", "A", N_("Direct"), mozc::commands::DIRECT, }, { "mozc-mode-hiragana", "fcitx-mozc-hiragana", "\xe3\x81\x82", // Hiragana letter A in UTF-8. N_("Hiragana"), mozc::commands::HIRAGANA, }, { "mozc-mode-katakana_full", "fcitx-mozc-katakana-full", "\xe3\x82\xa2", // Katakana letter A. N_("Full Katakana"), mozc::commands::FULL_KATAKANA, }, { "mozc-mode-alpha_half", "fcitx-mozc-alpha-half", "A", N_("Half ASCII"), mozc::commands::HALF_ASCII, }, { "mozc-mode-alpha_full", "fcitx-mozc-alpha-full", "\xef\xbc\xa1", // Full width ASCII letter A. N_("Full ASCII"), mozc::commands::FULL_ASCII, }, { "mozc-mode-katakana_half", "fcitx-mozc-katakana-half", "\xef\xbd\xb1", // Half width Katakana letter A. N_("Half Katakana"), mozc::commands::HALF_KATAKANA, }, }; const size_t kNumCompositionModes = arraysize(kPropCompositionModes); MozcModeSubAction::MozcModeSubAction(MozcEngine *engine, mozc::commands::CompositionMode mode) : engine_(engine), mode_(mode) { setShortText(_(kPropCompositionModes[mode].description)); setLongText(_(kPropCompositionModes[mode].description)); setIcon(kPropCompositionModes[mode].icon); setCheckable(true); } bool MozcModeSubAction::isChecked(InputContext *ic) const { auto mozc_state = engine_->mozcState(ic); return mozc_state->GetCompositionMode() == mode_; } void MozcModeSubAction::activate(InputContext *ic) { auto mozc_state = engine_->mozcState(ic); mozc_state->SendCompositionMode(mode_); } // This array must correspond with the CompositionMode enum in the // mozc/session/command.proto file. static_assert(mozc::commands::NUM_OF_COMPOSITIONS == kNumCompositionModes, "number of modes must match"); Instance *Init(Instance *instance) { int argc = 1; char argv0[] = "fcitx_mozc"; char *_argv[] = {argv0}; char **argv = _argv; mozc::InitMozc(argv[0], &argc, &argv); return instance; } MozcEngine::MozcEngine(Instance *instance) : instance_(Init(instance)), connection_(std::make_unique<MozcConnection>()), client_(connection_->CreateClient()), factory_([this](InputContext &ic) { return new MozcState(&ic, connection_->CreateClient(), this); }) { for (auto command : {mozc::commands::DIRECT, mozc::commands::HIRAGANA, mozc::commands::FULL_KATAKANA, mozc::commands::FULL_ASCII, mozc::commands::HALF_ASCII, mozc::commands::HALF_KATAKANA}) { modeActions_.push_back(std::make_unique<MozcModeSubAction>(this, command)); } instance_->inputContextManager().registerProperty("mozcState", &factory_); instance_->userInterfaceManager().registerAction("mozc-tool", &toolAction_); toolAction_.setShortText(_("Mozc Settings")); toolAction_.setLongText(_("Mozc Settings")); toolAction_.setIcon("fcitx-mozc-tool"); int i = 0; for (auto &modeAction : modeActions_) { instance_->userInterfaceManager().registerAction( kPropCompositionModes[i].name, modeAction.get()); toolMenu_.addAction(modeAction.get()); i++; } instance_->userInterfaceManager().registerAction("mozc-tool-config", &configToolAction_); configToolAction_.setShortText(_("Configuration Tool")); configToolAction_.setIcon("fcitx-mozc-tool"); configToolAction_.connect<SimpleAction::Activated>([](InputContext *) { mozc::Process::SpawnMozcProcess("mozc_tool", "--mode=config_dialog"); }); instance_->userInterfaceManager().registerAction("mozc-tool-dict", &dictionaryToolAction_); dictionaryToolAction_.setShortText(_("Dictionary Tool")); dictionaryToolAction_.setIcon("fcitx-mozc-dictionary"); dictionaryToolAction_.connect<SimpleAction::Activated>([](InputContext *) { mozc::Process::SpawnMozcProcess("mozc_tool", "--mode=dictionary_tool"); }); instance_->userInterfaceManager().registerAction("mozc-tool-add", &addWordAction_); addWordAction_.setShortText(_("Add Word")); addWordAction_.connect<SimpleAction::Activated>([](InputContext *) { mozc::Process::SpawnMozcProcess("mozc_tool", "--mode=word_register_dialog"); }); instance_->userInterfaceManager().registerAction("mozc-tool-about", &aboutAction_); aboutAction_.setShortText(_("About Mozc")); aboutAction_.connect<SimpleAction::Activated>([](InputContext *) { mozc::Process::SpawnMozcProcess("mozc_tool", "--mode=about_dialog"); }); toolMenu_.addAction(&configToolAction_); toolMenu_.addAction(&dictionaryToolAction_); toolMenu_.addAction(&addWordAction_); toolMenu_.addAction(&aboutAction_); toolAction_.setMenu(&toolMenu_); reloadConfig(); } MozcEngine::~MozcEngine() {} void MozcEngine::setConfig(const RawConfig &config) { config_.load(config, true); safeSaveAsIni(config_, "conf/mozc.conf"); } void MozcEngine::reloadConfig() { readAsIni(config_, "conf/mozc.conf"); } void MozcEngine::activate(const fcitx::InputMethodEntry &, fcitx::InputContextEvent &event) { if (client_) { client_->EnsureConnection(); } auto ic = event.inputContext(); auto mozc_state = mozcState(ic); mozc_state->FocusIn(); ic->statusArea().addAction(StatusGroup::InputMethod, &toolAction_); } void MozcEngine::deactivate(const fcitx::InputMethodEntry &, fcitx::InputContextEvent &event) { auto ic = event.inputContext(); auto mozc_state = mozcState(ic); mozc_state->FocusOut(); } void MozcEngine::keyEvent(const InputMethodEntry &entry, KeyEvent &event) { auto mozc_state = mozcState(event.inputContext()); auto &group = instance_->inputMethodManager().currentGroup(); std::string layout = group.layoutFor(entry.uniqueName()); if (layout.empty()) { layout = group.defaultLayout(); } const bool isJP = (layout == "jp" || stringutils::startsWith(layout, "jp-")); if (mozc_state->ProcessKeyEvent(event.rawKey().sym(), event.rawKey().code(), event.rawKey().states(), isJP, event.isRelease())) { event.filterAndAccept(); } } void MozcEngine::reset(const InputMethodEntry &, InputContextEvent &event) { auto mozc_state = mozcState(event.inputContext()); mozc_state->Reset(); } void MozcEngine::save() { if (client_ == nullptr) { return; } client_->SyncData(); } std::string MozcEngine::subMode(const fcitx::InputMethodEntry &, fcitx::InputContext &ic) { auto mozc_state = mozcState(&ic); return _(kPropCompositionModes[mozc_state->GetCompositionMode()].description); } std::string MozcEngine::subModeIconImpl(const fcitx::InputMethodEntry &, fcitx::InputContext &ic) { auto mozc_state = mozcState(&ic); return _(kPropCompositionModes[mozc_state->GetCompositionMode()].icon); } MozcState *MozcEngine::mozcState(InputContext *ic) { return ic->propertyFor(&factory_); } void MozcEngine::compositionModeUpdated(InputContext *ic) { for (const auto &modeAction : modeActions_) { modeAction->update(ic); } instance_->userInterfaceManager().update(UserInterfaceComponent::StatusArea, ic); } AddonInstance *MozcEngine::clipboardAddon() { return clipboard(); } } // namespace fcitx <commit_msg>Fix icon update.<commit_after>/* * Copyright (C) 2017~2017 by CSSlayer * wengxt@gmail.com * * This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 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; see the file COPYING. If not, * see <http://www.gnu.org/licenses/>. */ #include "unix/fcitx5/mozc_engine.h" #include <fcitx-config/iniparser.h> #include <fcitx-utils/i18n.h> #include <fcitx-utils/log.h> #include <fcitx-utils/standardpath.h> #include <fcitx/inputcontext.h> #include <fcitx/inputcontextmanager.h> #include <fcitx/inputmethodmanager.h> #include <fcitx/userinterfacemanager.h> #include <vector> #include "base/clock.h" #include "base/init_mozc.h" #include "base/process.h" #include "unix/fcitx5/mozc_connection.h" #include "unix/fcitx5/mozc_response_parser.h" namespace fcitx { const struct CompositionModeInfo { const char *name; const char *icon; const char *label; const char *description; mozc::commands::CompositionMode mode; } kPropCompositionModes[] = { { "mozc-mode-direct", "fcitx-mozc-direct", "A", N_("Direct"), mozc::commands::DIRECT, }, { "mozc-mode-hiragana", "fcitx-mozc-hiragana", "\xe3\x81\x82", // Hiragana letter A in UTF-8. N_("Hiragana"), mozc::commands::HIRAGANA, }, { "mozc-mode-katakana_full", "fcitx-mozc-katakana-full", "\xe3\x82\xa2", // Katakana letter A. N_("Full Katakana"), mozc::commands::FULL_KATAKANA, }, { "mozc-mode-alpha_half", "fcitx-mozc-alpha-half", "A", N_("Half ASCII"), mozc::commands::HALF_ASCII, }, { "mozc-mode-alpha_full", "fcitx-mozc-alpha-full", "\xef\xbc\xa1", // Full width ASCII letter A. N_("Full ASCII"), mozc::commands::FULL_ASCII, }, { "mozc-mode-katakana_half", "fcitx-mozc-katakana-half", "\xef\xbd\xb1", // Half width Katakana letter A. N_("Half Katakana"), mozc::commands::HALF_KATAKANA, }, }; const size_t kNumCompositionModes = arraysize(kPropCompositionModes); MozcModeSubAction::MozcModeSubAction(MozcEngine *engine, mozc::commands::CompositionMode mode) : engine_(engine), mode_(mode) { setShortText(_(kPropCompositionModes[mode].description)); setLongText(_(kPropCompositionModes[mode].description)); setIcon(kPropCompositionModes[mode].icon); setCheckable(true); } bool MozcModeSubAction::isChecked(InputContext *ic) const { auto mozc_state = engine_->mozcState(ic); return mozc_state->GetCompositionMode() == mode_; } void MozcModeSubAction::activate(InputContext *ic) { auto mozc_state = engine_->mozcState(ic); mozc_state->SendCompositionMode(mode_); } // This array must correspond with the CompositionMode enum in the // mozc/session/command.proto file. static_assert(mozc::commands::NUM_OF_COMPOSITIONS == kNumCompositionModes, "number of modes must match"); Instance *Init(Instance *instance) { int argc = 1; char argv0[] = "fcitx_mozc"; char *_argv[] = {argv0}; char **argv = _argv; mozc::InitMozc(argv[0], &argc, &argv); return instance; } MozcEngine::MozcEngine(Instance *instance) : instance_(Init(instance)), connection_(std::make_unique<MozcConnection>()), client_(connection_->CreateClient()), factory_([this](InputContext &ic) { return new MozcState(&ic, connection_->CreateClient(), this); }) { for (auto command : {mozc::commands::DIRECT, mozc::commands::HIRAGANA, mozc::commands::FULL_KATAKANA, mozc::commands::FULL_ASCII, mozc::commands::HALF_ASCII, mozc::commands::HALF_KATAKANA}) { modeActions_.push_back(std::make_unique<MozcModeSubAction>(this, command)); } instance_->inputContextManager().registerProperty("mozcState", &factory_); instance_->userInterfaceManager().registerAction("mozc-tool", &toolAction_); toolAction_.setShortText(_("Mozc Settings")); toolAction_.setLongText(_("Mozc Settings")); toolAction_.setIcon("fcitx-mozc-tool"); int i = 0; for (auto &modeAction : modeActions_) { instance_->userInterfaceManager().registerAction( kPropCompositionModes[i].name, modeAction.get()); toolMenu_.addAction(modeAction.get()); i++; } instance_->userInterfaceManager().registerAction("mozc-tool-config", &configToolAction_); configToolAction_.setShortText(_("Configuration Tool")); configToolAction_.setIcon("fcitx-mozc-tool"); configToolAction_.connect<SimpleAction::Activated>([](InputContext *) { mozc::Process::SpawnMozcProcess("mozc_tool", "--mode=config_dialog"); }); instance_->userInterfaceManager().registerAction("mozc-tool-dict", &dictionaryToolAction_); dictionaryToolAction_.setShortText(_("Dictionary Tool")); dictionaryToolAction_.setIcon("fcitx-mozc-dictionary"); dictionaryToolAction_.connect<SimpleAction::Activated>([](InputContext *) { mozc::Process::SpawnMozcProcess("mozc_tool", "--mode=dictionary_tool"); }); instance_->userInterfaceManager().registerAction("mozc-tool-add", &addWordAction_); addWordAction_.setShortText(_("Add Word")); addWordAction_.connect<SimpleAction::Activated>([](InputContext *) { mozc::Process::SpawnMozcProcess("mozc_tool", "--mode=word_register_dialog"); }); instance_->userInterfaceManager().registerAction("mozc-tool-about", &aboutAction_); aboutAction_.setShortText(_("About Mozc")); aboutAction_.connect<SimpleAction::Activated>([](InputContext *) { mozc::Process::SpawnMozcProcess("mozc_tool", "--mode=about_dialog"); }); toolMenu_.addAction(&configToolAction_); toolMenu_.addAction(&dictionaryToolAction_); toolMenu_.addAction(&addWordAction_); toolMenu_.addAction(&aboutAction_); toolAction_.setMenu(&toolMenu_); reloadConfig(); } MozcEngine::~MozcEngine() {} void MozcEngine::setConfig(const RawConfig &config) { config_.load(config, true); safeSaveAsIni(config_, "conf/mozc.conf"); } void MozcEngine::reloadConfig() { readAsIni(config_, "conf/mozc.conf"); } void MozcEngine::activate(const fcitx::InputMethodEntry &, fcitx::InputContextEvent &event) { if (client_) { client_->EnsureConnection(); } auto ic = event.inputContext(); auto mozc_state = mozcState(ic); mozc_state->FocusIn(); ic->statusArea().addAction(StatusGroup::InputMethod, &toolAction_); } void MozcEngine::deactivate(const fcitx::InputMethodEntry &, fcitx::InputContextEvent &event) { auto ic = event.inputContext(); auto mozc_state = mozcState(ic); mozc_state->FocusOut(); } void MozcEngine::keyEvent(const InputMethodEntry &entry, KeyEvent &event) { auto mozc_state = mozcState(event.inputContext()); auto &group = instance_->inputMethodManager().currentGroup(); std::string layout = group.layoutFor(entry.uniqueName()); if (layout.empty()) { layout = group.defaultLayout(); } const bool isJP = (layout == "jp" || stringutils::startsWith(layout, "jp-")); if (mozc_state->ProcessKeyEvent(event.rawKey().sym(), event.rawKey().code(), event.rawKey().states(), isJP, event.isRelease())) { event.filterAndAccept(); } } void MozcEngine::reset(const InputMethodEntry &, InputContextEvent &event) { auto mozc_state = mozcState(event.inputContext()); mozc_state->Reset(); } void MozcEngine::save() { if (client_ == nullptr) { return; } client_->SyncData(); } std::string MozcEngine::subMode(const fcitx::InputMethodEntry &, fcitx::InputContext &ic) { auto mozc_state = mozcState(&ic); return _(kPropCompositionModes[mozc_state->GetCompositionMode()].description); } std::string MozcEngine::subModeIconImpl(const fcitx::InputMethodEntry &, fcitx::InputContext &ic) { auto mozc_state = mozcState(&ic); return _(kPropCompositionModes[mozc_state->GetCompositionMode()].icon); } MozcState *MozcEngine::mozcState(InputContext *ic) { return ic->propertyFor(&factory_); } void MozcEngine::compositionModeUpdated(InputContext *ic) { for (const auto &modeAction : modeActions_) { modeAction->update(ic); } ic->updateUserInterface(UserInterfaceComponent::StatusArea); } AddonInstance *MozcEngine::clipboardAddon() { return clipboard(); } } // namespace fcitx <|endoftext|>
<commit_before>#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <list> #include <bitset> using namespace std; #define ll long long #define lson l,mid,id<<1 #define rson mid+1,r,id<<1|1 typedef pair<int, int>pii; typedef pair<ll, ll>pll; typedef pair<double, double>pdd; const double eps = 1e-6; const ll LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const double FINF = 1e18; #define x first #define y second #define REP(i,j,k) for(int i =(j);i<=(k);i++) #define REPD(i,j,k) for(int i =(j);i>=(k);i--) #define print(x) cout<<(x)<<endl; #define IOS ios::sync_with_stdio(0);cin.tie(0); void Init(){ return ; } void Solve(int t){ int n; scanf("%d",&n); int a=n*n; REPD(i,2051,3){ int b=i*i; int k1=sqrt(a+b); if(k1*k1==a+b&& k1>0 && i>=k1){ printf("%d %d\n",i,k1); } int k2=sqrt(a-b); if(k2*k2+b==a&& k2>0 && i>=k2){ printf("%d %d\n",i,k2); } int k3=sqrt(b-a); if(k3*k3+a==b&& k3>0 && i>=k3){ printf("%d %d\n",i,k3); } } if(t>1) printf("\n"); return ; } int main(){ freopen("uoj1079.in","r",stdin); int t; scanf("%d",&t); while(t--) Init(),Solve(t); return 0; }<commit_msg>update uoj1079<commit_after>#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <list> #include <bitset> using namespace std; #define ll long long #define lson l,mid,id<<1 #define rson mid+1,r,id<<1|1 typedef pair<int, int>pii; typedef pair<ll, ll>pll; typedef pair<double, double>pdd; const double eps = 1e-6; const ll LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const double FINF = 1e18; #define x first #define y second #define REP(i,j,k) for(int i =(j);i<=(k);i++) #define REPD(i,j,k) for(int i =(j);i>=(k);i--) #define print(x) cout<<(x)<<endl; #define IOS ios::sync_with_stdio(0);cin.tie(0); void Init(){ return ; } void Solve(int t){ int n; scanf("%d",&n); int a=n*n; REPD(i,2051,3){ int b=i*i; int k1=sqrt(a+b); if(k1*k1==a+b&& k1>0 && i>=k1){ printf("%d %d\n",i,k1); } int k2=sqrt(a-b); if(k2*k2+b==a&& k2>0 && i>=k2){ printf("%d %d\n",i,k2); } int k3=sqrt(b-a); if(k3*k3+a==b&& k3>0 && i>=k3){ printf("%d %d\n",i,k3); } } if(t>=1) printf("\n"); return ; } int main(){ freopen("uoj1079.in","r",stdin); int t; scanf("%d",&t); while(t--) Init(),Solve(t); return 0; }<|endoftext|>
<commit_before>#include <stdio.h> #include <iterator> #include <iostream> #include <vector> #define OK 1 #define ERROR 0 #define LIST_INIT_SIZE 100 #define LISTINCREMENT 10 #define ElemType int using namespace std; int main() { std::vector<ElemType> v; int a, i; ElemType e, x; if(v.empty()) // 判断顺序表是否创建成功 { printf("A Sequence List Has Created.\n"); } vector<ElemType>::iterator tempIterator=v.begin(); while(1) { printf("1:Insert element\n2:Delete element\n3:Load all elements\n0:Exit\nPlease choose:\n"); scanf("%d",&a); switch(a) { case 1: scanf("%d%d",&i,&x); if(i<1||i-1>v.size()){ printf("Insert Error!\n");} else{ v.insert(v.begin()+i-1,x); printf("The Element %d is Successfully Inserted!\n", x); } break; case 2: scanf("%d",&i); if(i<1 ||i>=v.size()){ printf("Delete Error!\n"); }else{ e=v.at(i-1); v.erase(v.begin()+i); printf("The Element %d is Successfully Deleted!\n", e); } break; case 3: for( tempIterator = v.begin(); tempIterator != v.end(); tempIterator++ ) std::cout << *tempIterator; cout << endl; break; case 0: return 1; } } } <commit_msg>update uoj8576<commit_after>#include <stdio.h> #include <iterator> #include <iostream> #include <vector> #define OK 1 #define ERROR 0 #define LIST_INIT_SIZE 100 #define LISTINCREMENT 10 #define ElemType int using namespace std; int main() { std::vector<ElemType> v; int a, i; ElemType e, x; if(v.empty()) // 判断顺序表是否创建成功 { printf("A Sequence List Has Created.\n"); } vector<ElemType>::iterator tempIterator; while(1) { printf("1:Insert element\n2:Delete element\n3:Load all elements\n0:Exit\nPlease choose:\n"); scanf("%d",&a); switch(a) { case 1: scanf("%d%d",&i,&x); if(i<1||i-1>v.size()){ printf("Insert Error!\n");} else{ v.insert(v.begin()+i-1,x); printf("The Element %d is Successfully Inserted!\n", x); } break; case 2: scanf("%d",&i); if(i<1 ||i>=v.size()){ printf("Delete Error!\n"); }else{ e=v.at(i-1); v.erase(v.begin()+i); printf("The Element %d is Successfully Deleted!\n", e); } break; case 3: if(v.size()==0) printf("The List is empty!"); // 请填空 else { printf("The List is: "); for( tempIterator = v.begin(); tempIterator != v.end(); tempIterator++ ) cout << *tempIterator <<" "; } printf("\n"); break; case 0: return 1; } } } <|endoftext|>
<commit_before>#include <stdio.h> #include <vector> #define OK 1 #define ERROR 0 #define LIST_INIT_SIZE 100 #define LISTINCREMENT 10 #define ElemType int using namespace std; int main() { std::vector<ElemType> v; int a, i; ElemType e, x; if(v.empty()) // 判断顺序表是否创建成功 { printf("A Sequence List Has Created.\n"); } while(1) { printf("1:Insert element\n2:Delete element\n3:Load all elements\n0:Exit\nPlease choose:\n"); scanf("%d",&a); switch(a) { case 1: scanf("%d%d",&i,&x); vector<ElemType>::iterator I = v.begin()+i; if(v.insert(I,x)) printf("Insert Error!\n"); // 判断i值是否合法,请填空 else printf("The Element %d is Successfully Inserted!\n", x); break; case 2: scanf("%d",&i); vector<ElemType>::iterator I = v.begin(); I=I+i; if(v.erase(I)) printf("Delete Error!\n"); // 判断i值是否合法,请填空 else printf("The Element %d is Successfully Deleted!\n", e); break; case 3: vector<ElemType>::iterator tempIterator; for( tempIterator = v.begin(); tempIterator != v.end(); tempIterator++ ) cout << *tempIterator; cout << endl; break; case 0: return 1; } } }<commit_msg>update uoj8576<commit_after>#include <stdio.h> #include <vector> #define OK 1 #define ERROR 0 #define LIST_INIT_SIZE 100 #define LISTINCREMENT 10 #define ElemType int using namespace std; int main() { std::vector<ElemType> v; int a, i; ElemType e, x; if(v.empty()) // 判断顺序表是否创建成功 { printf("A Sequence List Has Created.\n"); } while(1) { printf("1:Insert element\n2:Delete element\n3:Load all elements\n0:Exit\nPlease choose:\n"); scanf("%d",&a); switch(a) { case 1: scanf("%d%d",&i,&x); vector<ElemType>::iterator I; I = v.begin()+i; if(v.insert(I,x)) printf("Insert Error!\n"); // 判断i值是否合法,请填空 else printf("The Element %d is Successfully Inserted!\n", x); break; case 2: scanf("%d",&i); vector<ElemType>::iterator I = v.begin(); I=I+i; if(v.erase(I)) printf("Delete Error!\n"); // 判断i值是否合法,请填空 else printf("The Element %d is Successfully Deleted!\n", e); break; case 3: vector<ElemType>::iterator tempIterator; for( tempIterator = v.begin(); tempIterator != v.end(); tempIterator++ ) cout << *tempIterator; cout << endl; break; case 0: return 1; } } }<|endoftext|>
<commit_before>// Copyright (c) 2012 The Bitcoin developers // Copyright (c) 2014 The Peerunity developers // Previously distributed under the MIT/X11 software license, see the // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Copyright (c) 2015 Troy Benjegerdes, under AGPLv3 // Distributed under the Affero GNU General public license version 3 // file COPYING or http://www.gnu.org/licenses/agpl-3.0.html // Copyright (c) 2015 The Grantcoin Foundation #include <string> #include "codecoin.h" #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both peerunityd and peerunity(-qt), to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME(BRAND_upper); // Client version number #define CLIENT_VERSION_SUFFIX "-catoshi-beta" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, HG_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of hg identify) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // Placeholder for something that gets HG archive commit info #ifdef HG_ARCHIVE # define HG_COMMIT_ID "$Format:%h$" # define HG_COMMIT_DATE "$Format:%cD$" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef HG_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, HG_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef HG_COMMIT_DATE # define BUILD_DATE HG_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <commit_msg>change client version suffix<commit_after>// Copyright (c) 2012 The Bitcoin developers // Copyright (c) 2014 The Peerunity developers // Previously distributed under the MIT/X11 software license, see the // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Copyright (c) 2015 Troy Benjegerdes, under AGPLv3 // Distributed under the Affero GNU General public license version 3 // file COPYING or http://www.gnu.org/licenses/agpl-3.0.html // Copyright (c) 2015 The Grantcoin Foundation #include <string> #include "codecoin.h" #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both peerunityd and peerunity(-qt), to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME(BRAND_upper); // Client version number #define CLIENT_VERSION_SUFFIX "-beta" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, HG_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of hg identify) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // Placeholder for something that gets HG archive commit info #ifdef HG_ARCHIVE # define HG_COMMIT_ID "$Format:%h$" # define HG_COMMIT_DATE "$Format:%cD$" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef HG_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, HG_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef HG_COMMIT_DATE # define BUILD_DATE HG_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <|endoftext|>
<commit_before>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Satoshi"); // Client version number #define CLIENT_VERSION_SUFFIX "-cgb" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "0f2adcb" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <commit_msg>Version 1.1.5.2<commit_after>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Satoshi"); // Client version number #define CLIENT_VERSION_SUFFIX "-cgb" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "df9d55a" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <|endoftext|>
<commit_before>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("FreeTrade"); // Client version number #define CLIENT_VERSION_SUFFIX "-beta" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$ #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "$Format:%h$" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <commit_msg>Update to v3<commit_after>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Copyright (c) 2013-2014 Memorycoin Dev Team #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Memorycoin"); // Client version number #define CLIENT_VERSION_SUFFIX "-3.0.0" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$ #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "$Format:%h$" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <|endoftext|>
<commit_before>// Copyright (C) 2010, Vaclav Haisman. All rights reserved. // // Redistribution and use in source and binary forms, with or without modifica- // tion, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED ``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 (INCLU- // DING, 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 <log4cplus/version.h> namespace log4cplus { #if ! defined (LOG4CPLUS_VERSION_STR_SUFFIX) #define LOG4CPLUS_VERSION_STR_SUFFIX /* empty */ #endif unsigned const version = LOG4CPLUS_VERSION; char const versionStr[] = LOG4CPLUS_VERSION_STR LOG4CPLUS_VERSION_STR_SUFFIX; } <commit_msg>version.cxx: Set suffix to -RC1.<commit_after>// Copyright (C) 2010, Vaclav Haisman. All rights reserved. // // Redistribution and use in source and binary forms, with or without modifica- // tion, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED ``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 (INCLU- // DING, 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 <log4cplus/version.h> namespace log4cplus { #if ! defined (LOG4CPLUS_VERSION_STR_SUFFIX) #define LOG4CPLUS_VERSION_STR_SUFFIX "-RC1" #endif unsigned const version = LOG4CPLUS_VERSION; char const versionStr[] = LOG4CPLUS_VERSION_STR LOG4CPLUS_VERSION_STR_SUFFIX; } <|endoftext|>
<commit_before>#pragma once #include "base.hpp" #include <string> #include <vector> namespace krbn { namespace manipulator { namespace conditions { class variable final : public base { public: enum class type { variable_if, variable_unless, }; variable(const nlohmann::json& json) : base(), type_(type::variable_if) { if (!json.is_object()) { throw pqrs::json::unmarshal_error(fmt::format("json must be object, but is `{0}`", json.dump())); } for (const auto& [key, value] : json.items()) { // key is always std::string. if (key == "type") { if (!value.is_string()) { throw pqrs::json::unmarshal_error(fmt::format("{0} must be string, but is `{1}`", key, value.dump())); } auto t = value.get<std::string>(); if (t == "variable_if") { type_ = type::variable_if; } else if (t == "variable_unless") { type_ = type::variable_unless; } else { throw pqrs::json::unmarshal_error(fmt::format("unknown type `{0}`", t)); } } else if (key == "name") { if (!value.is_string()) { throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be string, but is `{1}`", key, value.dump())); } name_ = value.get<std::string>(); } else if (key == "value") { if (!value.is_number()) { throw pqrs::json::unmarshal_error(fmt::format("`{0}` must be number, but is `{1}`", key, value.dump())); } value_ = value.get<int>(); } else if (key == "description") { // Do nothing } else { throw pqrs::json::unmarshal_error(fmt::format("unknown key `{0}` in `{1}`", key, json.dump())); } } if (!name_) { throw pqrs::json::unmarshal_error(fmt::format("`name` is not found in `{0}`", json.dump())); } if (!value_) { throw pqrs::json::unmarshal_error(fmt::format("`value` is not found in `{0}`", json.dump())); } } virtual ~variable(void) { } virtual bool is_fulfilled(const event_queue::entry& entry, const manipulator_environment& manipulator_environment) const { switch (type_) { case type::variable_if: return manipulator_environment.get_variable(*name_) == *value_; case type::variable_unless: return manipulator_environment.get_variable(*name_) != *value_; } } private: type type_; std::optional<std::string> name_; std::optional<int> value_; }; } // namespace conditions } // namespace manipulator } // namespace krbn <commit_msg>use pqrs::json::requires_*<commit_after>#pragma once #include "base.hpp" #include <string> #include <vector> namespace krbn { namespace manipulator { namespace conditions { class variable final : public base { public: enum class type { variable_if, variable_unless, }; variable(const nlohmann::json& json) : base(), type_(type::variable_if) { pqrs::json::requires_object(json, "json"); for (const auto& [key, value] : json.items()) { // key is always std::string. if (key == "type") { pqrs::json::requires_string(value, key); auto t = value.get<std::string>(); if (t == "variable_if") { type_ = type::variable_if; } else if (t == "variable_unless") { type_ = type::variable_unless; } else { throw pqrs::json::unmarshal_error(fmt::format("unknown type `{0}`", t)); } } else if (key == "name") { pqrs::json::requires_string(value, "`name`"); name_ = value.get<std::string>(); } else if (key == "value") { pqrs::json::requires_number(value, "`value`"); value_ = value.get<int>(); } else if (key == "description") { // Do nothing } else { throw pqrs::json::unmarshal_error(fmt::format("unknown key `{0}` in `{1}`", key, json.dump())); } } if (!name_) { throw pqrs::json::unmarshal_error(fmt::format("`name` is not found in `{0}`", json.dump())); } if (!value_) { throw pqrs::json::unmarshal_error(fmt::format("`value` is not found in `{0}`", json.dump())); } } virtual ~variable(void) { } virtual bool is_fulfilled(const event_queue::entry& entry, const manipulator_environment& manipulator_environment) const { switch (type_) { case type::variable_if: return manipulator_environment.get_variable(*name_) == *value_; case type::variable_unless: return manipulator_environment.get_variable(*name_) != *value_; } } private: type type_; std::optional<std::string> name_; std::optional<int> value_; }; } // namespace conditions } // namespace manipulator } // namespace krbn <|endoftext|>
<commit_before>/* * Copyright 2016 Andrei Pangin * * 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 <fstream> #include <string.h> #include <stdlib.h> #include "asyncProfiler.h" #include "vmEntry.h" JavaVM* VM::_vm; jvmtiEnv* VM::_jvmti = NULL; template<class FunctionType> inline FunctionType getJvmFunction(const char *function_name) { // get address of function, return null if not found return (FunctionType) dlsym(RTLD_DEFAULT, function_name); } void VM::init(JavaVM* vm) { _vm = vm; if (_jvmti == NULL) { _vm->GetEnv((void**)&_jvmti, JVMTI_VERSION_1_0); } jvmtiCapabilities capabilities = {0}; capabilities.can_generate_all_class_hook_events = 1; capabilities.can_get_bytecodes = 1; capabilities.can_get_constant_pool = 1; capabilities.can_get_source_file_name = 1; capabilities.can_get_line_numbers = 1; capabilities.can_generate_compiled_method_load_events = 1; _jvmti->AddCapabilities(&capabilities); jvmtiEventCallbacks callbacks = {0}; callbacks.VMInit = VMInit; callbacks.ClassLoad = ClassLoad; callbacks.ClassPrepare = ClassPrepare; callbacks.CompiledMethodLoad = CompiledMethodLoad; _jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks)); _jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL); _jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_LOAD, NULL); _jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_PREPARE, NULL); _jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL); asgct = getJvmFunction<ASGCTType>("AsyncGetCallTrace"); } void VM::loadMethodIDs(jvmtiEnv* jvmti, jclass klass) { jint method_count; jmethodID* methods; if (jvmti->GetClassMethods(klass, &method_count, &methods) == 0) { jvmti->Deallocate((unsigned char*)methods); } } void VM::loadAllMethodIDs(jvmtiEnv* jvmti) { jint class_count; jclass* classes; if (jvmti->GetLoadedClasses(&class_count, &classes) == 0) { for (int i = 0; i < class_count; i++) { loadMethodIDs(jvmti, classes[i]); } jvmti->Deallocate((unsigned char*)classes); } } extern "C" JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* vm, char* options, void* reserved) { VM::init(vm); Profiler::_instance.start(DEFAULT_INTERVAL); return 0; } const char OPTION_DELIMITER[] = ","; const char FRAME_BUFFER_SIZE[] = "frameBufferSize:"; const char INTERVAL[] = "interval:"; const char START[] = "start"; const char STOP[] = "stop"; const char DUMP_RAW_TRACES[] = "dumpRawTraces:"; extern "C" JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM* vm, char* options, void* reserved) { VM::attach(vm); char args[1024]; if (strlen(options) >= sizeof(args)) { std::cerr << "List of options is too long" << std::endl; return -1; } strncpy(args, options, sizeof(args)); int interval = DEFAULT_INTERVAL; char *token = strtok(args, OPTION_DELIMITER); while (token) { if (strncmp(token, FRAME_BUFFER_SIZE, strlen(FRAME_BUFFER_SIZE)) == 0) { const char *text = token + strlen(FRAME_BUFFER_SIZE); const int value = atoi(text); std::cout << "Setting frame buffer size to " << value << std::endl; Profiler::_instance.frameBufferSize(value); } else if (strncmp(token, INTERVAL, strlen(INTERVAL)) == 0) { const char *text = token + strlen(INTERVAL); const int value = atoi(text); if (value <= 0) { std::cerr << "Interval must be positive: " << value << std::endl; return -1; } interval = value; } else if (strcmp(token, START) == 0) { if (!Profiler::_instance.is_running()) { std::cout << "Profiling started with interval " << interval << " ms" << std::endl; Profiler::_instance.start(interval); } } else if (strcmp(token, STOP) == 0) { std::cout << "Profiling stopped" << std::endl; Profiler::_instance.stop(); Profiler::_instance.dumpTraces(std::cout, DEFAULT_TRACES_TO_DUMP); Profiler::_instance.dumpMethods(std::cout); } else if (strncmp(token, DUMP_RAW_TRACES, strlen(DUMP_RAW_TRACES)) == 0) { std::cout << "Profiling stopped" << std::endl; Profiler::_instance.stop(); const char *fileName = token + strlen(DUMP_RAW_TRACES); std::ofstream dump(fileName, std::ios::out | std::ios::trunc); if (!dump.is_open()) { std::cerr << "Couldn't open: " << fileName << std::endl; return -1; } std::cout << "Dumping raw traces to " << fileName << std::endl; Profiler::_instance.dumpRawTraces(dump); dump.close(); } token = strtok(NULL, OPTION_DELIMITER); } return 0; } extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) { VM::attach(vm); return JNI_VERSION_1_6; } <commit_msg>Set JVMTI callbacks only once<commit_after>/* * Copyright 2016 Andrei Pangin * * 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 <fstream> #include <string.h> #include <stdlib.h> #include "asyncProfiler.h" #include "vmEntry.h" JavaVM* VM::_vm; jvmtiEnv* VM::_jvmti = NULL; template<class FunctionType> inline FunctionType getJvmFunction(const char *function_name) { // get address of function, return null if not found return (FunctionType) dlsym(RTLD_DEFAULT, function_name); } void VM::init(JavaVM* vm) { _vm = vm; if (_jvmti != NULL) return; _vm->GetEnv((void**)&_jvmti, JVMTI_VERSION_1_0); jvmtiCapabilities capabilities = {0}; capabilities.can_generate_all_class_hook_events = 1; capabilities.can_get_bytecodes = 1; capabilities.can_get_constant_pool = 1; capabilities.can_get_source_file_name = 1; capabilities.can_get_line_numbers = 1; capabilities.can_generate_compiled_method_load_events = 1; _jvmti->AddCapabilities(&capabilities); jvmtiEventCallbacks callbacks = {0}; callbacks.VMInit = VMInit; callbacks.ClassLoad = ClassLoad; callbacks.ClassPrepare = ClassPrepare; callbacks.CompiledMethodLoad = CompiledMethodLoad; _jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks)); _jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL); _jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_LOAD, NULL); _jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_PREPARE, NULL); _jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_COMPILED_METHOD_LOAD, NULL); asgct = getJvmFunction<ASGCTType>("AsyncGetCallTrace"); } void VM::loadMethodIDs(jvmtiEnv* jvmti, jclass klass) { jint method_count; jmethodID* methods; if (jvmti->GetClassMethods(klass, &method_count, &methods) == 0) { jvmti->Deallocate((unsigned char*)methods); } } void VM::loadAllMethodIDs(jvmtiEnv* jvmti) { jint class_count; jclass* classes; if (jvmti->GetLoadedClasses(&class_count, &classes) == 0) { for (int i = 0; i < class_count; i++) { loadMethodIDs(jvmti, classes[i]); } jvmti->Deallocate((unsigned char*)classes); } } extern "C" JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* vm, char* options, void* reserved) { VM::init(vm); Profiler::_instance.start(DEFAULT_INTERVAL); return 0; } const char OPTION_DELIMITER[] = ","; const char FRAME_BUFFER_SIZE[] = "frameBufferSize:"; const char INTERVAL[] = "interval:"; const char START[] = "start"; const char STOP[] = "stop"; const char DUMP_RAW_TRACES[] = "dumpRawTraces:"; extern "C" JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM* vm, char* options, void* reserved) { VM::attach(vm); char args[1024]; if (strlen(options) >= sizeof(args)) { std::cerr << "List of options is too long" << std::endl; return -1; } strncpy(args, options, sizeof(args)); int interval = DEFAULT_INTERVAL; char *token = strtok(args, OPTION_DELIMITER); while (token) { if (strncmp(token, FRAME_BUFFER_SIZE, strlen(FRAME_BUFFER_SIZE)) == 0) { const char *text = token + strlen(FRAME_BUFFER_SIZE); const int value = atoi(text); std::cout << "Setting frame buffer size to " << value << std::endl; Profiler::_instance.frameBufferSize(value); } else if (strncmp(token, INTERVAL, strlen(INTERVAL)) == 0) { const char *text = token + strlen(INTERVAL); const int value = atoi(text); if (value <= 0) { std::cerr << "Interval must be positive: " << value << std::endl; return -1; } interval = value; } else if (strcmp(token, START) == 0) { if (!Profiler::_instance.is_running()) { std::cout << "Profiling started with interval " << interval << " ms" << std::endl; Profiler::_instance.start(interval); } } else if (strcmp(token, STOP) == 0) { std::cout << "Profiling stopped" << std::endl; Profiler::_instance.stop(); Profiler::_instance.dumpTraces(std::cout, DEFAULT_TRACES_TO_DUMP); Profiler::_instance.dumpMethods(std::cout); } else if (strncmp(token, DUMP_RAW_TRACES, strlen(DUMP_RAW_TRACES)) == 0) { std::cout << "Profiling stopped" << std::endl; Profiler::_instance.stop(); const char *fileName = token + strlen(DUMP_RAW_TRACES); std::ofstream dump(fileName, std::ios::out | std::ios::trunc); if (!dump.is_open()) { std::cerr << "Couldn't open: " << fileName << std::endl; return -1; } std::cout << "Dumping raw traces to " << fileName << std::endl; Profiler::_instance.dumpRawTraces(dump); dump.close(); } token = strtok(NULL, OPTION_DELIMITER); } return 0; } extern "C" JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) { VM::attach(vm); return JNI_VERSION_1_6; } <|endoftext|>
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld 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 "flusspferd/xml/xml.hpp" #include "flusspferd/xml/parse.hpp" #include "flusspferd/xml/push_parser.hpp" #include "flusspferd/xml/node.hpp" #include "flusspferd/xml/document.hpp" #include "flusspferd/xml/text.hpp" #include "flusspferd/xml/namespace.hpp" #include "flusspferd/xml/reference.hpp" #include "flusspferd/xml/attribute.hpp" #include "flusspferd/xml/processing_instruction.hpp" #include "flusspferd/function_adapter.hpp" #include "flusspferd/local_root_scope.hpp" #include "flusspferd/create.hpp" #include "flusspferd/string.hpp" #include "flusspferd/security.hpp" #include <libxml/xmlIO.h> using namespace flusspferd; using namespace flusspferd::xml; extern "C" value flusspferd_load(object container) { return load_xml(container); } static void safety_io_callbacks(); object flusspferd::xml::load_xml(object container) { safety_io_callbacks(); local_root_scope scope; value previous = container.get_property("XML"); if (previous.is_object()) return previous.to_object(); LIBXML_TEST_VERSION object XML = flusspferd::create_object(); load_class<node>(XML); load_class<document>(XML); load_class<text>(XML); load_class<comment>(XML); load_class<cdata_section>(XML); load_class<reference_>(XML); load_class<processing_instruction>(XML); load_class<attribute_>(XML); load_class<namespace_>(XML); load_class<push_parser>(XML); create_native_function(XML, "parseBlob", &parse_blob); create_native_function(XML, "parseFile", &parse_file); container.define_property( "XML", XML, object::read_only_property | object::dont_enumerate); return XML; } template<int (*OldMatch)(char const *), unsigned mode> static int safety_match(char const *name) { if (!OldMatch(name)) return 0; std::string path(name); std::size_t nonletter = path.find_first_not_of( "abcdefghijklmnopqrstuvwxyz"); if (nonletter != 0 && nonletter != std::string::npos && path[nonletter] == ':') return flusspferd::security::get().check_url(path, mode); else return flusspferd::security::get().check_path(path, mode); } static void safety_io_callbacks() { xmlCleanupInputCallbacks(); xmlCleanupOutputCallbacks(); #define REG_INPUT(name) \ xmlRegisterInputCallbacks( \ safety_match<name ## Match, security::READ>, \ name ## Open, \ name ## Read, \ name ## Close) \ /**/ REG_INPUT(xmlFile); REG_INPUT(xmlIOHTTP); // disable any output xmlRegisterOutputCallbacks(0, 0, 0, 0); } <commit_msg>allow uppercase url schemes<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp: /* Copyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld 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 "flusspferd/xml/xml.hpp" #include "flusspferd/xml/parse.hpp" #include "flusspferd/xml/push_parser.hpp" #include "flusspferd/xml/node.hpp" #include "flusspferd/xml/document.hpp" #include "flusspferd/xml/text.hpp" #include "flusspferd/xml/namespace.hpp" #include "flusspferd/xml/reference.hpp" #include "flusspferd/xml/attribute.hpp" #include "flusspferd/xml/processing_instruction.hpp" #include "flusspferd/function_adapter.hpp" #include "flusspferd/local_root_scope.hpp" #include "flusspferd/create.hpp" #include "flusspferd/string.hpp" #include "flusspferd/security.hpp" #include <libxml/xmlIO.h> using namespace flusspferd; using namespace flusspferd::xml; extern "C" value flusspferd_load(object container) { return load_xml(container); } static void safety_io_callbacks(); object flusspferd::xml::load_xml(object container) { safety_io_callbacks(); local_root_scope scope; value previous = container.get_property("XML"); if (previous.is_object()) return previous.to_object(); LIBXML_TEST_VERSION object XML = flusspferd::create_object(); load_class<node>(XML); load_class<document>(XML); load_class<text>(XML); load_class<comment>(XML); load_class<cdata_section>(XML); load_class<reference_>(XML); load_class<processing_instruction>(XML); load_class<attribute_>(XML); load_class<namespace_>(XML); load_class<push_parser>(XML); create_native_function(XML, "parseBlob", &parse_blob); create_native_function(XML, "parseFile", &parse_file); container.define_property( "XML", XML, object::read_only_property | object::dont_enumerate); return XML; } template<int (*OldMatch)(char const *), unsigned mode> static int safety_match(char const *name) { if (!OldMatch(name)) return 0; std::string path(name); std::size_t nonletter = path.find_first_not_of( "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); if (nonletter != 0 && nonletter != std::string::npos && path[nonletter] == ':') return flusspferd::security::get().check_url(path, mode); else return flusspferd::security::get().check_path(path, mode); } static void safety_io_callbacks() { xmlCleanupInputCallbacks(); xmlCleanupOutputCallbacks(); #define REG_INPUT(name) \ xmlRegisterInputCallbacks( \ safety_match<name ## Match, security::READ>, \ name ## Open, \ name ## Read, \ name ## Close) \ /**/ REG_INPUT(xmlFile); REG_INPUT(xmlIOHTTP); // disable any output xmlRegisterOutputCallbacks(0, 0, 0, 0); } <|endoftext|>
<commit_before>#include <QApplication> #include <QDebug> #include "app.h" void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message) { Q_UNUSED(context) QString level; switch (type) { case QtDebugMsg: level = "DEBUG"; break; case QtInfoMsg: level = "INFO"; break; case QtWarningMsg: level = "WARNING"; break; case QtCriticalMsg: level = "CRITICAL"; break; case QtFatalMsg: level = "FATAL"; break; default: level = "UNDEFIEND"; break; } if (type != QtWarningMsg) { QString text = QString("[%1] [%2] %3") .arg(QDateTime::currentDateTime().toString("dd-MM-yyyy hh:mm:ss")) .arg(level) .arg(message); static QString logPath = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation) + "/log"; QDir().mkdir(logPath); QFile file(logPath + "/stacer.log"); QIODevice::OpenMode openMode; if (file.size() > (1L << 20)) openMode = QIODevice::WriteOnly | QIODevice::Truncate; else openMode = QIODevice::WriteOnly | QIODevice::Append; if (file.open(openMode)) { QTextStream stream(&file); stream << text << endl; file.close(); } } } int main(int argc, char *argv[]) { QApplication app(argc, argv); qApp->setApplicationName("stacer"); qApp->setApplicationDisplayName("Stacer"); qApp->setApplicationVersion("1.0.8"); qApp->setWindowIcon(QIcon(":/static/logo.png")); // qInstallMessageHandler(messageHandler); App w; w.show(); return app.exec(); } <commit_msg>added splashscreen<commit_after>#include <QApplication> #include <QSplashScreen> #include <QDebug> #include "app.h" void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message) { Q_UNUSED(context) QString level; switch (type) { case QtDebugMsg: level = "DEBUG"; break; case QtInfoMsg: level = "INFO"; break; case QtWarningMsg: level = "WARNING"; break; case QtCriticalMsg: level = "CRITICAL"; break; case QtFatalMsg: level = "FATAL"; break; default: level = "UNDEFIEND"; break; } if (type != QtWarningMsg) { QString text = QString("[%1] [%2] %3") .arg(QDateTime::currentDateTime().toString("dd-MM-yyyy hh:mm:ss")) .arg(level) .arg(message); static QString logPath = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation) + "/log"; QDir().mkdir(logPath); QFile file(logPath + "/stacer.log"); QIODevice::OpenMode openMode; if (file.size() > (1L << 20)) openMode = QIODevice::WriteOnly | QIODevice::Truncate; else openMode = QIODevice::WriteOnly | QIODevice::Append; if (file.open(openMode)) { QTextStream stream(&file); stream << text << endl; file.close(); } } } int main(int argc, char *argv[]) { QApplication app(argc, argv); qApp->setApplicationName("stacer"); qApp->setApplicationDisplayName("Stacer"); qApp->setApplicationVersion("1.0.8"); qApp->setWindowIcon(QIcon(":/static/logo.png")); QPixmap pixmap(":/static/logo.png"); QSplashScreen splash(pixmap); splash.show(); app.processEvents(); // qInstallMessageHandler(messageHandler); App w; w.show(); splash.finish(&w); return app.exec(); } <|endoftext|>
<commit_before>//===- PseudoLoweringEmitter.cpp - PseudoLowering Generator -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "pseudo-lowering" #include "CodeGenInstruction.h" #include "PseudoLoweringEmitter.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Record.h" #include "llvm/ADT/IndexedMap.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Debug.h" #include <vector> using namespace llvm; // FIXME: This pass currently can only expand a pseudo to a single instruction. // The pseudo expansion really should take a list of dags, not just // a single dag, so we can do fancier things. unsigned PseudoLoweringEmitter:: addDagOperandMapping(Record *Rec, DagInit *Dag, CodeGenInstruction &Insn, IndexedMap<OpData> &OperandMap, unsigned BaseIdx) { unsigned OpsAdded = 0; for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) { if (DefInit *DI = dynamic_cast<DefInit*>(Dag->getArg(i))) { // Physical register reference. Explicit check for the special case // "zero_reg" definition. if (DI->getDef()->isSubClassOf("Register") || DI->getDef()->getName() == "zero_reg") { OperandMap[BaseIdx + i].Kind = OpData::Reg; OperandMap[BaseIdx + i].Data.Reg = DI->getDef(); ++OpsAdded; continue; } // Normal operands should always have the same type, or we have a // problem. // FIXME: We probably shouldn't ever get a non-zero BaseIdx here. assert(BaseIdx == 0 && "Named subargument in pseudo expansion?!"); if (DI->getDef() != Insn.Operands[BaseIdx + i].Rec) throw TGError(Rec->getLoc(), "Pseudo operand type '" + DI->getDef()->getName() + "' does not match expansion operand type '" + Insn.Operands[BaseIdx + i].Rec->getName() + "'"); // Source operand maps to destination operand. The Data element // will be filled in later, just set the Kind for now. Do it // for each corresponding MachineInstr operand, not just the first. for (unsigned I = 0, E = Insn.Operands[i].MINumOperands; I != E; ++I) OperandMap[BaseIdx + i + I].Kind = OpData::Operand; OpsAdded += Insn.Operands[i].MINumOperands; } else if (IntInit *II = dynamic_cast<IntInit*>(Dag->getArg(i))) { OperandMap[BaseIdx + i].Kind = OpData::Imm; OperandMap[BaseIdx + i].Data.Imm = II->getValue(); ++OpsAdded; } else if (DagInit *SubDag = dynamic_cast<DagInit*>(Dag->getArg(i))) { // Just add the operands recursively. This is almost certainly // a constant value for a complex operand (> 1 MI operand). unsigned NewOps = addDagOperandMapping(Rec, SubDag, Insn, OperandMap, BaseIdx + i); OpsAdded += NewOps; // Since we added more than one, we also need to adjust the base. BaseIdx += NewOps - 1; } else llvm_unreachable("Unhandled pseudo-expansion argument type!"); } return OpsAdded; } void PseudoLoweringEmitter::evaluateExpansion(Record *Rec) { DEBUG(dbgs() << "Pseudo definition: " << Rec->getName() << "\n"); // Validate that the result pattern has the corrent number and types // of arguments for the instruction it references. DagInit *Dag = Rec->getValueAsDag("ResultInst"); assert(Dag && "Missing result instruction in pseudo expansion!"); DEBUG(dbgs() << " Result: " << *Dag << "\n"); DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator()); if (!OpDef) throw TGError(Rec->getLoc(), Rec->getName() + " has unexpected operator type!"); Record *Operator = OpDef->getDef(); if (!Operator->isSubClassOf("Instruction")) throw TGError(Rec->getLoc(), "Pseudo result '" + Operator->getName() + "' is not an instruction!"); CodeGenInstruction Insn(Operator); if (Insn.isCodeGenOnly || Insn.isPseudo) throw TGError(Rec->getLoc(), "Pseudo result '" + Operator->getName() + "' cannot be another pseudo instruction!"); if (Insn.Operands.size() != Dag->getNumArgs()) throw TGError(Rec->getLoc(), "Pseudo result '" + Operator->getName() + "' operand count mismatch"); IndexedMap<OpData> OperandMap; OperandMap.grow(Insn.Operands.size()); addDagOperandMapping(Rec, Dag, Insn, OperandMap, 0); // If there are more operands that weren't in the DAG, they have to // be operands that have default values, or we have an error. Currently, // PredicateOperand and OptionalDefOperand both have default values. // Validate that each result pattern argument has a matching (by name) // argument in the source instruction, in either the (outs) or (ins) list. // Also check that the type of the arguments match. // // Record the mapping of the source to result arguments for use by // the lowering emitter. CodeGenInstruction SourceInsn(Rec); StringMap<unsigned> SourceOperands; for (unsigned i = 0, e = SourceInsn.Operands.size(); i != e; ++i) SourceOperands[SourceInsn.Operands[i].Name] = i; DEBUG(dbgs() << " Operand mapping:\n"); for (unsigned i = 0, e = Insn.Operands.size(); i != e; ++i) { // We've already handled constant values. Just map instruction operands // here. if (OperandMap[Insn.Operands[i].MIOperandNo].Kind != OpData::Operand) continue; StringMap<unsigned>::iterator SourceOp = SourceOperands.find(Dag->getArgName(i)); if (SourceOp == SourceOperands.end()) throw TGError(Rec->getLoc(), "Pseudo output operand '" + Dag->getArgName(i) + "' has no matching source operand."); // Map the source operand to the destination operand index for each // MachineInstr operand. for (unsigned I = 0, E = Insn.Operands[i].MINumOperands; I != E; ++I) OperandMap[Insn.Operands[i].MIOperandNo + I].Data.Operand = SourceOp->getValue(); DEBUG(dbgs() << " " << SourceOp->getValue() << " ==> " << i << "\n"); } Expansions.push_back(PseudoExpansion(SourceInsn, Insn, OperandMap)); } void PseudoLoweringEmitter::emitLoweringEmitter(raw_ostream &o) { // Emit file header. EmitSourceFileHeader("Pseudo-instruction MC lowering Source Fragment", o); o << "bool " << Target.getName() + "AsmPrinter" << "::\n" << "emitPseudoExpansionLowering(MCStreamer &OutStreamer,\n" << " const MachineInstr *MI) {\n" << " switch (MI->getOpcode()) {\n" << " default: return false;\n"; for (unsigned i = 0, e = Expansions.size(); i != e; ++i) { PseudoExpansion &Expansion = Expansions[i]; CodeGenInstruction &Source = Expansion.Source; CodeGenInstruction &Dest = Expansion.Dest; o << " case " << Source.Namespace << "::" << Source.TheDef->getName() << ": {\n" << " MCInst TmpInst;\n" << " MCOperand MCOp;\n" << " TmpInst.setOpcode(" << Dest.Namespace << "::" << Dest.TheDef->getName() << ");\n"; // Copy the operands from the source instruction. // FIXME: Instruction operands with defaults values (predicates and cc_out // in ARM, for example shouldn't need explicit values in the // expansion DAG. unsigned MIOpNo = 0; for (unsigned OpNo = 0, E = Dest.Operands.size(); OpNo != E; ++OpNo) { o << " // Operand: " << Dest.Operands[OpNo].Name << "\n"; for (unsigned i = 0, e = Dest.Operands[OpNo].MINumOperands; i != e; ++i) { switch (Expansion.OperandMap[MIOpNo + i].Kind) { case OpData::Operand: o << " lowerOperand(MI->getOperand(" << Source.Operands[Expansion.OperandMap[MIOpNo].Data .Operand].MIOperandNo + i << "), MCOp);\n" << " TmpInst.addOperand(MCOp);\n"; break; case OpData::Imm: o << " TmpInst.addOperand(MCOperand::CreateImm(" << Expansion.OperandMap[MIOpNo + i].Data.Imm << "));\n"; break; case OpData::Reg: { Record *Reg = Expansion.OperandMap[MIOpNo + i].Data.Reg; o << " TmpInst.addOperand(MCOperand::CreateReg("; // "zero_reg" is special. if (Reg->getName() == "zero_reg") o << "0"; else o << Reg->getValueAsString("Namespace") << "::" << Reg->getName(); o << "));\n"; break; } } } MIOpNo += Dest.Operands[OpNo].MINumOperands; } if (Dest.Operands.isVariadic) { o << " // variable_ops\n"; o << " for (unsigned i = " << MIOpNo << ", e = MI->getNumOperands(); i != e; ++i)\n" << " if (lowerOperand(MI->getOperand(i), MCOp))\n" << " TmpInst.addOperand(MCOp);\n"; } o << " OutStreamer.EmitInstruction(TmpInst);\n" << " break;\n" << " }\n"; } o << " }\n return true;\n}\n\n"; } void PseudoLoweringEmitter::run(raw_ostream &o) { Record *ExpansionClass = Records.getClass("PseudoInstExpansion"); Record *InstructionClass = Records.getClass("PseudoInstExpansion"); assert(ExpansionClass && "PseudoInstExpansion class definition missing!"); assert(InstructionClass && "Instruction class definition missing!"); std::vector<Record*> Insts; for (std::map<std::string, Record*>::const_iterator I = Records.getDefs().begin(), E = Records.getDefs().end(); I != E; ++I) { if (I->second->isSubClassOf(ExpansionClass) && I->second->isSubClassOf(InstructionClass)) Insts.push_back(I->second); } // Process the pseudo expansion definitions, validating them as we do so. for (unsigned i = 0, e = Insts.size(); i != e; ++i) evaluateExpansion(Insts[i]); // Generate expansion code to lower the pseudo to an MCInst of the real // instruction. emitLoweringEmitter(o); } <commit_msg>Reserve number of MI operands to accom,odate complex patterns.<commit_after>//===- PseudoLoweringEmitter.cpp - PseudoLowering Generator -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "pseudo-lowering" #include "CodeGenInstruction.h" #include "PseudoLoweringEmitter.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Record.h" #include "llvm/ADT/IndexedMap.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Debug.h" #include <vector> using namespace llvm; // FIXME: This pass currently can only expand a pseudo to a single instruction. // The pseudo expansion really should take a list of dags, not just // a single dag, so we can do fancier things. unsigned PseudoLoweringEmitter:: addDagOperandMapping(Record *Rec, DagInit *Dag, CodeGenInstruction &Insn, IndexedMap<OpData> &OperandMap, unsigned BaseIdx) { unsigned OpsAdded = 0; for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) { if (DefInit *DI = dynamic_cast<DefInit*>(Dag->getArg(i))) { // Physical register reference. Explicit check for the special case // "zero_reg" definition. if (DI->getDef()->isSubClassOf("Register") || DI->getDef()->getName() == "zero_reg") { OperandMap[BaseIdx + i].Kind = OpData::Reg; OperandMap[BaseIdx + i].Data.Reg = DI->getDef(); ++OpsAdded; continue; } // Normal operands should always have the same type, or we have a // problem. // FIXME: We probably shouldn't ever get a non-zero BaseIdx here. assert(BaseIdx == 0 && "Named subargument in pseudo expansion?!"); if (DI->getDef() != Insn.Operands[BaseIdx + i].Rec) throw TGError(Rec->getLoc(), "Pseudo operand type '" + DI->getDef()->getName() + "' does not match expansion operand type '" + Insn.Operands[BaseIdx + i].Rec->getName() + "'"); // Source operand maps to destination operand. The Data element // will be filled in later, just set the Kind for now. Do it // for each corresponding MachineInstr operand, not just the first. for (unsigned I = 0, E = Insn.Operands[i].MINumOperands; I != E; ++I) OperandMap[BaseIdx + i + I].Kind = OpData::Operand; OpsAdded += Insn.Operands[i].MINumOperands; } else if (IntInit *II = dynamic_cast<IntInit*>(Dag->getArg(i))) { OperandMap[BaseIdx + i].Kind = OpData::Imm; OperandMap[BaseIdx + i].Data.Imm = II->getValue(); ++OpsAdded; } else if (DagInit *SubDag = dynamic_cast<DagInit*>(Dag->getArg(i))) { // Just add the operands recursively. This is almost certainly // a constant value for a complex operand (> 1 MI operand). unsigned NewOps = addDagOperandMapping(Rec, SubDag, Insn, OperandMap, BaseIdx + i); OpsAdded += NewOps; // Since we added more than one, we also need to adjust the base. BaseIdx += NewOps - 1; } else llvm_unreachable("Unhandled pseudo-expansion argument type!"); } return OpsAdded; } void PseudoLoweringEmitter::evaluateExpansion(Record *Rec) { DEBUG(dbgs() << "Pseudo definition: " << Rec->getName() << "\n"); // Validate that the result pattern has the corrent number and types // of arguments for the instruction it references. DagInit *Dag = Rec->getValueAsDag("ResultInst"); assert(Dag && "Missing result instruction in pseudo expansion!"); DEBUG(dbgs() << " Result: " << *Dag << "\n"); DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator()); if (!OpDef) throw TGError(Rec->getLoc(), Rec->getName() + " has unexpected operator type!"); Record *Operator = OpDef->getDef(); if (!Operator->isSubClassOf("Instruction")) throw TGError(Rec->getLoc(), "Pseudo result '" + Operator->getName() + "' is not an instruction!"); CodeGenInstruction Insn(Operator); if (Insn.isCodeGenOnly || Insn.isPseudo) throw TGError(Rec->getLoc(), "Pseudo result '" + Operator->getName() + "' cannot be another pseudo instruction!"); if (Insn.Operands.size() != Dag->getNumArgs()) throw TGError(Rec->getLoc(), "Pseudo result '" + Operator->getName() + "' operand count mismatch"); unsigned NumMIOperands = 0; for (unsigned i = 0, e = Insn.Operands.size(); i != e; ++i) NumMIOperands += Insn.Operands[i].MINumOperands; IndexedMap<OpData> OperandMap; OperandMap.grow(NumMIOperands); addDagOperandMapping(Rec, Dag, Insn, OperandMap, 0); // If there are more operands that weren't in the DAG, they have to // be operands that have default values, or we have an error. Currently, // PredicateOperand and OptionalDefOperand both have default values. // Validate that each result pattern argument has a matching (by name) // argument in the source instruction, in either the (outs) or (ins) list. // Also check that the type of the arguments match. // // Record the mapping of the source to result arguments for use by // the lowering emitter. CodeGenInstruction SourceInsn(Rec); StringMap<unsigned> SourceOperands; for (unsigned i = 0, e = SourceInsn.Operands.size(); i != e; ++i) SourceOperands[SourceInsn.Operands[i].Name] = i; DEBUG(dbgs() << " Operand mapping:\n"); for (unsigned i = 0, e = Insn.Operands.size(); i != e; ++i) { // We've already handled constant values. Just map instruction operands // here. if (OperandMap[Insn.Operands[i].MIOperandNo].Kind != OpData::Operand) continue; StringMap<unsigned>::iterator SourceOp = SourceOperands.find(Dag->getArgName(i)); if (SourceOp == SourceOperands.end()) throw TGError(Rec->getLoc(), "Pseudo output operand '" + Dag->getArgName(i) + "' has no matching source operand."); // Map the source operand to the destination operand index for each // MachineInstr operand. for (unsigned I = 0, E = Insn.Operands[i].MINumOperands; I != E; ++I) OperandMap[Insn.Operands[i].MIOperandNo + I].Data.Operand = SourceOp->getValue(); DEBUG(dbgs() << " " << SourceOp->getValue() << " ==> " << i << "\n"); } Expansions.push_back(PseudoExpansion(SourceInsn, Insn, OperandMap)); } void PseudoLoweringEmitter::emitLoweringEmitter(raw_ostream &o) { // Emit file header. EmitSourceFileHeader("Pseudo-instruction MC lowering Source Fragment", o); o << "bool " << Target.getName() + "AsmPrinter" << "::\n" << "emitPseudoExpansionLowering(MCStreamer &OutStreamer,\n" << " const MachineInstr *MI) {\n" << " switch (MI->getOpcode()) {\n" << " default: return false;\n"; for (unsigned i = 0, e = Expansions.size(); i != e; ++i) { PseudoExpansion &Expansion = Expansions[i]; CodeGenInstruction &Source = Expansion.Source; CodeGenInstruction &Dest = Expansion.Dest; o << " case " << Source.Namespace << "::" << Source.TheDef->getName() << ": {\n" << " MCInst TmpInst;\n" << " MCOperand MCOp;\n" << " TmpInst.setOpcode(" << Dest.Namespace << "::" << Dest.TheDef->getName() << ");\n"; // Copy the operands from the source instruction. // FIXME: Instruction operands with defaults values (predicates and cc_out // in ARM, for example shouldn't need explicit values in the // expansion DAG. unsigned MIOpNo = 0; for (unsigned OpNo = 0, E = Dest.Operands.size(); OpNo != E; ++OpNo) { o << " // Operand: " << Dest.Operands[OpNo].Name << "\n"; for (unsigned i = 0, e = Dest.Operands[OpNo].MINumOperands; i != e; ++i) { switch (Expansion.OperandMap[MIOpNo + i].Kind) { case OpData::Operand: o << " lowerOperand(MI->getOperand(" << Source.Operands[Expansion.OperandMap[MIOpNo].Data .Operand].MIOperandNo + i << "), MCOp);\n" << " TmpInst.addOperand(MCOp);\n"; break; case OpData::Imm: o << " TmpInst.addOperand(MCOperand::CreateImm(" << Expansion.OperandMap[MIOpNo + i].Data.Imm << "));\n"; break; case OpData::Reg: { Record *Reg = Expansion.OperandMap[MIOpNo + i].Data.Reg; o << " TmpInst.addOperand(MCOperand::CreateReg("; // "zero_reg" is special. if (Reg->getName() == "zero_reg") o << "0"; else o << Reg->getValueAsString("Namespace") << "::" << Reg->getName(); o << "));\n"; break; } } } MIOpNo += Dest.Operands[OpNo].MINumOperands; } if (Dest.Operands.isVariadic) { o << " // variable_ops\n"; o << " for (unsigned i = " << MIOpNo << ", e = MI->getNumOperands(); i != e; ++i)\n" << " if (lowerOperand(MI->getOperand(i), MCOp))\n" << " TmpInst.addOperand(MCOp);\n"; } o << " OutStreamer.EmitInstruction(TmpInst);\n" << " break;\n" << " }\n"; } o << " }\n return true;\n}\n\n"; } void PseudoLoweringEmitter::run(raw_ostream &o) { Record *ExpansionClass = Records.getClass("PseudoInstExpansion"); Record *InstructionClass = Records.getClass("PseudoInstExpansion"); assert(ExpansionClass && "PseudoInstExpansion class definition missing!"); assert(InstructionClass && "Instruction class definition missing!"); std::vector<Record*> Insts; for (std::map<std::string, Record*>::const_iterator I = Records.getDefs().begin(), E = Records.getDefs().end(); I != E; ++I) { if (I->second->isSubClassOf(ExpansionClass) && I->second->isSubClassOf(InstructionClass)) Insts.push_back(I->second); } // Process the pseudo expansion definitions, validating them as we do so. for (unsigned i = 0, e = Insts.size(); i != e; ++i) evaluateExpansion(Insts[i]); // Generate expansion code to lower the pseudo to an MCInst of the real // instruction. emitLoweringEmitter(o); } <|endoftext|>
<commit_before>#include "OgreOculusRender.hpp" OgreOculusRender::OgreOculusRender(std::string winName) { //Initialize some variables name = winName; root = NULL; window = NULL; smgr = NULL; for(size_t i(0); i < 2; i++) { cams[i] = NULL; rtts[i] = NULL; vpts[i] = NULL; } //Oc is an OculusInterface object. Communication with the Rift SDK is handeled by that class oc = NULL; CameraNode = NULL; cameraPosition = Ogre::Vector3(0,0,10); cameraOrientation = Ogre::Quaternion::IDENTITY; this->nearClippingDistance = (float) 0.05; this->lastOculusPosition = cameraPosition; this->lastOculusOrientation = cameraOrientation; this->updateTime = 0; fullscreen = true; hsDissmissed = false; } OgreOculusRender::~OgreOculusRender() { //The only thig we dynamicly load is the oculus interface delete oc; } //I may move this method back to the AnnEngine class... void OgreOculusRender::loadReseourceFile(const char path[]) { /*from ogre wiki : load the given resource file*/ Ogre::ConfigFile configFile; configFile.load(path); Ogre::ConfigFile::SectionIterator seci = configFile.getSectionIterator(); Ogre::String secName, typeName, archName; while (seci.hasMoreElements()) { secName = seci.peekNextKey(); Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext(); Ogre::ConfigFile::SettingsMultiMap::iterator i; for (i = settings->begin(); i != settings->end(); ++i) { typeName = i->first; archName = i->second; Ogre::ResourceGroupManager::getSingleton().addResourceLocation( archName, typeName, secName); } } } //See commant of the loadResourceFile method void OgreOculusRender::initAllResources() { Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); } void OgreOculusRender::initLibraries() { //Create the ogre root with standards Ogre configuration file root = new Ogre::Root("plugins.cfg","ogre.cfg","Ogre.log"); //Class to get basic information from the Rift. Initialize the RiftSDK oc = new OculusInterface(); } void OgreOculusRender::initialize() { //init libraries; initLibraries(); //Mandatory. If thouse pointers are unitilalized, program have to stop here. assert(root != NULL && oc != NULL); //Get configuration via ogre.cfg OR via the config dialog. getOgreConfig(); //Create the render window with the given sice from the Oculus createWindow(); //Load resources from the resources.cfg file loadReseourceFile("resources.cfg"); initAllResources(); //Create scene manager initScene(); //Create cameras and handeling nodes initCameras(); //Create rtts and viewports on them initRttRendering(); //Init the oculus rendering initOculus(); } void OgreOculusRender::getOgreConfig() { assert(root != NULL); if(!root->restoreConfig()) if(!root->showConfigDialog()) abort(); } void OgreOculusRender::createWindow() { assert(root != NULL && oc != NULL); Ogre::NameValuePairList misc; //This one only works on windows : "Borderless = no decoration" misc["border"]="none"; misc["vsync"]="true"; misc["displayFrequency"]="75"; misc["monitorIndex"]="1"; //Use the 2nd monitor, assuming the Oculus Rift is not the primary. Or is the only screen on the system. //Initialize a window ans specify that creation is manual window = root->initialise(false, name); //Create a non-fullscreen window using custom parameters if(fullscreen) window = root->createRenderWindow(name, oc->getHmd()->Resolution.w, oc->getHmd()->Resolution.h, true,&misc); else window = root->createRenderWindow(name, oc->getHmd()->Resolution.w, oc->getHmd()->Resolution.h, false, &misc); //Put the window at the place given by the SDK window->reposition(oc->getHmd()->WindowsPos.x,oc->getHmd()->WindowsPos.y); } void OgreOculusRender::initCameras() { assert(smgr != NULL); cams[left] = smgr->createCamera("lcam"); cams[right] = smgr->createCamera("rcam"); for(int i = 0; i < 2; i++) { cams[i]->setPosition(cameraPosition); cams[i]->setAutoAspectRatio(true); cams[i]->setNearClipDistance(1); cams[i]->setFarClipDistance(1000); } //do NOT attach camera to this node... CameraNode = smgr->getRootSceneNode()->createChildSceneNode(); } void OgreOculusRender::setCamerasNearClippingDistance(float distance) { nearClippingDistance = distance; } void OgreOculusRender::initScene() { assert(root != NULL); smgr = root->createSceneManager("OctreeSceneManager","OSM_SMGR"); } void OgreOculusRender::initRttRendering() { //get texture sice from ovr with default FOV texSizeL = ovrHmd_GetFovTextureSize(oc->getHmd(), ovrEye_Left, oc->getHmd()->DefaultEyeFov[0], 1.0f); texSizeR = ovrHmd_GetFovTextureSize(oc->getHmd(), ovrEye_Right, oc->getHmd()->DefaultEyeFov[1], 1.0f); //Create texture Ogre::TexturePtr rtt_textureL = Ogre::TextureManager::getSingleton().createManual("RttTexL", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, texSizeL.w, texSizeL.h, 0, Ogre::PF_R8G8B8, Ogre::TU_RENDERTARGET); Ogre::TexturePtr rtt_textureR = Ogre::TextureManager::getSingleton().createManual("RttTexR", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, texSizeR.w, texSizeR.h, 0, Ogre::PF_R8G8B8, Ogre::TU_RENDERTARGET); //Create Render Texture Ogre::RenderTexture* rttEyeLeft = rtt_textureL->getBuffer(0,0)->getRenderTarget(); Ogre::RenderTexture* rttEyeRight = rtt_textureR->getBuffer(0,0)->getRenderTarget(); //Create and bind a viewport to the texture Ogre::Viewport* vptl = rttEyeLeft->addViewport(cams[left]); vptl->setBackgroundColour(Ogre::ColourValue(0.3f,0.3f,0.9f)); Ogre::Viewport* vptr = rttEyeRight->addViewport(cams[right]); vptr->setBackgroundColour(Ogre::ColourValue(0.3f,0.3f,0.9f)); //Store viewport pointer vpts[left] = vptl; vpts[right] = vptr; //Pupulate textures with an initial render rttEyeLeft->update(); rttEyeRight->update(); //Store rtt textures pointer rtts[left] = rttEyeLeft; rtts[right] = rttEyeRight; } void OgreOculusRender::initOculus(bool fullscreenState) { setFullScreen(fullscreenState); //Get FOV EyeFov[left] = oc->getHmd()->DefaultEyeFov[left]; EyeFov[right] = oc->getHmd()->DefaultEyeFov[right]; //Set OpenGL configuration ovrGLConfig cfg; cfg.OGL.Header.API = ovrRenderAPI_OpenGL; cfg.OGL.Header.Multisample = 1; cfg.OGL.Header.RTSize = oc->getHmd()->Resolution; //OpenGL initialization differ between Windows and Linux #ifdef _WIN32 //If windows //Get window HWND hwnd; window->getCustomAttribute("WINDOW",&hwnd); //potential pointer problem here cfg.OGL.Window = hwnd; //Get GL Context HDC dc; window->getCustomAttribute("HDC", &dc); cfg.OGL.DC = dc; #else //Linux, even if OVR 0.4.2 is still NOT running on Linux //Get X window id size_t wID; window->getCustomAttribute("WINDOW", &wID); std::cout << "Wid : " << wID << endl; cfg.OGL.Win = wID; //Get X Display Display* display; window->getCustomAttribute("DISPLAY",&display); cfg.OGL.Disp = display; #endif if(!ovrHmd_ConfigureRendering( oc->getHmd(), &cfg.Config,oc->getHmd()->DistortionCaps, EyeFov, EyeRenderDesc)) abort(); // Direct rendering from a window handle to the Hmd. // Not required if ovrHmdCap_ExtendDesktop flag is set. #ifdef _WIN32 HWND directHWND; window->getCustomAttribute("WINDOW", &directHWND); ovrHmd_AttachToWindow(oc->getHmd(), directHWND, NULL, NULL); #else //Not currently available #endif //Send texture data to OVR for rendering //->left eye texture : EyeTexture[left].OGL.Header.API = ovrRenderAPI_OpenGL; EyeTexture[left].OGL.Header.TextureSize = texSizeL; EyeTexture[left].OGL.Header.RenderViewport.Pos.x = 0; EyeTexture[left].OGL.Header.RenderViewport.Pos.y = 0; EyeTexture[left].OGL.Header.RenderViewport.Size = texSizeL; Ogre::GLTexture* gl_rtt_l = static_cast<Ogre::GLTexture*>(Ogre::GLTextureManager::getSingleton().getByName("RttTexL").get()); EyeTexture[left].OGL.TexId = gl_rtt_l->getGLID(); //right eye texture : EyeTexture[right] = EyeTexture[left]; //Basic configuration is shared. EyeTexture[right].OGL.Header.TextureSize = texSizeR; EyeTexture[right].OGL.Header.RenderViewport.Size = texSizeR; Ogre::GLTexture* gl_rtt_r = static_cast<Ogre::GLTexture*>(Ogre::GLTextureManager::getSingleton().getByName("RttTexR").get()); EyeTexture[right].OGL.TexId = gl_rtt_r->getGLID(); } void OgreOculusRender::RenderOneFrame() { //get some info cameraPosition = this->CameraNode->getPosition(); cameraOrientation = this->CameraNode->getOrientation(); //Begin frame ovrFrameTiming hmdFrameTiming = ovrHmd_BeginFrame(oc->getHmd(), 0); //Tell ogre that Frame started root->_fireFrameStarted(); for (Ogre::SceneManagerEnumerator::SceneManagerIterator it = root->getSceneManagerIterator(); it.hasMoreElements(); it.moveNext()) it.peekNextValue()->_handleLodEvents(); ovrPosef headPose[2]; //Message pump events Ogre::WindowEventUtilities::messagePump(); for(int eyeIndex = 0; eyeIndex < ovrEye_Count; eyeIndex++) { //Get the correct eye to render ovrEyeType eye = oc->getHmd()->EyeRenderOrder[eyeIndex]; //Set the Ogre render target to the texture //root->getRenderSystem()->_setRenderTarget(rtts[eye]); vpts[eye]->clear(); //Get the eye pose ovrPosef eyePose = ovrHmd_GetEyePose(oc->getHmd(), eye); headPose[eye] = eyePose; //Get the hmd orientation OVR::Quatf camOrient = eyePose.Orientation; //Get the projection matrix OVR::Matrix4f proj = ovrMatrix4f_Projection(EyeRenderDesc[eye].Fov,static_cast<float>(nearClippingDistance), 10000.0f, true); //Convert it to Ogre matrix Ogre::Matrix4 OgreProj; for(int x(0); x < 4; x++) for(int y(0); y < 4; y++) OgreProj[x][y] = proj.M[x][y]; //Set the matrix cams[eye]->setCustomProjectionMatrix(true, OgreProj); //Set the orientation cams[eye]->setOrientation(cameraOrientation * Ogre::Quaternion(camOrient.w,camOrient.x,camOrient.y,camOrient.z)); //Set Position cams[eye]->setPosition (cameraPosition //the "gameplay" position of player's avatar head + (cams[eye]->getOrientation() * - Ogre::Vector3( //realword camera orientation + the oposite of the EyeRenderDesc[eye].ViewAdjust.x, //view adjust vector. we translate the camera, not the whole world EyeRenderDesc[eye].ViewAdjust.y, EyeRenderDesc[eye].ViewAdjust.z) + cameraOrientation * Ogre::Vector3( //cameraOrientation is in fact the direction the avatar is facing expressed as an Ogre::Quaternion headPose[eye].Position.x, headPose[eye].Position.y, headPose[eye].Position.z))); root->_fireFrameRenderingQueued(); rtts[eye]->update(); } //Ogre::Root::getSingleton().getRenderSystem()->_setRenderTarget(window); this->updateTime = hmdFrameTiming.DeltaSeconds; //Do the rendering then the buffer swap ovrHmd_EndFrame(oc->getHmd(), headPose, (ovrTexture*)EyeTexture); //Tell Ogre that frame ended root->_fireFrameEnded(); returnPose.position = cameraPosition + Ogre::Vector3 (headPose[0].Position.x, headPose[0].Position.y, headPose[0].Position.z); returnPose.orientation = cameraOrientation * Ogre::Quaternion (headPose[0].Orientation.w, headPose[0].Orientation.x, headPose[0].Orientation.y, headPose[0].Orientation.z); } void OgreOculusRender::dissmissHS() { ovrHmd_DismissHSWDisplay(oc->getHmd()); hsDissmissed = true; }<commit_msg>add line break<commit_after>#include "OgreOculusRender.hpp" OgreOculusRender::OgreOculusRender(std::string winName) { //Initialize some variables name = winName; root = NULL; window = NULL; smgr = NULL; for(size_t i(0); i < 2; i++) { cams[i] = NULL; rtts[i] = NULL; vpts[i] = NULL; } //Oc is an OculusInterface object. Communication with the Rift SDK is handeled by that class oc = NULL; CameraNode = NULL; cameraPosition = Ogre::Vector3(0,0,10); cameraOrientation = Ogre::Quaternion::IDENTITY; this->nearClippingDistance = (float) 0.05; this->lastOculusPosition = cameraPosition; this->lastOculusOrientation = cameraOrientation; this->updateTime = 0; fullscreen = true; hsDissmissed = false; } OgreOculusRender::~OgreOculusRender() { //The only thig we dynamicly load is the oculus interface delete oc; } //I may move this method back to the AnnEngine class... void OgreOculusRender::loadReseourceFile(const char path[]) { /*from ogre wiki : load the given resource file*/ Ogre::ConfigFile configFile; configFile.load(path); Ogre::ConfigFile::SectionIterator seci = configFile.getSectionIterator(); Ogre::String secName, typeName, archName; while (seci.hasMoreElements()) { secName = seci.peekNextKey(); Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext(); Ogre::ConfigFile::SettingsMultiMap::iterator i; for (i = settings->begin(); i != settings->end(); ++i) { typeName = i->first; archName = i->second; Ogre::ResourceGroupManager::getSingleton().addResourceLocation( archName, typeName, secName); } } } //See commant of the loadResourceFile method void OgreOculusRender::initAllResources() { Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); } void OgreOculusRender::initLibraries() { //Create the ogre root with standards Ogre configuration file root = new Ogre::Root("plugins.cfg","ogre.cfg","Ogre.log"); //Class to get basic information from the Rift. Initialize the RiftSDK oc = new OculusInterface(); } void OgreOculusRender::initialize() { //init libraries; initLibraries(); //Mandatory. If thouse pointers are unitilalized, program have to stop here. assert(root != NULL && oc != NULL); //Get configuration via ogre.cfg OR via the config dialog. getOgreConfig(); //Create the render window with the given sice from the Oculus createWindow(); //Load resources from the resources.cfg file loadReseourceFile("resources.cfg"); initAllResources(); //Create scene manager initScene(); //Create cameras and handeling nodes initCameras(); //Create rtts and viewports on them initRttRendering(); //Init the oculus rendering initOculus(); } void OgreOculusRender::getOgreConfig() { assert(root != NULL); if(!root->restoreConfig()) if(!root->showConfigDialog()) abort(); } void OgreOculusRender::createWindow() { assert(root != NULL && oc != NULL); Ogre::NameValuePairList misc; //This one only works on windows : "Borderless = no decoration" misc["border"]="none"; misc["vsync"]="true"; misc["displayFrequency"]="75"; misc["monitorIndex"]="1"; //Use the 2nd monitor, assuming the Oculus Rift is not the primary. Or is the only screen on the system. //Initialize a window ans specify that creation is manual window = root->initialise(false, name); //Create a non-fullscreen window using custom parameters if(fullscreen) window = root->createRenderWindow(name, oc->getHmd()->Resolution.w, oc->getHmd()->Resolution.h, true,&misc); else window = root->createRenderWindow(name, oc->getHmd()->Resolution.w, oc->getHmd()->Resolution.h, false, &misc); //Put the window at the place given by the SDK window->reposition(oc->getHmd()->WindowsPos.x,oc->getHmd()->WindowsPos.y); } void OgreOculusRender::initCameras() { assert(smgr != NULL); cams[left] = smgr->createCamera("lcam"); cams[right] = smgr->createCamera("rcam"); for(int i = 0; i < 2; i++) { cams[i]->setPosition(cameraPosition); cams[i]->setAutoAspectRatio(true); cams[i]->setNearClipDistance(1); cams[i]->setFarClipDistance(1000); } //do NOT attach camera to this node... CameraNode = smgr->getRootSceneNode()->createChildSceneNode(); } void OgreOculusRender::setCamerasNearClippingDistance(float distance) { nearClippingDistance = distance; } void OgreOculusRender::initScene() { assert(root != NULL); smgr = root->createSceneManager("OctreeSceneManager","OSM_SMGR"); } void OgreOculusRender::initRttRendering() { //get texture sice from ovr with default FOV texSizeL = ovrHmd_GetFovTextureSize(oc->getHmd(), ovrEye_Left, oc->getHmd()->DefaultEyeFov[0], 1.0f); texSizeR = ovrHmd_GetFovTextureSize(oc->getHmd(), ovrEye_Right, oc->getHmd()->DefaultEyeFov[1], 1.0f); //Create texture Ogre::TexturePtr rtt_textureL = Ogre::TextureManager::getSingleton().createManual("RttTexL", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, texSizeL.w, texSizeL.h, 0, Ogre::PF_R8G8B8, Ogre::TU_RENDERTARGET); Ogre::TexturePtr rtt_textureR = Ogre::TextureManager::getSingleton().createManual("RttTexR", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, texSizeR.w, texSizeR.h, 0, Ogre::PF_R8G8B8, Ogre::TU_RENDERTARGET); //Create Render Texture Ogre::RenderTexture* rttEyeLeft = rtt_textureL->getBuffer(0,0)->getRenderTarget(); Ogre::RenderTexture* rttEyeRight = rtt_textureR->getBuffer(0,0)->getRenderTarget(); //Create and bind a viewport to the texture Ogre::Viewport* vptl = rttEyeLeft->addViewport(cams[left]); vptl->setBackgroundColour(Ogre::ColourValue(0.3f,0.3f,0.9f)); Ogre::Viewport* vptr = rttEyeRight->addViewport(cams[right]); vptr->setBackgroundColour(Ogre::ColourValue(0.3f,0.3f,0.9f)); //Store viewport pointer vpts[left] = vptl; vpts[right] = vptr; //Pupulate textures with an initial render rttEyeLeft->update(); rttEyeRight->update(); //Store rtt textures pointer rtts[left] = rttEyeLeft; rtts[right] = rttEyeRight; } void OgreOculusRender::initOculus(bool fullscreenState) { setFullScreen(fullscreenState); //Get FOV EyeFov[left] = oc->getHmd()->DefaultEyeFov[left]; EyeFov[right] = oc->getHmd()->DefaultEyeFov[right]; //Set OpenGL configuration ovrGLConfig cfg; cfg.OGL.Header.API = ovrRenderAPI_OpenGL; cfg.OGL.Header.Multisample = 1; cfg.OGL.Header.RTSize = oc->getHmd()->Resolution; //OpenGL initialization differ between Windows and Linux #ifdef _WIN32 //If windows //Get window HWND hwnd; window->getCustomAttribute("WINDOW",&hwnd); //potential pointer problem here cfg.OGL.Window = hwnd; //Get GL Context HDC dc; window->getCustomAttribute("HDC", &dc); cfg.OGL.DC = dc; #else //Linux, even if OVR 0.4.2 is still NOT running on Linux //Get X window id size_t wID; window->getCustomAttribute("WINDOW", &wID); std::cout << "Wid : " << wID << endl; cfg.OGL.Win = wID; //Get X Display Display* display; window->getCustomAttribute("DISPLAY",&display); cfg.OGL.Disp = display; #endif if(!ovrHmd_ConfigureRendering( oc->getHmd(), &cfg.Config, oc->getHmd()->DistortionCaps, EyeFov, EyeRenderDesc)) abort(); // Direct rendering from a window handle to the Hmd. // Not required if ovrHmdCap_ExtendDesktop flag is set. #ifdef _WIN32 HWND directHWND; window->getCustomAttribute("WINDOW", &directHWND); ovrHmd_AttachToWindow(oc->getHmd(), directHWND, NULL, NULL); #else //Not currently available #endif //Send texture data to OVR for rendering //->left eye texture : EyeTexture[left].OGL.Header.API = ovrRenderAPI_OpenGL; EyeTexture[left].OGL.Header.TextureSize = texSizeL; EyeTexture[left].OGL.Header.RenderViewport.Pos.x = 0; EyeTexture[left].OGL.Header.RenderViewport.Pos.y = 0; EyeTexture[left].OGL.Header.RenderViewport.Size = texSizeL; Ogre::GLTexture* gl_rtt_l = static_cast<Ogre::GLTexture*>(Ogre::GLTextureManager::getSingleton().getByName("RttTexL").get()); EyeTexture[left].OGL.TexId = gl_rtt_l->getGLID(); //right eye texture : EyeTexture[right] = EyeTexture[left]; //Basic configuration is shared. EyeTexture[right].OGL.Header.TextureSize = texSizeR; EyeTexture[right].OGL.Header.RenderViewport.Size = texSizeR; Ogre::GLTexture* gl_rtt_r = static_cast<Ogre::GLTexture*>(Ogre::GLTextureManager::getSingleton().getByName("RttTexR").get()); EyeTexture[right].OGL.TexId = gl_rtt_r->getGLID(); } void OgreOculusRender::RenderOneFrame() { //get some info cameraPosition = this->CameraNode->getPosition(); cameraOrientation = this->CameraNode->getOrientation(); //Begin frame ovrFrameTiming hmdFrameTiming = ovrHmd_BeginFrame(oc->getHmd(), 0); //Tell ogre that Frame started root->_fireFrameStarted(); for (Ogre::SceneManagerEnumerator::SceneManagerIterator it = root->getSceneManagerIterator(); it.hasMoreElements(); it.moveNext()) it.peekNextValue()->_handleLodEvents(); ovrPosef headPose[2]; //Message pump events Ogre::WindowEventUtilities::messagePump(); for(int eyeIndex = 0; eyeIndex < ovrEye_Count; eyeIndex++) { //Get the correct eye to render ovrEyeType eye = oc->getHmd()->EyeRenderOrder[eyeIndex]; //Set the Ogre render target to the texture //root->getRenderSystem()->_setRenderTarget(rtts[eye]); vpts[eye]->clear(); //Get the eye pose ovrPosef eyePose = ovrHmd_GetEyePose(oc->getHmd(), eye); headPose[eye] = eyePose; //Get the hmd orientation OVR::Quatf camOrient = eyePose.Orientation; //Get the projection matrix OVR::Matrix4f proj = ovrMatrix4f_Projection(EyeRenderDesc[eye].Fov,static_cast<float>(nearClippingDistance), 10000.0f, true); //Convert it to Ogre matrix Ogre::Matrix4 OgreProj; for(int x(0); x < 4; x++) for(int y(0); y < 4; y++) OgreProj[x][y] = proj.M[x][y]; //Set the matrix cams[eye]->setCustomProjectionMatrix(true, OgreProj); //Set the orientation cams[eye]->setOrientation(cameraOrientation * Ogre::Quaternion(camOrient.w,camOrient.x,camOrient.y,camOrient.z)); //Set Position cams[eye]->setPosition (cameraPosition //the "gameplay" position of player's avatar head + (cams[eye]->getOrientation() * - Ogre::Vector3( //realword camera orientation + the oposite of the EyeRenderDesc[eye].ViewAdjust.x, //view adjust vector. we translate the camera, not the whole world EyeRenderDesc[eye].ViewAdjust.y, EyeRenderDesc[eye].ViewAdjust.z) + cameraOrientation * Ogre::Vector3( //cameraOrientation is in fact the direction the avatar is facing expressed as an Ogre::Quaternion headPose[eye].Position.x, headPose[eye].Position.y, headPose[eye].Position.z))); root->_fireFrameRenderingQueued(); rtts[eye]->update(); } //Ogre::Root::getSingleton().getRenderSystem()->_setRenderTarget(window); this->updateTime = hmdFrameTiming.DeltaSeconds; //Do the rendering then the buffer swap ovrHmd_EndFrame(oc->getHmd(), headPose, (ovrTexture*)EyeTexture); //Tell Ogre that frame ended root->_fireFrameEnded(); returnPose.position = cameraPosition + Ogre::Vector3 (headPose[0].Position.x, headPose[0].Position.y, headPose[0].Position.z); returnPose.orientation = cameraOrientation * Ogre::Quaternion (headPose[0].Orientation.w, headPose[0].Orientation.x, headPose[0].Orientation.y, headPose[0].Orientation.z); } void OgreOculusRender::dissmissHS() { ovrHmd_DismissHSWDisplay(oc->getHmd()); hsDissmissed = true; }<|endoftext|>
<commit_before>// // Name: ItemGroup.cpp // // Copyright (c) 2003 Virtual Terrain Project // Free for all uses, see license.txt for details. // #ifdef __GNUG__ #pragma implementation #pragma interface #endif // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "vtlib/vtlib.h" #include "vtdata/vtLog.h" #include "frame.h" #include "ItemGroup.h" ItemGroup::ItemGroup(vtItem *pItem) { m_pItem = pItem; } void ItemGroup::CreateNodes() { m_pAxes = NULL; m_pRulers = NULL; m_pGroup = new vtGroup(); m_pLOD = new vtLOD(); m_pTop = new vtGroup; m_pTop->SetName2("ItemGroupTop"); m_pTop->AddChild(m_pLOD); m_pTop->AddChild(m_pGroup); } void ItemGroup::AttemptToLoadModels() { int i, num_models = m_pItem->NumModels(); for (i = 0; i < num_models; i++) { vtModel *mod = m_pItem->GetModel(i); vtTransform *trans = GetMainFrame()->m_nodemap[mod]; if (!trans && !mod->m_attempted_load) { // haven't tried to load it yet GetMainFrame()->AttemptLoad(mod); } } } void ItemGroup::AttachModels(vtFont *font) { // Undo previous attachments vtNode *pNode; while (pNode = m_pLOD->GetChild(0)) m_pLOD->RemoveChild(pNode); while (pNode = m_pGroup->GetChild(0)) m_pGroup->RemoveChild(pNode); // re-attach int i, num_models = m_pItem->NumModels(); FSphere sph(FPoint3(0,0,0), 1.0f); for (i = 0; i < num_models; i++) { vtModel *mod = m_pItem->GetModel(i); vtNode *node = GetMainFrame()->m_nodemap[mod]; if (node) { m_pGroup->AddChild(node); m_pLOD->AddChild(node); node->GetBoundSphere(sph); } } UpdateCrosshair(sph); UpdateRulers(font, sph); } void ItemGroup::UpdateCrosshair(const FSphere &sph) { // Update origin crosshair if (m_pAxes) { m_pTop->RemoveChild(m_pAxes); m_pAxes->Release(); } float size = sph.radius * 2; m_pAxes = Create3DCursor(size, size/100, 0.4f); m_pAxes->SetName2("Origin Axes"); m_pTop->AddChild(m_pAxes); } void ItemGroup::UpdateRulers(vtFont *font, const FSphere &sph) { // Update rulers if (m_pRulers) { m_pTop->RemoveChild(m_pRulers); m_pRulers->Release(); } float size = sph.radius * 2; m_pRulers = CreateRulers(font, size); m_pRulers->SetName2("Rulers"); m_pTop->AddChild(m_pRulers); } void ItemGroup::ShowOrigin(bool bShow) { m_pAxes->SetEnabled(bShow); } void ItemGroup::ShowRulers(bool bShow) { m_pRulers->SetEnabled(bShow); } void ItemGroup::SetRanges() { // Now set the LOD ranges for each model int i, num_models = m_pItem->NumModels(); if (!num_models) return; // LOD documentation: For N children, you must have N+1 range values. // "Note that the last child (n) does not implicitly have a maximum // distance value of infinity. You must add a n+1'st range value to // specify its maximum distance. Otherwise, "bad things" will happen." m_ranges[0] = 0.0f; if (num_models == 1) m_ranges[1] = 10000000.0f; else { for (i = 0; i < num_models; i++) { vtModel *mod = m_pItem->GetModel(i); m_ranges[i+1] = mod->m_distance; } } m_pLOD->SetRanges(m_ranges, num_models+1); } void ItemGroup::ShowLOD(bool bTrue) { m_pLOD->SetEnabled(bTrue); m_pGroup->SetEnabled(!bTrue); if (bTrue) { // LOD requires all models to be enabled int i, num_models = m_pItem->NumModels(); for (i = 0; i < num_models; i++) { vtModel *mod = m_pItem->GetModel(i); vtTransform *trans = GetMainFrame()->m_nodemap[mod]; if (trans) trans->SetEnabled(true); } } else { // Group requires all models to be (initially) disabled int i, num_models = m_pItem->NumModels(); for (i = 0; i < num_models; i++) { vtModel *mod = m_pItem->GetModel(i); vtTransform *trans = GetMainFrame()->m_nodemap[mod]; if (trans) trans->SetEnabled(false); } } } /////////////////////////////////////////////////////////////////////// // Ruler geometry vtGeom *CreateRulers(vtFont *font, float fSize) { int i, j, start; vtMesh *mesh; vtTextMesh *text; vtGeom *pGeom = new vtGeom(); vtMaterialArray *pMats = new vtMaterialArray(); pMats->AddRGBMaterial1(RGBf(1.0f, 1.0f, 1.0f), false, false, false); pGeom->SetMaterials(pMats); pMats->Release(); int up = 0; float interval = 0.001f; while (fSize / interval > 22) { if (up == 0) interval *= 2; if (up == 1) interval *= 2.5; if (up == 1) interval *= 2; up++; if (up > 2) up = 0; } int ticks = fSize / interval; vtString str; FPoint3 p; float *wide; float *thin; for (i = 0; i < 3; i++) { p.Set(0,0,0); mesh = new vtMesh(GL_LINES, VT_Normals, 24); if (i == 0) { wide = &p.x; thin = &p.z; } if (i == 1) { wide = &p.y; thin = &p.x; } if (i == 2) { wide = &p.z; thin = &p.x; } *wide = -fSize; mesh->AddVertex(p); *wide = fSize; mesh->AddVertex(p); mesh->AddLine(0, 1); for (j = 1; j <= ticks; j++) { *wide = j * interval; *thin = -interval/2; start = mesh->AddVertex(p); *thin = interval/2; mesh->AddVertex(p); mesh->AddLine(start, start+1); } pGeom->AddMesh(mesh, 0); } for (i = 0; i < 3; i++) { p.Set(0,0,0); if (i == 0) { wide = &p.x; thin = &p.z; } if (i == 1) { wide = &p.y; thin = &p.x; } if (i == 2) { wide = &p.z; thin = &p.x; } for (j = 1; j <= ticks; j++) { *wide = j * interval; *thin = interval/2; if (font) { str.Format("%g", j * interval); text = new vtTextMesh(font, interval/2, false); text->SetPosition(p); if (i == 0) text->SetAlignment(0); else text->SetAlignment(1); text->SetText(str); pGeom->AddTextMesh(text, 0); } } } return pGeom; } <commit_msg>trying to fix memleaks<commit_after>// // Name: ItemGroup.cpp // // Copyright (c) 2003 Virtual Terrain Project // Free for all uses, see license.txt for details. // #ifdef __GNUG__ #pragma implementation #pragma interface #endif // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "vtlib/vtlib.h" #include "vtdata/vtLog.h" #include "frame.h" #include "ItemGroup.h" ItemGroup::ItemGroup(vtItem *pItem) { m_pItem = pItem; } void ItemGroup::CreateNodes() { m_pAxes = NULL; m_pRulers = NULL; m_pGroup = new vtGroup(); m_pLOD = new vtLOD(); m_pTop = new vtGroup; m_pTop->SetName2("ItemGroupTop"); m_pTop->AddChild(m_pLOD); m_pTop->AddChild(m_pGroup); } void ItemGroup::AttemptToLoadModels() { int i, num_models = m_pItem->NumModels(); for (i = 0; i < num_models; i++) { vtModel *mod = m_pItem->GetModel(i); vtTransform *trans = GetMainFrame()->m_nodemap[mod]; if (!trans && !mod->m_attempted_load) { // haven't tried to load it yet GetMainFrame()->AttemptLoad(mod); } } } void ItemGroup::AttachModels(vtFont *font) { // Undo previous attachments vtNode *pNode; while (pNode = m_pLOD->GetChild(0)) m_pLOD->RemoveChild(pNode); while (pNode = m_pGroup->GetChild(0)) m_pGroup->RemoveChild(pNode); // re-attach int i, num_models = m_pItem->NumModels(); FSphere sph(FPoint3(0,0,0), 1.0f); for (i = 0; i < num_models; i++) { vtModel *mod = m_pItem->GetModel(i); vtNode *node = GetMainFrame()->m_nodemap[mod]; if (node) { m_pGroup->AddChild(node); m_pLOD->AddChild(node); node->GetBoundSphere(sph); } } UpdateCrosshair(sph); UpdateRulers(font, sph); } void ItemGroup::UpdateCrosshair(const FSphere &sph) { // Update origin crosshair if (m_pAxes) { m_pTop->RemoveChild(m_pAxes); m_pAxes->Release(); } float size = sph.radius * 2; m_pAxes = Create3DCursor(size, size/100, 0.4f); m_pAxes->SetName2("Origin Axes"); m_pTop->AddChild(m_pAxes); } void ItemGroup::UpdateRulers(vtFont *font, const FSphere &sph) { // Update rulers if (m_pRulers) { m_pTop->RemoveChild(m_pRulers); m_pRulers->Release(); } float size = sph.radius * 2; m_pRulers = CreateRulers(font, size); m_pRulers->SetName2("Rulers"); m_pTop->AddChild(m_pRulers); } void ItemGroup::ShowOrigin(bool bShow) { m_pAxes->SetEnabled(bShow); } void ItemGroup::ShowRulers(bool bShow) { m_pRulers->SetEnabled(bShow); } void ItemGroup::SetRanges() { // Now set the LOD ranges for each model int i, num_models = m_pItem->NumModels(); if (!num_models) return; // LOD documentation: For N children, you must have N+1 range values. // "Note that the last child (n) does not implicitly have a maximum // distance value of infinity. You must add a n+1'st range value to // specify its maximum distance. Otherwise, "bad things" will happen." m_ranges[0] = 0.0f; if (num_models == 1) m_ranges[1] = 10000000.0f; else { for (i = 0; i < num_models; i++) { vtModel *mod = m_pItem->GetModel(i); m_ranges[i+1] = mod->m_distance; } } m_pLOD->SetRanges(m_ranges, num_models+1); } void ItemGroup::ShowLOD(bool bTrue) { m_pLOD->SetEnabled(bTrue); m_pGroup->SetEnabled(!bTrue); if (bTrue) { // LOD requires all models to be enabled int i, num_models = m_pItem->NumModels(); for (i = 0; i < num_models; i++) { vtModel *mod = m_pItem->GetModel(i); vtTransform *trans = GetMainFrame()->m_nodemap[mod]; if (trans) trans->SetEnabled(true); } } else { // Group requires all models to be (initially) disabled int i, num_models = m_pItem->NumModels(); for (i = 0; i < num_models; i++) { vtModel *mod = m_pItem->GetModel(i); vtTransform *trans = GetMainFrame()->m_nodemap[mod]; if (trans) trans->SetEnabled(false); } } } /////////////////////////////////////////////////////////////////////// // Ruler geometry vtGeom *CreateRulers(vtFont *font, float fSize) { int i, j, start; vtMesh *mesh; vtTextMesh *text; vtGeom *pGeom = new vtGeom(); vtMaterialArray *pMats = new vtMaterialArray(); pMats->AddRGBMaterial1(RGBf(1.0f, 1.0f, 1.0f), false, false, false); pGeom->SetMaterials(pMats); pMats->Release(); int up = 0; float interval = 0.001f; while (fSize / interval > 22) { if (up == 0) interval *= 2; if (up == 1) interval *= 2.5; if (up == 1) interval *= 2; up++; if (up > 2) up = 0; } int ticks = fSize / interval; vtString str; FPoint3 p; float *wide; float *thin; for (i = 0; i < 3; i++) { p.Set(0,0,0); mesh = new vtMesh(GL_LINES, VT_Normals, 24); if (i == 0) { wide = &p.x; thin = &p.z; } if (i == 1) { wide = &p.y; thin = &p.x; } if (i == 2) { wide = &p.z; thin = &p.x; } *wide = -fSize; mesh->AddVertex(p); *wide = fSize; mesh->AddVertex(p); mesh->AddLine(0, 1); for (j = 1; j <= ticks; j++) { *wide = j * interval; *thin = -interval/2; start = mesh->AddVertex(p); *thin = interval/2; mesh->AddVertex(p); mesh->AddLine(start, start+1); } pGeom->AddMesh(mesh, 0); mesh->Release(); } for (i = 0; i < 3; i++) { p.Set(0,0,0); if (i == 0) { wide = &p.x; thin = &p.z; } if (i == 1) { wide = &p.y; thin = &p.x; } if (i == 2) { wide = &p.z; thin = &p.x; } for (j = 1; j <= ticks; j++) { *wide = j * interval; *thin = interval/2; if (font) { str.Format("%g", j * interval); text = new vtTextMesh(font, interval/2, false); text->SetPosition(p); if (i == 0) text->SetAlignment(0); else text->SetAlignment(1); text->SetText(str); pGeom->AddTextMesh(text, 0); text->Release(); } } } return pGeom; } <|endoftext|>
<commit_before>#include "indexer/ftypes_matcher.hpp" #include "indexer/feature.hpp" #include "indexer/feature_data.hpp" #include "indexer/classificator.hpp" #include "std/sstream.hpp" #include "std/utility.hpp" namespace ftypes { uint32_t BaseChecker::PrepareToMatch(uint32_t type, uint8_t level) { ftype::TruncValue(type, level); return type; } bool BaseChecker::IsMatched(uint32_t type) const { return (find(m_types.begin(), m_types.end(), PrepareToMatch(type, m_level)) != m_types.end()); } bool BaseChecker::operator() (feature::TypesHolder const & types) const { for (uint32_t t : types) if (IsMatched(t)) return true; return false; } bool BaseChecker::operator() (FeatureType const & ft) const { return this->operator() (feature::TypesHolder(ft)); } bool BaseChecker::operator() (vector<uint32_t> const & types) const { for (size_t i = 0; i < types.size(); ++i) { if (IsMatched(types[i])) return true; } return false; } IsPeakChecker::IsPeakChecker() { Classificator const & c = classif(); m_types.push_back(c.GetTypeByPath({ "natural", "peak" })); } IsPeakChecker const & IsPeakChecker::Instance() { static const IsPeakChecker inst; return inst; } IsATMChecker::IsATMChecker() { Classificator const & c = classif(); m_types.push_back(c.GetTypeByPath({ "amenity", "atm" })); } IsATMChecker const & IsATMChecker::Instance() { static const IsATMChecker inst; return inst; } IsSpeedCamChecker::IsSpeedCamChecker() { Classificator const & c = classif(); m_types.push_back(c.GetTypeByPath({"highway", "speed_camera"})); } // static IsSpeedCamChecker const & IsSpeedCamChecker::Instance() { static const IsSpeedCamChecker instance; return instance; } IsFuelStationChecker::IsFuelStationChecker() { Classificator const & c = classif(); m_types.push_back(c.GetTypeByPath({ "amenity", "fuel" })); } IsFuelStationChecker const & IsFuelStationChecker::Instance() { static const IsFuelStationChecker inst; return inst; } IsStreetChecker::IsStreetChecker() { Classificator const & c = classif(); char const * arr[][2] = { { "highway", "trunk" }, { "highway", "primary" }, { "highway", "secondary" }, { "highway", "residential" }, { "highway", "pedestrian" }, { "highway", "tertiary" }, { "highway", "construction" }, { "highway", "living_street" }, { "highway", "service" }, { "highway", "unclassified" } }; for (size_t i = 0; i < ARRAY_SIZE(arr); ++i) m_types.push_back(c.GetTypeByPath(vector<string>(arr[i], arr[i] + 2))); } IsStreetChecker const & IsStreetChecker::Instance() { static const IsStreetChecker inst; return inst; } IsOneWayChecker::IsOneWayChecker() { Classificator const & c = classif(); m_types.push_back(c.GetTypeByPath({ "hwtag", "oneway" })); } IsOneWayChecker const & IsOneWayChecker::Instance() { static const IsOneWayChecker inst; return inst; } IsRoundAboutChecker::IsRoundAboutChecker() { Classificator const & c = classif(); m_types.push_back(c.GetTypeByPath({ "junction", "roundabout" })); } IsRoundAboutChecker const & IsRoundAboutChecker::Instance() { static const IsRoundAboutChecker inst; return inst; } IsLinkChecker::IsLinkChecker() { Classificator const & c = classif(); char const * arr[][2] = { { "highway", "motorway_link" }, { "highway", "trunk_link" }, { "highway", "primary_link" }, { "highway", "secondary_link" }, { "highway", "tertiary_link" } }; for (size_t i = 0; i < ARRAY_SIZE(arr); ++i) m_types.push_back(c.GetTypeByPath(vector<string>(arr[i], arr[i] + 2))); } IsLinkChecker const & IsLinkChecker::Instance() { static const IsLinkChecker inst; return inst; } IsBuildingChecker::IsBuildingChecker() { Classificator const & c = classif(); m_types.push_back(c.GetTypeByPath({ "building" })); m_types.push_back(c.GetTypeByPath({ "building", "address" })); } IsBuildingChecker const & IsBuildingChecker::Instance() { static const IsBuildingChecker inst; return inst; } IsLocalityChecker::IsLocalityChecker() { Classificator const & c = classif(); // Note! The order should be equal with constants in Type enum (add other villages to the end). char const * arr[][2] = { { "place", "country" }, { "place", "state" }, { "place", "city" }, { "place", "town" }, { "place", "village" }, { "place", "hamlet" } }; for (size_t i = 0; i < ARRAY_SIZE(arr); ++i) m_types.push_back(c.GetTypeByPath(vector<string>(arr[i], arr[i] + 2))); } IsBuildingPartChecker::IsBuildingPartChecker() : BaseChecker(3) { } IsBuildingPartChecker const & IsBuildingPartChecker::Instance() { static const IsBuildingPartChecker inst; return inst; } bool IsBuildingPartChecker::IsMatched(uint32_t type) const { return IsTypeConformed(type, {"building:part"}); } IsBridgeChecker::IsBridgeChecker() : BaseChecker(3) { } IsBridgeChecker const & IsBridgeChecker::Instance() { static const IsBridgeChecker inst; return inst; } bool IsBridgeChecker::IsMatched(uint32_t type) const { return IsTypeConformed(type, {"highway", "*", "bridge"}); } IsTunnelChecker::IsTunnelChecker() : BaseChecker(3) { } IsTunnelChecker const & IsTunnelChecker::Instance() { static const IsTunnelChecker inst; return inst; } bool IsTunnelChecker::IsMatched(uint32_t type) const { return IsTypeConformed(type, {"highway", "*", "tunnel"}); } Type IsLocalityChecker::GetType(feature::TypesHolder const & types) const { for (uint32_t t : types) { ftype::TruncValue(t, 2); size_t j = COUNTRY; for (; j < LOCALITY_COUNT; ++j) if (t == m_types[j]) return static_cast<Type>(j); for (; j < m_types.size(); ++j) if (t == m_types[j]) return VILLAGE; } return NONE; } Type IsLocalityChecker::GetType(const FeatureType & f) const { feature::TypesHolder types(f); return GetType(types); } IsLocalityChecker const & IsLocalityChecker::Instance() { static IsLocalityChecker const inst; return inst; } uint32_t GetPopulation(FeatureType const & ft) { uint32_t population = ft.GetPopulation(); if (population < 10) { switch (IsLocalityChecker::Instance().GetType(ft)) { case CITY: case TOWN: population = 10000; break; case VILLAGE: population = 100; break; default: population = 0; } } return population; } double GetRadiusByPopulation(uint32_t p) { return pow(static_cast<double>(p), 0.277778) * 550.0; } uint32_t GetPopulationByRadius(double r) { return my::rounds(pow(r / 550.0, 3.6)); } bool IsTypeConformed(uint32_t type, vector<string> const & path) { Classificator const & c = classif(); ClassifObject const * p = c.GetRoot(); ASSERT(p, ()); uint8_t val = 0, i = 0; for (auto const n : path) { if (!ftype::GetValue(type, i, val)) return false; p = p->GetObject(val); if (p == 0) return false; string const name = p->GetName(); if (n != name && n != "*") return false; ++i; } return true; } string DebugPrint(HighwayClass const cls) { stringstream out; out << "[ "; switch (cls) { case HighwayClass::Undefined: out << "Undefined"; case HighwayClass::Error: out << "Error"; case HighwayClass::Trunk: out << "Trunk"; case HighwayClass::Primary: out << "Primary"; case HighwayClass::Secondary: out << "Secondary"; case HighwayClass::Tertiary: out << "Tertiary"; case HighwayClass::LivingStreet: out << "LivingStreet"; case HighwayClass::Service: out << "Service"; case HighwayClass::Count: out << "Count"; default: out << "Unknown value of HighwayClass: " << static_cast<int>(cls); } out << " ]"; return out.str(); } HighwayClass GetHighwayClass(feature::TypesHolder const & types) { Classificator const & c = classif(); static pair<HighwayClass, uint32_t> const kHighwayClasses[] = { {HighwayClass::Trunk, c.GetTypeByPath({"highway", "motorway"})}, {HighwayClass::Trunk, c.GetTypeByPath({"highway", "motorway_link"})}, {HighwayClass::Trunk, c.GetTypeByPath({"highway", "trunk"})}, {HighwayClass::Trunk, c.GetTypeByPath({"highway", "trunk_link"})}, {HighwayClass::Trunk, c.GetTypeByPath({"route", "ferry"})}, {HighwayClass::Primary, c.GetTypeByPath({"highway", "primary"})}, {HighwayClass::Primary, c.GetTypeByPath({"highway", "primary_link"})}, {HighwayClass::Secondary, c.GetTypeByPath({"highway", "secondary"})}, {HighwayClass::Secondary, c.GetTypeByPath({"highway", "secondary_link"})}, {HighwayClass::Tertiary, c.GetTypeByPath({"highway", "tertiary"})}, {HighwayClass::Tertiary, c.GetTypeByPath({"highway", "tertiary_link"})}, {HighwayClass::LivingStreet, c.GetTypeByPath({"highway", "unclassified"})}, {HighwayClass::LivingStreet, c.GetTypeByPath({"highway", "residential"})}, {HighwayClass::LivingStreet, c.GetTypeByPath({"highway", "living_street"})}, {HighwayClass::Service, c.GetTypeByPath({"highway", "service"})}, {HighwayClass::Service, c.GetTypeByPath({"highway", "track"})}}; uint8_t const kTruncLevel = 2; for (auto t : types) { ftype::TruncValue(t, kTruncLevel); for (auto const & cls : kHighwayClasses) { if (cls.second == t) return cls.first; } } return HighwayClass::Error; } HighwayClass GetHighwayClass(FeatureType const & ft) { return GetHighwayClass(feature::TypesHolder(ft)); } } <commit_msg>Performance fix in IsTypeConformed().<commit_after>#include "indexer/ftypes_matcher.hpp" #include "indexer/feature.hpp" #include "indexer/feature_data.hpp" #include "indexer/classificator.hpp" #include "std/sstream.hpp" #include "std/utility.hpp" namespace ftypes { uint32_t BaseChecker::PrepareToMatch(uint32_t type, uint8_t level) { ftype::TruncValue(type, level); return type; } bool BaseChecker::IsMatched(uint32_t type) const { return (find(m_types.begin(), m_types.end(), PrepareToMatch(type, m_level)) != m_types.end()); } bool BaseChecker::operator() (feature::TypesHolder const & types) const { for (uint32_t t : types) if (IsMatched(t)) return true; return false; } bool BaseChecker::operator() (FeatureType const & ft) const { return this->operator() (feature::TypesHolder(ft)); } bool BaseChecker::operator() (vector<uint32_t> const & types) const { for (size_t i = 0; i < types.size(); ++i) { if (IsMatched(types[i])) return true; } return false; } IsPeakChecker::IsPeakChecker() { Classificator const & c = classif(); m_types.push_back(c.GetTypeByPath({ "natural", "peak" })); } IsPeakChecker const & IsPeakChecker::Instance() { static const IsPeakChecker inst; return inst; } IsATMChecker::IsATMChecker() { Classificator const & c = classif(); m_types.push_back(c.GetTypeByPath({ "amenity", "atm" })); } IsATMChecker const & IsATMChecker::Instance() { static const IsATMChecker inst; return inst; } IsSpeedCamChecker::IsSpeedCamChecker() { Classificator const & c = classif(); m_types.push_back(c.GetTypeByPath({"highway", "speed_camera"})); } // static IsSpeedCamChecker const & IsSpeedCamChecker::Instance() { static const IsSpeedCamChecker instance; return instance; } IsFuelStationChecker::IsFuelStationChecker() { Classificator const & c = classif(); m_types.push_back(c.GetTypeByPath({ "amenity", "fuel" })); } IsFuelStationChecker const & IsFuelStationChecker::Instance() { static const IsFuelStationChecker inst; return inst; } IsStreetChecker::IsStreetChecker() { Classificator const & c = classif(); char const * arr[][2] = { { "highway", "trunk" }, { "highway", "primary" }, { "highway", "secondary" }, { "highway", "residential" }, { "highway", "pedestrian" }, { "highway", "tertiary" }, { "highway", "construction" }, { "highway", "living_street" }, { "highway", "service" }, { "highway", "unclassified" } }; for (size_t i = 0; i < ARRAY_SIZE(arr); ++i) m_types.push_back(c.GetTypeByPath(vector<string>(arr[i], arr[i] + 2))); } IsStreetChecker const & IsStreetChecker::Instance() { static const IsStreetChecker inst; return inst; } IsOneWayChecker::IsOneWayChecker() { Classificator const & c = classif(); m_types.push_back(c.GetTypeByPath({ "hwtag", "oneway" })); } IsOneWayChecker const & IsOneWayChecker::Instance() { static const IsOneWayChecker inst; return inst; } IsRoundAboutChecker::IsRoundAboutChecker() { Classificator const & c = classif(); m_types.push_back(c.GetTypeByPath({ "junction", "roundabout" })); } IsRoundAboutChecker const & IsRoundAboutChecker::Instance() { static const IsRoundAboutChecker inst; return inst; } IsLinkChecker::IsLinkChecker() { Classificator const & c = classif(); char const * arr[][2] = { { "highway", "motorway_link" }, { "highway", "trunk_link" }, { "highway", "primary_link" }, { "highway", "secondary_link" }, { "highway", "tertiary_link" } }; for (size_t i = 0; i < ARRAY_SIZE(arr); ++i) m_types.push_back(c.GetTypeByPath(vector<string>(arr[i], arr[i] + 2))); } IsLinkChecker const & IsLinkChecker::Instance() { static const IsLinkChecker inst; return inst; } IsBuildingChecker::IsBuildingChecker() { Classificator const & c = classif(); m_types.push_back(c.GetTypeByPath({ "building" })); m_types.push_back(c.GetTypeByPath({ "building", "address" })); } IsBuildingChecker const & IsBuildingChecker::Instance() { static const IsBuildingChecker inst; return inst; } IsLocalityChecker::IsLocalityChecker() { Classificator const & c = classif(); // Note! The order should be equal with constants in Type enum (add other villages to the end). char const * arr[][2] = { { "place", "country" }, { "place", "state" }, { "place", "city" }, { "place", "town" }, { "place", "village" }, { "place", "hamlet" } }; for (size_t i = 0; i < ARRAY_SIZE(arr); ++i) m_types.push_back(c.GetTypeByPath(vector<string>(arr[i], arr[i] + 2))); } IsBuildingPartChecker::IsBuildingPartChecker() : BaseChecker(3) { } IsBuildingPartChecker const & IsBuildingPartChecker::Instance() { static const IsBuildingPartChecker inst; return inst; } bool IsBuildingPartChecker::IsMatched(uint32_t type) const { return IsTypeConformed(type, {"building:part"}); } IsBridgeChecker::IsBridgeChecker() : BaseChecker(3) { } IsBridgeChecker const & IsBridgeChecker::Instance() { static const IsBridgeChecker inst; return inst; } bool IsBridgeChecker::IsMatched(uint32_t type) const { return IsTypeConformed(type, {"highway", "*", "bridge"}); } IsTunnelChecker::IsTunnelChecker() : BaseChecker(3) { } IsTunnelChecker const & IsTunnelChecker::Instance() { static const IsTunnelChecker inst; return inst; } bool IsTunnelChecker::IsMatched(uint32_t type) const { return IsTypeConformed(type, {"highway", "*", "tunnel"}); } Type IsLocalityChecker::GetType(feature::TypesHolder const & types) const { for (uint32_t t : types) { ftype::TruncValue(t, 2); size_t j = COUNTRY; for (; j < LOCALITY_COUNT; ++j) if (t == m_types[j]) return static_cast<Type>(j); for (; j < m_types.size(); ++j) if (t == m_types[j]) return VILLAGE; } return NONE; } Type IsLocalityChecker::GetType(const FeatureType & f) const { feature::TypesHolder types(f); return GetType(types); } IsLocalityChecker const & IsLocalityChecker::Instance() { static IsLocalityChecker const inst; return inst; } uint32_t GetPopulation(FeatureType const & ft) { uint32_t population = ft.GetPopulation(); if (population < 10) { switch (IsLocalityChecker::Instance().GetType(ft)) { case CITY: case TOWN: population = 10000; break; case VILLAGE: population = 100; break; default: population = 0; } } return population; } double GetRadiusByPopulation(uint32_t p) { return pow(static_cast<double>(p), 0.277778) * 550.0; } uint32_t GetPopulationByRadius(double r) { return my::rounds(pow(r / 550.0, 3.6)); } bool IsTypeConformed(uint32_t type, vector<string> const & path) { Classificator const & c = classif(); ClassifObject const * p = c.GetRoot(); ASSERT(p, ()); uint8_t val = 0, i = 0; for (auto const & n : path) { if (!ftype::GetValue(type, i, val)) return false; p = p->GetObject(val); if (p == 0) return false; string const name = p->GetName(); if (n != name && n != "*") return false; ++i; } return true; } string DebugPrint(HighwayClass const cls) { stringstream out; out << "[ "; switch (cls) { case HighwayClass::Undefined: out << "Undefined"; case HighwayClass::Error: out << "Error"; case HighwayClass::Trunk: out << "Trunk"; case HighwayClass::Primary: out << "Primary"; case HighwayClass::Secondary: out << "Secondary"; case HighwayClass::Tertiary: out << "Tertiary"; case HighwayClass::LivingStreet: out << "LivingStreet"; case HighwayClass::Service: out << "Service"; case HighwayClass::Count: out << "Count"; default: out << "Unknown value of HighwayClass: " << static_cast<int>(cls); } out << " ]"; return out.str(); } HighwayClass GetHighwayClass(feature::TypesHolder const & types) { Classificator const & c = classif(); static pair<HighwayClass, uint32_t> const kHighwayClasses[] = { {HighwayClass::Trunk, c.GetTypeByPath({"highway", "motorway"})}, {HighwayClass::Trunk, c.GetTypeByPath({"highway", "motorway_link"})}, {HighwayClass::Trunk, c.GetTypeByPath({"highway", "trunk"})}, {HighwayClass::Trunk, c.GetTypeByPath({"highway", "trunk_link"})}, {HighwayClass::Trunk, c.GetTypeByPath({"route", "ferry"})}, {HighwayClass::Primary, c.GetTypeByPath({"highway", "primary"})}, {HighwayClass::Primary, c.GetTypeByPath({"highway", "primary_link"})}, {HighwayClass::Secondary, c.GetTypeByPath({"highway", "secondary"})}, {HighwayClass::Secondary, c.GetTypeByPath({"highway", "secondary_link"})}, {HighwayClass::Tertiary, c.GetTypeByPath({"highway", "tertiary"})}, {HighwayClass::Tertiary, c.GetTypeByPath({"highway", "tertiary_link"})}, {HighwayClass::LivingStreet, c.GetTypeByPath({"highway", "unclassified"})}, {HighwayClass::LivingStreet, c.GetTypeByPath({"highway", "residential"})}, {HighwayClass::LivingStreet, c.GetTypeByPath({"highway", "living_street"})}, {HighwayClass::Service, c.GetTypeByPath({"highway", "service"})}, {HighwayClass::Service, c.GetTypeByPath({"highway", "track"})}}; uint8_t const kTruncLevel = 2; for (auto t : types) { ftype::TruncValue(t, kTruncLevel); for (auto const & cls : kHighwayClasses) { if (cls.second == t) return cls.first; } } return HighwayClass::Error; } HighwayClass GetHighwayClass(FeatureType const & ft) { return GetHighwayClass(feature::TypesHolder(ft)); } } <|endoftext|>
<commit_before>#include <SimpleITKTestHarness.h> #include <sitkImage.h> #include <sitkImageFileReader.h> #include <sitkImageFileWriter.h> #include <sitkHashImageFilter.h> #include <sitkRecursiveGaussianImageFilter.h> #include <sitkCastImageFilter.h> #include <sitkPixelIDValues.h> #include <sitkLabelStatisticsImageFilter.h> #include <sitkExtractImageFilter.h> #include "itkRecursiveGaussianImageFilter.h" #include "itkExtractImageFilter.h" TEST(BasicFilters,RecursiveGaussian_ENUMCHECK) { typedef itk::RecursiveGaussianImageFilter< itk::Image<float,3> > ITKRecursiveGausianType; EXPECT_EQ( (int)ITKRecursiveGausianType::ZeroOrder, (int)itk::simple::RecursiveGaussianImageFilter::ZeroOrder ); EXPECT_EQ( (int)ITKRecursiveGausianType::FirstOrder, (int)itk::simple::RecursiveGaussianImageFilter::FirstOrder ); EXPECT_EQ( (int)ITKRecursiveGausianType::SecondOrder, (int)itk::simple::RecursiveGaussianImageFilter::SecondOrder ); } TEST(BasicFilters,Extract_ENUMCHECK) { typedef itk::ExtractImageFilter< itk::Image<float,3>, itk::Image<float,3> > ITKExtractType; EXPECT_EQ( (int)ITKExtractType::DIRECTIONCOLLAPSETOUNKOWN, (int)itk::simple::ExtractImageFilter::DIRECTIONCOLLAPSETOUNKOWN ); EXPECT_EQ( (int)ITKExtractType::DIRECTIONCOLLAPSETOIDENTITY, (int)itk::simple::ExtractImageFilter::DIRECTIONCOLLAPSETOIDENTITY ); EXPECT_EQ( (int)ITKExtractType::DIRECTIONCOLLAPSETOSUBMATRIX, (int)itk::simple::ExtractImageFilter::DIRECTIONCOLLAPSETOSUBMATRIX ); EXPECT_EQ( (int)ITKExtractType::DIRECTIONCOLLAPSETOGUESS, (int)itk::simple::ExtractImageFilter::DIRECTIONCOLLAPSETOGUESS ); } TEST(BasicFilters,Cast) { itk::simple::HashImageFilter hasher; itk::simple::ImageFileReader reader; reader.SetFileName ( dataFinder.GetFile ( "Input/RA-Float.nrrd" ) ); itk::simple::Image image = reader.Execute(); ASSERT_TRUE ( image.GetITKBase() != NULL ); hasher.SetHashFunction ( itk::simple::HashImageFilter::MD5 ); EXPECT_EQ ( "3ccccde44efaa3d688a86e94335c1f16", hasher.Execute ( image ) ); EXPECT_EQ ( image.GetPixelIDValue(), itk::simple::sitkFloat32 ); EXPECT_EQ ( image.GetPixelIDTypeAsString(), "32-bit float" ); typedef std::map<std::string,itk::simple::PixelIDValueType> MapType; MapType mapping; mapping["2f27e9260baeba84fb83dd35de23fa2d"] = (itk::simple::PixelIDValueType)itk::simple::sitkUInt8; mapping["2f27e9260baeba84fb83dd35de23fa2d"] = (itk::simple::PixelIDValueType)itk::simple::sitkInt8; mapping["a963bd6a755b853103a2d195e01a50d3"] = (itk::simple::PixelIDValueType)itk::simple::sitkUInt16; mapping["a963bd6a755b853103a2d195e01a50d3"] = (itk::simple::PixelIDValueType)itk::simple::sitkInt16; mapping["6ceea0011178a955b5be2d545d107199"] = (itk::simple::PixelIDValueType)itk::simple::sitkUInt32; mapping["6ceea0011178a955b5be2d545d107199"] = (itk::simple::PixelIDValueType)itk::simple::sitkInt32; mapping["efa4c3b27349b97b02a64f3d2b5ca9ed"] = (itk::simple::PixelIDValueType)itk::simple::sitkUInt64; mapping["sitkInt64"] = (itk::simple::PixelIDValueType)itk::simple::sitkInt64; mapping["3ccccde44efaa3d688a86e94335c1f16"] = (itk::simple::PixelIDValueType)itk::simple::sitkFloat32; mapping["ac0228acc17038fd1f1ed28eb2841c73"] = (itk::simple::PixelIDValueType)itk::simple::sitkFloat64; mapping["226dabda8fc07f20e2b9e44ca1c83955"] = (itk::simple::PixelIDValueType)itk::simple::sitkComplexFloat32; mapping["e92cbb187a92610068d7de0cb23364db"] = (itk::simple::PixelIDValueType)itk::simple::sitkComplexFloat64; mapping["2f27e9260baeba84fb83dd35de23fa2d"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorUInt8; mapping["2f27e9260baeba84fb83dd35de23fa2d"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorInt8; mapping["a963bd6a755b853103a2d195e01a50d3"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorUInt16; mapping["a963bd6a755b853103a2d195e01a50d3"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorInt16; mapping["6ceea0011178a955b5be2d545d107199"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorUInt32; mapping["6ceea0011178a955b5be2d545d107199"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorInt32; mapping["sitkVectorUInt64"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorUInt64; mapping["sitkVectorInt64"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorInt64; mapping["3ccccde44efaa3d688a86e94335c1f16"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorFloat32; mapping["ac0228acc17038fd1f1ed28eb2841c73"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorFloat64; mapping["sitkLabelUInt8"] = (itk::simple::PixelIDValueType)itk::simple::sitkLabelUInt8; mapping["sitkLabelUInt16"] = (itk::simple::PixelIDValueType)itk::simple::sitkLabelUInt16; mapping["sitkLabelUInt32"] = (itk::simple::PixelIDValueType)itk::simple::sitkLabelUInt32; mapping["sitkLabelUInt64"] = (itk::simple::PixelIDValueType)itk::simple::sitkLabelUInt64; bool failed = false; // Loop over the map, load each file, and compare the hash value for ( MapType::iterator it = mapping.begin(); it != mapping.end(); ++it ) { itk::simple::PixelIDValueType pixelID = it->second; std::string hash = it->first; std::cerr << std::flush; std::cerr << std::flush; if ( pixelID == itk::simple::sitkUnknown ) { std::cerr << "Enum value: " << pixelID << " (" << hash << ") is unknown and not instantiated" << std::endl; continue; } std::cerr << "Testing casting to pixelID: " << pixelID << " is " << itk::simple::GetPixelIDValueAsString ( pixelID ) << std::endl; try { itk::simple::CastImageFilter caster; itk::simple::Image test = caster.SetOutputPixelType ( pixelID ).Execute ( image ); hasher.SetHashFunction ( itk::simple::HashImageFilter::MD5 ); EXPECT_EQ ( hash, hasher.Execute ( test ) ) << "Cast to " << itk::simple::GetPixelIDValueAsString ( pixelID ); } catch ( ::itk::simple::GenericException &e ) { // hashing currently doesn't work for label images if ( hash.find( "sitkLabel" ) == 0 ) { std::cerr << "Hashing currently is not implemented for Label Images" << std::endl; } else { failed = true; std::cerr << "Failed to hash: " << e.what() << std::endl; } continue; } } EXPECT_FALSE ( failed ) << "Cast failed, or could not take the hash of the imoge"; } TEST(BasicFilters,HashImageFilter) { itk::simple::HashImageFilter hasher; EXPECT_EQ ( "itk::simple::HashImageFilter\nHashFunction: SHA1\n", hasher.ToString() ); EXPECT_EQ ( itk::simple::HashImageFilter::SHA1, hasher.SetHashFunction ( itk::simple::HashImageFilter::SHA1 ).GetHashFunction() ); EXPECT_EQ ( itk::simple::HashImageFilter::MD5, hasher.SetHashFunction ( itk::simple::HashImageFilter::MD5 ).GetHashFunction() ); } TEST(BasicFilters,LabelStatistics) { itk::simple::Image image = itk::simple::ReadImage ( dataFinder.GetFile ( "Input/cthead1.png" ) ); itk::simple::Image labels = itk::simple::ReadImage ( dataFinder.GetFile ( "Input/2th_cthead1.mha" ) ); itk::simple::LabelStatisticsImageFilter stats; stats.Execute ( image, labels ); EXPECT_TRUE ( stats.HasLabel ( 0 ) ); EXPECT_NEAR ( stats.GetMinimum ( 0 ), 0, 0.01 ); EXPECT_NEAR ( stats.GetMaximum ( 0 ), 99, 0.01 ); EXPECT_NEAR ( stats.GetMean ( 0 ), 13.0911, 0.001 ); EXPECT_NEAR ( stats.GetSigma ( 0 ), 16.4065, 0.01 ); EXPECT_NEAR ( stats.GetVariance ( 0 ), 269.173, 0.01 ); EXPECT_NEAR ( stats.GetCount ( 0 ), 36172, 0.01 ); EXPECT_NEAR ( stats.GetSum ( 0 ), 473533, 0.01 ); EXPECT_NEAR ( stats.GetMedian ( 0 ), 12.0, 0.001 ); const itk::simple::LabelStatisticsImageFilter::LabelListingType myLabels = stats.GetValidLabels(); EXPECT_EQ ( myLabels.size() , 3u); const itk::simple::LabelStatisticsImageFilter::LabelStatisticsMap myMap = stats.GetLabelStatisticsMap(); EXPECT_EQ( myLabels.size() , myMap.size() ); const itk::simple::MeasurementMap myMeasurementMap = stats.GetMeasurementMap(0); EXPECT_EQ( myMeasurementMap.size(), 8u ); //4 measurements produced const itk::simple::BasicMeasurementMap myBasicMeasurementMap = myMeasurementMap.GetBasicMeasurementMap(); EXPECT_EQ( myBasicMeasurementMap.size(), 8u ); //4 measurements produced EXPECT_EQ ( myMeasurementMap.ToString(), "Count, Maximum, Mean, Minimum, Sigma, Sum, Variance, approxMedian, \n36172, 99, 13.0911, 0, 16.4065, 473533, 269.173, 12, \n" ); } <commit_msg>ENH: adding test to ensure FastMarching Topo enum matches ITK<commit_after>#include <SimpleITKTestHarness.h> #include <sitkImage.h> #include <sitkImageFileReader.h> #include <sitkImageFileWriter.h> #include <sitkHashImageFilter.h> #include <sitkRecursiveGaussianImageFilter.h> #include <sitkCastImageFilter.h> #include <sitkPixelIDValues.h> #include <sitkLabelStatisticsImageFilter.h> #include <sitkExtractImageFilter.h> #include <sitkFastMarchingImageFilter.h> #include "itkRecursiveGaussianImageFilter.h" #include "itkExtractImageFilter.h" #include "itkFastMarchingImageFilterBase.h" TEST(BasicFilters,RecursiveGaussian_ENUMCHECK) { typedef itk::RecursiveGaussianImageFilter< itk::Image<float,3> > ITKRecursiveGausianType; EXPECT_EQ( (int)ITKRecursiveGausianType::ZeroOrder, (int)itk::simple::RecursiveGaussianImageFilter::ZeroOrder ); EXPECT_EQ( (int)ITKRecursiveGausianType::FirstOrder, (int)itk::simple::RecursiveGaussianImageFilter::FirstOrder ); EXPECT_EQ( (int)ITKRecursiveGausianType::SecondOrder, (int)itk::simple::RecursiveGaussianImageFilter::SecondOrder ); } TEST(BasicFilters,Extract_ENUMCHECK) { typedef itk::ExtractImageFilter< itk::Image<float,3>, itk::Image<float,3> > ITKExtractType; EXPECT_EQ( (int)ITKExtractType::DIRECTIONCOLLAPSETOUNKOWN, (int)itk::simple::ExtractImageFilter::DIRECTIONCOLLAPSETOUNKOWN ); EXPECT_EQ( (int)ITKExtractType::DIRECTIONCOLLAPSETOIDENTITY, (int)itk::simple::ExtractImageFilter::DIRECTIONCOLLAPSETOIDENTITY ); EXPECT_EQ( (int)ITKExtractType::DIRECTIONCOLLAPSETOSUBMATRIX, (int)itk::simple::ExtractImageFilter::DIRECTIONCOLLAPSETOSUBMATRIX ); EXPECT_EQ( (int)ITKExtractType::DIRECTIONCOLLAPSETOGUESS, (int)itk::simple::ExtractImageFilter::DIRECTIONCOLLAPSETOGUESS ); } TEST(BasicFilters,FastMarching_ENUMCHECK) { typedef itk::FastMarchingImageFilterBase< itk::Image<float,3>, itk::Image<float,3> > ITKType; EXPECT_EQ( (int) ITKType::None, (int) itk::simple::FastMarchingImageFilter::None ); EXPECT_EQ( (int) ITKType::NoHandles, (int) itk::simple::FastMarchingImageFilter::NoHandles ); EXPECT_EQ( (int) ITKType::Strict, (int) itk::simple::FastMarchingImageFilter::Strict ); } TEST(BasicFilters,Cast) { itk::simple::HashImageFilter hasher; itk::simple::ImageFileReader reader; reader.SetFileName ( dataFinder.GetFile ( "Input/RA-Float.nrrd" ) ); itk::simple::Image image = reader.Execute(); ASSERT_TRUE ( image.GetITKBase() != NULL ); hasher.SetHashFunction ( itk::simple::HashImageFilter::MD5 ); EXPECT_EQ ( "3ccccde44efaa3d688a86e94335c1f16", hasher.Execute ( image ) ); EXPECT_EQ ( image.GetPixelIDValue(), itk::simple::sitkFloat32 ); EXPECT_EQ ( image.GetPixelIDTypeAsString(), "32-bit float" ); typedef std::map<std::string,itk::simple::PixelIDValueType> MapType; MapType mapping; mapping["2f27e9260baeba84fb83dd35de23fa2d"] = (itk::simple::PixelIDValueType)itk::simple::sitkUInt8; mapping["2f27e9260baeba84fb83dd35de23fa2d"] = (itk::simple::PixelIDValueType)itk::simple::sitkInt8; mapping["a963bd6a755b853103a2d195e01a50d3"] = (itk::simple::PixelIDValueType)itk::simple::sitkUInt16; mapping["a963bd6a755b853103a2d195e01a50d3"] = (itk::simple::PixelIDValueType)itk::simple::sitkInt16; mapping["6ceea0011178a955b5be2d545d107199"] = (itk::simple::PixelIDValueType)itk::simple::sitkUInt32; mapping["6ceea0011178a955b5be2d545d107199"] = (itk::simple::PixelIDValueType)itk::simple::sitkInt32; mapping["efa4c3b27349b97b02a64f3d2b5ca9ed"] = (itk::simple::PixelIDValueType)itk::simple::sitkUInt64; mapping["sitkInt64"] = (itk::simple::PixelIDValueType)itk::simple::sitkInt64; mapping["3ccccde44efaa3d688a86e94335c1f16"] = (itk::simple::PixelIDValueType)itk::simple::sitkFloat32; mapping["ac0228acc17038fd1f1ed28eb2841c73"] = (itk::simple::PixelIDValueType)itk::simple::sitkFloat64; mapping["226dabda8fc07f20e2b9e44ca1c83955"] = (itk::simple::PixelIDValueType)itk::simple::sitkComplexFloat32; mapping["e92cbb187a92610068d7de0cb23364db"] = (itk::simple::PixelIDValueType)itk::simple::sitkComplexFloat64; mapping["2f27e9260baeba84fb83dd35de23fa2d"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorUInt8; mapping["2f27e9260baeba84fb83dd35de23fa2d"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorInt8; mapping["a963bd6a755b853103a2d195e01a50d3"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorUInt16; mapping["a963bd6a755b853103a2d195e01a50d3"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorInt16; mapping["6ceea0011178a955b5be2d545d107199"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorUInt32; mapping["6ceea0011178a955b5be2d545d107199"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorInt32; mapping["sitkVectorUInt64"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorUInt64; mapping["sitkVectorInt64"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorInt64; mapping["3ccccde44efaa3d688a86e94335c1f16"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorFloat32; mapping["ac0228acc17038fd1f1ed28eb2841c73"] = (itk::simple::PixelIDValueType)itk::simple::sitkVectorFloat64; mapping["sitkLabelUInt8"] = (itk::simple::PixelIDValueType)itk::simple::sitkLabelUInt8; mapping["sitkLabelUInt16"] = (itk::simple::PixelIDValueType)itk::simple::sitkLabelUInt16; mapping["sitkLabelUInt32"] = (itk::simple::PixelIDValueType)itk::simple::sitkLabelUInt32; mapping["sitkLabelUInt64"] = (itk::simple::PixelIDValueType)itk::simple::sitkLabelUInt64; bool failed = false; // Loop over the map, load each file, and compare the hash value for ( MapType::iterator it = mapping.begin(); it != mapping.end(); ++it ) { itk::simple::PixelIDValueType pixelID = it->second; std::string hash = it->first; std::cerr << std::flush; std::cerr << std::flush; if ( pixelID == itk::simple::sitkUnknown ) { std::cerr << "Enum value: " << pixelID << " (" << hash << ") is unknown and not instantiated" << std::endl; continue; } std::cerr << "Testing casting to pixelID: " << pixelID << " is " << itk::simple::GetPixelIDValueAsString ( pixelID ) << std::endl; try { itk::simple::CastImageFilter caster; itk::simple::Image test = caster.SetOutputPixelType ( pixelID ).Execute ( image ); hasher.SetHashFunction ( itk::simple::HashImageFilter::MD5 ); EXPECT_EQ ( hash, hasher.Execute ( test ) ) << "Cast to " << itk::simple::GetPixelIDValueAsString ( pixelID ); } catch ( ::itk::simple::GenericException &e ) { // hashing currently doesn't work for label images if ( hash.find( "sitkLabel" ) == 0 ) { std::cerr << "Hashing currently is not implemented for Label Images" << std::endl; } else { failed = true; std::cerr << "Failed to hash: " << e.what() << std::endl; } continue; } } EXPECT_FALSE ( failed ) << "Cast failed, or could not take the hash of the imoge"; } TEST(BasicFilters,HashImageFilter) { itk::simple::HashImageFilter hasher; EXPECT_EQ ( "itk::simple::HashImageFilter\nHashFunction: SHA1\n", hasher.ToString() ); EXPECT_EQ ( itk::simple::HashImageFilter::SHA1, hasher.SetHashFunction ( itk::simple::HashImageFilter::SHA1 ).GetHashFunction() ); EXPECT_EQ ( itk::simple::HashImageFilter::MD5, hasher.SetHashFunction ( itk::simple::HashImageFilter::MD5 ).GetHashFunction() ); } TEST(BasicFilters,LabelStatistics) { itk::simple::Image image = itk::simple::ReadImage ( dataFinder.GetFile ( "Input/cthead1.png" ) ); itk::simple::Image labels = itk::simple::ReadImage ( dataFinder.GetFile ( "Input/2th_cthead1.mha" ) ); itk::simple::LabelStatisticsImageFilter stats; stats.Execute ( image, labels ); EXPECT_TRUE ( stats.HasLabel ( 0 ) ); EXPECT_NEAR ( stats.GetMinimum ( 0 ), 0, 0.01 ); EXPECT_NEAR ( stats.GetMaximum ( 0 ), 99, 0.01 ); EXPECT_NEAR ( stats.GetMean ( 0 ), 13.0911, 0.001 ); EXPECT_NEAR ( stats.GetSigma ( 0 ), 16.4065, 0.01 ); EXPECT_NEAR ( stats.GetVariance ( 0 ), 269.173, 0.01 ); EXPECT_NEAR ( stats.GetCount ( 0 ), 36172, 0.01 ); EXPECT_NEAR ( stats.GetSum ( 0 ), 473533, 0.01 ); EXPECT_NEAR ( stats.GetMedian ( 0 ), 12.0, 0.001 ); const itk::simple::LabelStatisticsImageFilter::LabelListingType myLabels = stats.GetValidLabels(); EXPECT_EQ ( myLabels.size() , 3u); const itk::simple::LabelStatisticsImageFilter::LabelStatisticsMap myMap = stats.GetLabelStatisticsMap(); EXPECT_EQ( myLabels.size() , myMap.size() ); const itk::simple::MeasurementMap myMeasurementMap = stats.GetMeasurementMap(0); EXPECT_EQ( myMeasurementMap.size(), 8u ); //4 measurements produced const itk::simple::BasicMeasurementMap myBasicMeasurementMap = myMeasurementMap.GetBasicMeasurementMap(); EXPECT_EQ( myBasicMeasurementMap.size(), 8u ); //4 measurements produced EXPECT_EQ ( myMeasurementMap.ToString(), "Count, Maximum, Mean, Minimum, Sigma, Sum, Variance, approxMedian, \n36172, 99, 13.0911, 0, 16.4065, 473533, 269.173, 12, \n" ); } <|endoftext|>
<commit_before>#include <x0/Logging.h> #include <sd-daemon.h> #include <typeinfo> #include <cstdarg> #include <cstdio> namespace x0 { Logging::Logging() : prefix_(), className_(), enabled_(false) { } Logging::Logging(const char *prefix, ...) : prefix_(), className_(), enabled_(false) { char buf[1024]; va_list va; va_start(va, prefix); vsnprintf(buf, sizeof(buf), prefix, va); va_end(va); prefix_ = buf; updateClassName(); } void Logging::updateClassName() { static const char splits[] = "/[(-"; for (auto i = prefix_.begin(), e = prefix_.end(); i != e; ++i) { if (strchr(splits, *i)) { className_ = prefix_.substr(0, i - prefix_.begin()); goto done; } } className_ = prefix_; } bool Logging::checkEnabled() { const char* env = getenv("XZERO_DEBUG"); // TODO do a simple substring match for now but tokenize-split at ':' later return enabled_ || (env && strstr(env, className_.c_str())); } void Logging::setLoggingPrefix(const char *prefix, ...) { char buf[1024]; va_list va; va_start(va, prefix); vsnprintf(buf, sizeof(buf), prefix, va); va_end(va); prefix_ = buf; updateClassName(); } void Logging::setLogging(bool enable) { enabled_ = enable; } void Logging::debug(const char *fmt, ...) { if (!checkEnabled()) return; char buf[1024]; va_list va; va_start(va, fmt); vsnprintf(buf, sizeof(buf), fmt, va); va_end(va); fprintf(stdout, SD_DEBUG "%s: %s\n", prefix_.c_str(), buf); fflush(stdout); } } // namespace x0 <commit_msg>[base] Logging: compile-fix.<commit_after>#include <x0/Logging.h> #include <sd-daemon.h> #include <typeinfo> #include <cstdarg> #include <cstdio> namespace x0 { Logging::Logging() : prefix_(), className_(), enabled_(false) { } Logging::Logging(const char *prefix, ...) : prefix_(), className_(), enabled_(false) { char buf[1024]; va_list va; va_start(va, prefix); vsnprintf(buf, sizeof(buf), prefix, va); va_end(va); prefix_ = buf; updateClassName(); } void Logging::updateClassName() { static const char splits[] = "/[(-"; for (auto i = prefix_.begin(), e = prefix_.end(); i != e; ++i) { if (strchr(splits, *i)) { className_ = prefix_.substr(0, i - prefix_.begin()); return; } } className_ = prefix_; } bool Logging::checkEnabled() { const char* env = getenv("XZERO_DEBUG"); // TODO do a simple substring match for now but tokenize-split at ':' later return enabled_ || (env && strstr(env, className_.c_str())); } void Logging::setLoggingPrefix(const char *prefix, ...) { char buf[1024]; va_list va; va_start(va, prefix); vsnprintf(buf, sizeof(buf), prefix, va); va_end(va); prefix_ = buf; updateClassName(); } void Logging::setLogging(bool enable) { enabled_ = enable; } void Logging::debug(const char *fmt, ...) { if (!checkEnabled()) return; char buf[1024]; va_list va; va_start(va, fmt); vsnprintf(buf, sizeof(buf), fmt, va); va_end(va); fprintf(stdout, SD_DEBUG "%s: %s\n", prefix_.c_str(), buf); fflush(stdout); } } // namespace x0 <|endoftext|>
<commit_before>// MIT License // // Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT 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 <iostream> #include <chrono> #include <vector> #include <limits> #include <string> #include <cstdio> #include <cstdlib> // Google Benchmark #include "benchmark/benchmark.h" // CmdParser #include "cmdparser.hpp" #include "benchmark_utils.hpp" // HIP API #include <hip/hip_runtime.h> #include <hip/hip_hcc.h> // rocPRIM #include <rocprim.hpp> #define HIP_CHECK(condition) \ { \ hipError_t error = condition; \ if(error != hipSuccess){ \ std::cout << "HIP error: " << error << " line: " << __LINE__ << std::endl; \ exit(error); \ } \ } #ifndef DEFAULT_N const size_t DEFAULT_N = 1024 * 1024 * 128; #endif namespace rp = rocprim; template<rocprim::block_reduce_algorithm algorithm> struct reduce { template< class T, unsigned int BlockSize, unsigned int ItemsPerThread, unsigned int Trials > __global__ static void kernel(const T* input, T* output) { const unsigned int i = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; T values[ItemsPerThread]; T reduced_value; for(unsigned int k = 0; k < ItemsPerThread; k++) { values[k] = input[i * ItemsPerThread + k]; } using breduce_t = rp::block_reduce<T, BlockSize, algorithm>; __shared__ typename breduce_t::storage_type storage; #pragma nounroll for(unsigned int trial = 0; trial < Trials; trial++) { breduce_t().reduce(values, reduced_value, storage); } if(hipThreadIdx_x == 0) { output[hipBlockIdx_x] = reduced_value; } } }; template< class Benchmark, class T, unsigned int BlockSize, unsigned int ItemsPerThread, unsigned int Trials = 100 > void run_benchmark(benchmark::State& state, hipStream_t stream, size_t N) { // Make sure size is a multiple of BlockSize constexpr auto items_per_block = BlockSize * ItemsPerThread; const auto size = items_per_block * ((N + items_per_block - 1)/items_per_block); // Allocate and fill memory std::vector<T> input(size, 1.0f); T * d_input; T * d_output; HIP_CHECK(hipMalloc(&d_input, size * sizeof(T))); HIP_CHECK(hipMalloc(&d_output, size * sizeof(T))); HIP_CHECK( hipMemcpy( d_input, input.data(), size * sizeof(T), hipMemcpyHostToDevice ) ); HIP_CHECK(hipDeviceSynchronize()); for (auto _ : state) { auto start = std::chrono::high_resolution_clock::now(); hipLaunchKernelGGL( HIP_KERNEL_NAME(Benchmark::template kernel<T, BlockSize, ItemsPerThread, Trials>), dim3(size/items_per_block), dim3(BlockSize), 0, stream, d_input, d_output ); HIP_CHECK(hipPeekAtLastError()); HIP_CHECK(hipDeviceSynchronize()); auto end = std::chrono::high_resolution_clock::now(); auto elapsed_seconds = std::chrono::duration_cast<std::chrono::duration<double>>(end - start); state.SetIterationTime(elapsed_seconds.count()); } state.SetBytesProcessed(state.iterations() * size * sizeof(T) * Trials); state.SetItemsProcessed(state.iterations() * size * Trials); HIP_CHECK(hipFree(d_input)); HIP_CHECK(hipFree(d_output)); } // IPT - items per thread #define CREATE_BENCHMARK(T, BS, IPT) \ benchmark::RegisterBenchmark( \ (std::string("block_reduce<"#T", "#BS", "#IPT", " + algorithm_name + ">.") + method_name).c_str(), \ run_benchmark<Benchmark, T, BS, IPT>, \ stream, size \ ) template<class Benchmark> void add_benchmarks(std::vector<benchmark::internal::Benchmark*>& benchmarks, const std::string& method_name, const std::string& algorithm_name, hipStream_t stream, size_t size) { std::vector<benchmark::internal::Benchmark*> new_benchmarks = { CREATE_BENCHMARK(float, 256, 1), CREATE_BENCHMARK(float, 256, 2), CREATE_BENCHMARK(float, 256, 3), CREATE_BENCHMARK(float, 256, 4), CREATE_BENCHMARK(float, 256, 8), CREATE_BENCHMARK(float, 256, 11), CREATE_BENCHMARK(float, 256, 16), CREATE_BENCHMARK(int, 256, 1), CREATE_BENCHMARK(int, 256, 2), CREATE_BENCHMARK(int, 256, 3), CREATE_BENCHMARK(int, 256, 4), CREATE_BENCHMARK(int, 256, 8), CREATE_BENCHMARK(int, 256, 11), CREATE_BENCHMARK(int, 256, 16), CREATE_BENCHMARK(int, 320, 1), CREATE_BENCHMARK(int, 320, 2), CREATE_BENCHMARK(int, 320, 3), CREATE_BENCHMARK(int, 320, 4), CREATE_BENCHMARK(int, 320, 8), CREATE_BENCHMARK(int, 320, 11), CREATE_BENCHMARK(int, 320, 16), CREATE_BENCHMARK(double, 256, 1), CREATE_BENCHMARK(double, 256, 2), CREATE_BENCHMARK(double, 256, 3), CREATE_BENCHMARK(double, 256, 4), CREATE_BENCHMARK(double, 256, 8), CREATE_BENCHMARK(double, 256, 11), CREATE_BENCHMARK(double, 256, 16), }; benchmarks.insert(benchmarks.end(), new_benchmarks.begin(), new_benchmarks.end()); } int main(int argc, char *argv[]) { cli::Parser parser(argc, argv); parser.set_optional<size_t>("size", "size", DEFAULT_N, "number of values"); parser.set_optional<int>("trials", "trials", -1, "number of iterations"); parser.run_and_exit_if_error(); // Parse argv benchmark::Initialize(&argc, argv); const size_t size = parser.get<size_t>("size"); const int trials = parser.get<int>("trials"); // HIP hipStream_t stream = 0; // default hipDeviceProp_t devProp; int device_id = 0; HIP_CHECK(hipGetDevice(&device_id)); HIP_CHECK(hipGetDeviceProperties(&devProp, device_id)); std::cout << "[HIP] Device name: " << devProp.name << std::endl; // Add benchmarks std::vector<benchmark::internal::Benchmark*> benchmarks; // using_warp_scan using reduce_uwr_t = reduce<rocprim::block_reduce_algorithm::using_warp_reduce>; add_benchmarks<reduce_uwr_t>( benchmarks, "reduce", "using_warp_reduce", stream, size ); // reduce then scan using reduce_rr_t = reduce<rocprim::block_reduce_algorithm::raking_reduce>; add_benchmarks<reduce_rr_t>( benchmarks, "reduce", "raking_reduce", stream, size ); // Use manual timing for(auto& b : benchmarks) { b->UseManualTime(); b->Unit(benchmark::kMillisecond); } // Force number of iterations if(trials > 0) { for(auto& b : benchmarks) { b->Iterations(trials); } } // Run benchmarks benchmark::RunSpecifiedBenchmarks(); return 0; } <commit_msg>Fix block_reduce benchmark<commit_after>// MIT License // // Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT 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 <iostream> #include <chrono> #include <vector> #include <limits> #include <string> #include <cstdio> #include <cstdlib> // Google Benchmark #include "benchmark/benchmark.h" // CmdParser #include "cmdparser.hpp" #include "benchmark_utils.hpp" // HIP API #include <hip/hip_runtime.h> #include <hip/hip_hcc.h> // rocPRIM #include <block/block_reduce.hpp> #define HIP_CHECK(condition) \ { \ hipError_t error = condition; \ if(error != hipSuccess){ \ std::cout << "HIP error: " << error << " line: " << __LINE__ << std::endl; \ exit(error); \ } \ } #ifndef DEFAULT_N const size_t DEFAULT_N = 1024 * 1024 * 128; #endif namespace rp = rocprim; template<rocprim::block_reduce_algorithm algorithm> struct reduce { template< class T, unsigned int BlockSize, unsigned int ItemsPerThread, unsigned int Trials > __global__ static void kernel(const T* input, T* output) { const unsigned int i = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; T values[ItemsPerThread]; T reduced_value; for(unsigned int k = 0; k < ItemsPerThread; k++) { values[k] = input[i * ItemsPerThread + k]; } using breduce_t = rp::block_reduce<T, BlockSize, algorithm>; __shared__ typename breduce_t::storage_type storage; #pragma nounroll for(unsigned int trial = 0; trial < Trials; trial++) { breduce_t().reduce(values, reduced_value, storage); values[0] = reduced_value; } if(hipThreadIdx_x == 0) { output[hipBlockIdx_x] = reduced_value; } } }; template< class Benchmark, class T, unsigned int BlockSize, unsigned int ItemsPerThread, unsigned int Trials = 100 > void run_benchmark(benchmark::State& state, hipStream_t stream, size_t N) { // Make sure size is a multiple of BlockSize constexpr auto items_per_block = BlockSize * ItemsPerThread; const auto size = items_per_block * ((N + items_per_block - 1)/items_per_block); // Allocate and fill memory std::vector<T> input(size, 1.0f); T * d_input; T * d_output; HIP_CHECK(hipMalloc(&d_input, size * sizeof(T))); HIP_CHECK(hipMalloc(&d_output, size * sizeof(T))); HIP_CHECK( hipMemcpy( d_input, input.data(), size * sizeof(T), hipMemcpyHostToDevice ) ); HIP_CHECK(hipDeviceSynchronize()); for (auto _ : state) { auto start = std::chrono::high_resolution_clock::now(); hipLaunchKernelGGL( HIP_KERNEL_NAME(Benchmark::template kernel<T, BlockSize, ItemsPerThread, Trials>), dim3(size/items_per_block), dim3(BlockSize), 0, stream, d_input, d_output ); HIP_CHECK(hipPeekAtLastError()); HIP_CHECK(hipDeviceSynchronize()); auto end = std::chrono::high_resolution_clock::now(); auto elapsed_seconds = std::chrono::duration_cast<std::chrono::duration<double>>(end - start); state.SetIterationTime(elapsed_seconds.count()); } state.SetBytesProcessed(state.iterations() * size * sizeof(T) * Trials); state.SetItemsProcessed(state.iterations() * size * Trials); HIP_CHECK(hipFree(d_input)); HIP_CHECK(hipFree(d_output)); } // IPT - items per thread #define CREATE_BENCHMARK(T, BS, IPT) \ benchmark::RegisterBenchmark( \ (std::string("block_reduce<"#T", "#BS", "#IPT", " + algorithm_name + ">.") + method_name).c_str(), \ run_benchmark<Benchmark, T, BS, IPT>, \ stream, size \ ) template<class Benchmark> void add_benchmarks(std::vector<benchmark::internal::Benchmark*>& benchmarks, const std::string& method_name, const std::string& algorithm_name, hipStream_t stream, size_t size) { using custom_double2 = custom_type<double, double>; using custom_int_double = custom_type<int, double>; std::vector<benchmark::internal::Benchmark*> new_benchmarks = { CREATE_BENCHMARK(float, 256, 1), CREATE_BENCHMARK(float, 256, 2), CREATE_BENCHMARK(float, 256, 3), CREATE_BENCHMARK(float, 256, 4), CREATE_BENCHMARK(float, 256, 8), CREATE_BENCHMARK(float, 256, 11), CREATE_BENCHMARK(float, 256, 16), CREATE_BENCHMARK(int, 256, 1), CREATE_BENCHMARK(int, 256, 2), CREATE_BENCHMARK(int, 256, 3), CREATE_BENCHMARK(int, 256, 4), CREATE_BENCHMARK(int, 256, 8), CREATE_BENCHMARK(int, 256, 11), CREATE_BENCHMARK(int, 256, 16), CREATE_BENCHMARK(int, 320, 1), CREATE_BENCHMARK(int, 320, 2), CREATE_BENCHMARK(int, 320, 3), CREATE_BENCHMARK(int, 320, 4), CREATE_BENCHMARK(int, 320, 8), CREATE_BENCHMARK(int, 320, 11), CREATE_BENCHMARK(int, 320, 16), CREATE_BENCHMARK(double, 256, 1), CREATE_BENCHMARK(double, 256, 2), CREATE_BENCHMARK(double, 256, 3), CREATE_BENCHMARK(double, 256, 4), CREATE_BENCHMARK(double, 256, 8), CREATE_BENCHMARK(double, 256, 11), CREATE_BENCHMARK(double, 256, 16), CREATE_BENCHMARK(custom_double2, 256, 1), CREATE_BENCHMARK(custom_double2, 256, 4), CREATE_BENCHMARK(custom_double2, 256, 8), CREATE_BENCHMARK(custom_int_double, 256, 1), CREATE_BENCHMARK(custom_int_double, 256, 4), CREATE_BENCHMARK(custom_int_double, 256, 8) }; benchmarks.insert(benchmarks.end(), new_benchmarks.begin(), new_benchmarks.end()); } int main(int argc, char *argv[]) { cli::Parser parser(argc, argv); parser.set_optional<size_t>("size", "size", DEFAULT_N, "number of values"); parser.set_optional<int>("trials", "trials", -1, "number of iterations"); parser.run_and_exit_if_error(); // Parse argv benchmark::Initialize(&argc, argv); const size_t size = parser.get<size_t>("size"); const int trials = parser.get<int>("trials"); // HIP hipStream_t stream = 0; // default hipDeviceProp_t devProp; int device_id = 0; HIP_CHECK(hipGetDevice(&device_id)); HIP_CHECK(hipGetDeviceProperties(&devProp, device_id)); std::cout << "[HIP] Device name: " << devProp.name << std::endl; // Add benchmarks std::vector<benchmark::internal::Benchmark*> benchmarks; // using_warp_scan using reduce_uwr_t = reduce<rocprim::block_reduce_algorithm::using_warp_reduce>; add_benchmarks<reduce_uwr_t>( benchmarks, "reduce", "using_warp_reduce", stream, size ); // reduce then scan using reduce_rr_t = reduce<rocprim::block_reduce_algorithm::raking_reduce>; add_benchmarks<reduce_rr_t>( benchmarks, "reduce", "raking_reduce", stream, size ); // Use manual timing for(auto& b : benchmarks) { b->UseManualTime(); b->Unit(benchmark::kMillisecond); } // Force number of iterations if(trials > 0) { for(auto& b : benchmarks) { b->Iterations(trials); } } // Run benchmarks benchmark::RunSpecifiedBenchmarks(); return 0; } <|endoftext|>
<commit_before>#include "TestUtils/ResponseUtils.h" #include "gtest/gtest.h" #include <Managers/GameAgent.h> #include <Managers/GameInterface.h> #include <Tasks/BasicTasks/Draw.h> #include <Tasks/BasicTasks/PlayCard.h> #include <future> using namespace Hearthstonepp; TEST(BasicCard, EX1_066) { GameAgent agent( Player(new Account("Player 1", ""), new Deck("", CardClass::WARRIOR)), Player(new Account("Player 2", ""), new Deck("", CardClass::MAGE))); TaskAgent& taskAgent = agent.GetTaskAgent(); TestUtils::AutoResponder response(agent); Player& player1 = agent.GetPlayer1(); Player& player2 = agent.GetPlayer2(); player1.totalMana = player1.existMana = 10; player2.totalMana = player2.existMana = 10; Card* FieryWarAxe = Cards::GetInstance()->FindCardByName("Fiery War Axe"); Card* AcidicSwampOoze = Cards::GetInstance()->FindCardByName("Acidic Swamp Ooze"); agent.RunTask(BasicTasks::DrawCardTask(FieryWarAxe), player1, player2); EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(1)); EXPECT_EQ(agent.GetPlayer1().hand[0]->card->name, "Fiery War Axe"); agent.RunTask(BasicTasks::DrawCardTask(AcidicSwampOoze), player2, player1); EXPECT_EQ(agent.GetPlayer2().hand.size(), static_cast<size_t>(1)); EXPECT_EQ(agent.GetPlayer2().hand[0]->card->name, "Acidic Swamp Ooze"); // Create Response for GameAgent to Run PlayCardTask std::future<TaskMeta> respPlayCard = response.PlayCard(0); MetaData result = agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player1, player2); EXPECT_EQ(result, MetaData::PLAY_WEAPON_SUCCESS); EXPECT_NE(agent.GetPlayer1().hero->weapon, nullptr); TaskMeta reqPlayCard = respPlayCard.get(); EXPECT_EQ(reqPlayCard.id, +TaskID::REQUIRE); auto require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(reqPlayCard); EXPECT_EQ(TaskID::_from_integral(require->required()), +TaskID::SELECT_CARD); // Create Multiple Response for PlayCardTask And PlayMinionTask auto resp = response.AutoMinion(0, 0); result = agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player2, player1); EXPECT_EQ(result, MetaData::PLAY_MINION_SUCCESS); EXPECT_EQ(agent.GetPlayer1().hero->weapon, nullptr); auto [respPlayCard2, respPlayMinion] = resp.get(); require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayCard2); EXPECT_EQ(TaskID::_from_integral(require->required()), +TaskID::SELECT_CARD); require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayMinion); EXPECT_EQ(TaskID::_from_integral(require->required()), +TaskID::SELECT_POSITION); } TEST(BasicCard, CS2_041) { GameAgent agent( Player(new Account("Player 1", ""), new Deck("", CardClass::SHAMAN)), Player(new Account("Player 2", ""), new Deck("", CardClass::MAGE))); Player& player1 = agent.GetPlayer1(); Player& player2 = agent.GetPlayer2(); player1.totalMana = agent.GetPlayer1().existMana = 10; player2.totalMana = agent.GetPlayer2().existMana = 10; Card* AcidicSwampOoze = Cards::GetInstance()->FindCardByName("Acidic Swamp Ooze"); Card* AncestralHealing = Cards::GetInstance()->FindCardByName("Ancestral Healing"); agent.RunTask(BasicTasks::DrawCardTask(AcidicSwampOoze), player1, player2); agent.RunTask(BasicTasks::DrawCardTask(AncestralHealing), player1, player2); EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(2)); // // agent.Process(agent.GetPlayer1(), BasicTask::PlayCardTask(0, 0)); // auto minion = // dynamic_cast<Character*>(agent.GetPlayer1().field.at(0)); // minion->health -= 1; // EXPECT_EQ(minion->health, 1u); // // agent.Process(agent.GetPlayer1(), // BasicTask::PlayCardTask(0, -1, TargetType::MY_FIELD, // 1)); // EXPECT_EQ(static_cast<bool>(minion->gameTags[GameTag::TAUNT]), true); // EXPECT_EQ(minion->health, 2); } <commit_msg>[ci skip] Add tests for CS2_041<commit_after>#include "TestUtils/ResponseUtils.h" #include "gtest/gtest.h" #include <Managers/GameAgent.h> #include <Managers/GameInterface.h> #include <Tasks/BasicTasks/Combat.h> #include <Tasks/BasicTasks/Draw.h> #include <Tasks/BasicTasks/PlayCard.h> #include <future> using namespace Hearthstonepp; TEST(BasicCard, EX1_066) { GameAgent agent( Player(new Account("Player 1", ""), new Deck("", CardClass::WARRIOR)), Player(new Account("Player 2", ""), new Deck("", CardClass::MAGE))); TaskAgent& taskAgent = agent.GetTaskAgent(); TestUtils::AutoResponder response(agent); Player& player1 = agent.GetPlayer1(); Player& player2 = agent.GetPlayer2(); player1.totalMana = player1.existMana = 10; player2.totalMana = player2.existMana = 10; agent.RunTask(BasicTasks::DrawCardTask( Cards::GetInstance()->FindCardByName("Fiery War Axe")), player1, player2); EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(1)); EXPECT_EQ(agent.GetPlayer1().hand[0]->card->name, "Fiery War Axe"); agent.RunTask(BasicTasks::DrawCardTask(Cards::GetInstance()->FindCardByName( "Acidic Swamp Ooze")), player2, player1); EXPECT_EQ(agent.GetPlayer2().hand.size(), static_cast<size_t>(1)); EXPECT_EQ(agent.GetPlayer2().hand[0]->card->name, "Acidic Swamp Ooze"); // Create response for GameAgent to run PlayCardTask auto respPlayCard1 = response.PlayCard(0); MetaData result = agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player1, player2); EXPECT_EQ(result, MetaData::PLAY_WEAPON_SUCCESS); EXPECT_NE(agent.GetPlayer1().hero->weapon, nullptr); TaskMeta reqPlayCard1 = respPlayCard1.get(); EXPECT_EQ(reqPlayCard1.id, +TaskID::REQUIRE); auto require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(reqPlayCard1); EXPECT_EQ(TaskID::_from_integral(require->required()), +TaskID::SELECT_CARD); // Create multiple response for PlayCardTask And PlayMinionTask auto respAutoMinion = response.AutoMinion(0, 0); result = agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player2, player1); EXPECT_EQ(result, MetaData::PLAY_MINION_SUCCESS); EXPECT_EQ(agent.GetPlayer1().hero->weapon, nullptr); auto[respPlayCard2, respPlayMinion] = respAutoMinion.get(); require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayCard2); EXPECT_EQ(TaskID::_from_integral(require->required()), +TaskID::SELECT_CARD); require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayMinion); EXPECT_EQ(TaskID::_from_integral(require->required()), +TaskID::SELECT_POSITION); } TEST(BasicCard, CS2_041) { GameAgent agent( Player(new Account("Player 1", ""), new Deck("", CardClass::SHAMAN)), Player(new Account("Player 2", ""), new Deck("", CardClass::MAGE))); TaskAgent& taskAgent = agent.GetTaskAgent(); TestUtils::AutoResponder response(agent); Player& player1 = agent.GetPlayer1(); Player& player2 = agent.GetPlayer2(); player1.totalMana = agent.GetPlayer1().existMana = 10; player2.totalMana = agent.GetPlayer2().existMana = 10; agent.RunTask(BasicTasks::DrawCardTask(Cards::GetInstance()->FindCardByName( "Acidic Swamp Ooze")), player1, player2); EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(1)); EXPECT_EQ(agent.GetPlayer1().hand[0]->card->name, "Acidic Swamp Ooze"); agent.RunTask(BasicTasks::DrawCardTask(Cards::GetInstance()->FindCardByName( "Ancestral Healing")), player1, player2); EXPECT_EQ(agent.GetPlayer1().hand.size(), static_cast<size_t>(2)); EXPECT_EQ(agent.GetPlayer1().hand[1]->card->name, "Ancestral Healing"); agent.RunTask(BasicTasks::DrawCardTask( Cards::GetInstance()->FindCardByName("Stonetusk Boar")), player2, player1); EXPECT_EQ(agent.GetPlayer2().hand.size(), static_cast<size_t>(1)); EXPECT_EQ(agent.GetPlayer2().hand[0]->card->name, "Stonetusk Boar"); // Create multiple response for PlayCardTask And PlayMinionTask auto respAutoMinion = response.AutoMinion(0, 0); MetaData result = agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player1, player2); EXPECT_EQ(result, MetaData::PLAY_MINION_SUCCESS); EXPECT_EQ(agent.GetPlayer1().field[0]->card->name, "Acidic Swamp Ooze"); auto[respPlayCard1, respPlayMinion1] = respAutoMinion.get(); auto require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayCard1); EXPECT_EQ(TaskID::_from_integral(require->required()), +TaskID::SELECT_CARD); require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayMinion1); EXPECT_EQ(TaskID::_from_integral(require->required()), +TaskID::SELECT_POSITION); // Create multiple response for PlayCardTask And PlayMinionTask respAutoMinion = response.AutoMinion(0, 0); result = agent.RunTask(BasicTasks::PlayCardTask(taskAgent), player2, player1); EXPECT_EQ(result, MetaData::PLAY_MINION_SUCCESS); EXPECT_EQ(agent.GetPlayer2().field[0]->card->name, "Stonetusk Boar"); auto[respPlayCard2, respPlayMinion2] = respAutoMinion.get(); require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayCard2); EXPECT_EQ(TaskID::_from_integral(require->required()), +TaskID::SELECT_CARD); require = TaskMeta::ConvertTo<FlatData::RequireTaskMeta>(respPlayMinion2); EXPECT_EQ(TaskID::_from_integral(require->required()), +TaskID::SELECT_POSITION); // // agent.Process(agent.GetPlayer1(), BasicTask::PlayCardTask(0, 0)); // auto minion = // dynamic_cast<Character*>(agent.GetPlayer1().field.at(0)); // minion->health -= 1; // EXPECT_EQ(minion->health, 1u); // // agent.Process(agent.GetPlayer1(), // BasicTask::PlayCardTask(0, -1, TargetType::MY_FIELD, // 1)); // EXPECT_EQ(static_cast<bool>(minion->gameTags[GameTag::TAUNT]), true); // EXPECT_EQ(minion->health, 2); } <|endoftext|>
<commit_before>// // Copyright 2018 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // VulkanFormatTablesTest: // Tests to validate our Vulkan support tables match hardware support. // #include "libANGLE/Context.h" #include "libANGLE/angletypes.h" #include "libANGLE/formatutils.h" #include "libANGLE/renderer/vulkan/ContextVk.h" #include "libANGLE/renderer/vulkan/RendererVk.h" #include "test_utils/ANGLETest.h" #include "test_utils/angle_test_instantiate.h" using namespace angle; namespace { class VulkanFormatTablesTest : public ANGLETest { }; struct ParametersToTest { VkImageType imageType; VkImageCreateFlags createFlags; }; // This test enumerates all GL formats - for each, it queries the Vulkan support for // using it as a texture, filterable, and a render target. It checks this against our // speed-optimized baked tables, and validates they would give the same result. TEST_P(VulkanFormatTablesTest, TestFormatSupport) { ASSERT_TRUE(IsVulkan()); // Hack the angle! const gl::Context *context = reinterpret_cast<gl::Context *>(getEGLWindow()->getContext()); auto *contextVk = rx::GetImplAs<rx::ContextVk>(context); rx::RendererVk *renderer = contextVk->getRenderer(); // We need to test normal 2D images as well as Cube images. const std::vector<ParametersToTest> parametersToTest = { {VK_IMAGE_TYPE_2D, 0}, {VK_IMAGE_TYPE_2D, VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT}}; const gl::FormatSet &allFormats = gl::GetAllSizedInternalFormats(); for (GLenum internalFormat : allFormats) { const rx::vk::Format &vkFormat = renderer->getFormat(internalFormat); // Similar loop as when we build caps in vk_caps_utils.cpp, but query using // vkGetPhysicalDeviceImageFormatProperties instead of vkGetPhysicalDeviceFormatProperties // and verify we have all the same caps. if (!vkFormat.valid()) { // TODO(jmadill): Every angle format should be mapped to a vkFormat. // This hasn't been defined in our vk_format_map.json yet so the caps won't be filled. continue; } const gl::TextureCaps &textureCaps = renderer->getNativeTextureCaps().get(internalFormat); for (const ParametersToTest params : parametersToTest) { // Now lets verify that that agaisnt vulkan. VkFormatProperties formatProperties; vkGetPhysicalDeviceFormatProperties(renderer->getPhysicalDevice(), vkFormat.vkTextureFormat, &formatProperties); VkImageFormatProperties imageProperties; // isTexturable? bool isTexturable = vkGetPhysicalDeviceImageFormatProperties( renderer->getPhysicalDevice(), vkFormat.vkTextureFormat, params.imageType, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_SAMPLED_BIT, params.createFlags, &imageProperties) == VK_SUCCESS; EXPECT_EQ(isTexturable, textureCaps.texturable) << vkFormat.vkTextureFormat; // TODO(jmadill): Support ES3 textures. // isFilterable? bool isFilterable = (formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) == VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT; EXPECT_EQ(isFilterable, textureCaps.filterable) << vkFormat.vkTextureFormat; // isRenderable? const bool isRenderableColor = (vkGetPhysicalDeviceImageFormatProperties( renderer->getPhysicalDevice(), vkFormat.vkTextureFormat, params.imageType, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, params.createFlags, &imageProperties)) == VK_SUCCESS; const bool isRenderableDepthStencil = (vkGetPhysicalDeviceImageFormatProperties( renderer->getPhysicalDevice(), vkFormat.vkTextureFormat, params.imageType, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, params.createFlags, &imageProperties)) == VK_SUCCESS; bool isRenderable = isRenderableColor || isRenderableDepthStencil; EXPECT_EQ(isRenderable, textureCaps.renderable) << vkFormat.vkTextureFormat; } } } ANGLE_INSTANTIATE_TEST(VulkanFormatTablesTest, ES2_VULKAN()); } // anonymous namespace <commit_msg>Fix standalone Linux build<commit_after>// // Copyright 2018 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // VulkanFormatTablesTest: // Tests to validate our Vulkan support tables match hardware support. // #include "test_utils/ANGLETest.h" #include "test_utils/angle_test_instantiate.h" // 'None' is defined as 'struct None {};' in // third_party/googletest/src/googletest/include/gtest/internal/gtest-type-util.h. // But 'None' is also defined as a numeric constant 0L in <X11/X.h>. // So we need to include ANGLETest.h first to avoid this conflict. #include "libANGLE/Context.h" #include "libANGLE/angletypes.h" #include "libANGLE/formatutils.h" #include "libANGLE/renderer/vulkan/ContextVk.h" #include "libANGLE/renderer/vulkan/RendererVk.h" using namespace angle; namespace { class VulkanFormatTablesTest : public ANGLETest { }; struct ParametersToTest { VkImageType imageType; VkImageCreateFlags createFlags; }; // This test enumerates all GL formats - for each, it queries the Vulkan support for // using it as a texture, filterable, and a render target. It checks this against our // speed-optimized baked tables, and validates they would give the same result. TEST_P(VulkanFormatTablesTest, TestFormatSupport) { ASSERT_TRUE(IsVulkan()); // Hack the angle! const gl::Context *context = reinterpret_cast<gl::Context *>(getEGLWindow()->getContext()); auto *contextVk = rx::GetImplAs<rx::ContextVk>(context); rx::RendererVk *renderer = contextVk->getRenderer(); // We need to test normal 2D images as well as Cube images. const std::vector<ParametersToTest> parametersToTest = { {VK_IMAGE_TYPE_2D, 0}, {VK_IMAGE_TYPE_2D, VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT}}; const gl::FormatSet &allFormats = gl::GetAllSizedInternalFormats(); for (GLenum internalFormat : allFormats) { const rx::vk::Format &vkFormat = renderer->getFormat(internalFormat); // Similar loop as when we build caps in vk_caps_utils.cpp, but query using // vkGetPhysicalDeviceImageFormatProperties instead of vkGetPhysicalDeviceFormatProperties // and verify we have all the same caps. if (!vkFormat.valid()) { // TODO(jmadill): Every angle format should be mapped to a vkFormat. // This hasn't been defined in our vk_format_map.json yet so the caps won't be filled. continue; } const gl::TextureCaps &textureCaps = renderer->getNativeTextureCaps().get(internalFormat); for (const ParametersToTest params : parametersToTest) { // Now lets verify that that agaisnt vulkan. VkFormatProperties formatProperties; vkGetPhysicalDeviceFormatProperties(renderer->getPhysicalDevice(), vkFormat.vkTextureFormat, &formatProperties); VkImageFormatProperties imageProperties; // isTexturable? bool isTexturable = vkGetPhysicalDeviceImageFormatProperties( renderer->getPhysicalDevice(), vkFormat.vkTextureFormat, params.imageType, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_SAMPLED_BIT, params.createFlags, &imageProperties) == VK_SUCCESS; EXPECT_EQ(isTexturable, textureCaps.texturable) << vkFormat.vkTextureFormat; // TODO(jmadill): Support ES3 textures. // isFilterable? bool isFilterable = (formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) == VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT; EXPECT_EQ(isFilterable, textureCaps.filterable) << vkFormat.vkTextureFormat; // isRenderable? const bool isRenderableColor = (vkGetPhysicalDeviceImageFormatProperties( renderer->getPhysicalDevice(), vkFormat.vkTextureFormat, params.imageType, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, params.createFlags, &imageProperties)) == VK_SUCCESS; const bool isRenderableDepthStencil = (vkGetPhysicalDeviceImageFormatProperties( renderer->getPhysicalDevice(), vkFormat.vkTextureFormat, params.imageType, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, params.createFlags, &imageProperties)) == VK_SUCCESS; bool isRenderable = isRenderableColor || isRenderableDepthStencil; EXPECT_EQ(isRenderable, textureCaps.renderable) << vkFormat.vkTextureFormat; } } } ANGLE_INSTANTIATE_TEST(VulkanFormatTablesTest, ES2_VULKAN()); } // anonymous namespace <|endoftext|>
<commit_before>/* * Copyright (c)2015 - 2016 Oasis LMF Limited * 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 original author of this software nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT 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: Ben Matharu email: ben.matharu@oasislmf.org */ #include <iostream> #include <stdio.h> #include <stdlib.h> #if defined(_MSC_VER) #include "../wingetopt/wingetopt.h" #else #include <unistd.h> #endif #include "../include/oasis.h" int damage_bins_ = -1; int max_damage_bin_found = -1; void doit() { Vulnerability v; char line[4096]; int lineno=0; fwrite(&damage_bins_, sizeof(damage_bins_), 1, stdout); fgets(line, sizeof(line), stdin); lineno++; while (fgets(line, sizeof(line), stdin) != 0) { if (sscanf(line, "%d,%d,%d,%f", &v.vulnerability_id, &v.intensity_bin_id, &v.damage_bin_id, &v.probability) != 4){ fprintf(stderr, "Invalid data in line %d:\n%s", lineno, line); return; } else { if (damage_bins_ < v.damage_bin_id) { fprintf(stderr, "Max damage bin specifed %d is less than encountered in data %d\n", damage_bins_, v.damage_bin_id); } fwrite(&v, sizeof(v), 1, stdout); if (v.damage_bin_id > max_damage_bin_found) max_damage_bin_found = v.damage_bin_id; } lineno++; } } void help() { fprintf(stderr, "-d maximum damage bin\n" "-v version\n" "-h help\n" ) ; } int main(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "vhd:")) != -1) { switch (opt) { case 'd': damage_bins_ = atoi(optarg); break; case 'v': fprintf(stderr, "%s : version: %s\n", argv[0], VERSION); exit(EXIT_FAILURE); break; case 'h': help(); exit(EXIT_FAILURE); default: help(); exit(EXIT_FAILURE); } } if (damage_bins_ == -1) { std::cerr << "Damage bin paramter not supplied\n"; help(); exit(EXIT_FAILURE); } initstreams("", ""); doit(); if (max_damage_bin_found != damage_bins_) { fprintf(stderr, "Warning: Max damage bin found %d you suppplied %d\n", max_damage_bin_found); } return 0; } <commit_msg>fix vulnerbabilytobin warning message<commit_after>/* * Copyright (c)2015 - 2016 Oasis LMF Limited * 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 original author of this software nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT 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: Ben Matharu email: ben.matharu@oasislmf.org */ #include <iostream> #include <stdio.h> #include <stdlib.h> #if defined(_MSC_VER) #include "../wingetopt/wingetopt.h" #else #include <unistd.h> #endif #include "../include/oasis.h" int damage_bins_ = -1; int max_damage_bin_found = -1; void doit() { Vulnerability v; char line[4096]; int lineno=0; fwrite(&damage_bins_, sizeof(damage_bins_), 1, stdout); fgets(line, sizeof(line), stdin); lineno++; while (fgets(line, sizeof(line), stdin) != 0) { if (sscanf(line, "%d,%d,%d,%f", &v.vulnerability_id, &v.intensity_bin_id, &v.damage_bin_id, &v.probability) != 4){ fprintf(stderr, "Invalid data in line %d:\n%s", lineno, line); return; } else { if (damage_bins_ < v.damage_bin_id) { fprintf(stderr, "Max damage bin specifed %d is less than encountered in data %d\n", damage_bins_, v.damage_bin_id); } fwrite(&v, sizeof(v), 1, stdout); if (v.damage_bin_id > max_damage_bin_found) max_damage_bin_found = v.damage_bin_id; } lineno++; } } void help() { fprintf(stderr, "-d maximum damage bin\n" "-v version\n" "-h help\n" ) ; } int main(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "vhd:")) != -1) { switch (opt) { case 'd': damage_bins_ = atoi(optarg); break; case 'v': fprintf(stderr, "%s : version: %s\n", argv[0], VERSION); exit(EXIT_FAILURE); break; case 'h': help(); exit(EXIT_FAILURE); default: help(); exit(EXIT_FAILURE); } } if (damage_bins_ == -1) { std::cerr << "Damage bin paramter not supplied\n"; help(); exit(EXIT_FAILURE); } initstreams("", ""); doit(); if (max_damage_bin_found != damage_bins_) { fprintf(stderr, "Warning: Max damage bin found %d you suppplied %d\n", max_damage_bin_found, damage_bins_); } return 0; } <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_FUN_CSR_MATRIX_TIMES_VECTOR_HPP #define STAN_MATH_REV_FUN_CSR_MATRIX_TIMES_VECTOR_HPP #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/csr_u_to_z.hpp> #include <vector> namespace stan { namespace math { namespace internal { template <typename T1, typename T2, typename Res, require_eigen_t<T1>* = nullptr> void update_w(T1& w, int m, int n, std::vector<int, arena_allocator<int>>& u, std::vector<int, arena_allocator<int>>& v, T2&& b, Res&& res) { Eigen::Map<Eigen::SparseMatrix<var>> w_mat(m, n, w.size(), v.data(), u.data(), w.data()); for (int k = 0; k < w_mat.outerSize(); ++k) { for (Eigen::Map<Eigen::SparseMatrix<var>>::InnerIterator it(w_mat, k); it; ++it) { it.valueRef().adj() += res.adj_op().coeff(it.row()) * value_of(b).coeff(it.col()); } } } template <typename T1, typename T2, typename Res, require_var_matrix_t<T1>* = nullptr> void update_w(T1& w, int m, int n, std::vector<int, arena_allocator<int>>& u, std::vector<int, arena_allocator<int>>& v, T2&& b, Res&& res) { Eigen::Map<Eigen::SparseMatrix<double>> w_mat(m, n, w.size(), v.data(), u.data(), w.adj().data()); for (int k = 0; k < w_mat.outerSize(); ++k) { for (Eigen::Map<Eigen::SparseMatrix<double>>::InnerIterator it(w_mat, k); it; ++it) { it.valueRef() += res.adj_op().coeff(it.row()) * value_of(b).coeff(it.col()); } } } } // namespace internal /** * \addtogroup csr_format * Return the multiplication of the sparse matrix (specified by * by values and indexing) by the specified dense vector. * * The sparse matrix X of dimension m by n is represented by the * vector w (of values), the integer array v (containing one-based * column index of each value), the integer array u (containing * one-based indexes of where each row starts in w). * * @tparam T1 type of the sparse matrix * @tparam T2 type of the dense vector * @param m Number of rows in matrix. * @param n Number of columns in matrix. * @param w Vector of non-zero values in matrix. * @param v Column index of each non-zero value, same * length as w. * @param u Index of where each row starts in w, length equal to * the number of rows plus one. * @param b Eigen vector which the matrix is multiplied by. * @return Dense vector for the product. * @throw std::domain_error if m and n are not positive or are nan. * @throw std::domain_error if the implied sparse matrix and b are * not multiplicable. * @throw std::invalid_argument if m/n/w/v/u are not internally * consistent, as defined by the indexing scheme. Extractors are * defined in Stan which guarantee a consistent set of m/n/w/v/u * for a given sparse matrix. * @throw std::out_of_range if any of the indexes are out of range. */ template <typename T1, typename T2, require_any_rev_matrix_t<T1, T2>* = nullptr> inline auto csr_matrix_times_vector(int m, int n, const T1& w, const std::vector<int>& v, const std::vector<int>& u, const T2& b) { using result_t = return_type_t<T1, T2>; using sparse_val_mat = Eigen::Map<const Eigen::SparseMatrix<double>>; using sparse_dense_mul_type = decltype((std::declval<sparse_val_mat>() * value_of(b)).eval()); using return_t = return_var_matrix_t<sparse_dense_mul_type, T1, T2>; check_positive("csr_matrix_times_vector", "m", m); check_positive("csr_matrix_times_vector", "n", n); check_positive("csr_matrix_times_vector", "v", v); check_positive("csr_matrix_times_vector", "u", u); check_size_match("csr_matrix_times_vector", "n", n, "b", b.size()); check_size_match("csr_matrix_times_vector", "w", w.size(), "v", v.size()); check_size_match("csr_matrix_times_vector", "v + 1", v.size() + 1, "u", u.size()); check_size_match("csr_matrix_times_vector", "m", m, "u", u.size() - 1); check_size_match("csr_matrix_times_vector", "w", w.size(), "v", v.size()); check_size_match("csr_matrix_times_vector", "u/z", u[m - 1] + csr_u_to_z(u, m - 1) - 1, "v", v.size()); for (int i : v) { check_range("csr_matrix_times_vector", "v[]", n, i); } std::vector<int, arena_allocator<int>> u_arena(u.size()); std::transform(u.begin(), u.end(), u_arena.begin(), [](auto&& x) { return x - 1; }); std::vector<int, arena_allocator<int>> v_arena(u.size()); std::transform(v.begin(), v.end(), v_arena.begin(), [](auto&& x) { return x - 1; }); if (!is_constant<T2>::value && !is_constant<T1>::value) { arena_t<promote_scalar_t<var, T2>> b_arena = b; arena_t<promote_scalar_t<var, T1>> w_arena = to_arena(w); auto&& w_val_arena = to_arena(value_of(w_arena)); Eigen::Map<const Eigen::SparseMatrix<double>> w_val_mat( m, n, w_val_arena.size(), v_arena.data(), u_arena.data(), w_val_arena.data()); arena_t<return_t> res = w_val_mat * value_of(b_arena); reverse_pass_callback([m, n, w_arena, w_val_arena, v_arena, u_arena, res, b_arena]() mutable { sparse_val_mat w_val_mat(m, n, w_val_arena.size(), v_arena.data(), u_arena.data(), w_val_arena.data()); internal::update_w(w_arena, m, n, u_arena, v_arena, b_arena, res); b_arena.adj() += w_val_mat.transpose() * res.adj_op(); }); return return_t(res); } else if (!is_constant<T2>::value) { arena_t<promote_scalar_t<var, T2>> b_arena = b; auto&& w_val_arena = to_arena(value_of(w)); sparse_val_mat w_val_mat(m, n, w_val_arena.size(), v_arena.data(), u_arena.data(), w_val_arena.data()); arena_t<return_t> res = w_val_mat * value_of(b_arena); reverse_pass_callback( [m, n, w_val_arena, v_arena, u_arena, res, b_arena]() mutable { sparse_val_mat w_val_mat(m, n, w_val_arena.size(), v_arena.data(), u_arena.data(), w_val_arena.data()); b_arena.adj() += w_val_mat.transpose() * res.adj_op(); }); return return_t(res); } else { arena_t<promote_scalar_t<var, T1>> w_arena = to_arena(w); auto&& w_val = eval(value_of(w_arena)); sparse_val_mat w_val_mat(m, n, w_val.size(), v_arena.data(), u_arena.data(), w_val.data()); auto&& b_arena = to_arena(value_of(b)); arena_t<return_t> res = w_val_mat * b_arena; reverse_pass_callback([m, n, w_arena, v_arena, u_arena, res, b_arena]() mutable { internal::update_w(w_arena, m, n, u_arena, v_arena, b_arena, res); }); return return_t(res); } } } // namespace math } // namespace stan #endif <commit_msg>remove use of adj_op() for adj()<commit_after>#ifndef STAN_MATH_REV_FUN_CSR_MATRIX_TIMES_VECTOR_HPP #define STAN_MATH_REV_FUN_CSR_MATRIX_TIMES_VECTOR_HPP #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/csr_u_to_z.hpp> #include <vector> namespace stan { namespace math { namespace internal { template <typename T1, typename T2, typename Res, require_eigen_t<T1>* = nullptr> void update_w(T1& w, int m, int n, std::vector<int, arena_allocator<int>>& u, std::vector<int, arena_allocator<int>>& v, T2&& b, Res&& res) { Eigen::Map<Eigen::SparseMatrix<var>> w_mat(m, n, w.size(), v.data(), u.data(), w.data()); for (int k = 0; k < w_mat.outerSize(); ++k) { for (Eigen::Map<Eigen::SparseMatrix<var>>::InnerIterator it(w_mat, k); it; ++it) { it.valueRef().adj() += res.adj().coeff(it.row()) * value_of(b).coeff(it.col()); } } } template <typename T1, typename T2, typename Res, require_var_matrix_t<T1>* = nullptr> void update_w(T1& w, int m, int n, std::vector<int, arena_allocator<int>>& u, std::vector<int, arena_allocator<int>>& v, T2&& b, Res&& res) { Eigen::Map<Eigen::SparseMatrix<double>> w_mat(m, n, w.size(), v.data(), u.data(), w.adj().data()); for (int k = 0; k < w_mat.outerSize(); ++k) { for (Eigen::Map<Eigen::SparseMatrix<double>>::InnerIterator it(w_mat, k); it; ++it) { it.valueRef() += res.adj().coeff(it.row()) * value_of(b).coeff(it.col()); } } } } // namespace internal /** * \addtogroup csr_format * Return the multiplication of the sparse matrix (specified by * by values and indexing) by the specified dense vector. * * The sparse matrix X of dimension m by n is represented by the * vector w (of values), the integer array v (containing one-based * column index of each value), the integer array u (containing * one-based indexes of where each row starts in w). * * @tparam T1 type of the sparse matrix * @tparam T2 type of the dense vector * @param m Number of rows in matrix. * @param n Number of columns in matrix. * @param w Vector of non-zero values in matrix. * @param v Column index of each non-zero value, same * length as w. * @param u Index of where each row starts in w, length equal to * the number of rows plus one. * @param b Eigen vector which the matrix is multiplied by. * @return Dense vector for the product. * @throw std::domain_error if m and n are not positive or are nan. * @throw std::domain_error if the implied sparse matrix and b are * not multiplicable. * @throw std::invalid_argument if m/n/w/v/u are not internally * consistent, as defined by the indexing scheme. Extractors are * defined in Stan which guarantee a consistent set of m/n/w/v/u * for a given sparse matrix. * @throw std::out_of_range if any of the indexes are out of range. */ template <typename T1, typename T2, require_any_rev_matrix_t<T1, T2>* = nullptr> inline auto csr_matrix_times_vector(int m, int n, const T1& w, const std::vector<int>& v, const std::vector<int>& u, const T2& b) { using result_t = return_type_t<T1, T2>; using sparse_val_mat = Eigen::Map<const Eigen::SparseMatrix<double>>; using sparse_dense_mul_type = decltype((std::declval<sparse_val_mat>() * value_of(b)).eval()); using return_t = return_var_matrix_t<sparse_dense_mul_type, T1, T2>; check_positive("csr_matrix_times_vector", "m", m); check_positive("csr_matrix_times_vector", "n", n); check_positive("csr_matrix_times_vector", "v", v); check_positive("csr_matrix_times_vector", "u", u); check_size_match("csr_matrix_times_vector", "n", n, "b", b.size()); check_size_match("csr_matrix_times_vector", "w", w.size(), "v", v.size()); check_size_match("csr_matrix_times_vector", "v + 1", v.size() + 1, "u", u.size()); check_size_match("csr_matrix_times_vector", "m", m, "u", u.size() - 1); check_size_match("csr_matrix_times_vector", "w", w.size(), "v", v.size()); check_size_match("csr_matrix_times_vector", "u/z", u[m - 1] + csr_u_to_z(u, m - 1) - 1, "v", v.size()); for (int i : v) { check_range("csr_matrix_times_vector", "v[]", n, i); } std::vector<int, arena_allocator<int>> u_arena(u.size()); std::transform(u.begin(), u.end(), u_arena.begin(), [](auto&& x) { return x - 1; }); std::vector<int, arena_allocator<int>> v_arena(u.size()); std::transform(v.begin(), v.end(), v_arena.begin(), [](auto&& x) { return x - 1; }); if (!is_constant<T2>::value && !is_constant<T1>::value) { arena_t<promote_scalar_t<var, T2>> b_arena = b; arena_t<promote_scalar_t<var, T1>> w_arena = to_arena(w); auto&& w_val_arena = to_arena(value_of(w_arena)); Eigen::Map<const Eigen::SparseMatrix<double>> w_val_mat( m, n, w_val_arena.size(), v_arena.data(), u_arena.data(), w_val_arena.data()); arena_t<return_t> res = w_val_mat * value_of(b_arena); reverse_pass_callback([m, n, w_arena, w_val_arena, v_arena, u_arena, res, b_arena]() mutable { sparse_val_mat w_val_mat(m, n, w_val_arena.size(), v_arena.data(), u_arena.data(), w_val_arena.data()); internal::update_w(w_arena, m, n, u_arena, v_arena, b_arena, res); b_arena.adj() += w_val_mat.transpose() * res.adj(); }); return return_t(res); } else if (!is_constant<T2>::value) { arena_t<promote_scalar_t<var, T2>> b_arena = b; auto&& w_val_arena = to_arena(value_of(w)); sparse_val_mat w_val_mat(m, n, w_val_arena.size(), v_arena.data(), u_arena.data(), w_val_arena.data()); arena_t<return_t> res = w_val_mat * value_of(b_arena); reverse_pass_callback( [m, n, w_val_arena, v_arena, u_arena, res, b_arena]() mutable { sparse_val_mat w_val_mat(m, n, w_val_arena.size(), v_arena.data(), u_arena.data(), w_val_arena.data()); b_arena.adj() += w_val_mat.transpose() * res.adj(); }); return return_t(res); } else { arena_t<promote_scalar_t<var, T1>> w_arena = to_arena(w); auto&& w_val = eval(value_of(w_arena)); sparse_val_mat w_val_mat(m, n, w_val.size(), v_arena.data(), u_arena.data(), w_val.data()); auto&& b_arena = to_arena(value_of(b)); arena_t<return_t> res = w_val_mat * b_arena; reverse_pass_callback([m, n, w_arena, v_arena, u_arena, res, b_arena]() mutable { internal::update_w(w_arena, m, n, u_arena, v_arena, b_arena, res); }); return return_t(res); } } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_MAT_FUN_MATRIX_EXP_MULTIPLY_HPP #define STAN_MATH_REV_MAT_FUN_MATRIX_EXP_MULTIPLY_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/arr/err/check_nonzero_size.hpp> #include <stan/math/prim/mat/err/check_multiplicable.hpp> #include <stan/math/prim/mat/err/check_square.hpp> #include <stan/math/prim/mat/fun/matrix_exp.hpp> #include <stan/math/rev/mat/fun/multiply.hpp> #include <stan/math/rev/core.hpp> namespace stan { namespace math { /** * Wrapper of matrix_exp_action function for a more literal name * @tparam Ta scalar type matrix A * @tparam Tb scalar type matrix B * @tparam Cb Columns matrix B * @param[in] A Matrix * @param[in] B Matrix * @return exponential of A multiplies B */ template <typename Ta, typename Tb, int Cb> inline Eigen::Matrix<typename stan::return_type<Ta, Tb>::type, -1, Cb> matrix_exp_multiply(const Eigen::Matrix<Ta, -1, -1>& A, const Eigen::Matrix<Tb, -1, Cb>& B) { check_nonzero_size("matrix_exp_multiply", "input matrix", A); check_nonzero_size("matrix_exp_multiply", "input matrix", B); check_multiplicable("matrix_exp_multiply", "A", A, "B", B); check_square("matrix_exp_multiply", "input matrix", A); return multiply(matrix_exp(A), B); } } // namespace math } // namespace stan #endif <commit_msg>adding include<commit_after>#ifndef STAN_MATH_REV_MAT_FUN_MATRIX_EXP_MULTIPLY_HPP #define STAN_MATH_REV_MAT_FUN_MATRIX_EXP_MULTIPLY_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/arr/err/check_nonzero_size.hpp> #include <stan/math/prim/mat/err/check_multiplicable.hpp> #include <stan/math/prim/mat/err/check_square.hpp> #include <stan/math/prim/mat/fun/matrix_exp.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <stan/math/rev/mat/fun/multiply.hpp> #include <stan/math/rev/core.hpp> namespace stan { namespace math { /** * Wrapper of matrix_exp_action function for a more literal name * @tparam Ta scalar type matrix A * @tparam Tb scalar type matrix B * @tparam Cb Columns matrix B * @param[in] A Matrix * @param[in] B Matrix * @return exponential of A multiplies B */ template <typename Ta, typename Tb, int Cb> inline Eigen::Matrix<typename stan::return_type<Ta, Tb>::type, -1, Cb> matrix_exp_multiply(const Eigen::Matrix<Ta, -1, -1>& A, const Eigen::Matrix<Tb, -1, Cb>& B) { check_nonzero_size("matrix_exp_multiply", "input matrix", A); check_nonzero_size("matrix_exp_multiply", "input matrix", B); check_multiplicable("matrix_exp_multiply", "A", A, "B", B); check_square("matrix_exp_multiply", "input matrix", A); return multiply(matrix_exp(A), B); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/* * File: Calendar.cpp * Author: Martin Novak, xnovak1c@stud.fit.vutbr.cz * * Created on 20. January 2016 */ #include "Calendar.h" #include <chrono> #include <ctime> #include <memory> #include <thread> #include <vector> #include "TaskInstance.h" #include "Logger.h" // Definition of singleton instance. std::shared_ptr<Calendar> Calendar::m_instance; Calendar::Calendar(): m_wakeup_time(std::chrono::system_clock::now()), m_should_run(true), m_running(false) { } Calendar::~Calendar() { } void Calendar::createInstance() { if (!m_instance) { logger.LOGFILE("calendar", "INFO") << "Calendar created." << std::endl; m_instance = std::shared_ptr<Calendar>(new Calendar); } } std::shared_ptr<Calendar> Calendar::getInstance() { if (m_instance) { return m_instance; } else { throw std::runtime_error("Calendar singleton was not created or already destructed."); } } void Calendar::runCalendar() { if (m_running) { return; } else { m_running = true; } // Stores all event which should be executed. std::multimap<std::chrono::system_clock::time_point, TaskInstance*> to_activate; // Run for all eternity (until whole system shuts down). while(m_should_run) { // If event queue is empty, wait in thread until event comes. waitUntilCalendarIsNotEmpty(); if (m_calendar_events.empty()) { break; } m_calendar_events_mx.lock(); // Save current time. std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); while (m_calendar_events.begin()->first <= now) { // Stores every event with activation time less or equal to now. to_activate.emplace(m_calendar_events.begin()->first, m_calendar_events.begin()->second); // Pops stored event from queue. m_calendar_events.erase(m_calendar_events.begin()); // If the queue is empty, stop loop immediately. if (m_calendar_events.empty()) { break; } } if(!m_calendar_events.empty()) { // Set the activation time of event with lowest activation time as time to wake up this thread. m_wakeup_time = m_calendar_events.begin()->first; } else { // If there is no event in queue this thread will won't wait in this iteration, // but in next iteration waits at waitUntilCalendarIsNotEmpty(). m_wakeup_time = std::chrono::system_clock::now(); } m_calendar_events_mx.unlock(); // Launch thread to execute stored events. std::thread t_execute_events(&Calendar::activateInstances, this, to_activate); t_execute_events.detach(); to_activate.clear(); // Creates lock by which can thread wake up if to queue comes event which has // lower activation time then the one for which thread waits now. std::unique_lock<std::mutex> lock(m_new_wakeup_time_mx); // Wait until the activation time of event with a lowest activation time in queue. m_new_wakeup_time_cv.wait_until(lock, m_wakeup_time); } logger.LOGFILE("calendar", "INFO") << "Calendar algorithm stopped." << std::endl; // HERE CAN BE STORED EVERYTHING IN CALENDAR. } void Calendar::activateInstances(std::multimap<std::chrono::system_clock::time_point, TaskInstance*> to_activate) { if(!to_activate.empty()) { for (auto instance : to_activate) { // Print time of activation and activate instances. time_t tn = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); instance.second->activate(instance.first); } } } void Calendar::waitUntilCalendarIsNotEmpty() { m_test_calendar_empty_mx.lock(); bool calendar_empty = m_calendar_events.empty(); if (calendar_empty) { // Until it's not notified that there is an event in calendar, wait for event to be emplaced. std::unique_lock<std::mutex> lock(m_calendar_not_empty_mx); m_test_calendar_empty_mx.unlock(); m_calendar_not_empty_cv.wait(lock); } if (!calendar_empty) { m_test_calendar_empty_mx.unlock(); } } void Calendar::emplaceActivation(std::chrono::system_clock::time_point activation_time, TaskInstance* instance_ptr) { m_calendar_events_mx.lock(); m_test_calendar_empty_mx.lock(); // Before new event is created, check if queue is empty. bool calendar_empty = m_calendar_events.empty(); // Create new event and push to queue. m_calendar_events.emplace(activation_time, instance_ptr); if (!calendar_empty) { // If activation time of pushed event is lower than time for which main calendar algorithm (run()) waits, // it should wake up said thread so it can calculate new time to wake up. if (activation_time < m_wakeup_time ) { m_new_wakeup_time_cv.notify_all(); } } else { // If queue is empty that means that main calendar algorithm (run())is waiting // in waitUntilCalendarIsNotEmpty() function and should be notified to wake up. m_calendar_not_empty_cv.notify_all(); } m_test_calendar_empty_mx.unlock(); m_calendar_events_mx.unlock(); } std::chrono::system_clock::time_point Calendar::planActivation(int seconds, TaskInstance* instance_ptr) { std::chrono::system_clock::time_point activation_time = std::chrono::system_clock::now() + std::chrono::seconds(seconds); // Compute exact time when event should activate and push event. emplaceActivation(activation_time, instance_ptr); return activation_time; } std::chrono::system_clock::time_point Calendar::planActivation(TaskInstance* instance_ptr) { // Push event at current time. std::chrono::system_clock::time_point activation_time = std::chrono::system_clock::now(); emplaceActivation(activation_time, instance_ptr); return activation_time; } std::chrono::system_clock::time_point Calendar::planActivation(std::string date_time, TaskInstance* instance_ptr) { std::tm tm = {}; // Format: "1 9 2014 12:35:34" -> "month day_of_month year time" strptime(date_time.c_str(), "%m %d %Y %H:%M:%S", &tm); std::chrono::system_clock::time_point activation_time = std::chrono::system_clock::from_time_t(std::mktime(&tm)); emplaceActivation(activation_time, instance_ptr); return activation_time; } void Calendar::stopCalendar() { m_should_run = false; // Wakeup calendar algorithm to end. if (m_calendar_events.empty()) { m_calendar_not_empty_cv.notify_all(); } m_new_wakeup_time_cv.notify_all(); } void Calendar::removeAllActivationsOfInstance(std::set<std::chrono::system_clock::time_point> planned_times, TaskInstance* instance_ptr) { // Lock m_calendar_events container. std::lock_guard<std::mutex> lock(m_calendar_events_mx); for (auto activation_time : planned_times) { removeActivation(activation_time, instance_ptr); } } void Calendar::removeActivation(std::chrono::system_clock::time_point activation_time, TaskInstance* instance_ptr) { // Lock m_calendar_events container. std::mutex remove_activation_mx; std::lock_guard<std::mutex> lock(remove_activation_mx); // Find range of all activations containing activation_time as key. auto range_of_keys = m_calendar_events.equal_range(activation_time); // Iterate over all activations and remove those by instance_ptr. for (auto it = range_of_keys.first; it != range_of_keys.second; it++) { if (it->second == instance_ptr) { m_calendar_events.erase(it); } } } <commit_msg>Fix calendar.<commit_after>/* * File: Calendar.cpp * Author: Martin Novak, xnovak1c@stud.fit.vutbr.cz * * Created on 20. January 2016 */ #include "Calendar.h" #include <chrono> #include <ctime> #include <memory> #include <thread> #include <vector> #include "TaskInstance.h" #include "Logger.h" // Definition of singleton instance. std::shared_ptr<Calendar> Calendar::m_instance; Calendar::Calendar(): m_wakeup_time(std::chrono::system_clock::now()), m_should_run(true), m_running(false) { } Calendar::~Calendar() { } void Calendar::createInstance() { if (!m_instance) { logger.LOGFILE("calendar", "INFO") << "Calendar created." << std::endl; m_instance = std::shared_ptr<Calendar>(new Calendar); } } std::shared_ptr<Calendar> Calendar::getInstance() { if (m_instance) { return m_instance; } else { throw std::runtime_error("Calendar singleton was not created or already destructed."); } } void Calendar::runCalendar() { if (m_running) { return; } else { m_running = true; } // Stores all event which should be executed. std::multimap<std::chrono::system_clock::time_point, TaskInstance*> to_activate; // Run for all eternity (until whole system shuts down). while(m_should_run) { // If event queue is empty, wait in thread until event comes. waitUntilCalendarIsNotEmpty(); if (m_calendar_events.empty()) { break; } m_calendar_events_mx.lock(); // Save current time. std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); while (m_calendar_events.begin()->first <= now) { // Stores every event with activation time less or equal to now. to_activate.emplace(m_calendar_events.begin()->first, m_calendar_events.begin()->second); // Pops stored event from queue. m_calendar_events.erase(m_calendar_events.begin()); // If the queue is empty, stop loop immediately. if (m_calendar_events.empty()) { break; } } if(!m_calendar_events.empty()) { // Set the activation time of event with lowest activation time as time to wake up this thread. m_wakeup_time = m_calendar_events.begin()->first; } else { // If there is no event in queue this thread will won't wait in this iteration, // but in next iteration waits at waitUntilCalendarIsNotEmpty(). m_wakeup_time = std::chrono::system_clock::now(); } // Launch thread to execute stored events. std::thread t_execute_events(&Calendar::activateInstances, this, to_activate); t_execute_events.detach(); to_activate.clear(); // Creates lock by which can thread wake up if to queue comes event which has // lower activation time then the one for which thread waits now. std::unique_lock<std::mutex> lock(m_new_wakeup_time_mx); m_calendar_events_mx.unlock(); // Wait until the activation time of event with a lowest activation time in queue. m_new_wakeup_time_cv.wait_until(lock, m_wakeup_time); } logger.LOGFILE("calendar", "INFO") << "Calendar algorithm stopped." << std::endl; // HERE CAN BE STORED EVERYTHING IN CALENDAR. } void Calendar::activateInstances(std::multimap<std::chrono::system_clock::time_point, TaskInstance*> to_activate) { if(!to_activate.empty()) { for (auto instance : to_activate) { // Print time of activation and activate instances. time_t tn = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); instance.second->activate(instance.first); } } } void Calendar::waitUntilCalendarIsNotEmpty() { //m_test_calendar_empty_mx.lock(); bool calendar_empty = m_calendar_events.empty(); if (calendar_empty) { // Until it's not notified that there is an event in calendar, wait for event to be emplaced. std::unique_lock<std::mutex> lock(m_calendar_not_empty_mx); //m_test_calendar_empty_mx.unlock(); m_calendar_not_empty_cv.wait(lock); } if (!calendar_empty) { //m_test_calendar_empty_mx.unlock(); } } void Calendar::emplaceActivation(std::chrono::system_clock::time_point activation_time, TaskInstance* instance_ptr) { m_calendar_events_mx.lock(); //m_test_calendar_empty_mx.lock(); // Before new event is created, check if queue is empty. bool calendar_empty = m_calendar_events.empty(); // Create new event and push to queue. m_calendar_events.emplace(activation_time, instance_ptr); if (!calendar_empty) { // If activation time of pushed event is lower than time for which main calendar algorithm (run()) waits, // it should wake up said thread so it can calculate new time to wake up. if (activation_time < m_wakeup_time ) { m_new_wakeup_time_cv.notify_all(); } } else { // If queue is empty that means that main calendar algorithm (run())is waiting // in waitUntilCalendarIsNotEmpty() function and should be notified to wake up. m_calendar_not_empty_cv.notify_all(); } //m_test_calendar_empty_mx.unlock(); m_calendar_events_mx.unlock(); } std::chrono::system_clock::time_point Calendar::planActivation(int seconds, TaskInstance* instance_ptr) { std::chrono::system_clock::time_point activation_time = std::chrono::system_clock::now() + std::chrono::seconds(seconds); // Compute exact time when event should activate and push event. emplaceActivation(activation_time, instance_ptr); return activation_time; } std::chrono::system_clock::time_point Calendar::planActivation(TaskInstance* instance_ptr) { // Push event at current time. std::chrono::system_clock::time_point activation_time = std::chrono::system_clock::now(); emplaceActivation(activation_time, instance_ptr); return activation_time; } std::chrono::system_clock::time_point Calendar::planActivation(std::string date_time, TaskInstance* instance_ptr) { std::tm tm = {}; // Format: "1 9 2014 12:35:34" -> "month day_of_month year time" strptime(date_time.c_str(), "%m %d %Y %H:%M:%S", &tm); std::chrono::system_clock::time_point activation_time = std::chrono::system_clock::from_time_t(std::mktime(&tm)); emplaceActivation(activation_time, instance_ptr); return activation_time; } void Calendar::stopCalendar() { m_should_run = false; // Wakeup calendar algorithm to end. if (m_calendar_events.empty()) { m_calendar_not_empty_cv.notify_all(); } m_new_wakeup_time_cv.notify_all(); } void Calendar::removeAllActivationsOfInstance(std::set<std::chrono::system_clock::time_point> planned_times, TaskInstance* instance_ptr) { // Lock m_calendar_events container. for (auto activation_time : planned_times) { removeActivation(activation_time, instance_ptr); } } void Calendar::removeActivation(std::chrono::system_clock::time_point activation_time, TaskInstance* instance_ptr) { // Lock m_calendar_events container. //std::mutex remove_activation_mx; //std::lock_guard<std::mutex> lock(remove_activation_mx); std::lock_guard<std::mutex> lock(m_calendar_events_mx); // Find range of all activations containing activation_time as key. auto range_of_keys = m_calendar_events.equal_range(activation_time); // Iterate over all activations and remove those by instance_ptr. for (auto it = range_of_keys.first; it != range_of_keys.second; it++) { if (it->second == instance_ptr) { m_calendar_events.erase(it); } } } <|endoftext|>
<commit_before>#include "stdsneezy.h" #include "obj_cookware.h" #include "task_cook.h" #include "obj_pool.h" #include "obj_corpse.h" #include "obj_food.h" bool check_ingredients(TCookware *pot, int recipe){ int nfound=0; TThing *t; TPool *pool; TCorpse *corpse; TObj *obj; // check basic ingredients for(int i=0;ingredients[i].recipe>=0;++i){ if(ingredients[i].recipe!=recipe) continue; for(int j=i;ingredients[j].recipe>=0 && ingredients[j].ingredient==ingredients[i].ingredient;++j){ // look for this ingredient nfound=0; for(t=pot->getStuff();t;t=t->nextThing){ switch(ingredients[i].type){ case TYPE_VNUM: if(obj_index[t->number].virt==ingredients[i].num) nfound++; break; case TYPE_LIQUID: if((pool=dynamic_cast<TPool *>(t)) && pool->getDrinkType() == ingredients[i].num) nfound += pool->getDrinkUnits(); break; case TYPE_MATERIAL: if(t->getMaterial() == ingredients[i].num) nfound++; break; case TYPE_CORPSE: if((corpse=dynamic_cast<TCorpse *>(t)) && corpse->getCorpseRace() == ingredients[i].num) nfound++; break; case TYPE_ITEM: if((obj=dynamic_cast<TObj *>(t)) && obj->itemType() == ingredients[i].num) nfound++; break; } } i=j; } if(nfound < ingredients[i].amt){ return false; } } return true; } TCookware *find_pot(TBeing *ch, const sstring &cookware){ TThing *tpot=NULL; TCookware *pot=NULL; int count=0; if((tpot=searchLinkedListVis(ch, cookware, ch->getStuff(), &count))){ pot=dynamic_cast<TCookware *>(tpot); } return pot; } int find_recipe(sstring recipearg){ int recipe=-1; // find which recipe for(int i=0;recipes[i].recipe>=0;++i){ if(isname(recipearg, recipes[i].keywords)) recipe=recipes[i].recipe; } return recipe; } void TBeing::doCook(sstring arg) { int recipe=-1; TCookware *pot=NULL; sstring cookware, recipearg, tmparg=arg; tmparg=one_argument(tmparg, cookware); tmparg=one_argument(tmparg, recipearg); if(!(pot=find_pot(this, cookware))){ sendTo("You need to specify a piece of cookware to use.\n\r"); return; } if((recipe=find_recipe(recipearg))==-1){ sendTo("You need to specify a recipe.\n\r"); return; } // if(isImmortal()) // show_recipe(this, recipe); // check ingredients if(!check_ingredients(pot, recipe)){ sendTo("You seem to be missing an ingredient.\n\r"); return; } // delete the ingredients and then place the finished product in the pot // if the cooking fails we delete the finished product later TThing *t2, *t=pot->getStuff(); while(t){ t2=t->nextThing; delete t; t=t2; } TObj *o; if((o=read_object(recipes[recipe].vnum, VIRTUAL))) *pot+=*o; else { sendTo("Error loading food, alert an admin.\n\r"); return; } sendTo(COLOR_BASIC, fmt("You begin to cook %s.\n\r") % recipes[recipe].name); start_task(this, pot, NULL, TASK_COOK, "", 2, inRoom(), 0, 0, 5); } int task_cook(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *, TObj *pot) { // basic tasky safechecking if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom) || !pot){ act("You stop cooking.", FALSE, ch, 0, 0, TO_CHAR); act("$n stops cooking.", TRUE, ch, 0, 0, TO_ROOM); ch->stopTask(); if(pot) delete pot->getStuff(); return FALSE; // returning FALSE lets command be interpreted } if (ch->utilityTaskCommand(cmd) || ch->nobrainerTaskCommand(cmd)){ return FALSE; } if (ch->task->timeLeft < 0){ act("You finish cooking.", FALSE, ch, pot, 0, TO_CHAR); act("$n finishes cooking.", TRUE, ch, pot, 0, TO_ROOM); ch->stopTask(); return FALSE; } switch (cmd) { case CMD_TASK_CONTINUE: ch->task->calcNextUpdate(pulse, PULSE_MOBACT * 3); switch (ch->task->timeLeft) { case 2: act("You prepare the ingredients in $p.", FALSE, ch, pot, 0, TO_CHAR); act("$n prepares $s ingredients.", TRUE, ch, pot, 0, TO_ROOM); ch->task->timeLeft--; break; case 1: act("You cook the ingredients in $p.", FALSE, ch, pot, 0, TO_CHAR); act("$n cooks the ingredients in $p.", TRUE, ch, pot, 0, TO_ROOM); ch->task->timeLeft--; break; case 0: act("You continue cooking the ingredients in $p.", FALSE, ch, pot, 0, TO_CHAR); act("$n continues cooking.", TRUE, ch, pot, 0, TO_ROOM); ch->task->timeLeft--; break; } break; case CMD_ABORT: case CMD_STOP: act("You stop cooking.", FALSE, ch, 0, 0, TO_CHAR); act("$n stops cooking.", TRUE, ch, 0, 0, TO_ROOM); ch->stopTask(); delete pot->getStuff(); break; case CMD_TASK_FIGHTING: ch->sendTo("You can't properly cook while under attack.\n\r"); ch->stopTask(); delete pot->getStuff(); break; default: if (cmd < MAX_CMD_LIST) warn_busy(ch); delete pot->getStuff(); break; // eat the command } return TRUE; } <commit_msg>fixed a bug in the cooking ingredient search code<commit_after>#include "stdsneezy.h" #include "obj_cookware.h" #include "task_cook.h" #include "obj_pool.h" #include "obj_corpse.h" #include "obj_food.h" bool check_ingredients(TCookware *pot, int recipe){ int nfound=0; TThing *t; TPool *pool; TCorpse *corpse; TObj *obj; // check basic ingredients for(int i=0;ingredients[i].recipe>=0;++i){ if(ingredients[i].recipe!=recipe) continue; nfound=0; for(int j=i;ingredients[j].recipe>=0 && ingredients[j].ingredient==ingredients[i].ingredient;++j){ // look for this ingredient for(t=pot->getStuff();t;t=t->nextThing){ switch(ingredients[i].type){ case TYPE_VNUM: if(obj_index[t->number].virt==ingredients[i].num) nfound++; break; case TYPE_LIQUID: if((pool=dynamic_cast<TPool *>(t)) && pool->getDrinkType() == ingredients[i].num) nfound += pool->getDrinkUnits(); break; case TYPE_MATERIAL: if(t->getMaterial() == ingredients[i].num) nfound++; break; case TYPE_CORPSE: if((corpse=dynamic_cast<TCorpse *>(t)) && corpse->getCorpseRace() == ingredients[i].num) nfound++; break; case TYPE_ITEM: if((obj=dynamic_cast<TObj *>(t)) && obj->itemType() == ingredients[i].num) nfound++; break; } } i=j; } if(nfound < ingredients[i].amt){ return false; } } return true; } TCookware *find_pot(TBeing *ch, const sstring &cookware){ TThing *tpot=NULL; TCookware *pot=NULL; int count=0; if((tpot=searchLinkedListVis(ch, cookware, ch->getStuff(), &count))){ pot=dynamic_cast<TCookware *>(tpot); } return pot; } int find_recipe(sstring recipearg){ int recipe=-1; // find which recipe for(int i=0;recipes[i].recipe>=0;++i){ if(isname(recipearg, recipes[i].keywords)) recipe=recipes[i].recipe; } return recipe; } void TBeing::doCook(sstring arg) { int recipe=-1; TCookware *pot=NULL; sstring cookware, recipearg, tmparg=arg; tmparg=one_argument(tmparg, cookware); tmparg=one_argument(tmparg, recipearg); if(!(pot=find_pot(this, cookware))){ sendTo("You need to specify a piece of cookware to use.\n\r"); return; } if((recipe=find_recipe(recipearg))==-1){ sendTo("You need to specify a recipe.\n\r"); return; } // if(isImmortal()) // show_recipe(this, recipe); // check ingredients if(!check_ingredients(pot, recipe)){ sendTo("You seem to be missing an ingredient.\n\r"); return; } // delete the ingredients and then place the finished product in the pot // if the cooking fails we delete the finished product later TThing *t2, *t=pot->getStuff(); while(t){ t2=t->nextThing; delete t; t=t2; } TObj *o; if((o=read_object(recipes[recipe].vnum, VIRTUAL))) *pot+=*o; else { sendTo("Error loading food, alert an admin.\n\r"); return; } sendTo(COLOR_BASIC, fmt("You begin to cook %s.\n\r") % recipes[recipe].name); start_task(this, pot, NULL, TASK_COOK, "", 2, inRoom(), 0, 0, 5); } int task_cook(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *, TObj *pot) { // basic tasky safechecking if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom) || !pot){ act("You stop cooking.", FALSE, ch, 0, 0, TO_CHAR); act("$n stops cooking.", TRUE, ch, 0, 0, TO_ROOM); ch->stopTask(); if(pot) delete pot->getStuff(); return FALSE; // returning FALSE lets command be interpreted } if (ch->utilityTaskCommand(cmd) || ch->nobrainerTaskCommand(cmd)){ return FALSE; } if (ch->task->timeLeft < 0){ act("You finish cooking.", FALSE, ch, pot, 0, TO_CHAR); act("$n finishes cooking.", TRUE, ch, pot, 0, TO_ROOM); ch->stopTask(); return FALSE; } switch (cmd) { case CMD_TASK_CONTINUE: ch->task->calcNextUpdate(pulse, PULSE_MOBACT * 3); switch (ch->task->timeLeft) { case 2: act("You prepare the ingredients in $p.", FALSE, ch, pot, 0, TO_CHAR); act("$n prepares $s ingredients.", TRUE, ch, pot, 0, TO_ROOM); ch->task->timeLeft--; break; case 1: act("You cook the ingredients in $p.", FALSE, ch, pot, 0, TO_CHAR); act("$n cooks the ingredients in $p.", TRUE, ch, pot, 0, TO_ROOM); ch->task->timeLeft--; break; case 0: act("You continue cooking the ingredients in $p.", FALSE, ch, pot, 0, TO_CHAR); act("$n continues cooking.", TRUE, ch, pot, 0, TO_ROOM); ch->task->timeLeft--; break; } break; case CMD_ABORT: case CMD_STOP: act("You stop cooking.", FALSE, ch, 0, 0, TO_CHAR); act("$n stops cooking.", TRUE, ch, 0, 0, TO_ROOM); ch->stopTask(); delete pot->getStuff(); break; case CMD_TASK_FIGHTING: ch->sendTo("You can't properly cook while under attack.\n\r"); ch->stopTask(); delete pot->getStuff(); break; default: if (cmd < MAX_CMD_LIST) warn_busy(ch); delete pot->getStuff(); break; // eat the command } return TRUE; } <|endoftext|>
<commit_before> #include "geometry.hpp" #include "quadrics.hpp" #include "line.hpp" #include "accurate_intersections.hpp" #include "timer.hpp" #include <list> #include <fstream> #include <iomanip> template <int dim, typename fptype> std::list<Geometry::Quadric<dim, fptype>> parseQuadrics( const char *fname) { std::ifstream file(fname); using Qf = Geometry::Quadric<dim, fptype>; std::list<Qf> quads; while(!file.eof()) { Qf q; file >> q; quads.push_back(q); } return quads; } bool isSameInt(mpfr::mpreal int1, mpfr::mpreal int2) { /* Use a heuristic on truth to determine whether adjacent * intersections occur at the same place. * This will basically be a threshold on the largest * different bit in the mantissa. */ mpfr::mpreal largest = mpfr::max(mpfr::fabs(int1), mpfr::fabs(int2)); mp_exp_t largestExp = largest.get_exp(); mpfr::mpreal diff = mpfr::fabs(int1 - int2); int p1 = int1.getPrecision(), p2 = int2.getPrecision(); int minPrec = std::min(p1, p2); mp_exp_t deltaExp = largestExp - minPrec * 3 / 4 - diff.get_exp(); return deltaExp > 0; } void validateResults(std::ostream &results, auto &inter, auto &truth) { auto j = truth->begin(); bool printAll = false; for(auto i = inter->begin(); i != inter->end() || j != truth->end();) { bool printQ = false; /* First determine the length of the region of equal * intersections. * Then verify there's an equal number of * intersections in the approximately equal range and * that they correspond to the correct intersections. * If not, then print the intersection */ auto expected = j; if(j != truth->end()) { /* Create the region boundaries [sameBeg, sameEnd). * These are intersections which are probably the same */ auto sameBeg = j; auto sameEnd = j; int regLen = 0; while(sameEnd != truth->end() && isSameInt(j->intPos, sameEnd->intPos)) { sameEnd++; regLen++; } /* Increment i until it's not found in the region */ int numInRegion = 0; bool isInRegion = true; while(i != inter->end() && isInRegion && numInRegion < regLen) { j = sameBeg; while(j != sameEnd && i->q != j->q) j++; if(j == sameEnd) { isInRegion = false; } else { i++; numInRegion++; } } /* i isn't in the region. * Verify all elements in the region were used */ if(regLen != numInRegion) { printQ = true; } j = sameEnd; } /* And output the result */ if(printQ && i != inter->end() && j != truth->end()) { printAll = true; results << "Incorrect Result\n"; results << "Expected: " << std::setprecision(20) << expected->intPos << "; Got: " << std::setprecision(20) << i->intPos << "\nDelta: " << std::setprecision(20) << expected->intPos - i->intPos << "\n"; } } if(printAll) { j = truth->begin(); auto i = inter->begin(); do { if(i != inter->end() && j != truth->end() && i->q == j->q) { results << "Correct Order " << i->intPos << " vs " << j->intPos << "\n"; i++; j++; } else { if(i != inter->end()) { results << "FP Quadric: " << i->q << "\nPosition: " << i->intPos << "\n"; i++; } if(j != truth->end()) { results << "MP Quadric: " << j->q << "\nPosition: " << j->intPos << "\n"; j++; } } } while(i != inter->end() || j != truth->end()); } results << "\n"; } template <int dim, typename fptype> void intersectionTest( std::list<Geometry::Quadric<dim, fptype>> &quads, const int numTests) { /* First build a scene of quadrics. * Then generate random lines on a disk centered at the * intersection of the cylinders. * Then sort the intersections * Finally validate them with a higher precision sort */ using Vf = Geometry::Vector<dim, fptype>; using Pf = Geometry::Point<dim, fptype>; using Lf = Geometry::Line<dim, fptype>; using Qm = Geometry::Quadric<dim, mpfr::mpreal>; using Lm = Geometry::Line<dim, mpfr::mpreal>; constexpr const int machPrec = GenericFP::fpconvert<fptype>::precision; constexpr const int truthPrec = 48 * machPrec; mpfr::mpreal::set_default_prec(truthPrec); std::list<Qm> truthQuads; /* Generate the quadrics */ for(auto q : quads) { Qm quadMP(q); truthQuads.push_back(quadMP); } std::random_device rd; std::mt19937_64 engine(rd()); constexpr const fptype maxPos = 10000; std::uniform_real_distribution<fptype> genPos(-maxPos, maxPos); std::uniform_real_distribution<fptype> genDir(-1.0, 1.0); std::ofstream results("results"); Timer::Timer fp_time, mp_time; /* Run the tests */ for(int t = 0; t < numTests; t++) { /* First build the line */ Vf lineDir; Vf lineInt; for(int i = 0; i < dim; i++) { fptype tmp = genPos(engine); lineInt.set(i, tmp); tmp = genDir(engine); lineDir.set(i, tmp); } Lf line(Pf(lineInt), lineDir); Lm truthLine(line); constexpr const fptype eps = 1e-3; /* Then sort the intersections */ fp_time.startTimer(); auto inter = Geometry::sortIntersections(line, quads, eps); fp_time.stopTimer(); mp_time.startTimer(); auto truth = Geometry::sortIntersections<dim, mpfr::mpreal>( truthLine, truthQuads, eps); mp_time.stopTimer(); results << "Test " << t << "\n"; results << "FP Time:\n" << fp_time << "\n"; results << "MP Time:\n" << mp_time << "\n"; validateResults(results, inter, truth); } } int main(int argc, char **argv) { using fptype = float; constexpr const int dim = 3; std::list<Geometry::Quadric<dim, fptype>> quads; if(argc > 1) quads = parseQuadrics<dim, fptype>(argv[1]); else quads = parseQuadrics<dim, fptype>("cylinders.csg"); intersectionTest(quads, 1e5); return 0; } <commit_msg>Added ability to specify the number of tests to run as well as the file to put the results into.<commit_after> #include "geometry.hpp" #include "quadrics.hpp" #include "line.hpp" #include "accurate_intersections.hpp" #include "timer.hpp" #include <list> #include <fstream> #include <iomanip> template <int dim, typename fptype> std::list<Geometry::Quadric<dim, fptype>> parseQuadrics( const char *fname) { std::ifstream file(fname); using Qf = Geometry::Quadric<dim, fptype>; std::list<Qf> quads; while(!file.eof()) { Qf q; file >> q; quads.push_back(q); } return quads; } bool isSameInt(mpfr::mpreal int1, mpfr::mpreal int2) { /* Use a heuristic on truth to determine whether adjacent * intersections occur at the same place. * This will basically be a threshold on the largest * different bit in the mantissa. */ mpfr::mpreal largest = mpfr::max(mpfr::fabs(int1), mpfr::fabs(int2)); mp_exp_t largestExp = largest.get_exp(); mpfr::mpreal diff = mpfr::fabs(int1 - int2); int p1 = int1.getPrecision(), p2 = int2.getPrecision(); int minPrec = std::min(p1, p2); mp_exp_t deltaExp = largestExp - minPrec * 3 / 4 - diff.get_exp(); return deltaExp > 0; } void validateResults(std::ostream &results, auto &inter, auto &truth) { auto j = truth->begin(); bool printAll = false; for(auto i = inter->begin(); i != inter->end() || j != truth->end();) { bool printQ = false; /* First determine the length of the region of equal * intersections. * Then verify there's an equal number of * intersections in the approximately equal range and * that they correspond to the correct intersections. * If not, then print the intersection */ auto expected = j; if(j != truth->end()) { /* Create the region boundaries [sameBeg, sameEnd). * These are intersections which are probably the same */ auto sameBeg = j; auto sameEnd = j; int regLen = 0; while(sameEnd != truth->end() && isSameInt(j->intPos, sameEnd->intPos)) { sameEnd++; regLen++; } /* Increment i until it's not found in the region */ int numInRegion = 0; bool isInRegion = true; while(i != inter->end() && isInRegion && numInRegion < regLen) { j = sameBeg; while(j != sameEnd && i->q != j->q) j++; if(j == sameEnd) { isInRegion = false; } else { i++; numInRegion++; } } /* i isn't in the region. * Verify all elements in the region were used */ if(regLen != numInRegion) { printQ = true; } j = sameEnd; } else { results << "Extra elements in the computed list\n" << "Expected " << truth->size() << " elements, got " << inter->size() << "\n" << "Computed Intersection " << i->intPos << " for " << i->q << "\n"; i++; } /* And output the result */ if(printQ && i != inter->end() && j != truth->end()) { printAll = true; results << "Incorrect Result\n"; results << "Expected: " << std::setprecision(20) << expected->intPos << "; Got: " << std::setprecision(20) << i->intPos << "\nDelta: " << std::setprecision(20) << expected->intPos - i->intPos << "\n"; } } if(printAll) { j = truth->begin(); auto i = inter->begin(); do { if(i != inter->end() && j != truth->end() && i->q == j->q) { results << "Correct Order " << i->intPos << " vs " << j->intPos << "\n"; i++; j++; } else { if(i != inter->end()) { results << "FP Quadric: " << i->q << "\nPosition: " << i->intPos << "\n"; i++; } if(j != truth->end()) { results << "MP Quadric: " << j->q << "\nPosition: " << j->intPos << "\n"; j++; } } } while(i != inter->end() || j != truth->end()); } results << "\n"; } template <int dim, typename fptype> void intersectionTest( std::list<Geometry::Quadric<dim, fptype>> &quads, std::ostream &results, const int numTests) { /* First build a scene of quadrics. * Then generate random lines on a disk centered at the * intersection of the cylinders. * Then sort the intersections * Finally validate them with a higher precision sort */ using Vf = Geometry::Vector<dim, fptype>; using Pf = Geometry::Point<dim, fptype>; using Lf = Geometry::Line<dim, fptype>; using Qm = Geometry::Quadric<dim, mpfr::mpreal>; using Lm = Geometry::Line<dim, mpfr::mpreal>; constexpr const int machPrec = GenericFP::fpconvert<fptype>::precision; constexpr const int truthPrec = 48 * machPrec; mpfr::mpreal::set_default_prec(truthPrec); std::list<Qm> truthQuads; /* Generate the quadrics */ for(auto q : quads) { Qm quadMP(q); truthQuads.push_back(quadMP); } std::random_device rd; std::mt19937_64 engine(rd()); constexpr const fptype maxPos = 10000; std::uniform_real_distribution<fptype> genPos(-maxPos, maxPos); std::uniform_real_distribution<fptype> genDir(-1.0, 1.0); Timer::Timer fp_time, mp_time; /* Run the tests */ for(int t = 0; t < numTests; t++) { /* First build the line */ Vf lineDir; Vf lineInt; for(int i = 0; i < dim; i++) { fptype tmp = genPos(engine); lineInt.set(i, tmp); tmp = genDir(engine); lineDir.set(i, tmp); } Lf line(Pf(lineInt), lineDir); Lm truthLine(line); constexpr const fptype eps = 1e-3; /* Then sort the intersections */ fp_time.startTimer(); auto inter = Geometry::sortIntersections(line, quads, eps); fp_time.stopTimer(); mp_time.startTimer(); auto truth = Geometry::sortIntersections<dim, mpfr::mpreal>( truthLine, truthQuads, eps); mp_time.stopTimer(); results << "Test " << t << "\n"; results << "FP Time:\n" << fp_time << "\n"; results << "MP Time:\n" << mp_time << "\n"; validateResults(results, inter, truth); } } int main(int argc, char **argv) { using fptype = float; constexpr const int dim = 3; std::list<Geometry::Quadric<dim, fptype>> quads; const char *outFName = "results"; int numTests = 1e5; if(argc > 1) { quads = parseQuadrics<dim, fptype>(argv[1]); if(argc > 2) { outFName = argv[2]; if(argc > 3) numTests = atoi(argv[3]); } } else quads = parseQuadrics<dim, fptype>("cylinders.csg"); std::ofstream results(outFName); intersectionTest(quads, results, numTests); return 0; } <|endoftext|>
<commit_before>//Copyright (c) 2020 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "PolylineStitcher.h" namespace cura { }//namespace cura <commit_msg>lil copyright notice<commit_after>//Copyright (c) 2022 Ultimaker B.V. //CuraEngine is released under the terms of the AGPLv3 or higher. #include "PolylineStitcher.h" namespace cura { }//namespace cura <|endoftext|>
<commit_before>// conversion.cpp: step-by-step example of conversion of values to posits // // Copyright (C) 2017-2019 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <universal/posit/posit> // convert a floating point value to a specific posit configuration. Semantically, p = v, return reference to p template<size_t nbits, size_t es, typename Ty> sw::unum::posit<nbits, es> convert_to_posit(Ty rhs) { constexpr size_t fbits = std::numeric_limits<Ty>::digits - 1; using namespace std; using namespace sw::unum; value<fbits> v((Ty)rhs); posit<nbits, es> p; cout << setprecision(numeric_limits<Ty>::digits10) << v << " input value\n"; cout << "Test for ZERO\n"; cout << components(v); if (v.iszero()) { p.setzero(); cout << " input value is zero\n"; cout << info_print(p); return p; } else { cout << " input value is NOT zero\n"; } cout << "Test for NaR\n"; cout << components(v); if (v.isnan() || v.isinf()) { p.setnar(); cout << " input value is NaR\n"; cout << info_print(p); return p; } else { cout << " input value is NOT NaR\n"; } bool _sign = v.sign(); int _scale = v.scale(); sw::unum::bitblock<fbits> fraction_in = v.fraction(); p.clear(); cout << " construct the posit\n"; // interpolation rule checks if (check_inward_projection_range<nbits, es>(_scale)) { // regime dominated // we are projecting to minpos/maxpos int k = calculate_unconstrained_k<nbits, es>(_scale); k < 0 ? p.set(minpos_pattern<nbits, es>(_sign)) : p.set(maxpos_pattern<nbits, es>(_sign)); // we are done std::cout << "projection rounding "; } else { constexpr size_t pt_len = nbits + 3 + es; bitblock<pt_len> pt_bits; bitblock<pt_len> regime; bitblock<pt_len> exponent; bitblock<pt_len> fraction; bitblock<pt_len> sticky_bit; bool s = _sign; int e = _scale; bool r = (e >= 0); unsigned run = (r ? 1 + (e >> es) : -(e >> es)); regime.set(0, 1 ^ r); for (unsigned i = 1; i <= run; i++) regime.set(i, r); unsigned esval = e % (uint32_t(1) << es); exponent = convert_to_bitblock<pt_len>(esval); unsigned nf = (unsigned)std::max<int>(0, (nbits + 1) - (2 + run + es)); // copy the most significant nf fraction bits into fraction unsigned lsb = nf <= fbits ? 0 : nf - fbits; for (unsigned i = lsb; i < nf; i++) fraction[i] = fraction_in[fbits - nf + i]; cout << fraction_in << " full fraction bits\n"; int remaining_bits = fbits - 1 - nf; bool sb = false; if (remaining_bits > 0) { sb = anyAfter(fraction_in, fbits - 1 - nf); bitblock<fbits> sb_mask; for (int i = 0; i < remaining_bits; i++) sb_mask.set(i); cout << sb_mask << " mask of remainder bits\n"; } // construct the untruncated posit cout << pt_bits << " unconstrained posit: length = nbits(" << nbits << ") + es(" << es << ") + 3 guard bits: " << pt_len << "\n"; // pt = BitOr[BitShiftLeft[reg, es + nf + 1], BitShiftLeft[esval, nf + 1], BitShiftLeft[fv, 1], sb]; regime <<= es + nf + 1; cout << regime << " runlength = " << run << endl; exponent <<= nf + 1; cout << exponent << " exponent value = " << hex << esval << dec << endl; fraction <<= 1; cout << fraction << " most significant " << nf << " fraction bits (nbits-1-run-es)\n"; sticky_bit.set(0, sb); if (remaining_bits > 0) { cout << sticky_bit << " sticky bit representing the truncated fraction bits\n"; } else { cout << sticky_bit << " sticky bit representing the fraction bits which are not truncated\n"; } pt_bits |= regime; pt_bits |= exponent; pt_bits |= fraction; pt_bits |= sticky_bit; cout << pt_bits << " unconstrained posit bits "; unsigned len = 1 + std::max<unsigned>((nbits + 1), (2 + run + es)); cout << " length = " << len << endl; bool blast = pt_bits.test(len - nbits); bitblock<pt_len> blast_bb; blast_bb.set(len - nbits); cout << blast_bb << " last bit mask\n"; bool bafter = pt_bits.test(len - nbits - 1); bitblock<pt_len> bafter_bb; bafter_bb.set(len - nbits - 1); cout << bafter_bb << " bit after last bit mask\n"; bool bsticky = anyAfter(pt_bits, len - nbits - 1 - 1); bitblock<pt_len> bsticky_bb; for (int i = len - nbits - 2; i >= 0; --i) bsticky_bb.set(i); cout << bsticky_bb << " sticky bit mask\n"; bool rb = (blast & bafter) | (bafter & bsticky); cout << "rounding decision (blast & bafter) | (bafter & bsticky): " << (rb ? "round up" : "round down") << endl; bitblock<nbits> ptt; pt_bits <<= pt_len - len; cout << pt_bits << " shifted posit\n"; truncate(pt_bits, ptt); cout << ptt << " truncated posit\n"; if (rb) increment_bitset(ptt); cout << ptt << " rounded posit\n"; if (s) ptt = twos_complement(ptt); cout << ptt << " final posit\n"; p.set(ptt); } return p; } int main(int argc, char** argv) try { using namespace std; using namespace sw::unum; constexpr size_t nbits = 16; constexpr size_t es = 1; #define ONE_SAMPLE 1 #if ONE_SAMPLE posit<nbits, es> p(-1.0); --p; float sample = float(p); p = convert_to_posit<nbits, es, float>(sample); cout << color_print(p) << endl; #else float samples[20]; posit<nbits, es> p_one_minus_eps, p_one, p_one_plus_eps; p_one = 1.0; p_one_minus_eps = 1.0; --p_one_minus_eps; p_one_plus_eps = 1.0; ++p_one_plus_eps; posit<nbits, es> p_minpos, p_maxpos(NAR); ++p_minpos; --p_maxpos; samples[0] = 0.0f; samples[1] = float(p_minpos) / 2.0f; samples[2] = float(p_minpos); samples[3] = float(++p_minpos); samples[4] = float(p_one_minus_eps); samples[5] = float(p_one); samples[6] = float(p_one_plus_eps); samples[7] = float(--p_maxpos); samples[8] = float(p_maxpos); samples[9] = float(p_maxpos) * 2.0f; samples[10] = INFINITY; samples[11] = -samples[9]; samples[12] = -samples[8]; samples[13] = -samples[7]; samples[14] = -samples[6]; samples[15] = -1.0f; samples[16] = -samples[4]; samples[17] = -samples[3]; samples[18] = -samples[2]; samples[19] = -samples[1]; posit<nbits, es> p; int i = 0; for (auto sample : samples) { cout << "Sample[" << i++ << "] = " << sample << endl; p = convert_to_posit<nbits,es,float>(sample); cout << "********************************************************************\n"; } #endif return EXIT_SUCCESS; } catch (char const* msg) { std::cerr << msg << std::endl; return EXIT_FAILURE; } catch (...) { std::cerr << "Caught unknown exception" << std::endl; return EXIT_FAILURE; } <commit_msg>adding a new example to conversion educational example<commit_after>// conversion.cpp: step-by-step example of conversion of values to posits // // Copyright (C) 2017-2019 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <universal/posit/posit> // convert a floating point value to a specific posit configuration. Semantically, p = v, return reference to p template<size_t nbits, size_t es, typename Ty> sw::unum::posit<nbits, es> convert_to_posit(Ty rhs) { constexpr size_t fbits = std::numeric_limits<Ty>::digits - 1; using namespace std; using namespace sw::unum; value<fbits> v((Ty)rhs); posit<nbits, es> p; cout << setprecision(numeric_limits<Ty>::digits10) << v << " input value\n"; cout << "Test for ZERO\n"; cout << components(v); if (v.iszero()) { p.setzero(); cout << " input value is zero\n"; cout << info_print(p); return p; } else { cout << " input value is NOT zero\n"; } cout << "Test for NaR\n"; cout << components(v); if (v.isnan() || v.isinf()) { p.setnar(); cout << " input value is NaR\n"; cout << info_print(p); return p; } else { cout << " input value is NOT NaR\n"; } bool _sign = v.sign(); int _scale = v.scale(); sw::unum::bitblock<fbits> fraction_in = v.fraction(); p.clear(); cout << " construct the posit\n"; // interpolation rule checks if (check_inward_projection_range<nbits, es>(_scale)) { // regime dominated // we are projecting to minpos/maxpos int k = calculate_unconstrained_k<nbits, es>(_scale); k < 0 ? p.set(minpos_pattern<nbits, es>(_sign)) : p.set(maxpos_pattern<nbits, es>(_sign)); // we are done std::cout << "projection rounding "; } else { constexpr size_t pt_len = nbits + 3 + es; bitblock<pt_len> pt_bits; bitblock<pt_len> regime; bitblock<pt_len> exponent; bitblock<pt_len> fraction; bitblock<pt_len> sticky_bit; bool s = _sign; int e = _scale; bool r = (e >= 0); unsigned run = (r ? 1 + (e >> es) : -(e >> es)); regime.set(0, 1 ^ r); for (unsigned i = 1; i <= run; i++) regime.set(i, r); unsigned esval = e % (uint32_t(1) << es); exponent = convert_to_bitblock<pt_len>(esval); unsigned nf = (unsigned)std::max<int>(0, (nbits + 1) - (2 + run + es)); // copy the most significant nf fraction bits into fraction unsigned lsb = nf <= fbits ? 0 : nf - fbits; for (unsigned i = lsb; i < nf; i++) fraction[i] = fraction_in[fbits - nf + i]; cout << fraction_in << " full fraction bits\n"; int remaining_bits = fbits - 1 - nf; bool sb = false; if (remaining_bits > 0) { sb = anyAfter(fraction_in, fbits - 1 - nf); bitblock<fbits> sb_mask; for (int i = 0; i < remaining_bits; i++) sb_mask.set(i); cout << sb_mask << " mask of remainder bits\n"; } // construct the untruncated posit cout << pt_bits << " unconstrained posit: length = nbits(" << nbits << ") + es(" << es << ") + 3 guard bits: " << pt_len << "\n"; // pt = BitOr[BitShiftLeft[reg, es + nf + 1], BitShiftLeft[esval, nf + 1], BitShiftLeft[fv, 1], sb]; regime <<= es + nf + 1; cout << regime << " runlength = " << run << endl; exponent <<= nf + 1; cout << exponent << " exponent value = " << hex << esval << dec << endl; fraction <<= 1; cout << fraction << " most significant " << nf << " fraction bits (nbits-1-run-es)\n"; sticky_bit.set(0, sb); if (remaining_bits > 0) { cout << sticky_bit << " sticky bit representing the truncated fraction bits\n"; } else { cout << sticky_bit << " sticky bit representing the fraction bits which are not truncated\n"; } pt_bits |= regime; pt_bits |= exponent; pt_bits |= fraction; pt_bits |= sticky_bit; cout << pt_bits << " unconstrained posit bits "; unsigned len = 1 + std::max<unsigned>((nbits + 1), (2 + run + es)); cout << " length = " << len << endl; bool blast = pt_bits.test(len - nbits); bitblock<pt_len> blast_bb; blast_bb.set(len - nbits); cout << blast_bb << " last bit mask\n"; bool bafter = pt_bits.test(len - nbits - 1); bitblock<pt_len> bafter_bb; bafter_bb.set(len - nbits - 1); cout << bafter_bb << " bit after last bit mask\n"; bool bsticky = anyAfter(pt_bits, len - nbits - 1 - 1); bitblock<pt_len> bsticky_bb; for (int i = len - nbits - 2; i >= 0; --i) bsticky_bb.set(i); cout << bsticky_bb << " sticky bit mask\n"; bool rb = (blast & bafter) | (bafter & bsticky); cout << "rounding decision (blast & bafter) | (bafter & bsticky): " << (rb ? "round up" : "round down") << endl; bitblock<nbits> ptt; pt_bits <<= pt_len - len; cout << pt_bits << " shifted posit\n"; truncate(pt_bits, ptt); cout << ptt << " truncated posit\n"; if (rb) increment_bitset(ptt); cout << ptt << " rounded posit\n"; if (s) ptt = twos_complement(ptt); cout << ptt << " final posit\n"; p.set(ptt); } return p; } int main(int argc, char** argv) try { using namespace std; using namespace sw::unum; constexpr size_t nbits = 16; constexpr size_t es = 1; #define ONE_SAMPLE 1 #if ONE_SAMPLE { posit<nbits, es> p(-1.0); --p; float sample = float(p); p = convert_to_posit<nbits, es, float>(sample); cout << color_print(p) << endl; cout << hex_format(p) << endl; cout << p << endl; } { cout << "Tracing conversion algorithm\n"; long long sample = 1614591918; posit<32, 2> p(sample); posit<32, 2> pp(p); cout << "long : " << sample << " posit : " << hex_format(p) << " rounded : " << (long long)p << endl; p = convert_to_posit<32, 2, long long>(sample); cout << color_print(p) << endl; cout << hex_format(p) << endl; cout << p << endl; } #else float samples[20]; posit<nbits, es> p_one_minus_eps, p_one, p_one_plus_eps; p_one = 1.0; p_one_minus_eps = 1.0; --p_one_minus_eps; p_one_plus_eps = 1.0; ++p_one_plus_eps; posit<nbits, es> p_minpos, p_maxpos(NAR); ++p_minpos; --p_maxpos; samples[0] = 0.0f; samples[1] = float(p_minpos) / 2.0f; samples[2] = float(p_minpos); samples[3] = float(++p_minpos); samples[4] = float(p_one_minus_eps); samples[5] = float(p_one); samples[6] = float(p_one_plus_eps); samples[7] = float(--p_maxpos); samples[8] = float(p_maxpos); samples[9] = float(p_maxpos) * 2.0f; samples[10] = INFINITY; samples[11] = -samples[9]; samples[12] = -samples[8]; samples[13] = -samples[7]; samples[14] = -samples[6]; samples[15] = -1.0f; samples[16] = -samples[4]; samples[17] = -samples[3]; samples[18] = -samples[2]; samples[19] = -samples[1]; posit<nbits, es> p; int i = 0; for (auto sample : samples) { cout << "Sample[" << i++ << "] = " << sample << endl; p = convert_to_posit<nbits,es,float>(sample); cout << "********************************************************************\n"; } #endif return EXIT_SUCCESS; } catch (char const* msg) { std::cerr << msg << std::endl; return EXIT_FAILURE; } catch (...) { std::cerr << "Caught unknown exception" << std::endl; return EXIT_FAILURE; } <|endoftext|>
<commit_before>/** * @file action_test.cpp * @copyright defined in eos/LICENSE.txt */ #include <eosiolib/action.hpp> #include <eosiolib/transaction.hpp> #include <eosiolib/chain.h> #include <eosiolib/db.h> #include <eosiolib/crypto.h> #include <eosiolib/privileged.h> #include <eosiolib/eosio.hpp> #include <eosiolib/datastream.hpp> #include <eosiolib/print.hpp> #include <eosiolib/compiler_builtins.h> #include "test_api.hpp" void test_action::read_action_normal() { char buffer[100]; uint32_t total = 0; eosio_assert(action_data_size() == sizeof(dummy_action), "action_size() == sizeof(dummy_action)"); total = read_action_data(buffer, 30); eosio_assert(total == sizeof(dummy_action) , "read_action(30)" ); total = read_action_data(buffer, 100); eosio_assert(total == sizeof(dummy_action) , "read_action(100)" ); total = read_action_data(buffer, 5); eosio_assert(total == 5 , "read_action(5)" ); total = read_action_data(buffer, sizeof(dummy_action) ); eosio_assert(total == sizeof(dummy_action), "read_action(sizeof(dummy_action))" ); dummy_action *dummy13 = reinterpret_cast<dummy_action *>(buffer); eosio_assert(dummy13->a == DUMMY_ACTION_DEFAULT_A, "dummy13->a == DUMMY_ACTION_DEFAULT_A"); eosio_assert(dummy13->b == DUMMY_ACTION_DEFAULT_B, "dummy13->b == DUMMY_ACTION_DEFAULT_B"); eosio_assert(dummy13->c == DUMMY_ACTION_DEFAULT_C, "dummy13->c == DUMMY_ACTION_DEFAULT_C"); } void test_action::test_dummy_action() { char buffer[100]; int total = 0; // get_action total = get_action( 1, 0, buffer, 0 ); total = get_action( 1, 0, buffer, static_cast<size_t>(total) ); eosio_assert( total > 0, "get_action failed" ); eosio::action act = eosio::get_action( 1, 0 ); eosio_assert( eosio::pack_size(act) == static_cast<size_t>(total), "pack_size does not match get_action size" ); eosio_assert( act.account == N(testapi), "expected testapi account" ); dummy_action dum13 = act.data_as<dummy_action>(); if ( dum13.b == 200 ) { // attempt to access context free only api get_context_free_data( 0, nullptr, 0 ); eosio_assert(false, "get_context_free_data() not allowed in non-context free action"); } else { eosio_assert(dum13.a == DUMMY_ACTION_DEFAULT_A, "dum13.a == DUMMY_ACTION_DEFAULT_A"); eosio_assert(dum13.b == DUMMY_ACTION_DEFAULT_B, "dum13.b == DUMMY_ACTION_DEFAULT_B"); eosio_assert(dum13.c == DUMMY_ACTION_DEFAULT_C, "dum13.c == DUMMY_ACTION_DEFAULT_C"); } } void test_action::read_action_to_0() { read_action_data((void *)0, action_data_size()); } void test_action::read_action_to_64k() { read_action_data( (void *)((1<<16)-2), action_data_size()); } void test_action::test_cf_action() { eosio::action act = eosio::get_action( 0, 0 ); cf_action cfa = act.data_as<cf_action>(); if ( cfa.payload == 100 ) { // verify read of get_context_free_data, also verifies system api access int size = get_context_free_data( cfa.cfd_idx, nullptr, 0 ); eosio_assert( size > 0, "size determination failed" ); eosio::bytes cfd( static_cast<size_t>(size) ); size = get_context_free_data( cfa.cfd_idx, &cfd[0], static_cast<size_t>(size) ); eosio_assert(static_cast<size_t>(size) == cfd.size(), "get_context_free_data failed" ); uint32_t v = eosio::unpack<uint32_t>( &cfd[0], cfd.size() ); eosio_assert( v == cfa.payload, "invalid value" ); // verify crypto api access checksum256 hash; char test[] = "test"; sha256( test, sizeof(test), &hash ); assert_sha256( test, sizeof(test), &hash ); // verify action api access action_data_size(); // verify console api access eosio::print("test\n"); // verify memory api access uint32_t i = 42; memccpy(&v, &i, sizeof(i), sizeof(i)); // verify transaction api access eosio_assert(transaction_size() > 0, "transaction_size failed"); } else if ( cfa.payload == 200 ) { // attempt to access non context free api, privileged_api is_privileged(act.name); eosio_assert( false, "privileged_api should not be allowed" ); } else if ( cfa.payload == 201 ) { // attempt to access non context free api, producer_api get_active_producers( nullptr, 0 ); eosio_assert( false, "producer_api should not be allowed" ); } else if ( cfa.payload == 202 ) { // attempt to access non context free api, db_api db_store_i64( N(testapi), N(testapi), N(testapi), 0, "test", 4 ); eosio_assert( false, "db_api should not be allowed" ); } else if ( cfa.payload == 203 ) { // attempt to access non context free api, db_api uint64_t i = 0; db_idx64_store( N(testapi), N(testapi), N(testapi), 0, &i ); eosio_assert( false, "db_api should not be allowed" ); } else if ( cfa.payload == 204 ) { // attempt to access non context free api, send action eosio::action dum_act; dum_act.send(); eosio_assert( false, "action send should not be allowed" ); } } void test_action::require_notice(uint64_t receiver, uint64_t code, uint64_t action) { (void)code;(void)action; if( receiver == N(testapi) ) { eosio::require_recipient( N(acc1) ); eosio::require_recipient( N(acc2) ); eosio::require_recipient( N(acc1), N(acc2) ); eosio_assert(false, "Should've failed"); } else if ( receiver == N(acc1) || receiver == N(acc2) ) { return; } eosio_assert(false, "Should've failed"); } void test_action::require_auth() { prints("require_auth"); eosio::require_auth( N(acc3) ); eosio::require_auth( N(acc4) ); } void test_action::assert_false() { eosio_assert(false, "test_action::assert_false"); } void test_action::assert_true() { eosio_assert(true, "test_action::assert_true"); } void test_action::assert_true_cf() { eosio_assert(true, "test_action::assert_true"); } void test_action::test_abort() { abort(); eosio_assert( false, "should've aborted" ); } void test_action::test_publication_time() { uint32_t pub_time = 0; read_action_data(&pub_time, sizeof(uint32_t)); eosio_assert( pub_time == publication_time(), "pub_time == publication_time()" ); } void test_action::test_current_receiver(uint64_t receiver, uint64_t code, uint64_t action) { (void)code;(void)action; account_name cur_rec; read_action_data(&cur_rec, sizeof(account_name)); eosio_assert( receiver == cur_rec, "the current receiver does not match" ); } void test_action::test_current_sender() { account_name cur_send; read_action_data(&cur_send, sizeof(account_name)); eosio_assert( current_sender() == cur_send, "the current sender does not match" ); } void test_action::now() { uint32_t tmp = 0; uint32_t total = read_action_data(&tmp, sizeof(uint32_t)); eosio_assert( total == sizeof(uint32_t), "total == sizeof(uint32_t)"); eosio_assert( tmp == ::now(), "tmp == now()" ); } <commit_msg>Add additional assert to verify permission<commit_after>/** * @file action_test.cpp * @copyright defined in eos/LICENSE.txt */ #include <eosiolib/action.hpp> #include <eosiolib/transaction.hpp> #include <eosiolib/chain.h> #include <eosiolib/db.h> #include <eosiolib/crypto.h> #include <eosiolib/privileged.h> #include <eosiolib/eosio.hpp> #include <eosiolib/datastream.hpp> #include <eosiolib/print.hpp> #include <eosiolib/compiler_builtins.h> #include "test_api.hpp" void test_action::read_action_normal() { char buffer[100]; uint32_t total = 0; eosio_assert(action_data_size() == sizeof(dummy_action), "action_size() == sizeof(dummy_action)"); total = read_action_data(buffer, 30); eosio_assert(total == sizeof(dummy_action) , "read_action(30)" ); total = read_action_data(buffer, 100); eosio_assert(total == sizeof(dummy_action) , "read_action(100)" ); total = read_action_data(buffer, 5); eosio_assert(total == 5 , "read_action(5)" ); total = read_action_data(buffer, sizeof(dummy_action) ); eosio_assert(total == sizeof(dummy_action), "read_action(sizeof(dummy_action))" ); dummy_action *dummy13 = reinterpret_cast<dummy_action *>(buffer); eosio_assert(dummy13->a == DUMMY_ACTION_DEFAULT_A, "dummy13->a == DUMMY_ACTION_DEFAULT_A"); eosio_assert(dummy13->b == DUMMY_ACTION_DEFAULT_B, "dummy13->b == DUMMY_ACTION_DEFAULT_B"); eosio_assert(dummy13->c == DUMMY_ACTION_DEFAULT_C, "dummy13->c == DUMMY_ACTION_DEFAULT_C"); } void test_action::test_dummy_action() { char buffer[100]; int total = 0; // get_action total = get_action( 1, 0, buffer, 0 ); total = get_action( 1, 0, buffer, static_cast<size_t>(total) ); eosio_assert( total > 0, "get_action failed" ); eosio::action act = eosio::get_action( 1, 0 ); eosio_assert( act.authorization.back().actor == N(testapi), "incorrect permission actor" ); eosio_assert( act.authorization.back().permission == N(active), "incorrect permission name" ); eosio_assert( eosio::pack_size(act) == static_cast<size_t>(total), "pack_size does not match get_action size" ); eosio_assert( act.account == N(testapi), "expected testapi account" ); dummy_action dum13 = act.data_as<dummy_action>(); if ( dum13.b == 200 ) { // attempt to access context free only api get_context_free_data( 0, nullptr, 0 ); eosio_assert(false, "get_context_free_data() not allowed in non-context free action"); } else { eosio_assert(dum13.a == DUMMY_ACTION_DEFAULT_A, "dum13.a == DUMMY_ACTION_DEFAULT_A"); eosio_assert(dum13.b == DUMMY_ACTION_DEFAULT_B, "dum13.b == DUMMY_ACTION_DEFAULT_B"); eosio_assert(dum13.c == DUMMY_ACTION_DEFAULT_C, "dum13.c == DUMMY_ACTION_DEFAULT_C"); } } void test_action::read_action_to_0() { read_action_data((void *)0, action_data_size()); } void test_action::read_action_to_64k() { read_action_data( (void *)((1<<16)-2), action_data_size()); } void test_action::test_cf_action() { eosio::action act = eosio::get_action( 0, 0 ); cf_action cfa = act.data_as<cf_action>(); if ( cfa.payload == 100 ) { // verify read of get_context_free_data, also verifies system api access int size = get_context_free_data( cfa.cfd_idx, nullptr, 0 ); eosio_assert( size > 0, "size determination failed" ); eosio::bytes cfd( static_cast<size_t>(size) ); size = get_context_free_data( cfa.cfd_idx, &cfd[0], static_cast<size_t>(size) ); eosio_assert(static_cast<size_t>(size) == cfd.size(), "get_context_free_data failed" ); uint32_t v = eosio::unpack<uint32_t>( &cfd[0], cfd.size() ); eosio_assert( v == cfa.payload, "invalid value" ); // verify crypto api access checksum256 hash; char test[] = "test"; sha256( test, sizeof(test), &hash ); assert_sha256( test, sizeof(test), &hash ); // verify action api access action_data_size(); // verify console api access eosio::print("test\n"); // verify memory api access uint32_t i = 42; memccpy(&v, &i, sizeof(i), sizeof(i)); // verify transaction api access eosio_assert(transaction_size() > 0, "transaction_size failed"); } else if ( cfa.payload == 200 ) { // attempt to access non context free api, privileged_api is_privileged(act.name); eosio_assert( false, "privileged_api should not be allowed" ); } else if ( cfa.payload == 201 ) { // attempt to access non context free api, producer_api get_active_producers( nullptr, 0 ); eosio_assert( false, "producer_api should not be allowed" ); } else if ( cfa.payload == 202 ) { // attempt to access non context free api, db_api db_store_i64( N(testapi), N(testapi), N(testapi), 0, "test", 4 ); eosio_assert( false, "db_api should not be allowed" ); } else if ( cfa.payload == 203 ) { // attempt to access non context free api, db_api uint64_t i = 0; db_idx64_store( N(testapi), N(testapi), N(testapi), 0, &i ); eosio_assert( false, "db_api should not be allowed" ); } else if ( cfa.payload == 204 ) { // attempt to access non context free api, send action eosio::action dum_act; dum_act.send(); eosio_assert( false, "action send should not be allowed" ); } } void test_action::require_notice(uint64_t receiver, uint64_t code, uint64_t action) { (void)code;(void)action; if( receiver == N(testapi) ) { eosio::require_recipient( N(acc1) ); eosio::require_recipient( N(acc2) ); eosio::require_recipient( N(acc1), N(acc2) ); eosio_assert(false, "Should've failed"); } else if ( receiver == N(acc1) || receiver == N(acc2) ) { return; } eosio_assert(false, "Should've failed"); } void test_action::require_auth() { prints("require_auth"); eosio::require_auth( N(acc3) ); eosio::require_auth( N(acc4) ); } void test_action::assert_false() { eosio_assert(false, "test_action::assert_false"); } void test_action::assert_true() { eosio_assert(true, "test_action::assert_true"); } void test_action::assert_true_cf() { eosio_assert(true, "test_action::assert_true"); } void test_action::test_abort() { abort(); eosio_assert( false, "should've aborted" ); } void test_action::test_publication_time() { uint32_t pub_time = 0; read_action_data(&pub_time, sizeof(uint32_t)); eosio_assert( pub_time == publication_time(), "pub_time == publication_time()" ); } void test_action::test_current_receiver(uint64_t receiver, uint64_t code, uint64_t action) { (void)code;(void)action; account_name cur_rec; read_action_data(&cur_rec, sizeof(account_name)); eosio_assert( receiver == cur_rec, "the current receiver does not match" ); } void test_action::test_current_sender() { account_name cur_send; read_action_data(&cur_send, sizeof(account_name)); eosio_assert( current_sender() == cur_send, "the current sender does not match" ); } void test_action::now() { uint32_t tmp = 0; uint32_t total = read_action_data(&tmp, sizeof(uint32_t)); eosio_assert( total == sizeof(uint32_t), "total == sizeof(uint32_t)"); eosio_assert( tmp == ::now(), "tmp == now()" ); } <|endoftext|>
<commit_before>#include <QNote.h> #include <ui_QNote.h> #include <fileviewmodel.h> #include <cassert> #include <QFileDialog> #include <QFile> #include <QMessageBox> #include <QTextStream> #include <QListWidget> #include <QtPrintSupport> #include <QListView> #include <QDebug> #include <QLabel> #include <QBuffer> QNote::QNote(QWidget *parent) : QMainWindow(parent), ui(new Ui::QNote) { ui->setupUi(this); } QNote::~QNote() { delete ui; } void QNote::setup() { readConfig(); QStringList files = parentDir.entryList(QDir::AllEntries | QDir::NoDotAndDotDot); fileModel = new FileViewModel(files, 0); ui->listView->setModel(fileModel); } void QNote::readConfig() { QFile configFile(QDir::homePath() + QDir::separator() + ".notetakinginfo"); if (!configFile.exists()) { QMessageBox::warning(this, tr("No default directory found"), tr("Please choose a default directory")); QString working_dir_name = QFileDialog::getExistingDirectory(this, tr("Default directory"), QDir::homePath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (!working_dir_name.isEmpty()) parentDir = QDir(working_dir_name); else readConfig(); writeToFile(configFile, working_dir_name + "\n"); } else { checkedOpenFile(configFile, QIODevice::ReadOnly); QTextStream in(&configFile); parentDir = QDir(in.readLine()); configFile.close(); } } bool QNote::saveFile(QFile& file) { return writeToFile(file, ui->mainTextEdit->toPlainText()); } void QNote::on_actionNew_triggered() { QString fileName = QFileDialog::getSaveFileName(this, tr("New File"), parentDir.absolutePath(), tr("All Files (*);;Text Files (*.txt);;RTF Files(*.rtf);;C++ Files (*.cpp *.h)")); if (fileName.isEmpty()) return; currentFileName = fileName; ui->mainTextEdit->clear(); QFile file(currentFileName); saveFile(file); QFileInfo fileInfo(file); QString localFileName(fileInfo.fileName()); fileModel->addFile(localFileName); } void QNote::on_actionOpen_triggered() { // TODO: As soon as we implement a file sys watcher, look for unsaved changes, // and prompt the user here instead of saving all the time // saveFile(currentFileName); QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), parentDir.absolutePath(), tr("All Files (*);;Text Files (*.txt);;RTF Files(*.rtf);;C++ Files (*.cpp *.h)")); if (!fileName.isEmpty()) { if(fileName.contains(".o", Qt::CaseInsensitive)) { QMessageBox::critical(this, tr("Error"), tr("Can not open this file format yet")); return; } updateListViewSelection(fileName); QFile file(fileName); QFileInfo fileInfo(file); currentFileName = file.fileName(); QString simpleFileName = fileInfo.fileName(); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(this, tr("Error"), tr("Could not open file")); return; } QTextStream in(&file); ui->mainTextEdit->setText(in.readAll()); file.close(); QTextStream titleIn(&simpleFileName); ui->titleEdit->setText(titleIn.readAll()); } } void QNote::on_actionSave_triggered() { QFile file(currentFileName); saveFile(file); updateDate(); } void QNote::on_actionSaveAs_triggered() { QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), parentDir.absolutePath(), tr("Text Files (*.txt);;C++ Files (*.cpp *.h)")); QFile file(fileName); saveFile(file); } // Called when the "Print" option is triggered by C-p or menu void QNote::on_actionPrint_triggered() { // QPrinter printer; // QPrintDialog dialog(&printer, this); // dialog.setWindowTitle(tr("Print Document")); // if (dialog.exec() != QDialog::Accepted) { // return; // } } // Called when the "Exit" option is triggered by C-q or menu void QNote::on_actionExit_triggered() { // TODO need to check if there are any unsaved buffers qApp->quit(); } // Triggered when the mainTextEdit region has its text changed // TODO figure out how frequently this method is called void QNote::on_mainTextEdit_textChanged() { // Save the current buffer QFile file(currentFileName); qDebug() << ui->mainTextEdit->toPlainText(); //saveFile(file); } void QNote::on_listView_clicked(const QModelIndex &index) { // Same as the comment in the New-slot, should only save when changes have been made // saveFile(currentFileName); QString fileName = parentDir.absoluteFilePath(fileModel->data(index).toString()); if (!fileName.isEmpty()) { QFile file(fileName); if(fileName.contains(".o", Qt::CaseInsensitive)) { QMessageBox::critical(this, tr("Error"), tr("Could not open this file format yet")); return; } QFileInfo fileInfo(file); QString simpleFileName = fileInfo.fileName(); currentFileName = file.fileName(); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(this, tr("Error"), tr("Could not open file")); return; } QTextStream in(&file); ui->mainTextEdit->setText(in.readAll()); file.close(); QTextStream titleIn(&simpleFileName); ui->titleEdit->setText(titleIn.readAll()); updateDate(); } } // Called as a simple about section void QNote::on_actionAbout_triggered() { QString abouttext = tr("<h1>Notetaking</h1>"); abouttext.append(tr("<p><b>Easy - Intuitive -Anywhere</b></p>")); abouttext.append(tr("<p><a href=\"http://qt-project.org/\">QT: </a>")); abouttext.append(tr("editor of Notetaking</p>")); abouttext.append(tr("<p>Project page: <a href=\"https://github.com/pybae/notetaking\">source</a></p>")); abouttext.append(tr("<p>Awesome Devs: <br/><br/> Paul Bae<br/>")); abouttext.append(tr("Tianyu Cheng<br/>")); abouttext.append(tr("Kim Yu Ng<br/>")); abouttext.append(tr("Pikachu</p>")); abouttext.append(tr("<p>This software is released under the " "<a href=\"http://opensource.org/licenses/MIT\"" \ ">MIT License</a></p>")); QMessageBox::about(this, tr("About us"), abouttext); } // renames the current file when enter is pressed in the title void QNote::on_titleEdit_returnPressed() { if(!currentFileName.isEmpty()) { // rename the file QFile file(currentFileName); QFileInfo fileInfo(file); QString path = parentDir.absolutePath() + QDir::separator(); QString newFileName = path + ui->titleEdit->displayText(); QFile newFile(newFileName); QFileInfo newFileInfo(newFile); QModelIndex newIndex = fileModel->indexOf(newFileInfo.fileName()); if (newIndex.isValid()) { // new file name already exists QMessageBox::critical(this, tr("Error"), tr("File already exists")); return; } file.rename(newFileName); QModelIndex index = fileModel->indexOf(fileInfo.fileName()); fileModel->setData(index, newFileInfo.fileName(), Qt::EditRole); currentFileName = newFileName; updateDate(); } } // Simple function to update the date void QNote::updateDate() { QFile file(currentFileName); QFileInfo fileInfo(file); QDateTime dateTime = fileInfo.lastModified(); ui->dateLabel->setText(dateTime.toString("dddd, MMM d, h:mm A")); return; } // Function to update the listView selection void QNote::updateListViewSelection(QString fileName) { QFile file(fileName); QFileInfo fileInfo(file); QDir fileDir = fileInfo.absoluteDir(); if (parentDir == fileDir) { QModelIndex index = fileModel->indexOf(fileInfo.fileName()); if (index.isValid()) ui->listView->setCurrentIndex(index); } else qDebug("Not in working directory, can't show in list view yet (not implemented)!"); } // Function to write the provided data to the file bool QNote::writeToFile(QFile& file, QString data) { if (!checkedOpenFile(file, QIODevice::WriteOnly)) return false; QTextStream stream(&file); stream << data; stream.flush(); file.close(); return true; } // Opens and returns whether the operation was successful bool QNote::checkedOpenFile(QFile& file, QIODevice::OpenMode mode) { if (!file.open(mode)) { QMessageBox::critical(this, tr("Error"), tr("Could not open file")); return false; } return true; } <commit_msg>including hunspells<commit_after>#include <QNote.h> #include <ui_QNote.h> #include <fileviewmodel.h> #include <cassert> #include <QFileDialog> #include <QFile> #include <QMessageBox> #include <QTextStream> #include <QListWidget> #include <QtPrintSupport> #include <QListView> #include <QDebug> #include <QLabel> #include <QBuffer> #include "/usr/local/include/hunspell/hunspell.hxx" QNote::QNote(QWidget *parent) : QMainWindow(parent), ui(new Ui::QNote) { ui->setupUi(this); } QNote::~QNote() { delete ui; } void QNote::setup() { readConfig(); QStringList files = parentDir.entryList(QDir::AllEntries | QDir::NoDotAndDotDot); fileModel = new FileViewModel(files, 0); ui->listView->setModel(fileModel); } void QNote::readConfig() { QFile configFile(QDir::homePath() + QDir::separator() + ".notetakinginfo"); if (!configFile.exists()) { QMessageBox::warning(this, tr("No default directory found"), tr("Please choose a default directory")); QString working_dir_name = QFileDialog::getExistingDirectory(this, tr("Default directory"), QDir::homePath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (!working_dir_name.isEmpty()) parentDir = QDir(working_dir_name); else readConfig(); writeToFile(configFile, working_dir_name + "\n"); } else { checkedOpenFile(configFile, QIODevice::ReadOnly); QTextStream in(&configFile); parentDir = QDir(in.readLine()); configFile.close(); } } bool QNote::saveFile(QFile& file) { return writeToFile(file, ui->mainTextEdit->toPlainText()); } void QNote::on_actionNew_triggered() { QString fileName = QFileDialog::getSaveFileName(this, tr("New File"), parentDir.absolutePath(), tr("All Files (*);;Text Files (*.txt);;RTF Files(*.rtf);;C++ Files (*.cpp *.h)")); if (fileName.isEmpty()) return; currentFileName = fileName; ui->mainTextEdit->clear(); QFile file(currentFileName); saveFile(file); QFileInfo fileInfo(file); QString localFileName(fileInfo.fileName()); fileModel->addFile(localFileName); } void QNote::on_actionOpen_triggered() { // TODO: As soon as we implement a file sys watcher, look for unsaved changes, // and prompt the user here instead of saving all the time // saveFile(currentFileName); QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), parentDir.absolutePath(), tr("All Files (*);;Text Files (*.txt);;RTF Files(*.rtf);;C++ Files (*.cpp *.h)")); if (!fileName.isEmpty()) { if(fileName.contains(".o", Qt::CaseInsensitive)) { QMessageBox::critical(this, tr("Error"), tr("Can not open this file format yet")); return; } updateListViewSelection(fileName); QFile file(fileName); QFileInfo fileInfo(file); currentFileName = file.fileName(); QString simpleFileName = fileInfo.fileName(); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(this, tr("Error"), tr("Could not open file")); return; } QTextStream in(&file); ui->mainTextEdit->setText(in.readAll()); file.close(); QTextStream titleIn(&simpleFileName); ui->titleEdit->setText(titleIn.readAll()); } } void QNote::on_actionSave_triggered() { QFile file(currentFileName); saveFile(file); updateDate(); } void QNote::on_actionSaveAs_triggered() { QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), parentDir.absolutePath(), tr("Text Files (*.txt);;C++ Files (*.cpp *.h)")); QFile file(fileName); saveFile(file); } // Called when the "Print" option is triggered by C-p or menu void QNote::on_actionPrint_triggered() { // QPrinter printer; // QPrintDialog dialog(&printer, this); // dialog.setWindowTitle(tr("Print Document")); // if (dialog.exec() != QDialog::Accepted) { // return; // } } // Called when the "Exit" option is triggered by C-q or menu void QNote::on_actionExit_triggered() { // TODO need to check if there are any unsaved buffers qApp->quit(); } // Triggered when the mainTextEdit region has its text changed // TODO figure out how frequently this method is called void QNote::on_mainTextEdit_textChanged() { // Save the current buffer QFile file(currentFileName); qDebug() << ui->mainTextEdit->toPlainText(); //saveFile(file); } void QNote::on_listView_clicked(const QModelIndex &index) { // Same as the comment in the New-slot, should only save when changes have been made // saveFile(currentFileName); QString fileName = parentDir.absoluteFilePath(fileModel->data(index).toString()); if (!fileName.isEmpty()) { QFile file(fileName); if(fileName.contains(".o", Qt::CaseInsensitive)) { QMessageBox::critical(this, tr("Error"), tr("Could not open this file format yet")); return; } QFileInfo fileInfo(file); QString simpleFileName = fileInfo.fileName(); currentFileName = file.fileName(); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::critical(this, tr("Error"), tr("Could not open file")); return; } QTextStream in(&file); ui->mainTextEdit->setText(in.readAll()); file.close(); QTextStream titleIn(&simpleFileName); ui->titleEdit->setText(titleIn.readAll()); updateDate(); } } // Called as a simple about section void QNote::on_actionAbout_triggered() { QString abouttext = tr("<h1>Notetaking</h1>"); abouttext.append(tr("<p><b>Easy - Intuitive -Anywhere</b></p>")); abouttext.append(tr("<p><a href=\"http://qt-project.org/\">QT: </a>")); abouttext.append(tr("editor of Notetaking</p>")); abouttext.append(tr("<p>Project page: <a href=\"https://github.com/pybae/notetaking\">source</a></p>")); abouttext.append(tr("<p>Awesome Devs: <br/><br/> Paul Bae<br/>")); abouttext.append(tr("Tianyu Cheng<br/>")); abouttext.append(tr("Kim Yu Ng<br/>")); abouttext.append(tr("Pikachu</p>")); abouttext.append(tr("<p>This software is released under the " "<a href=\"http://opensource.org/licenses/MIT\"" \ ">MIT License</a></p>")); QMessageBox::about(this, tr("About us"), abouttext); } // renames the current file when enter is pressed in the title void QNote::on_titleEdit_returnPressed() { if(!currentFileName.isEmpty()) { // rename the file QFile file(currentFileName); QFileInfo fileInfo(file); QString path = parentDir.absolutePath() + QDir::separator(); QString newFileName = path + ui->titleEdit->displayText(); QFile newFile(newFileName); QFileInfo newFileInfo(newFile); QModelIndex newIndex = fileModel->indexOf(newFileInfo.fileName()); if (newIndex.isValid()) { // new file name already exists QMessageBox::critical(this, tr("Error"), tr("File already exists")); return; } file.rename(newFileName); QModelIndex index = fileModel->indexOf(fileInfo.fileName()); fileModel->setData(index, newFileInfo.fileName(), Qt::EditRole); currentFileName = newFileName; updateDate(); } } // Simple function to update the date void QNote::updateDate() { QFile file(currentFileName); QFileInfo fileInfo(file); QDateTime dateTime = fileInfo.lastModified(); ui->dateLabel->setText(dateTime.toString("dddd, MMM d, h:mm A")); return; } // Function to update the listView selection void QNote::updateListViewSelection(QString fileName) { QFile file(fileName); QFileInfo fileInfo(file); QDir fileDir = fileInfo.absoluteDir(); if (parentDir == fileDir) { QModelIndex index = fileModel->indexOf(fileInfo.fileName()); if (index.isValid()) ui->listView->setCurrentIndex(index); } else qDebug("Not in working directory, can't show in list view yet (not implemented)!"); } // Function to write the provided data to the file bool QNote::writeToFile(QFile& file, QString data) { if (!checkedOpenFile(file, QIODevice::WriteOnly)) return false; QTextStream stream(&file); stream << data; stream.flush(); file.close(); return true; } // Opens and returns whether the operation was successful bool QNote::checkedOpenFile(QFile& file, QIODevice::OpenMode mode) { if (!file.open(mode)) { QMessageBox::critical(this, tr("Error"), tr("Could not open file")); return false; } return true; } <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "ActiveObjects.h" #include "ModuleManager.h" #include "Pipeline.h" #include "Utilities.h" #include <pqActiveObjects.h> #include <pqApplicationCore.h> #include <pqObjectBuilder.h> #include <pqPipelineSource.h> #include <pqRenderView.h> #include <pqServer.h> #include <pqView.h> #include <vtkNew.h> #include <vtkSMProxyIterator.h> #include <vtkSMRenderViewProxy.h> #include <vtkSMSourceProxy.h> #include <vtkSMViewProxy.h> #include <functional> namespace tomviz { ActiveObjects::ActiveObjects() : QObject() { connect(&pqActiveObjects::instance(), SIGNAL(viewChanged(pqView*)), SLOT(viewChanged(pqView*))); connect(&ModuleManager::instance(), SIGNAL(dataSourceRemoved(DataSource*)), SLOT(dataSourceRemoved(DataSource*))); connect(&ModuleManager::instance(), SIGNAL(moduleRemoved(Module*)), SLOT(moduleRemoved(Module*))); } ActiveObjects::~ActiveObjects() = default; ActiveObjects& ActiveObjects::instance() { static ActiveObjects theInstance; return theInstance; } void ActiveObjects::setActiveView(vtkSMViewProxy* view) { pqActiveObjects::instance().setActiveView(tomviz::convert<pqView*>(view)); } vtkSMViewProxy* ActiveObjects::activeView() const { pqView* view = activePqView(); return view ? view->getViewProxy() : nullptr; } pqView* ActiveObjects::activePqView() const { return pqActiveObjects::instance().activeView(); } pqRenderView* ActiveObjects::activePqRenderView() const { return qobject_cast<pqRenderView*>(activePqView()); } void ActiveObjects::viewChanged(pqView* view) { emit viewChanged(view ? view->getViewProxy() : nullptr); } void ActiveObjects::dataSourceRemoved(DataSource* ds) { if (m_activeDataSource == ds) { setActiveDataSource(nullptr); } } void ActiveObjects::moduleRemoved(Module* mdl) { if (m_activeModule == mdl) { setActiveModule(nullptr); } } void ActiveObjects::setActiveDataSource(DataSource* source) { if (m_activeDataSource != source) { if (m_activeDataSource) { disconnect(m_activeDataSource, SIGNAL(dataChanged()), this, SLOT(dataSourceChanged())); } if (source) { connect(source, SIGNAL(dataChanged()), this, SLOT(dataSourceChanged())); m_activeDataSourceType = source->type(); } m_activeDataSource = source; emit dataSourceChanged(m_activeDataSource); // Setting to nullptr so the traverse logic is re-run. m_activeParentDataSource = nullptr; } emit dataSourceActivated(m_activeDataSource); if (!m_activeDataSource.isNull() && m_activeDataSource->pipeline() != nullptr) { setActiveTransformedDataSource( m_activeDataSource->pipeline()->transformedDataSource()); } } void ActiveObjects::setSelectedDataSource(DataSource* source) { m_selectedDataSource = source; if (!m_selectedDataSource.isNull()) { setActiveDataSource(m_selectedDataSource); } } void ActiveObjects::setActiveTransformedDataSource(DataSource* source) { if (m_activeTransformedDataSource != source) { m_activeTransformedDataSource = source; } emit transformedDataSourceActivated(m_activeTransformedDataSource); } void ActiveObjects::dataSourceChanged() { if (m_activeDataSource->type() != m_activeDataSourceType) { m_activeDataSourceType = m_activeDataSource->type(); emit dataSourceChanged(m_activeDataSource); } } vtkSMSessionProxyManager* ActiveObjects::proxyManager() const { pqServer* server = pqActiveObjects::instance().activeServer(); return server ? server->proxyManager() : nullptr; } void ActiveObjects::setActiveModule(Module* module) { if (module) { setActiveView(module->view()); setActiveDataSource(module->dataSource()); } if (m_activeModule != module) { m_activeModule = module; emit moduleChanged(module); } emit moduleActivated(module); } void ActiveObjects::setActiveOperator(Operator* op) { if (op) { setActiveDataSource(op->dataSource()); } if (m_activeOperator != op) { m_activeOperator = op; emit operatorChanged(op); } emit operatorActivated(op); } void ActiveObjects::setActiveOperatorResult(OperatorResult* result) { if (result) { auto op = qobject_cast<Operator*>(result->parent()); if (op) { setActiveOperator(op); setActiveDataSource(op->dataSource()); } } if (m_activeOperatorResult != result) { m_activeOperatorResult = result; emit resultChanged(result); } emit resultActivated(result); } void ActiveObjects::createRenderViewIfNeeded() { vtkNew<vtkSMProxyIterator> iter; iter->SetSessionProxyManager(proxyManager()); iter->SetModeToOneGroup(); for (iter->Begin("views"); !iter->IsAtEnd(); iter->Next()) { vtkSMRenderViewProxy* renderView = vtkSMRenderViewProxy::SafeDownCast(iter->GetProxy()); if (renderView) { return; } } // If we get here, there was no existing view, so create one. pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder(); pqServer* server = pqApplicationCore::instance()->getActiveServer(); builder->createView("RenderView", server); } void ActiveObjects::setActiveViewToFirstRenderView() { vtkNew<vtkSMProxyIterator> iter; iter->SetSessionProxyManager(proxyManager()); iter->SetModeToOneGroup(); for (iter->Begin("views"); !iter->IsAtEnd(); iter->Next()) { vtkSMRenderViewProxy* renderView = vtkSMRenderViewProxy::SafeDownCast(iter->GetProxy()); if (renderView) { setActiveView(renderView); break; } } } void ActiveObjects::setMoveObjectsMode(bool moveObjectsOn) { if (m_moveObjectsEnabled != moveObjectsOn) { m_moveObjectsEnabled = moveObjectsOn; emit moveObjectsModeChanged(moveObjectsOn); } } void ActiveObjects::renderAllViews() { pqApplicationCore::instance()->render(); } DataSource* ActiveObjects::activeParentDataSource() { if (m_activeParentDataSource == nullptr) { auto pipeline = activePipeline(); auto dataSource = activeDataSource(); if (dataSource == nullptr) { return nullptr; } if (dataSource->forkable()) { return dataSource; } std::function<QList<DataSource*>(DataSource*, DataSource*, QList<DataSource*>)> dfs = [&dfs](DataSource* currentDataSource, DataSource* targetDataSource, QList<DataSource*> path) { path.append(currentDataSource); if (currentDataSource == targetDataSource) { return path; } foreach (Operator* op, currentDataSource->operators()) { if (op->childDataSource() != nullptr) { QList<DataSource*> p = dfs(op->childDataSource(), targetDataSource, path); if (!p.isEmpty()) { return p; } } } return QList<DataSource*>(); }; // Find path to the active datasource auto path = dfs(pipeline->dataSource(), dataSource, QList<DataSource*>()); // Return the first non output data source for (auto itr = path.rbegin(); itr != path.rend(); ++itr) { auto ds = *itr; if (ds->forkable()) { m_activeParentDataSource = ds; break; } } } return m_activeParentDataSource; } Pipeline* ActiveObjects::activePipeline() const { if (m_activeDataSource != nullptr) { return m_activeDataSource->pipeline(); } return nullptr; } } // end of namespace tomviz <commit_msg>Emit dataSourceChanged every time a source is activated<commit_after>/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "ActiveObjects.h" #include "ModuleManager.h" #include "Pipeline.h" #include "Utilities.h" #include <pqActiveObjects.h> #include <pqApplicationCore.h> #include <pqObjectBuilder.h> #include <pqPipelineSource.h> #include <pqRenderView.h> #include <pqServer.h> #include <pqView.h> #include <vtkNew.h> #include <vtkSMProxyIterator.h> #include <vtkSMRenderViewProxy.h> #include <vtkSMSourceProxy.h> #include <vtkSMViewProxy.h> #include <functional> namespace tomviz { ActiveObjects::ActiveObjects() : QObject() { connect(&pqActiveObjects::instance(), SIGNAL(viewChanged(pqView*)), SLOT(viewChanged(pqView*))); connect(&ModuleManager::instance(), SIGNAL(dataSourceRemoved(DataSource*)), SLOT(dataSourceRemoved(DataSource*))); connect(&ModuleManager::instance(), SIGNAL(moduleRemoved(Module*)), SLOT(moduleRemoved(Module*))); } ActiveObjects::~ActiveObjects() = default; ActiveObjects& ActiveObjects::instance() { static ActiveObjects theInstance; return theInstance; } void ActiveObjects::setActiveView(vtkSMViewProxy* view) { pqActiveObjects::instance().setActiveView(tomviz::convert<pqView*>(view)); } vtkSMViewProxy* ActiveObjects::activeView() const { pqView* view = activePqView(); return view ? view->getViewProxy() : nullptr; } pqView* ActiveObjects::activePqView() const { return pqActiveObjects::instance().activeView(); } pqRenderView* ActiveObjects::activePqRenderView() const { return qobject_cast<pqRenderView*>(activePqView()); } void ActiveObjects::viewChanged(pqView* view) { emit viewChanged(view ? view->getViewProxy() : nullptr); } void ActiveObjects::dataSourceRemoved(DataSource* ds) { if (m_activeDataSource == ds) { setActiveDataSource(nullptr); } } void ActiveObjects::moduleRemoved(Module* mdl) { if (m_activeModule == mdl) { setActiveModule(nullptr); } } void ActiveObjects::setActiveDataSource(DataSource* source) { if (m_activeDataSource != source) { if (m_activeDataSource) { disconnect(m_activeDataSource, SIGNAL(dataChanged()), this, SLOT(dataSourceChanged())); } if (source) { connect(source, SIGNAL(dataChanged()), this, SLOT(dataSourceChanged())); m_activeDataSourceType = source->type(); } m_activeDataSource = source; // Setting to nullptr so the traverse logic is re-run. m_activeParentDataSource = nullptr; } emit dataSourceActivated(m_activeDataSource); emit dataSourceChanged(m_activeDataSource); if (!m_activeDataSource.isNull() && m_activeDataSource->pipeline() != nullptr) { setActiveTransformedDataSource( m_activeDataSource->pipeline()->transformedDataSource()); } } void ActiveObjects::setSelectedDataSource(DataSource* source) { m_selectedDataSource = source; if (!m_selectedDataSource.isNull()) { setActiveDataSource(m_selectedDataSource); } } void ActiveObjects::setActiveTransformedDataSource(DataSource* source) { if (m_activeTransformedDataSource != source) { m_activeTransformedDataSource = source; } emit transformedDataSourceActivated(m_activeTransformedDataSource); } void ActiveObjects::dataSourceChanged() { if (m_activeDataSource->type() != m_activeDataSourceType) { m_activeDataSourceType = m_activeDataSource->type(); emit dataSourceChanged(m_activeDataSource); } } vtkSMSessionProxyManager* ActiveObjects::proxyManager() const { pqServer* server = pqActiveObjects::instance().activeServer(); return server ? server->proxyManager() : nullptr; } void ActiveObjects::setActiveModule(Module* module) { if (module) { setActiveView(module->view()); setActiveDataSource(module->dataSource()); } if (m_activeModule != module) { m_activeModule = module; emit moduleChanged(module); } emit moduleActivated(module); } void ActiveObjects::setActiveOperator(Operator* op) { if (op) { setActiveDataSource(op->dataSource()); } if (m_activeOperator != op) { m_activeOperator = op; emit operatorChanged(op); } emit operatorActivated(op); } void ActiveObjects::setActiveOperatorResult(OperatorResult* result) { if (result) { auto op = qobject_cast<Operator*>(result->parent()); if (op) { setActiveOperator(op); setActiveDataSource(op->dataSource()); } } if (m_activeOperatorResult != result) { m_activeOperatorResult = result; emit resultChanged(result); } emit resultActivated(result); } void ActiveObjects::createRenderViewIfNeeded() { vtkNew<vtkSMProxyIterator> iter; iter->SetSessionProxyManager(proxyManager()); iter->SetModeToOneGroup(); for (iter->Begin("views"); !iter->IsAtEnd(); iter->Next()) { vtkSMRenderViewProxy* renderView = vtkSMRenderViewProxy::SafeDownCast(iter->GetProxy()); if (renderView) { return; } } // If we get here, there was no existing view, so create one. pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder(); pqServer* server = pqApplicationCore::instance()->getActiveServer(); builder->createView("RenderView", server); } void ActiveObjects::setActiveViewToFirstRenderView() { vtkNew<vtkSMProxyIterator> iter; iter->SetSessionProxyManager(proxyManager()); iter->SetModeToOneGroup(); for (iter->Begin("views"); !iter->IsAtEnd(); iter->Next()) { vtkSMRenderViewProxy* renderView = vtkSMRenderViewProxy::SafeDownCast(iter->GetProxy()); if (renderView) { setActiveView(renderView); break; } } } void ActiveObjects::setMoveObjectsMode(bool moveObjectsOn) { if (m_moveObjectsEnabled != moveObjectsOn) { m_moveObjectsEnabled = moveObjectsOn; emit moveObjectsModeChanged(moveObjectsOn); } } void ActiveObjects::renderAllViews() { pqApplicationCore::instance()->render(); } DataSource* ActiveObjects::activeParentDataSource() { if (m_activeParentDataSource == nullptr) { auto pipeline = activePipeline(); auto dataSource = activeDataSource(); if (dataSource == nullptr) { return nullptr; } if (dataSource->forkable()) { return dataSource; } std::function<QList<DataSource*>(DataSource*, DataSource*, QList<DataSource*>)> dfs = [&dfs](DataSource* currentDataSource, DataSource* targetDataSource, QList<DataSource*> path) { path.append(currentDataSource); if (currentDataSource == targetDataSource) { return path; } foreach (Operator* op, currentDataSource->operators()) { if (op->childDataSource() != nullptr) { QList<DataSource*> p = dfs(op->childDataSource(), targetDataSource, path); if (!p.isEmpty()) { return p; } } } return QList<DataSource*>(); }; // Find path to the active datasource auto path = dfs(pipeline->dataSource(), dataSource, QList<DataSource*>()); // Return the first non output data source for (auto itr = path.rbegin(); itr != path.rend(); ++itr) { auto ds = *itr; if (ds->forkable()) { m_activeParentDataSource = ds; break; } } } return m_activeParentDataSource; } Pipeline* ActiveObjects::activePipeline() const { if (m_activeDataSource != nullptr) { return m_activeDataSource->pipeline(); } return nullptr; } } // end of namespace tomviz <|endoftext|>
<commit_before>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/config.hpp" #include "vast/detail/adjust_resource_consumption.hpp" #include "vast/detail/process.hpp" #include "vast/detail/system.hpp" #include "vast/error.hpp" #include "vast/event_types.hpp" #include "vast/filesystem.hpp" #include "vast/logger.hpp" #include "vast/schema.hpp" #include "vast/system/application.hpp" #include "vast/system/default_configuration.hpp" #include <caf/actor_system.hpp> #include <caf/atom.hpp> #include <caf/io/middleman.hpp> #include <caf/timestamp.hpp> #include <cstdlib> #ifdef VAST_USE_OPENSSL # include <caf/openssl/manager.hpp> #endif using namespace vast; using namespace vast::system; int main(int argc, char** argv) { // CAF scaffold. default_configuration cfg; if (auto err = cfg.parse(argc, argv)) { std::cerr << "failed to parse configuration: " << to_string(err) << std::endl; return EXIT_FAILURE; } // Make sure we have enough resources (e.g., file descriptors) if (!detail::adjust_resource_consumption()) return EXIT_FAILURE; // Application setup. const auto [root, factory] = make_application(argv[0]); if (!root) return EXIT_FAILURE; // Parse CLI. auto invocation = parse(*root, cfg.command_line.begin(), cfg.command_line.end()); if (!invocation) { render_error(*root, invocation.error(), std::cerr); return EXIT_FAILURE; } // Initialize actor system (and thereby CAF's logger). if (!init_config(cfg, *invocation, std::cerr)) return EXIT_FAILURE; caf::actor_system sys{cfg}; // Get filesystem path to the executable. auto binary = detail::objectpath(); if (!binary) { VAST_ERROR_ANON("failed to get program path"); return EXIT_FAILURE; } auto vast_share = binary->parent().parent() / "share" / "vast"; // Load event types. auto default_dirs = std::vector{vast_share / "schema"}; using string_list = std::vector<std::string>; if (auto user_dirs = caf::get_if<string_list>(&cfg, "system.schema-paths")) default_dirs.insert(default_dirs.end(), user_dirs->begin(), user_dirs->end()); if (auto schema = load_schema(default_dirs)) { event_types::init(*std::move(schema)); } else { VAST_ERROR_ANON("failed to read schema dirs:", to_string(schema.error())); return EXIT_FAILURE; } // Dispatch to root command. auto result = run(*invocation, sys, factory); if (!result) { render_error(*root, result.error(), std::cerr); return EXIT_FAILURE; } if (result->match_elements<caf::error>()) { auto& err = result->get_as<caf::error>(0); if (err) { vast::system::render_error(*root, err, std::cerr); return EXIT_FAILURE; } } return EXIT_SUCCESS; } <commit_msg>Return zero when printing help/documentation texts<commit_after>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/config.hpp" #include "vast/detail/adjust_resource_consumption.hpp" #include "vast/detail/process.hpp" #include "vast/detail/system.hpp" #include "vast/error.hpp" #include "vast/event_types.hpp" #include "vast/filesystem.hpp" #include "vast/logger.hpp" #include "vast/schema.hpp" #include "vast/system/application.hpp" #include "vast/system/default_configuration.hpp" #include <caf/actor_system.hpp> #include <caf/atom.hpp> #include <caf/io/middleman.hpp> #include <caf/timestamp.hpp> #include <cstdlib> #ifdef VAST_USE_OPENSSL # include <caf/openssl/manager.hpp> #endif using namespace vast; using namespace vast::system; int main(int argc, char** argv) { // CAF scaffold. default_configuration cfg; if (auto err = cfg.parse(argc, argv)) { std::cerr << "failed to parse configuration: " << to_string(err) << std::endl; return EXIT_FAILURE; } // Make sure we have enough resources (e.g., file descriptors) if (!detail::adjust_resource_consumption()) return EXIT_FAILURE; // Application setup. const auto [root, factory] = make_application(argv[0]); if (!root) return EXIT_FAILURE; // Parse CLI. auto invocation = parse(*root, cfg.command_line.begin(), cfg.command_line.end()); if (!invocation) { if (invocation.error()) { render_error(*root, invocation.error(), std::cerr); return EXIT_FAILURE; } // Printing help/documentation returns a no_error, and we want to indicate // success when printing the help/documentation texts. return EXIT_SUCCESS; } // Initialize actor system (and thereby CAF's logger). if (!init_config(cfg, *invocation, std::cerr)) return EXIT_FAILURE; caf::actor_system sys{cfg}; // Get filesystem path to the executable. auto binary = detail::objectpath(); if (!binary) { VAST_ERROR_ANON("failed to get program path"); return EXIT_FAILURE; } auto vast_share = binary->parent().parent() / "share" / "vast"; // Load event types. auto default_dirs = std::vector{vast_share / "schema"}; using string_list = std::vector<std::string>; if (auto user_dirs = caf::get_if<string_list>(&cfg, "system.schema-paths")) default_dirs.insert(default_dirs.end(), user_dirs->begin(), user_dirs->end()); if (auto schema = load_schema(default_dirs)) { event_types::init(*std::move(schema)); } else { VAST_ERROR_ANON("failed to read schema dirs:", to_string(schema.error())); return EXIT_FAILURE; } // Dispatch to root command. auto result = run(*invocation, sys, factory); if (!result) { render_error(*root, result.error(), std::cerr); return EXIT_FAILURE; } if (result->match_elements<caf::error>()) { auto& err = result->get_as<caf::error>(0); if (err) { vast::system::render_error(*root, err, std::cerr); return EXIT_FAILURE; } } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#ifndef STAN_MATH_OPENCL_MATRIX_CL_HPP #define STAN_MATH_OPENCL_MATRIX_CL_HPP #ifdef STAN_OPENCL #include <stan/math/opencl/opencl_context.hpp> #include <stan/math/opencl/matrix_cl_view.hpp> #include <stan/math/opencl/err/check_opencl.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/meta.hpp> #include <stan/math/prim/arr/fun/vec_concat.hpp> #include <stan/math/prim/scal/err/check_size_match.hpp> #include <stan/math/prim/scal/err/domain_error.hpp> #include <CL/cl.hpp> #include <iostream> #include <string> #include <vector> #include <algorithm> /** * @file stan/math/opencl/matrix_cl.hpp * @brief The matrix_cl class - allocates memory space on the OpenCL device, * functions for transfering matrices to and from OpenCL devices */ namespace stan { namespace math { // Dummy class to instantiate matrix_cl to enable for specific types. template <typename T, typename = void> class matrix_cl {}; /** * Represents a matrix on the OpenCL device. * * @tparam T an arithmetic type for the type stored in the OpenCL buffer. */ template <typename T> class matrix_cl<T, enable_if_arithmetic<T>> { private: cl::Buffer buffer_cl_; // Holds the allocated memory on the device const int rows_; const int cols_; matrix_cl_view view_; // Holds info on if matrix is a special type mutable std::vector<cl::Event> write_events_; // Tracks write jobs mutable std::vector<cl::Event> read_events_; // Tracks reads public: typedef T type; // Forward declare the methods that work in place on the matrix template <matrix_cl_view matrix_view = matrix_cl_view::Entire> void zeros(); template <TriangularMapCL triangular_map = TriangularMapCL::LowerToUpper> void triangular_transpose(); void sub_block(const matrix_cl<T, enable_if_arithmetic<T>>& A, size_t A_i, size_t A_j, size_t this_i, size_t this_j, size_t nrows, size_t ncols); int rows() const { return rows_; } int cols() const { return cols_; } int size() const { return rows_ * cols_; } const matrix_cl_view& view() const { return view_; } void view(const matrix_cl_view& view) { view_ = view; } /** * Clear the write events from the event stacks. */ inline void clear_write_events() const { write_events_.clear(); return; } /** * Clear the read events from the event stacks. */ inline void clear_read_events() const { read_events_.clear(); return; } /** * Clear the write events from the event stacks. */ inline void clear_read_write_events() const { read_events_.clear(); write_events_.clear(); return; } /** * Get the events from the event stacks. * @return The write event stack. */ inline const std::vector<cl::Event>& write_events() const { return write_events_; } /** * Get the events from the event stacks. * @return The read/write event stack. */ inline const std::vector<cl::Event>& read_events() const { return read_events_; } /** * Get the events from the event stacks. * @return The read/write event stack. */ inline const std::vector<cl::Event> read_write_events() const { return vec_concat(this->read_events(), this->write_events()); } /** * Add an event to the read event stack. * @param new_event The event to be pushed on the event stack. */ inline void add_read_event(cl::Event new_event) const { this->read_events_.push_back(new_event); } /** * Add an event to the write event stack. * @param new_event The event to be pushed on the event stack. */ inline void add_write_event(cl::Event new_event) const { this->write_events_.push_back(new_event); } /** * Add an event to the read/write event stack. * @param new_event The event to be pushed on the event stack. */ inline void add_read_write_event(cl::Event new_event) const { this->read_events_.push_back(new_event); this->write_events_.push_back(new_event); } /** * Waits for the write events and clears the read event stack. */ inline void wait_for_write_events() const { cl::CommandQueue queue = opencl_context.queue(); cl::Event copy_event; queue.enqueueBarrierWithWaitList(&this->write_events(), &copy_event); copy_event.wait(); write_events_.clear(); return; } /** * Waits for the read events and clears the read event stack. */ inline void wait_for_read_events() const { cl::CommandQueue queue = opencl_context.queue(); cl::Event copy_event; queue.enqueueBarrierWithWaitList(&this->read_events(), &copy_event); copy_event.wait(); read_events_.clear(); return; } /** * Waits for read and write events to finish and clears the read, write, and * read/write event stacks. */ inline void wait_for_read_write_events() const { cl::CommandQueue queue = opencl_context.queue(); cl::Event copy_event; const std::vector<cl::Event> mat_events = this->read_write_events(); queue.enqueueBarrierWithWaitList(&mat_events, &copy_event); copy_event.wait(); read_events_.clear(); write_events_.clear(); return; } const cl::Buffer& buffer() const { return buffer_cl_; } cl::Buffer& buffer() { return buffer_cl_; } matrix_cl() : rows_(0), cols_(0) {} matrix_cl(const matrix_cl<T>& A) : rows_(A.rows()), cols_(A.cols()), view_(A.view()) { if (A.size() == 0) return; cl::Context& ctx = opencl_context.context(); cl::CommandQueue queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * size()); cl::Event cstr_event; queue.enqueueCopyBuffer(A.buffer(), this->buffer(), 0, 0, A.size() * sizeof(T), &A.write_events(), &cstr_event); this->add_write_event(cstr_event); } catch (const cl::Error& e) { check_opencl_error("copy (OpenCL)->(OpenCL)", e); } } /** * Constructor for the matrix_cl that * creates a copy of the Eigen matrix on the OpenCL device. * * * @tparam R row type * @tparam C column type * @param A the Eigen matrix * * @throw <code>std::invalid_argument</code> if the * matrices do not have matching dimensions */ template <int R, int C> explicit matrix_cl(const std::vector<Eigen::Matrix<T, R, C>>& A) try : rows_(A.empty() ? 0 : A[0].size()), cols_(A.size()) { if (this->size() == 0) return; cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); // creates the OpenCL buffer to copy the Eigen // matrix to the OpenCL device buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * size()); for (int i = 0, offset_size = 0; i < cols_; i++, offset_size += rows_) { check_size_match("matrix constructor", "input rows", A[i].size(), "matrix_cl rows", rows_); /** * Writes the contents of A[i] to the OpenCL buffer * starting at the offset sizeof(double)*start. * CL_TRUE denotes that the call is blocking as * we do not want to execute any further kernels * on the device until we are sure that the data * is finished transfering */ cl::Event write_event; queue.enqueueWriteBuffer( buffer_cl_, CL_FALSE, sizeof(double) * offset_size, sizeof(double) * rows_, A[i].data(), NULL, &write_event); this->add_write_event(write_event); } } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } /** * Constructor for the matrix_cl that * only allocates the buffer on the OpenCL device. * Regardless of `partial_view`, whole matrix is stored. * * @param rows number of matrix rows, must be greater or equal to 0 * @param cols number of matrix columns, must be greater or equal to 0 * @param partial_view which part of the matrix is used * * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions * */ matrix_cl(const int& rows, const int& cols, matrix_cl_view partial_view = matrix_cl_view::Entire) : rows_(rows), cols_(cols), view_(partial_view) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); try { // creates the OpenCL buffer of the provided size buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * rows_ * cols_); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Constructor for the matrix_cl that * creates a copy of the Eigen matrix on the OpenCL device. * Regardless of `partial_view`, whole matrix is stored. * * @tparam T type of data in the \c Eigen \c Matrix * @param A the \c Eigen \c Matrix * @param partial_view which part of the matrix is used * * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions */ explicit matrix_cl( const Eigen::Ref<const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>>& A, matrix_cl_view partial_view = matrix_cl_view::Entire) : rows_(A.rows()), cols_(A.cols()), view_(partial_view) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * A.size()); cl::Event transfer_event; queue.enqueueWriteBuffer(buffer_cl_, CL_FALSE, 0, sizeof(T) * A.size(), A.data(), NULL, &transfer_event); this->add_write_event(transfer_event); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Construct from \c std::vector with given rows and columns * * @param A Standard vector * @param R Number of rows the matrix should have. * @param C Number of columns the matrix should have. * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions */ explicit matrix_cl(const std::vector<T>& A, const int& R, const int& C) : rows_(R), cols_(C) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * A.size()); cl::Event transfer_event; queue.enqueueWriteBuffer(buffer_cl_, CL_FALSE, 0, sizeof(T) * A.size(), A.data(), NULL, &transfer_event); this->add_write_event(transfer_event); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Construct from \c array of doubles with given rows and columns * * @param A array of doubles * @param R Number of rows the matrix should have. * @param C Number of columns the matrix should have. * @param partial_view which part of the matrix is used * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions */ explicit matrix_cl(const double* A, const int& R, const int& C, matrix_cl_view partial_view = matrix_cl_view::Entire) : rows_(R), cols_(C), view_(partial_view) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * size()); cl::Event transfer_event; queue.enqueueWriteBuffer(buffer_cl_, CL_FALSE, 0, sizeof(T) * size(), A, NULL, &transfer_event); this->add_write_event(transfer_event); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Assign a \c matrix_cl to another */ matrix_cl<T>& operator=(const matrix_cl<T>& a) { check_size_match("assignment of (OpenCL) matrices", "source.rows()", a.rows(), "destination.rows()", rows()); check_size_match("assignment of (OpenCL) matrices", "source.cols()", a.cols(), "destination.cols()", cols()); // Need to wait for all of matrices events before destroying old buffer this->wait_for_read_write_events(); buffer_cl_ = a.buffer(); view_ = a.view(); return *this; } /** * Assign a \c matrix_cl of one arithmetic type to another */ template <typename U, typename = enable_if_arithmetic<U>> matrix_cl<T>& operator=(const matrix_cl<U>& a) { check_size_match("assignment of (OpenCL) matrices", "source.rows()", a.rows(), "destination.rows()", rows()); check_size_match("assignment of (OpenCL) matrices", "source.cols()", a.cols(), "destination.cols()", cols()); // Need to wait for all of matrices events before destroying old buffer this->wait_for_read_write_events(); buffer_cl_ = a.buffer(); view_ = a.view(); return *this; } }; template <typename T> using matrix_cl_prim = matrix_cl<T, enable_if_arithmetic<T>>; template <typename T> using matrix_cl_fp = matrix_cl<T, enable_if_floating_point<T>>; } // namespace math } // namespace stan #endif #endif <commit_msg>Generalize matrix_cl constructor from Eigen<commit_after>#ifndef STAN_MATH_OPENCL_MATRIX_CL_HPP #define STAN_MATH_OPENCL_MATRIX_CL_HPP #ifdef STAN_OPENCL #include <stan/math/opencl/opencl_context.hpp> #include <stan/math/opencl/matrix_cl_view.hpp> #include <stan/math/opencl/err/check_opencl.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/meta.hpp> #include <stan/math/prim/arr/fun/vec_concat.hpp> #include <stan/math/prim/scal/err/check_size_match.hpp> #include <stan/math/prim/scal/err/domain_error.hpp> #include <CL/cl.hpp> #include <iostream> #include <string> #include <vector> #include <algorithm> /** * @file stan/math/opencl/matrix_cl.hpp * @brief The matrix_cl class - allocates memory space on the OpenCL device, * functions for transfering matrices to and from OpenCL devices */ namespace stan { namespace math { // Dummy class to instantiate matrix_cl to enable for specific types. template <typename T, typename = void> class matrix_cl {}; /** * Represents a matrix on the OpenCL device. * * @tparam T an arithmetic type for the type stored in the OpenCL buffer. */ template <typename T> class matrix_cl<T, enable_if_arithmetic<T>> { private: cl::Buffer buffer_cl_; // Holds the allocated memory on the device const int rows_; const int cols_; matrix_cl_view view_; // Holds info on if matrix is a special type mutable std::vector<cl::Event> write_events_; // Tracks write jobs mutable std::vector<cl::Event> read_events_; // Tracks reads public: typedef T type; // Forward declare the methods that work in place on the matrix template <matrix_cl_view matrix_view = matrix_cl_view::Entire> void zeros(); template <TriangularMapCL triangular_map = TriangularMapCL::LowerToUpper> void triangular_transpose(); void sub_block(const matrix_cl<T, enable_if_arithmetic<T>>& A, size_t A_i, size_t A_j, size_t this_i, size_t this_j, size_t nrows, size_t ncols); int rows() const { return rows_; } int cols() const { return cols_; } int size() const { return rows_ * cols_; } const matrix_cl_view& view() const { return view_; } void view(const matrix_cl_view& view) { view_ = view; } /** * Clear the write events from the event stacks. */ inline void clear_write_events() const { write_events_.clear(); return; } /** * Clear the read events from the event stacks. */ inline void clear_read_events() const { read_events_.clear(); return; } /** * Clear the write events from the event stacks. */ inline void clear_read_write_events() const { read_events_.clear(); write_events_.clear(); return; } /** * Get the events from the event stacks. * @return The write event stack. */ inline const std::vector<cl::Event>& write_events() const { return write_events_; } /** * Get the events from the event stacks. * @return The read/write event stack. */ inline const std::vector<cl::Event>& read_events() const { return read_events_; } /** * Get the events from the event stacks. * @return The read/write event stack. */ inline const std::vector<cl::Event> read_write_events() const { return vec_concat(this->read_events(), this->write_events()); } /** * Add an event to the read event stack. * @param new_event The event to be pushed on the event stack. */ inline void add_read_event(cl::Event new_event) const { this->read_events_.push_back(new_event); } /** * Add an event to the write event stack. * @param new_event The event to be pushed on the event stack. */ inline void add_write_event(cl::Event new_event) const { this->write_events_.push_back(new_event); } /** * Add an event to the read/write event stack. * @param new_event The event to be pushed on the event stack. */ inline void add_read_write_event(cl::Event new_event) const { this->read_events_.push_back(new_event); this->write_events_.push_back(new_event); } /** * Waits for the write events and clears the read event stack. */ inline void wait_for_write_events() const { cl::CommandQueue queue = opencl_context.queue(); cl::Event copy_event; queue.enqueueBarrierWithWaitList(&this->write_events(), &copy_event); copy_event.wait(); write_events_.clear(); return; } /** * Waits for the read events and clears the read event stack. */ inline void wait_for_read_events() const { cl::CommandQueue queue = opencl_context.queue(); cl::Event copy_event; queue.enqueueBarrierWithWaitList(&this->read_events(), &copy_event); copy_event.wait(); read_events_.clear(); return; } /** * Waits for read and write events to finish and clears the read, write, and * read/write event stacks. */ inline void wait_for_read_write_events() const { cl::CommandQueue queue = opencl_context.queue(); cl::Event copy_event; const std::vector<cl::Event> mat_events = this->read_write_events(); queue.enqueueBarrierWithWaitList(&mat_events, &copy_event); copy_event.wait(); read_events_.clear(); write_events_.clear(); return; } const cl::Buffer& buffer() const { return buffer_cl_; } cl::Buffer& buffer() { return buffer_cl_; } matrix_cl() : rows_(0), cols_(0) {} matrix_cl(const matrix_cl<T>& A) : rows_(A.rows()), cols_(A.cols()), view_(A.view()) { if (A.size() == 0) return; cl::Context& ctx = opencl_context.context(); cl::CommandQueue queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * size()); cl::Event cstr_event; queue.enqueueCopyBuffer(A.buffer(), this->buffer(), 0, 0, A.size() * sizeof(T), &A.write_events(), &cstr_event); this->add_write_event(cstr_event); } catch (const cl::Error& e) { check_opencl_error("copy (OpenCL)->(OpenCL)", e); } } /** * Constructor for the matrix_cl that * creates a copy of the Eigen matrix on the OpenCL device. * * * @tparam R row type * @tparam C column type * @param A the Eigen matrix * * @throw <code>std::invalid_argument</code> if the * matrices do not have matching dimensions */ template <int R, int C> explicit matrix_cl(const std::vector<Eigen::Matrix<T, R, C>>& A) try : rows_(A.empty() ? 0 : A[0].size()), cols_(A.size()) { if (this->size() == 0) return; cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); // creates the OpenCL buffer to copy the Eigen // matrix to the OpenCL device buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * size()); for (int i = 0, offset_size = 0; i < cols_; i++, offset_size += rows_) { check_size_match("matrix constructor", "input rows", A[i].size(), "matrix_cl rows", rows_); /** * Writes the contents of A[i] to the OpenCL buffer * starting at the offset sizeof(double)*start. * CL_TRUE denotes that the call is blocking as * we do not want to execute any further kernels * on the device until we are sure that the data * is finished transfering */ cl::Event write_event; queue.enqueueWriteBuffer( buffer_cl_, CL_FALSE, sizeof(double) * offset_size, sizeof(double) * rows_, A[i].data(), NULL, &write_event); this->add_write_event(write_event); } } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } /** * Constructor for the matrix_cl that * only allocates the buffer on the OpenCL device. * Regardless of `partial_view`, whole matrix is stored. * * @param rows number of matrix rows, must be greater or equal to 0 * @param cols number of matrix columns, must be greater or equal to 0 * @param partial_view which part of the matrix is used * * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions * */ matrix_cl(const int& rows, const int& cols, matrix_cl_view partial_view = matrix_cl_view::Entire) : rows_(rows), cols_(cols), view_(partial_view) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); try { // creates the OpenCL buffer of the provided size buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * rows_ * cols_); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } template <typename Type> using enable_if_eigen_base = std::enable_if_t<std::is_base_of<Eigen::EigenBase<Type>, std::decay_t<Type>>::value>; /** * Constructor for the matrix_cl that * creates a copy of the Eigen matrix on the OpenCL device. * Regardless of `partial_view`, whole matrix is stored. * * @tparam T type of data in the \c Eigen \c Matrix * @param A the \c Eigen \c Matrix * @param partial_view which part of the matrix is used * * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions */ template <typename eigen_base, typename = enable_if_eigen_base<eigen_base>> explicit matrix_cl(const eigen_base& A, matrix_cl_view partial_view = matrix_cl_view::Entire) : rows_(A.rows()), cols_(A.cols()), view_(partial_view) { if (this->size() == 0) { return; } cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * A.size()); cl::Event transfer_event; queue.enqueueWriteBuffer(buffer_cl_, CL_FALSE, 0, sizeof(T) * A.size(), A.eval().data(), NULL, &transfer_event); this->add_write_event(transfer_event); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Construct from \c std::vector with given rows and columns * * @param A Standard vector * @param R Number of rows the matrix should have. * @param C Number of columns the matrix should have. * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions */ explicit matrix_cl(const std::vector<T>& A, const int& R, const int& C) : rows_(R), cols_(C) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * A.size()); cl::Event transfer_event; queue.enqueueWriteBuffer(buffer_cl_, CL_FALSE, 0, sizeof(T) * A.size(), A.data(), NULL, &transfer_event); this->add_write_event(transfer_event); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Construct from \c array of doubles with given rows and columns * * @param A array of doubles * @param R Number of rows the matrix should have. * @param C Number of columns the matrix should have. * @param partial_view which part of the matrix is used * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions */ explicit matrix_cl(const double* A, const int& R, const int& C, matrix_cl_view partial_view = matrix_cl_view::Entire) : rows_(R), cols_(C), view_(partial_view) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * size()); cl::Event transfer_event; queue.enqueueWriteBuffer(buffer_cl_, CL_FALSE, 0, sizeof(T) * size(), A, NULL, &transfer_event); this->add_write_event(transfer_event); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Assign a \c matrix_cl to another */ matrix_cl<T>& operator=(const matrix_cl<T>& a) { check_size_match("assignment of (OpenCL) matrices", "source.rows()", a.rows(), "destination.rows()", rows()); check_size_match("assignment of (OpenCL) matrices", "source.cols()", a.cols(), "destination.cols()", cols()); // Need to wait for all of matrices events before destroying old buffer this->wait_for_read_write_events(); buffer_cl_ = a.buffer(); view_ = a.view(); return *this; } /** * Assign a \c matrix_cl of one arithmetic type to another */ template <typename U, typename = enable_if_arithmetic<U>> matrix_cl<T>& operator=(const matrix_cl<U>& a) { check_size_match("assignment of (OpenCL) matrices", "source.rows()", a.rows(), "destination.rows()", rows()); check_size_match("assignment of (OpenCL) matrices", "source.cols()", a.cols(), "destination.cols()", cols()); // Need to wait for all of matrices events before destroying old buffer this->wait_for_read_write_events(); buffer_cl_ = a.buffer(); view_ = a.view(); return *this; } }; template <typename T> using matrix_cl_prim = matrix_cl<T, enable_if_arithmetic<T>>; template <typename T> using matrix_cl_fp = matrix_cl<T, enable_if_floating_point<T>>; } // namespace math } // namespace stan #endif #endif <|endoftext|>
<commit_before>#ifndef STAN_MATH_OPENCL_MATRIX_CL_HPP #define STAN_MATH_OPENCL_MATRIX_CL_HPP #ifdef STAN_OPENCL #include <stan/math/opencl/opencl_context.hpp> #include <stan/math/opencl/matrix_cl_view.hpp> #include <stan/math/opencl/err/check_opencl.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/meta.hpp> #include <stan/math/prim/arr/fun/vec_concat.hpp> #include <stan/math/prim/scal/err/check_size_match.hpp> #include <stan/math/prim/scal/err/domain_error.hpp> #include <CL/cl.hpp> #include <iostream> #include <string> #include <vector> #include <algorithm> /** * @file stan/math/opencl/matrix_cl.hpp * @brief The matrix_cl class - allocates memory space on the OpenCL device, * functions for transfering matrices to and from OpenCL devices */ namespace stan { namespace math { // Dummy class to instantiate matrix_cl to enable for specific types. template <typename T, typename = void> class matrix_cl {}; /** * Represents a matrix on the OpenCL device. * * @tparam T an arithmetic type for the type stored in the OpenCL buffer. */ template <typename T> class matrix_cl<T, enable_if_arithmetic<T>> { private: cl::Buffer buffer_cl_; // Holds the allocated memory on the device const int rows_; const int cols_; matrix_cl_view view_; // Holds info on if matrix is a special type mutable std::vector<cl::Event> write_events_; // Tracks write jobs mutable std::vector<cl::Event> read_events_; // Tracks reads public: typedef T type; // Forward declare the methods that work in place on the matrix template <matrix_cl_view matrix_view = matrix_cl_view::Entire> void zeros(); template <TriangularMapCL triangular_map = TriangularMapCL::LowerToUpper> void triangular_transpose(); void sub_block(const matrix_cl<T, enable_if_arithmetic<T>>& A, size_t A_i, size_t A_j, size_t this_i, size_t this_j, size_t nrows, size_t ncols); int rows() const { return rows_; } int cols() const { return cols_; } int size() const { return rows_ * cols_; } const matrix_cl_view& view() const { return view_; } void view(const matrix_cl_view& view) { view_ = view; } /** * Clear the write events from the event stacks. */ inline void clear_write_events() const { write_events_.clear(); return; } /** * Clear the read events from the event stacks. */ inline void clear_read_events() const { read_events_.clear(); return; } /** * Clear the write events from the event stacks. */ inline void clear_read_write_events() const { read_events_.clear(); write_events_.clear(); return; } /** * Get the events from the event stacks. * @return The write event stack. */ inline const std::vector<cl::Event>& write_events() const { return write_events_; } /** * Get the events from the event stacks. * @return The read/write event stack. */ inline const std::vector<cl::Event>& read_events() const { return read_events_; } /** * Get the events from the event stacks. * @return The read/write event stack. */ inline const std::vector<cl::Event> read_write_events() const { return vec_concat(this->read_events(), this->write_events()); } /** * Add an event to the read event stack. * @param new_event The event to be pushed on the event stack. */ inline void add_read_event(cl::Event new_event) const { this->read_events_.push_back(new_event); } /** * Add an event to the write event stack. * @param new_event The event to be pushed on the event stack. */ inline void add_write_event(cl::Event new_event) const { this->write_events_.push_back(new_event); } /** * Add an event to the read/write event stack. * @param new_event The event to be pushed on the event stack. */ inline void add_read_write_event(cl::Event new_event) const { this->read_events_.push_back(new_event); this->write_events_.push_back(new_event); } /** * Waits for the write events and clears the read event stack. */ inline void wait_for_write_events() const { cl::CommandQueue queue = opencl_context.queue(); cl::Event copy_event; queue.enqueueBarrierWithWaitList(&this->write_events(), &copy_event); copy_event.wait(); write_events_.clear(); return; } /** * Waits for the read events and clears the read event stack. */ inline void wait_for_read_events() const { cl::CommandQueue queue = opencl_context.queue(); cl::Event copy_event; queue.enqueueBarrierWithWaitList(&this->read_events(), &copy_event); copy_event.wait(); read_events_.clear(); return; } /** * Waits for read and write events to finish and clears the read, write, and * read/write event stacks. */ inline void wait_for_read_write_events() const { cl::CommandQueue queue = opencl_context.queue(); cl::Event copy_event; const std::vector<cl::Event> mat_events = this->read_write_events(); queue.enqueueBarrierWithWaitList(&mat_events, &copy_event); copy_event.wait(); read_events_.clear(); write_events_.clear(); return; } const cl::Buffer& buffer() const { return buffer_cl_; } cl::Buffer& buffer() { return buffer_cl_; } matrix_cl() : rows_(0), cols_(0) {} matrix_cl(const matrix_cl<T>& A) : rows_(A.rows()), cols_(A.cols()), view_(A.view()) { if (A.size() == 0) return; this->wait_for_read_write_events(); A.wait_for_write_events(); cl::Context& ctx = opencl_context.context(); cl::CommandQueue queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * size()); cl::Event cstr_event; queue.enqueueCopyBuffer(A.buffer(), this->buffer(), 0, 0, A.size() * sizeof(T), &A.write_events(), &cstr_event); this->add_write_event(cstr_event); A.add_read_event(cstr_event); } catch (const cl::Error& e) { check_opencl_error("copy (OpenCL)->(OpenCL)", e); } } matrix_cl(matrix_cl<T>&& A) : buffer_cl_(A.buffer_cl_), rows_(A.rows_), cols_(A.cols_), view_(A.view_), write_events_(std::move(A.write_events_)), read_events_(std::move(A.read_events_)) {} /** * Constructor for the matrix_cl that * creates a copy of the Eigen matrix on the OpenCL device. * * * @tparam R row type * @tparam C column type * @param A the Eigen matrix * * @throw <code>std::invalid_argument</code> if the * matrices do not have matching dimensions */ template <int R, int C> explicit matrix_cl(const std::vector<Eigen::Matrix<T, R, C>>& A) try : rows_(A.empty() ? 0 : A[0].size()), cols_(A.size()) { if (this->size() == 0) return; cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); // creates the OpenCL buffer to copy the Eigen // matrix to the OpenCL device buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * size()); for (int i = 0, offset_size = 0; i < cols_; i++, offset_size += rows_) { check_size_match("matrix constructor", "input rows", A[i].size(), "matrix_cl rows", rows_); /** * Writes the contents of A[i] to the OpenCL buffer * starting at the offset sizeof(double)*start. * CL_TRUE denotes that the call is blocking as * we do not want to execute any further kernels * on the device until we are sure that the data * is finished transfering */ cl::Event write_event; queue.enqueueWriteBuffer( buffer_cl_, CL_FALSE, sizeof(double) * offset_size, sizeof(double) * rows_, A[i].data(), NULL, &write_event); this->add_write_event(write_event); } } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } /** * Constructor for the matrix_cl that * only allocates the buffer on the OpenCL device. * Regardless of `partial_view`, whole matrix is stored. * * @param rows number of matrix rows, must be greater or equal to 0 * @param cols number of matrix columns, must be greater or equal to 0 * @param partial_view which part of the matrix is used * * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions * */ matrix_cl(const int& rows, const int& cols, matrix_cl_view partial_view = matrix_cl_view::Entire) : rows_(rows), cols_(cols), view_(partial_view) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); try { // creates the OpenCL buffer of the provided size buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * rows_ * cols_); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Constructor for the matrix_cl that * creates a copy of the Eigen matrix on the OpenCL device. * Regardless of `partial_view`, whole matrix is stored. * * @tparam T type of data in the \c Eigen \c Matrix * @param A the \c Eigen \c Matrix * @param partial_view which part of the matrix is used * * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions */ template <int R, int C> explicit matrix_cl(const Eigen::Matrix<T, R, C>& A, matrix_cl_view partial_view = matrix_cl_view::Entire) : rows_(A.rows()), cols_(A.cols()), view_(partial_view) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * A.size()); cl::Event transfer_event; queue.enqueueWriteBuffer(buffer_cl_, CL_FALSE, 0, sizeof(T) * A.size(), A.data(), NULL, &transfer_event); this->add_write_event(transfer_event); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Construct from \c std::vector with given rows and columns * * @param A Standard vector * @param R Number of rows the matrix should have. * @param C Number of columns the matrix should have. * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions */ explicit matrix_cl(const std::vector<T>& A, const int& R, const int& C) : rows_(R), cols_(C) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * A.size()); cl::Event transfer_event; queue.enqueueWriteBuffer(buffer_cl_, CL_FALSE, 0, sizeof(T) * A.size(), A.data(), NULL, &transfer_event); this->add_write_event(transfer_event); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Assign a \c matrix_cl to another */ matrix_cl<T>& operator=(const matrix_cl<T>& a) { check_size_match("assignment of (OpenCL) matrices", "source.rows()", a.rows(), "destination.rows()", rows()); check_size_match("assignment of (OpenCL) matrices", "source.cols()", a.cols(), "destination.cols()", cols()); if (a.size() == 0) return; view_ = a.view(); this->wait_for_read_write_events(); a.wait_for_write_events(); cl::CommandQueue queue = opencl_context.queue(); try { cl::Event copy_event; queue.enqueueCopyBuffer(a.buffer(), this->buffer(), 0, 0, a.size() * sizeof(T), &a.write_events(), &copy_event); this->add_write_event(copy_event); a.add_read_event(copy_event); } catch (const cl::Error& e) { check_opencl_error("copy (OpenCL)->(OpenCL)", e); } return *this; } /** * Move a \c matrix_cl to another */ matrix_cl<T>& operator=(matrix_cl<T>&& a) { check_size_match("move of (OpenCL) matrix", "source.rows()", a.rows(), "destination.rows()", rows()); check_size_match("move of (OpenCL) matrix", "source.cols()", a.cols(), "destination.cols()", cols()); // Need to wait for all of matrices events before destroying old buffer this->wait_for_read_write_events(); buffer_cl_ = a.buffer(); view_ = a.view(); write_events_ = std::move(a.write_events_); read_events_ = std::move(a.read_events_); return *this; } /** * Assign a \c matrix_cl of one arithmetic type to another */ template <typename U, typename = enable_if_arithmetic<U>> matrix_cl<T>& operator=(const matrix_cl<U>& a) { check_size_match("assignment of (OpenCL) matrices", "source.rows()", a.rows(), "destination.rows()", rows()); check_size_match("assignment of (OpenCL) matrices", "source.cols()", a.cols(), "destination.cols()", cols()); // Need to wait for all of matrices events before destroying old buffer this->wait_for_read_write_events(); buffer_cl_ = a.buffer(); view_ = a.view(); return *this; } }; template <typename T> using matrix_cl_prim = matrix_cl<T, enable_if_arithmetic<T>>; template <typename T> using matrix_cl_fp = matrix_cl<T, enable_if_floating_point<T>>; } // namespace math } // namespace stan #endif #endif <commit_msg>fixed return with no value<commit_after>#ifndef STAN_MATH_OPENCL_MATRIX_CL_HPP #define STAN_MATH_OPENCL_MATRIX_CL_HPP #ifdef STAN_OPENCL #include <stan/math/opencl/opencl_context.hpp> #include <stan/math/opencl/matrix_cl_view.hpp> #include <stan/math/opencl/err/check_opencl.hpp> #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/meta.hpp> #include <stan/math/prim/arr/fun/vec_concat.hpp> #include <stan/math/prim/scal/err/check_size_match.hpp> #include <stan/math/prim/scal/err/domain_error.hpp> #include <CL/cl.hpp> #include <iostream> #include <string> #include <vector> #include <algorithm> /** * @file stan/math/opencl/matrix_cl.hpp * @brief The matrix_cl class - allocates memory space on the OpenCL device, * functions for transfering matrices to and from OpenCL devices */ namespace stan { namespace math { // Dummy class to instantiate matrix_cl to enable for specific types. template <typename T, typename = void> class matrix_cl {}; /** * Represents a matrix on the OpenCL device. * * @tparam T an arithmetic type for the type stored in the OpenCL buffer. */ template <typename T> class matrix_cl<T, enable_if_arithmetic<T>> { private: cl::Buffer buffer_cl_; // Holds the allocated memory on the device const int rows_; const int cols_; matrix_cl_view view_; // Holds info on if matrix is a special type mutable std::vector<cl::Event> write_events_; // Tracks write jobs mutable std::vector<cl::Event> read_events_; // Tracks reads public: typedef T type; // Forward declare the methods that work in place on the matrix template <matrix_cl_view matrix_view = matrix_cl_view::Entire> void zeros(); template <TriangularMapCL triangular_map = TriangularMapCL::LowerToUpper> void triangular_transpose(); void sub_block(const matrix_cl<T, enable_if_arithmetic<T>>& A, size_t A_i, size_t A_j, size_t this_i, size_t this_j, size_t nrows, size_t ncols); int rows() const { return rows_; } int cols() const { return cols_; } int size() const { return rows_ * cols_; } const matrix_cl_view& view() const { return view_; } void view(const matrix_cl_view& view) { view_ = view; } /** * Clear the write events from the event stacks. */ inline void clear_write_events() const { write_events_.clear(); return; } /** * Clear the read events from the event stacks. */ inline void clear_read_events() const { read_events_.clear(); return; } /** * Clear the write events from the event stacks. */ inline void clear_read_write_events() const { read_events_.clear(); write_events_.clear(); return; } /** * Get the events from the event stacks. * @return The write event stack. */ inline const std::vector<cl::Event>& write_events() const { return write_events_; } /** * Get the events from the event stacks. * @return The read/write event stack. */ inline const std::vector<cl::Event>& read_events() const { return read_events_; } /** * Get the events from the event stacks. * @return The read/write event stack. */ inline const std::vector<cl::Event> read_write_events() const { return vec_concat(this->read_events(), this->write_events()); } /** * Add an event to the read event stack. * @param new_event The event to be pushed on the event stack. */ inline void add_read_event(cl::Event new_event) const { this->read_events_.push_back(new_event); } /** * Add an event to the write event stack. * @param new_event The event to be pushed on the event stack. */ inline void add_write_event(cl::Event new_event) const { this->write_events_.push_back(new_event); } /** * Add an event to the read/write event stack. * @param new_event The event to be pushed on the event stack. */ inline void add_read_write_event(cl::Event new_event) const { this->read_events_.push_back(new_event); this->write_events_.push_back(new_event); } /** * Waits for the write events and clears the read event stack. */ inline void wait_for_write_events() const { cl::CommandQueue queue = opencl_context.queue(); cl::Event copy_event; queue.enqueueBarrierWithWaitList(&this->write_events(), &copy_event); copy_event.wait(); write_events_.clear(); return; } /** * Waits for the read events and clears the read event stack. */ inline void wait_for_read_events() const { cl::CommandQueue queue = opencl_context.queue(); cl::Event copy_event; queue.enqueueBarrierWithWaitList(&this->read_events(), &copy_event); copy_event.wait(); read_events_.clear(); return; } /** * Waits for read and write events to finish and clears the read, write, and * read/write event stacks. */ inline void wait_for_read_write_events() const { cl::CommandQueue queue = opencl_context.queue(); cl::Event copy_event; const std::vector<cl::Event> mat_events = this->read_write_events(); queue.enqueueBarrierWithWaitList(&mat_events, &copy_event); copy_event.wait(); read_events_.clear(); write_events_.clear(); return; } const cl::Buffer& buffer() const { return buffer_cl_; } cl::Buffer& buffer() { return buffer_cl_; } matrix_cl() : rows_(0), cols_(0) {} matrix_cl(const matrix_cl<T>& A) : rows_(A.rows()), cols_(A.cols()), view_(A.view()) { if (A.size() == 0) return; this->wait_for_read_write_events(); A.wait_for_write_events(); cl::Context& ctx = opencl_context.context(); cl::CommandQueue queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * size()); cl::Event cstr_event; queue.enqueueCopyBuffer(A.buffer(), this->buffer(), 0, 0, A.size() * sizeof(T), &A.write_events(), &cstr_event); this->add_write_event(cstr_event); A.add_read_event(cstr_event); } catch (const cl::Error& e) { check_opencl_error("copy (OpenCL)->(OpenCL)", e); } } matrix_cl(matrix_cl<T>&& A) : buffer_cl_(A.buffer_cl_), rows_(A.rows_), cols_(A.cols_), view_(A.view_), write_events_(std::move(A.write_events_)), read_events_(std::move(A.read_events_)) {} /** * Constructor for the matrix_cl that * creates a copy of the Eigen matrix on the OpenCL device. * * * @tparam R row type * @tparam C column type * @param A the Eigen matrix * * @throw <code>std::invalid_argument</code> if the * matrices do not have matching dimensions */ template <int R, int C> explicit matrix_cl(const std::vector<Eigen::Matrix<T, R, C>>& A) try : rows_(A.empty() ? 0 : A[0].size()), cols_(A.size()) { if (this->size() == 0) return; cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); // creates the OpenCL buffer to copy the Eigen // matrix to the OpenCL device buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * size()); for (int i = 0, offset_size = 0; i < cols_; i++, offset_size += rows_) { check_size_match("matrix constructor", "input rows", A[i].size(), "matrix_cl rows", rows_); /** * Writes the contents of A[i] to the OpenCL buffer * starting at the offset sizeof(double)*start. * CL_TRUE denotes that the call is blocking as * we do not want to execute any further kernels * on the device until we are sure that the data * is finished transfering */ cl::Event write_event; queue.enqueueWriteBuffer( buffer_cl_, CL_FALSE, sizeof(double) * offset_size, sizeof(double) * rows_, A[i].data(), NULL, &write_event); this->add_write_event(write_event); } } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } /** * Constructor for the matrix_cl that * only allocates the buffer on the OpenCL device. * Regardless of `partial_view`, whole matrix is stored. * * @param rows number of matrix rows, must be greater or equal to 0 * @param cols number of matrix columns, must be greater or equal to 0 * @param partial_view which part of the matrix is used * * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions * */ matrix_cl(const int& rows, const int& cols, matrix_cl_view partial_view = matrix_cl_view::Entire) : rows_(rows), cols_(cols), view_(partial_view) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); try { // creates the OpenCL buffer of the provided size buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * rows_ * cols_); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Constructor for the matrix_cl that * creates a copy of the Eigen matrix on the OpenCL device. * Regardless of `partial_view`, whole matrix is stored. * * @tparam T type of data in the \c Eigen \c Matrix * @param A the \c Eigen \c Matrix * @param partial_view which part of the matrix is used * * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions */ template <int R, int C> explicit matrix_cl(const Eigen::Matrix<T, R, C>& A, matrix_cl_view partial_view = matrix_cl_view::Entire) : rows_(A.rows()), cols_(A.cols()), view_(partial_view) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * A.size()); cl::Event transfer_event; queue.enqueueWriteBuffer(buffer_cl_, CL_FALSE, 0, sizeof(T) * A.size(), A.data(), NULL, &transfer_event); this->add_write_event(transfer_event); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Construct from \c std::vector with given rows and columns * * @param A Standard vector * @param R Number of rows the matrix should have. * @param C Number of columns the matrix should have. * @throw <code>std::system_error</code> if the * matrices do not have matching dimensions */ explicit matrix_cl(const std::vector<T>& A, const int& R, const int& C) : rows_(R), cols_(C) { if (size() == 0) { return; } cl::Context& ctx = opencl_context.context(); cl::CommandQueue& queue = opencl_context.queue(); try { buffer_cl_ = cl::Buffer(ctx, CL_MEM_READ_WRITE, sizeof(T) * A.size()); cl::Event transfer_event; queue.enqueueWriteBuffer(buffer_cl_, CL_FALSE, 0, sizeof(T) * A.size(), A.data(), NULL, &transfer_event); this->add_write_event(transfer_event); } catch (const cl::Error& e) { check_opencl_error("matrix constructor", e); } } /** * Assign a \c matrix_cl to another */ matrix_cl<T>& operator=(const matrix_cl<T>& a) { check_size_match("assignment of (OpenCL) matrices", "source.rows()", a.rows(), "destination.rows()", rows()); check_size_match("assignment of (OpenCL) matrices", "source.cols()", a.cols(), "destination.cols()", cols()); if (a.size() == 0) return *this; view_ = a.view(); this->wait_for_read_write_events(); a.wait_for_write_events(); cl::CommandQueue queue = opencl_context.queue(); try { cl::Event copy_event; queue.enqueueCopyBuffer(a.buffer(), this->buffer(), 0, 0, a.size() * sizeof(T), &a.write_events(), &copy_event); this->add_write_event(copy_event); a.add_read_event(copy_event); } catch (const cl::Error& e) { check_opencl_error("copy (OpenCL)->(OpenCL)", e); } return *this; } /** * Move a \c matrix_cl to another */ matrix_cl<T>& operator=(matrix_cl<T>&& a) { check_size_match("move of (OpenCL) matrix", "source.rows()", a.rows(), "destination.rows()", rows()); check_size_match("move of (OpenCL) matrix", "source.cols()", a.cols(), "destination.cols()", cols()); // Need to wait for all of matrices events before destroying old buffer this->wait_for_read_write_events(); buffer_cl_ = a.buffer(); view_ = a.view(); write_events_ = std::move(a.write_events_); read_events_ = std::move(a.read_events_); return *this; } /** * Assign a \c matrix_cl of one arithmetic type to another */ template <typename U, typename = enable_if_arithmetic<U>> matrix_cl<T>& operator=(const matrix_cl<U>& a) { check_size_match("assignment of (OpenCL) matrices", "source.rows()", a.rows(), "destination.rows()", rows()); check_size_match("assignment of (OpenCL) matrices", "source.cols()", a.cols(), "destination.cols()", cols()); // Need to wait for all of matrices events before destroying old buffer this->wait_for_read_write_events(); buffer_cl_ = a.buffer(); view_ = a.view(); return *this; } }; template <typename T> using matrix_cl_prim = matrix_cl<T, enable_if_arithmetic<T>>; template <typename T> using matrix_cl_fp = matrix_cl<T, enable_if_floating_point<T>>; } // namespace math } // namespace stan #endif #endif <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_ARR_FUN_SUM_HPP #define STAN_MATH_PRIM_ARR_FUN_SUM_HPP #include <cstddef> #include <vector> namespace stan { namespace math { /** * Return the sum of the values in the specified standard vector. * * @tparam T Type of elements summed. * @param xs Standard vector to sum. * @return Sum of elements. */ template <typename T> inline T sum(const std::vector<T>& xs) { if (xs.size() == 0) return 0; T sum(xs[0]); for (size_t i = 1; i < xs.size(); ++i) sum += xs[i]; return sum; } } // namespace math } // namespace stan #endif <commit_msg>Use std::accumulate in prim sum's std::vector impl.<commit_after>#ifndef STAN_MATH_PRIM_ARR_FUN_SUM_HPP #define STAN_MATH_PRIM_ARR_FUN_SUM_HPP #include <cstddef> #include <vector> #include <numeric> namespace stan { namespace math { /** * Return the sum of the values in the specified standard vector. * * @tparam T Type of elements summed. * @param xs Standard vector to sum. * @return Sum of elements. */ template <typename T> inline T sum(const std::vector<T>& xs) { return std::accumulate(xs.begin(), xs.end(), T{0}); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2014 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Abaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #include <abaclade.hxx> #include <abaclade/process.hxx> #if ABC_HOST_API_POSIX #include <sys/types.h> #include <sys/wait.h> #endif //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::process namespace abc { process::process() : #if ABC_HOST_API_POSIX m_h(0) { #elif ABC_HOST_API_WIN32 m_h(nullptr) { #else #error "TODO: HOST_API" #endif } process::~process() { if (joinable()) { // TODO: std::abort() or something similar. } #if ABC_HOST_API_WIN32 if (m_h) { ::CloseHandle(m_h); } #endif } #if ABC_HOST_API_WIN32 id_type process::id() const { DWORD iPid = ::GetProcessId(m_h); if (iPid == 0) { throw_os_error(); } return iPid; } #endif void process::join() { ABC_TRACE_FUNC(this); #if ABC_HOST_API_POSIX ::siginfo_t si; if (::waitid(P_PID, static_cast< ::pid_t>(m_h), &si, WEXITED) == -1) { throw_os_error(); } #elif ABC_HOST_API_WIN32 DWORD iRet = ::WaitForSingleObject(m_h, INFINITE); if (iRet == WAIT_FAILED) { throw_os_error(); } #else #error "TODO: HOST_API" #endif } } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// <commit_msg>Fix cast to ::id_t instead of ::pid_t<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2014 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Abaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #include <abaclade.hxx> #include <abaclade/process.hxx> #if ABC_HOST_API_POSIX #include <sys/types.h> #include <sys/wait.h> #endif //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::process namespace abc { process::process() : #if ABC_HOST_API_POSIX m_h(0) { #elif ABC_HOST_API_WIN32 m_h(nullptr) { #else #error "TODO: HOST_API" #endif } process::~process() { if (joinable()) { // TODO: std::abort() or something similar. } #if ABC_HOST_API_WIN32 if (m_h) { ::CloseHandle(m_h); } #endif } #if ABC_HOST_API_WIN32 id_type process::id() const { DWORD iPid = ::GetProcessId(m_h); if (iPid == 0) { throw_os_error(); } return iPid; } #endif void process::join() { ABC_TRACE_FUNC(this); #if ABC_HOST_API_POSIX ::siginfo_t si; if (::waitid(P_PID, static_cast< ::id_t>(m_h), &si, WEXITED) == -1) { throw_os_error(); } #elif ABC_HOST_API_WIN32 DWORD iRet = ::WaitForSingleObject(m_h, INFINITE); if (iRet == WAIT_FAILED) { throw_os_error(); } #else #error "TODO: HOST_API" #endif } } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>#include "TestConfigurator.h" #include <iostream> #include "Catch.h" #include "EACirc.h" TestConfigurator::TestConfigurator() : m_currentProject(0) { m_projects.push(PROJECT_ESTREAM); m_projects.push(PROJECT_SHA3); m_projects.push(PROJECT_FILE_DISTINGUISHER); } TestConfigurator::TestConfigurator(int projectType) : m_currentProject(0) { m_projects.push(projectType); } TestConfigurator::~TestConfigurator() {} bool TestConfigurator::nextProject() { if (m_projects.empty()) { return false; } m_currentProject = m_projects.front(); m_projects.pop(); if (mainLogger.getLogging()) { WARN("########"); WARN(string("######## Testing project ")+toString(m_currentProject)+" ########"); WARN("########"); } return true; } int TestConfigurator::getCurrentProject() { return m_currentProject; } void TestConfigurator::compareFilesByLine(string filename1, string filename2) const { string line1,line2; ifstream file1(filename1); ifstream file2(filename2); if (!file1.is_open() || !file2.is_open()) { WARN("Could not open files " << filename1 << " and " << filename2 << "."); return; } int differCount = 0; while ((!file1.eof() || !file2.eof()) && differCount <=5 ) { getline(file1,line1); getline(file2,line2); if (line1 != line2) { differCount++; } SCOPED_INFO("Comparing files " << filename1 << " and " << filename2 << "."); CHECK(line1 == line2); } if (differCount > 5) { WARN("Given files (" << filename1 << ", " << filename2 << " differ in more than 6 lines!"); } file1.close(); file2.close(); } void TestConfigurator::backupFile(string filename) { string backupFilename = filename + BACKUP_SUFFIX; remove(backupFilename.c_str()); CHECK(rename(filename.c_str(),backupFilename.c_str()) == 0); } void TestConfigurator::backupResults() { backupFile(FILE_GALIB_SCORES); backupFile(FILE_FITNESS_PROGRESS); backupFile(FILE_BEST_FITNESS); backupFile(FILE_AVG_FITNESS); backupFile(FILE_STATE); backupFile(FILE_POPULATION); } void TestConfigurator::compareResults() const { compareFilesByLine(FILE_GALIB_SCORES,string(FILE_GALIB_SCORES)+BACKUP_SUFFIX); compareFilesByLine(FILE_FITNESS_PROGRESS,string(FILE_FITNESS_PROGRESS)+BACKUP_SUFFIX); compareFilesByLine(FILE_BEST_FITNESS,string(FILE_BEST_FITNESS)+BACKUP_SUFFIX); compareFilesByLine(FILE_AVG_FITNESS,string(FILE_AVG_FITNESS)+BACKUP_SUFFIX); compareFilesByLine(FILE_STATE,string(FILE_STATE)+BACKUP_SUFFIX); compareFilesByLine(FILE_POPULATION,string(FILE_POPULATION)+BACKUP_SUFFIX); } void TestConfigurator::runEACirc() const { if (mainLogger.getLogging()) { WARN("######## Running EACirc ########"); mainLogger.out(LOGGER_INFO) << "Configuration file: " << FILE_CONFIG << endl; } EACirc eacirc; eacirc.loadConfiguration(FILE_CONFIG); eacirc.prepare(); eacirc.initializeState(); eacirc.run(); if (mainLogger.getLogging()) { WARN("######## Ending EACirc (status: " << statusToString(eacirc.getStatus()) << " ) ########"); } CHECK(eacirc.getStatus() == STAT_OK); } void TestConfigurator::prepareConfiguration(int projectType) const { string projectConfiguration = IProject::getTestingConfiguration(projectType); string configuration; configuration += "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><EACIRC>"; configuration += mainConfiguration; configuration += projectConfiguration; configuration += "</EACIRC>"; ofstream configFile(FILE_CONFIG); REQUIRE(configFile.is_open()); configFile << configuration; configFile.close(); // set correct project constant TiXmlNode* pRootConfig = NULL; REQUIRE(loadXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK); REQUIRE(setXMLElementValue(pRootConfig,"MAIN/PROJECT",toString(projectType)) == STAT_OK); REQUIRE(saveXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK); pRootConfig = NULL; } void TestConfigurator::prepareConfiguration() const { prepareConfiguration(m_currentProject); } string TestConfigurator::mainConfiguration = "<NOTES>self-test configuration</NOTES>" "<MAIN>" " <CIRCUIT_REPRESENTATION>1</CIRCUIT_REPRESENTATION>" " <PROJECT>100</PROJECT>" " <EVALUATOR>26</EVALUATOR>" " <EVALUATOR_PRECISION>10</EVALUATOR_PRECISION>" " <RECOMMENCE_COMPUTATION>0</RECOMMENCE_COMPUTATION>" " <LOAD_INITIAL_POPULATION>0</LOAD_INITIAL_POPULATION>" " <NUM_GENERATIONS>20</NUM_GENERATIONS>" " <SAVE_STATE_FREQ>10</SAVE_STATE_FREQ>" " <CIRCUIT_SIZE_INPUT>16</CIRCUIT_SIZE_INPUT>" " <CIRCUIT_SIZE_OUTPUT>2</CIRCUIT_SIZE_OUTPUT>" "</MAIN>" "<OUTPUTS>" " <GRAPH_FILES>1</GRAPH_FILES>" " <INTERMEDIATE_CIRCUITS>1</INTERMEDIATE_CIRCUITS>" " <ALLOW_PRUNNING>0</ALLOW_PRUNNING>" " <SAVE_TEST_VECTORS>0</SAVE_TEST_VECTORS>" "</OUTPUTS>" "<RANDOM>" " <USE_FIXED_SEED>1</USE_FIXED_SEED>" " <SEED>123456789</SEED>" " <BIAS_RNDGEN_FACTOR>95</BIAS_RNDGEN_FACTOR>" " <USE_NET_SHARE>0</USE_NET_SHARE>" " <QRNG_PATH>../../qrng/;/mnt/centaur/home/eacirc/qrng/;C:/RNG/;D:/RandomData/</QRNG_PATH>" " <QRNG_MAX_INDEX>192</QRNG_MAX_INDEX>" "</RANDOM>" "<CUDA>" " <ENABLED>0</ENABLED>" " <SOMETHING>something</SOMETHING>" "</CUDA>" "<GA>" " <EVOLUTION_OFF>0</EVOLUTION_OFF>" " <PROB_MUTATION>0.05</PROB_MUTATION>" " <MUTATE_FUNCTIONS>1</MUTATE_FUNCTIONS>" " <MUTATE_CONNECTORS>1</MUTATE_CONNECTORS>" " <PROB_CROSSING>0.5</PROB_CROSSING>" " <POPULATION_SIZE>20</POPULATION_SIZE>" " <REPLACEMENT_SIZE>13</REPLACEMENT_SIZE>" "</GA>" "<GATE_CIRCUIT>" " <NUM_LAYERS>5</NUM_LAYERS>" " <SIZE_LAYER>8</SIZE_LAYER>" " <NUM_CONNECTORS>4</NUM_CONNECTORS>" " <USE_MEMORY>0</USE_MEMORY>" " <SIZE_MEMORY>2</SIZE_MEMORY>" " <ALLOWED_FUNCTIONS>" " <FNC_NOP>1</FNC_NOP>" " <FNC_CONS>1</FNC_CONS>" " <FNC_AND>1</FNC_AND>" " <FNC_NAND>1</FNC_NAND>" " <FNC_OR>1</FNC_OR>" " <FNC_XOR>1</FNC_XOR>" " <FNC_NOR>1</FNC_NOR>" " <FNC_NOT>1</FNC_NOT>" " <FNC_SHIL>1</FNC_SHIL>" " <FNC_SHIR>1</FNC_SHIR>" " <FNC_ROTL>1</FNC_ROTL>" " <FNC_ROTR>1</FNC_ROTR>" " <FNC_EQ>1</FNC_EQ>" " <FNC_LT>1</FNC_LT>" " <FNC_GT>1</FNC_GT>" " <FNC_LEQ>1</FNC_LEQ>" " <FNC_GEQ>1</FNC_GEQ>" " <FNC_BSLC>1</FNC_BSLC>" " <FNC_READ>1</FNC_READ>" " <FNC_EXT>0</FNC_EXT>" " </ALLOWED_FUNCTIONS>" "</GATE_CIRCUIT>" "<POLYNOMIAL_CIRCUIT>" " <MUTATE_TERM_STRATEGY>0</MUTATE_TERM_STRATEGY>" " <MAX_TERMS>50</MAX_TERMS>" " <TERM_COUNT_P>0.70</TERM_COUNT_P>" " <TERM_VAR_P>0.60</TERM_VAR_P>" " <ADD_TERM_P>0.05</ADD_TERM_P>" " <ADD_TERM_STRATEGY>0</ADD_TERM_STRATEGY>" " <RM_TERM_P>0.05</RM_TERM_P>" " <RM_TERM_STRATEGY>0</RM_TERM_STRATEGY>" " <CROSSOVER_RANDOMIZE_POLY>1</CROSSOVER_RANDOMIZE_POLY>" " <CROSSOVER_TERM_P>0.1</CROSSOVER_TERM_P>" "</POLYNOMIAL_CIRCUIT>" "<TEST_VECTORS>" " <INPUT_LENGTH>16</INPUT_LENGTH>" " <OUTPUT_LENGTH>2</OUTPUT_LENGTH>" " <SET_SIZE>1000</SET_SIZE>" " <SET_CHANGE_FREQ>5</SET_CHANGE_FREQ>" " <EVALUATE_BEFORE_TEST_VECTOR_CHANGE>0</EVALUATE_BEFORE_TEST_VECTOR_CHANGE>" " <EVALUATE_EVERY_STEP>0</EVALUATE_EVERY_STEP>" "</TEST_VECTORS>"; <commit_msg>Added missing XML config NUM_POLYNOMIALS to the test configuration.<commit_after>#include "TestConfigurator.h" #include <iostream> #include "Catch.h" #include "EACirc.h" TestConfigurator::TestConfigurator() : m_currentProject(0) { m_projects.push(PROJECT_ESTREAM); m_projects.push(PROJECT_SHA3); m_projects.push(PROJECT_FILE_DISTINGUISHER); } TestConfigurator::TestConfigurator(int projectType) : m_currentProject(0) { m_projects.push(projectType); } TestConfigurator::~TestConfigurator() {} bool TestConfigurator::nextProject() { if (m_projects.empty()) { return false; } m_currentProject = m_projects.front(); m_projects.pop(); if (mainLogger.getLogging()) { WARN("########"); WARN(string("######## Testing project ")+toString(m_currentProject)+" ########"); WARN("########"); } return true; } int TestConfigurator::getCurrentProject() { return m_currentProject; } void TestConfigurator::compareFilesByLine(string filename1, string filename2) const { string line1,line2; ifstream file1(filename1); ifstream file2(filename2); if (!file1.is_open() || !file2.is_open()) { WARN("Could not open files " << filename1 << " and " << filename2 << "."); return; } int differCount = 0; while ((!file1.eof() || !file2.eof()) && differCount <=5 ) { getline(file1,line1); getline(file2,line2); if (line1 != line2) { differCount++; } SCOPED_INFO("Comparing files " << filename1 << " and " << filename2 << "."); CHECK(line1 == line2); } if (differCount > 5) { WARN("Given files (" << filename1 << ", " << filename2 << " differ in more than 6 lines!"); } file1.close(); file2.close(); } void TestConfigurator::backupFile(string filename) { string backupFilename = filename + BACKUP_SUFFIX; remove(backupFilename.c_str()); CHECK(rename(filename.c_str(),backupFilename.c_str()) == 0); } void TestConfigurator::backupResults() { backupFile(FILE_GALIB_SCORES); backupFile(FILE_FITNESS_PROGRESS); backupFile(FILE_BEST_FITNESS); backupFile(FILE_AVG_FITNESS); backupFile(FILE_STATE); backupFile(FILE_POPULATION); } void TestConfigurator::compareResults() const { compareFilesByLine(FILE_GALIB_SCORES,string(FILE_GALIB_SCORES)+BACKUP_SUFFIX); compareFilesByLine(FILE_FITNESS_PROGRESS,string(FILE_FITNESS_PROGRESS)+BACKUP_SUFFIX); compareFilesByLine(FILE_BEST_FITNESS,string(FILE_BEST_FITNESS)+BACKUP_SUFFIX); compareFilesByLine(FILE_AVG_FITNESS,string(FILE_AVG_FITNESS)+BACKUP_SUFFIX); compareFilesByLine(FILE_STATE,string(FILE_STATE)+BACKUP_SUFFIX); compareFilesByLine(FILE_POPULATION,string(FILE_POPULATION)+BACKUP_SUFFIX); } void TestConfigurator::runEACirc() const { if (mainLogger.getLogging()) { WARN("######## Running EACirc ########"); mainLogger.out(LOGGER_INFO) << "Configuration file: " << FILE_CONFIG << endl; } EACirc eacirc; eacirc.loadConfiguration(FILE_CONFIG); eacirc.prepare(); eacirc.initializeState(); eacirc.run(); if (mainLogger.getLogging()) { WARN("######## Ending EACirc (status: " << statusToString(eacirc.getStatus()) << " ) ########"); } CHECK(eacirc.getStatus() == STAT_OK); } void TestConfigurator::prepareConfiguration(int projectType) const { string projectConfiguration = IProject::getTestingConfiguration(projectType); string configuration; configuration += "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><EACIRC>"; configuration += mainConfiguration; configuration += projectConfiguration; configuration += "</EACIRC>"; ofstream configFile(FILE_CONFIG); REQUIRE(configFile.is_open()); configFile << configuration; configFile.close(); // set correct project constant TiXmlNode* pRootConfig = NULL; REQUIRE(loadXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK); REQUIRE(setXMLElementValue(pRootConfig,"MAIN/PROJECT",toString(projectType)) == STAT_OK); REQUIRE(saveXMLFile(pRootConfig,FILE_CONFIG) == STAT_OK); pRootConfig = NULL; } void TestConfigurator::prepareConfiguration() const { prepareConfiguration(m_currentProject); } string TestConfigurator::mainConfiguration = "<NOTES>self-test configuration</NOTES>" "<MAIN>" " <CIRCUIT_REPRESENTATION>1</CIRCUIT_REPRESENTATION>" " <PROJECT>100</PROJECT>" " <EVALUATOR>26</EVALUATOR>" " <EVALUATOR_PRECISION>10</EVALUATOR_PRECISION>" " <RECOMMENCE_COMPUTATION>0</RECOMMENCE_COMPUTATION>" " <LOAD_INITIAL_POPULATION>0</LOAD_INITIAL_POPULATION>" " <NUM_GENERATIONS>20</NUM_GENERATIONS>" " <SAVE_STATE_FREQ>10</SAVE_STATE_FREQ>" " <CIRCUIT_SIZE_INPUT>16</CIRCUIT_SIZE_INPUT>" " <CIRCUIT_SIZE_OUTPUT>2</CIRCUIT_SIZE_OUTPUT>" "</MAIN>" "<OUTPUTS>" " <GRAPH_FILES>1</GRAPH_FILES>" " <INTERMEDIATE_CIRCUITS>1</INTERMEDIATE_CIRCUITS>" " <ALLOW_PRUNNING>0</ALLOW_PRUNNING>" " <SAVE_TEST_VECTORS>0</SAVE_TEST_VECTORS>" "</OUTPUTS>" "<RANDOM>" " <USE_FIXED_SEED>1</USE_FIXED_SEED>" " <SEED>123456789</SEED>" " <BIAS_RNDGEN_FACTOR>95</BIAS_RNDGEN_FACTOR>" " <USE_NET_SHARE>0</USE_NET_SHARE>" " <QRNG_PATH>../../qrng/;/mnt/centaur/home/eacirc/qrng/;C:/RNG/;D:/RandomData/</QRNG_PATH>" " <QRNG_MAX_INDEX>192</QRNG_MAX_INDEX>" "</RANDOM>" "<CUDA>" " <ENABLED>0</ENABLED>" " <SOMETHING>something</SOMETHING>" "</CUDA>" "<GA>" " <EVOLUTION_OFF>0</EVOLUTION_OFF>" " <PROB_MUTATION>0.05</PROB_MUTATION>" " <MUTATE_FUNCTIONS>1</MUTATE_FUNCTIONS>" " <MUTATE_CONNECTORS>1</MUTATE_CONNECTORS>" " <PROB_CROSSING>0.5</PROB_CROSSING>" " <POPULATION_SIZE>20</POPULATION_SIZE>" " <REPLACEMENT_SIZE>13</REPLACEMENT_SIZE>" "</GA>" "<GATE_CIRCUIT>" " <NUM_LAYERS>5</NUM_LAYERS>" " <SIZE_LAYER>8</SIZE_LAYER>" " <NUM_CONNECTORS>4</NUM_CONNECTORS>" " <USE_MEMORY>0</USE_MEMORY>" " <SIZE_MEMORY>2</SIZE_MEMORY>" " <ALLOWED_FUNCTIONS>" " <FNC_NOP>1</FNC_NOP>" " <FNC_CONS>1</FNC_CONS>" " <FNC_AND>1</FNC_AND>" " <FNC_NAND>1</FNC_NAND>" " <FNC_OR>1</FNC_OR>" " <FNC_XOR>1</FNC_XOR>" " <FNC_NOR>1</FNC_NOR>" " <FNC_NOT>1</FNC_NOT>" " <FNC_SHIL>1</FNC_SHIL>" " <FNC_SHIR>1</FNC_SHIR>" " <FNC_ROTL>1</FNC_ROTL>" " <FNC_ROTR>1</FNC_ROTR>" " <FNC_EQ>1</FNC_EQ>" " <FNC_LT>1</FNC_LT>" " <FNC_GT>1</FNC_GT>" " <FNC_LEQ>1</FNC_LEQ>" " <FNC_GEQ>1</FNC_GEQ>" " <FNC_BSLC>1</FNC_BSLC>" " <FNC_READ>1</FNC_READ>" " <FNC_EXT>0</FNC_EXT>" " </ALLOWED_FUNCTIONS>" "</GATE_CIRCUIT>" "<POLYNOMIAL_CIRCUIT>" " <NUM_POLYNOMIALS>1</NUM_POLYNOMIALS>" " <MUTATE_TERM_STRATEGY>0</MUTATE_TERM_STRATEGY>" " <MAX_TERMS>50</MAX_TERMS>" " <TERM_COUNT_P>0.70</TERM_COUNT_P>" " <TERM_VAR_P>0.60</TERM_VAR_P>" " <ADD_TERM_P>0.05</ADD_TERM_P>" " <ADD_TERM_STRATEGY>0</ADD_TERM_STRATEGY>" " <RM_TERM_P>0.05</RM_TERM_P>" " <RM_TERM_STRATEGY>0</RM_TERM_STRATEGY>" " <CROSSOVER_RANDOMIZE_POLY>1</CROSSOVER_RANDOMIZE_POLY>" " <CROSSOVER_TERM_P>0.1</CROSSOVER_TERM_P>" "</POLYNOMIAL_CIRCUIT>" "<TEST_VECTORS>" " <INPUT_LENGTH>16</INPUT_LENGTH>" " <OUTPUT_LENGTH>2</OUTPUT_LENGTH>" " <SET_SIZE>1000</SET_SIZE>" " <SET_CHANGE_FREQ>5</SET_CHANGE_FREQ>" " <EVALUATE_BEFORE_TEST_VECTOR_CHANGE>0</EVALUATE_BEFORE_TEST_VECTOR_CHANGE>" " <EVALUATE_EVERY_STEP>0</EVALUATE_EVERY_STEP>" "</TEST_VECTORS>"; <|endoftext|>
<commit_before>#ifndef MULTIWORDINTEGERARITHMETICS_HPP #define MULTIWORDINTEGERARITHMETICS_HPP #include "MultiwordInteger.hpp" template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType>& MultiwordInteger<size, storageType>::operator+=(MultiwordInteger<size, storageType> const &o) { storageType c = 0; for(unsigned i = 0; i < size; i++) { bigType t = this->s[i] + o.s[i] + c; this->s[i] = t; c = t >> storageSize; } return *this; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType>& MultiwordInteger<size, storageType>::operator-=(MultiwordInteger<size, storageType> const &o) { bigType c = 0; for (unsigned i = 0; i < size; i++) { c += this->s[i]; c -= o.s[i]; this->s[i] = c; c = signedType(c>>storageSize); } return *this; } template<unsigned size, typename storageType> template<unsigned otherSize> constexpr MultiwordInteger<size, storageType>& MultiwordInteger<size, storageType>::operator*=(MultiwordInteger<otherSize, storageType> const &o) { MultiwordInteger<size, storageType> nv; this->mul<otherSize, size>(o, &nv); *this = nv; return *this; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType>& MultiwordInteger<size, storageType>::operator*=(int64_t const &o) { MultiwordInteger<size, storageType> nv(o); nv *= *this; *this = nv; return *this; } template<unsigned size, typename storageType> template<unsigned otherSize> constexpr MultiwordInteger<size, storageType>& MultiwordInteger<size, storageType>::operator/=(MultiwordInteger<otherSize, storageType> const &o) { quotrem(o, *this, static_cast<MultiwordInteger<otherSize, storageType>*>(nullptr)); return *this; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType>& MultiwordInteger<size, storageType>::operator%=(MultiwordInteger<size, storageType> const &o) { *this = *this % o; return *this; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType> operator+ (MultiwordInteger<size, storageType> left, MultiwordInteger<size, storageType> const &right) { return left += right; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType> operator- (MultiwordInteger<size, storageType> left, MultiwordInteger<size, storageType> const &right) { return left -= right; } template<unsigned size, typename storageType, unsigned otherSize> constexpr MultiwordInteger<size+otherSize, storageType> operator* (MultiwordInteger<size, storageType> left, MultiwordInteger<otherSize, storageType> const &right) { MultiwordInteger<size+otherSize, storageType> out; left.mul(right, &out); return out; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size+8/sizeof(storageType), storageType> operator* (MultiwordInteger<size, storageType> left, int64_t const &right) { MultiwordInteger<size+8/sizeof(storageType), storageType> out(right); out *= *left; return out; } template<unsigned size, typename storageType, unsigned otherSize> constexpr MultiwordInteger<size, storageType> operator/ (MultiwordInteger<size, storageType> left, MultiwordInteger<otherSize, storageType> const &right) { return left /= right; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType> operator/ (MultiwordInteger<size, storageType> left, int64_t const &right) { return left /= right; } template<unsigned size, typename storageType, unsigned otherSize> constexpr MultiwordInteger<otherSize, storageType> operator% (MultiwordInteger<size, storageType> left, MultiwordInteger<otherSize, storageType> const &right) { MultiwordInteger<size, storageType> q; MultiwordInteger<otherSize, storageType> r; left.quotrem(right, q, &r); return r; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType>& MultiwordInteger<size, storageType>::operator++() { bigType c = 1; for (unsigned i = 0; i < size && c; i++) { c += s[i]; s[i] = c; c >>= storageSize; } return *this; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType> MultiwordInteger<size, storageType>::operator++(int) { MultiwordInteger<size, storageType> r(*this); ++(*this); return r; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType>& MultiwordInteger<size, storageType>::operator--() { bigType c = ~static_cast<bigType>(0); for (unsigned i = 0; i < size && c; i++) { c += s[i]; s[i] = c; c >>= storageSize; } return *this; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType> MultiwordInteger<size, storageType>::operator--(int) { MultiwordInteger<size, storageType> r(*this); --(*this); return r; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType> MultiwordInteger<size, storageType>::operator- () const { MultiwordInteger<size, storageType> r(*this); r.negate(); return r; } template<unsigned size, typename storageType> template<unsigned otherSize, unsigned outSize> constexpr void MultiwordInteger<size, storageType>::mul ( MultiwordInteger<otherSize, storageType> const &o, MultiwordInteger<outSize, storageType> *out) const{ *out = storageType(0); unsigned limitThis = size > outSize ? outSize : size; for (unsigned i = 0; i < limitThis; i++) { unsigned limitOther = i + otherSize < outSize ? otherSize : outSize - i; storageType k = 0; for (unsigned j = 0; j < limitOther; j++) { bigType t = static_cast<bigType>(this->s[i]) * o.s[j] + out->s[i+j] + k; out->s[i+j] = t; k = t >> storageSize; } out->s[i + limitOther] = k; } // r has unsigned product, correct if this or o are less than zero if (static_cast<signedType>(o.s[otherSize-1]) < 0 && otherSize < outSize) { MultiwordInteger<outSize, storageType> tmp(*this); tmp <<= (storageSize * otherSize); *out -= tmp; } if(static_cast<signedType>(this->s[size-1]) < 0 && size < outSize) { MultiwordInteger<outSize, storageType> tmp(o); tmp <<= storageSize * size; *out -= tmp; } } template<unsigned size, typename storageType> template<unsigned otherSize> constexpr void MultiwordInteger<size, storageType>::quotrem( MultiwordInteger<otherSize, storageType> divisor, MultiwordInteger<size, storageType> &qotient, MultiwordInteger<otherSize, storageType> *remainder) const { unsigned divisor_length = otherSize, dividend_length = size; size_t divisor_nlz = divisor.is_negative() ? ((-divisor).leading_zeros()) : divisor.leading_zeros(); divisor_length -= divisor_nlz / storageSize; if (otherSize > 1) { divisor_nlz %= storageSize; } dividend_length -= this->leading_zeros()/storageSize; if (dividend_length == 0) { qotient = storageType(0); if (remainder) { *remainder = *this; } return; } /* Dividing by zero. Set the dividend as close to infinity as we can, * and the remainder to zero. */ if (divisor_length == 0) { if (this->is_negative()) { qotient = _minVal(); } else { qotient = _maxVal(); } if (remainder) { *remainder = storageType(0); } return; } bool negate_result = false; bool negative_remainder = false; MultiwordInteger<size+1, storageType> unsigned_dividend(*this); if (this->is_negative()) { negate_result = true; unsigned_dividend.negate(); } if (divisor.is_negative()) { negate_result = !negate_result; negative_remainder = true; divisor.negate(); } if (divisor_length < 2) { unsignedQuotrem(unsigned_dividend, divisor, qotient, dividend_length); } else { unsignedQuotrem(unsigned_dividend, divisor, qotient, dividend_length, divisor_length, divisor_nlz); } if (negate_result) { qotient.negate(); if (unsigned_dividend) { --qotient; } } if (!remainder) { return; } if (divisor_length >= 2) { unsigned_dividend >>= divisor_nlz; } *remainder = unsigned_dividend; if (negate_result && unsigned_dividend) { *remainder -= MultiwordInteger<size+1, storageType>(divisor); if (!negative_remainder) { // Remainder's negative, we want it to be positive remainder->negate(); } } else if (negative_remainder) { remainder->negate(); } } template<unsigned size, typename storageType> template<unsigned divisorSize> constexpr void MultiwordInteger<size, storageType>::unsignedQuotrem( MultiwordInteger<size+1, storageType> &dividend, MultiwordInteger<divisorSize, storageType> const &divisor, MultiwordInteger<size, storageType> &quotient, unsigned dividendSize) const { storageType k = 0; bigType b = ((bigType)1)<<storageSize; for (unsigned i = size; i-- > dividendSize; ) { quotient.s[i] = 0; } while (dividendSize-- > 0) { bigType t = b*k; t += dividend.s[dividendSize]; quotient.s[dividendSize] = t / divisor.s[0]; k = t - quotient.s[dividendSize] * divisor.s[0]; } dividend = k; } template<unsigned size, typename storageType> template<unsigned divisorSize> constexpr void MultiwordInteger<size, storageType>::unsignedQuotrem( MultiwordInteger<size+1, storageType> &dividend, MultiwordInteger<divisorSize, storageType> divisor, MultiwordInteger<size, storageType> &quotient, unsigned dividend_length, unsigned divisor_length, unsigned divisor_nlz) const { divisor <<= divisor_nlz; dividend <<= divisor_nlz; quotient = storageType(0); for (int j = dividend_length - divisor_length; j >= 0; j--) { bigType b = bigType(1)<<storageSize; bigType p = 0; bigType qhat = (dividend.s[j+divisor_length] * b + dividend.s[j+divisor_length-1]) / divisor.s[divisor_length-1]; bigType rhat = (dividend.s[j+divisor_length] * b + dividend.s[j+divisor_length-1]) - qhat * divisor.s[divisor_length-1]; bool retry = false; do { retry = false; if (qhat >= b || qhat * divisor.s[divisor_length-2] > b*rhat + dividend.s[j+divisor_length-2]) { qhat--; rhat += divisor.s[divisor_length-1]; if (rhat < b) { retry = true; } } } while (retry); typename std::make_signed<bigType>::type k = 0; typename std::make_signed<bigType>::type t = 0; for (unsigned i = 0; i < divisor_length; i++) { p = qhat * divisor.s[i]; t = dividend.s[i+j] - k - (p & ((bigType(1)<<storageSize)-1)); dividend.s[i+j] = t; k = (p >> storageSize) - (t >> storageSize); } t = dividend.s[j+divisor_length] - k; dividend.s[j+divisor_length] = t; quotient.s[j] = qhat; if (t < 0) { quotient.s[j]--; k = 0; for (unsigned i = 0; i < divisor_length; i++) { t = dividend.s[i+j] + divisor.s[i] + k; dividend.s[i+j] = t; k = t >> storageSize; } dividend.s[j+divisor_length] += k; } } } #endif // MULTIWORDINTEGERARITHMETICS_HPP <commit_msg>Fix multiplication<commit_after>#ifndef MULTIWORDINTEGERARITHMETICS_HPP #define MULTIWORDINTEGERARITHMETICS_HPP #include "MultiwordInteger.hpp" template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType>& MultiwordInteger<size, storageType>::operator+=(MultiwordInteger<size, storageType> const &o) { storageType c = 0; for(unsigned i = 0; i < size; i++) { bigType t = this->s[i] + o.s[i] + c; this->s[i] = t; c = t >> storageSize; } return *this; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType>& MultiwordInteger<size, storageType>::operator-=(MultiwordInteger<size, storageType> const &o) { bigType c = 0; for (unsigned i = 0; i < size; i++) { c += this->s[i]; c -= o.s[i]; this->s[i] = c; c = signedType(c>>storageSize); } return *this; } template<unsigned size, typename storageType> template<unsigned otherSize> constexpr MultiwordInteger<size, storageType>& MultiwordInteger<size, storageType>::operator*=(MultiwordInteger<otherSize, storageType> const &o) { MultiwordInteger<size, storageType> nv; this->mul<otherSize, size>(o, &nv); *this = nv; return *this; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType>& MultiwordInteger<size, storageType>::operator*=(int64_t const &o) { MultiwordInteger<size, storageType> nv(o); nv *= *this; *this = nv; return *this; } template<unsigned size, typename storageType> template<unsigned otherSize> constexpr MultiwordInteger<size, storageType>& MultiwordInteger<size, storageType>::operator/=(MultiwordInteger<otherSize, storageType> const &o) { quotrem(o, *this, static_cast<MultiwordInteger<otherSize, storageType>*>(nullptr)); return *this; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType>& MultiwordInteger<size, storageType>::operator%=(MultiwordInteger<size, storageType> const &o) { *this = *this % o; return *this; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType> operator+ (MultiwordInteger<size, storageType> left, MultiwordInteger<size, storageType> const &right) { return left += right; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType> operator- (MultiwordInteger<size, storageType> left, MultiwordInteger<size, storageType> const &right) { return left -= right; } template<unsigned size, typename storageType, unsigned otherSize> constexpr MultiwordInteger<size+otherSize, storageType> operator* (MultiwordInteger<size, storageType> left, MultiwordInteger<otherSize, storageType> const &right) { MultiwordInteger<size+otherSize, storageType> out; left.mul(right, &out); return out; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size+8/sizeof(storageType), storageType> operator* (MultiwordInteger<size, storageType> left, int64_t const &right) { MultiwordInteger<size+8/sizeof(storageType), storageType> out(right); out *= *left; return out; } template<unsigned size, typename storageType, unsigned otherSize> constexpr MultiwordInteger<size, storageType> operator/ (MultiwordInteger<size, storageType> left, MultiwordInteger<otherSize, storageType> const &right) { return left /= right; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType> operator/ (MultiwordInteger<size, storageType> left, int64_t const &right) { return left /= right; } template<unsigned size, typename storageType, unsigned otherSize> constexpr MultiwordInteger<otherSize, storageType> operator% (MultiwordInteger<size, storageType> left, MultiwordInteger<otherSize, storageType> const &right) { MultiwordInteger<size, storageType> q; MultiwordInteger<otherSize, storageType> r; left.quotrem(right, q, &r); return r; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType>& MultiwordInteger<size, storageType>::operator++() { bigType c = 1; for (unsigned i = 0; i < size && c; i++) { c += s[i]; s[i] = c; c >>= storageSize; } return *this; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType> MultiwordInteger<size, storageType>::operator++(int) { MultiwordInteger<size, storageType> r(*this); ++(*this); return r; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType>& MultiwordInteger<size, storageType>::operator--() { bigType c = ~static_cast<bigType>(0); for (unsigned i = 0; i < size && c; i++) { c += s[i]; s[i] = c; c >>= storageSize; } return *this; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType> MultiwordInteger<size, storageType>::operator--(int) { MultiwordInteger<size, storageType> r(*this); --(*this); return r; } template<unsigned size, typename storageType> constexpr MultiwordInteger<size, storageType> MultiwordInteger<size, storageType>::operator- () const { MultiwordInteger<size, storageType> r(*this); r.negate(); return r; } template<unsigned size, typename storageType> template<unsigned otherSize, unsigned outSize> constexpr void MultiwordInteger<size, storageType>::mul ( MultiwordInteger<otherSize, storageType> const &o, MultiwordInteger<outSize, storageType> *out) const{ *out = storageType(0); unsigned limitThis = size > outSize ? outSize : size; for (unsigned i = 0; i < limitThis; i++) { unsigned limitOther = i + otherSize < outSize ? otherSize : outSize - i; storageType k = 0; for (unsigned j = 0; j < limitOther; j++) { bigType t = static_cast<bigType>(this->s[i]) * o.s[j] + out->s[i+j] + k; out->s[i+j] = t; k = t >> storageSize; } if (i + limitOther < outSize) { out->s[i + limitOther] = k; } } // r has unsigned product, correct if this or o are less than zero if (static_cast<signedType>(o.s[otherSize-1]) < 0 && otherSize < outSize) { MultiwordInteger<outSize, storageType> tmp(*this); tmp <<= (storageSize * otherSize); *out -= tmp; } if(static_cast<signedType>(this->s[size-1]) < 0 && size < outSize) { MultiwordInteger<outSize, storageType> tmp(o); tmp <<= storageSize * size; *out -= tmp; } } template<unsigned size, typename storageType> template<unsigned otherSize> constexpr void MultiwordInteger<size, storageType>::quotrem( MultiwordInteger<otherSize, storageType> divisor, MultiwordInteger<size, storageType> &qotient, MultiwordInteger<otherSize, storageType> *remainder) const { unsigned divisor_length = otherSize, dividend_length = size; size_t divisor_nlz = divisor.is_negative() ? ((-divisor).leading_zeros()) : divisor.leading_zeros(); divisor_length -= divisor_nlz / storageSize; if (otherSize > 1) { divisor_nlz %= storageSize; } dividend_length -= this->leading_zeros()/storageSize; if (dividend_length == 0) { qotient = storageType(0); if (remainder) { *remainder = *this; } return; } /* Dividing by zero. Set the dividend as close to infinity as we can, * and the remainder to zero. */ if (divisor_length == 0) { if (this->is_negative()) { qotient = _minVal(); } else { qotient = _maxVal(); } if (remainder) { *remainder = storageType(0); } return; } bool negate_result = false; bool negative_remainder = false; MultiwordInteger<size+1, storageType> unsigned_dividend(*this); if (this->is_negative()) { negate_result = true; unsigned_dividend.negate(); } if (divisor.is_negative()) { negate_result = !negate_result; negative_remainder = true; divisor.negate(); } if (divisor_length < 2) { unsignedQuotrem(unsigned_dividend, divisor, qotient, dividend_length); } else { unsignedQuotrem(unsigned_dividend, divisor, qotient, dividend_length, divisor_length, divisor_nlz); } if (negate_result) { qotient.negate(); if (unsigned_dividend) { --qotient; } } if (!remainder) { return; } if (divisor_length >= 2) { unsigned_dividend >>= divisor_nlz; } *remainder = unsigned_dividend; if (negate_result && unsigned_dividend) { *remainder -= MultiwordInteger<size+1, storageType>(divisor); if (!negative_remainder) { // Remainder's negative, we want it to be positive remainder->negate(); } } else if (negative_remainder) { remainder->negate(); } } template<unsigned size, typename storageType> template<unsigned divisorSize> constexpr void MultiwordInteger<size, storageType>::unsignedQuotrem( MultiwordInteger<size+1, storageType> &dividend, MultiwordInteger<divisorSize, storageType> const &divisor, MultiwordInteger<size, storageType> &quotient, unsigned dividendSize) const { storageType k = 0; bigType b = ((bigType)1)<<storageSize; for (unsigned i = size; i-- > dividendSize; ) { quotient.s[i] = 0; } while (dividendSize-- > 0) { bigType t = b*k; t += dividend.s[dividendSize]; quotient.s[dividendSize] = t / divisor.s[0]; k = t - quotient.s[dividendSize] * divisor.s[0]; } dividend = k; } template<unsigned size, typename storageType> template<unsigned divisorSize> constexpr void MultiwordInteger<size, storageType>::unsignedQuotrem( MultiwordInteger<size+1, storageType> &dividend, MultiwordInteger<divisorSize, storageType> divisor, MultiwordInteger<size, storageType> &quotient, unsigned dividend_length, unsigned divisor_length, unsigned divisor_nlz) const { divisor <<= divisor_nlz; dividend <<= divisor_nlz; quotient = storageType(0); for (int j = dividend_length - divisor_length; j >= 0; j--) { bigType b = bigType(1)<<storageSize; bigType p = 0; bigType qhat = (dividend.s[j+divisor_length] * b + dividend.s[j+divisor_length-1]) / divisor.s[divisor_length-1]; bigType rhat = (dividend.s[j+divisor_length] * b + dividend.s[j+divisor_length-1]) - qhat * divisor.s[divisor_length-1]; bool retry = false; do { retry = false; if (qhat >= b || qhat * divisor.s[divisor_length-2] > b*rhat + dividend.s[j+divisor_length-2]) { qhat--; rhat += divisor.s[divisor_length-1]; if (rhat < b) { retry = true; } } } while (retry); typename std::make_signed<bigType>::type k = 0; typename std::make_signed<bigType>::type t = 0; for (unsigned i = 0; i < divisor_length; i++) { p = qhat * divisor.s[i]; t = dividend.s[i+j] - k - (p & ((bigType(1)<<storageSize)-1)); dividend.s[i+j] = t; k = (p >> storageSize) - (t >> storageSize); } t = dividend.s[j+divisor_length] - k; dividend.s[j+divisor_length] = t; quotient.s[j] = qhat; if (t < 0) { quotient.s[j]--; k = 0; for (unsigned i = 0; i < divisor_length; i++) { t = dividend.s[i+j] + divisor.s[i] + k; dividend.s[i+j] = t; k = t >> storageSize; } dividend.s[j+divisor_length] += k; } } } #endif // MULTIWORDINTEGERARITHMETICS_HPP <|endoftext|>
<commit_before>// (C) Copyright Gennadiy Rozental 2001-2005. // 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) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : storage for unit test framework parameters information // *************************************************************************** #ifndef BOOST_TEST_UNIT_TEST_PARAMETERS_HPP_071894GER #define BOOST_TEST_UNIT_TEST_PARAMETERS_HPP_071894GER #include <boost/test/detail/global_typedef.hpp> #include <boost/test/detail/log_level.hpp> #include <boost/test/detail/suppress_warnings.hpp> //____________________________________________________________________________// namespace boost { namespace unit_test { // ************************************************************************** // // ************** runtime_config ************** // // ************************************************************************** // namespace runtime_config { void init( int* argc, char** argv ); unit_test::log_level log_level(); bool no_result_code(); unit_test::report_level report_level(); const_string test_to_run(); bool save_pattern(); bool show_build_info(); bool show_progress(); bool catch_sys_errors(); output_format report_format(); output_format log_format(); long detect_memory_leak(); int random_seed(); } // namespace runtime_config } // namespace unit_test } // namespace boost //____________________________________________________________________________// #include <boost/test/detail/enable_warnings.hpp> // *************************************************************************** // Revision History : // // $Log$ // Revision 1.21 2005/04/05 06:11:37 rogeeff // memory leak allocation point detection\nextra help with _WIN32_WINNT // // Revision 1.20 2005/02/21 10:18:30 rogeeff // random cla support // // Revision 1.19 2005/02/20 08:27:06 rogeeff // This a major update for Boost.Test framework. See release docs for complete list of fixes/updates // // *************************************************************************** #endif // BOOST_TEST_UNIT_TEST_PARAMETERS_HPP_071894GER <commit_msg>new parameter --break_exec_path introduced<commit_after>// (C) Copyright Gennadiy Rozental 2001-2005. // 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) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : storage for unit test framework parameters information // *************************************************************************** #ifndef BOOST_TEST_UNIT_TEST_PARAMETERS_HPP_071894GER #define BOOST_TEST_UNIT_TEST_PARAMETERS_HPP_071894GER #include <boost/test/detail/global_typedef.hpp> #include <boost/test/detail/log_level.hpp> #include <boost/test/detail/suppress_warnings.hpp> //____________________________________________________________________________// namespace boost { namespace unit_test { // ************************************************************************** // // ************** runtime_config ************** // // ************************************************************************** // namespace runtime_config { void init( int* argc, char** argv ); unit_test::log_level log_level(); bool no_result_code(); unit_test::report_level report_level(); const_string test_to_run(); const_string break_exec_path(); bool save_pattern(); bool show_build_info(); bool show_progress(); bool catch_sys_errors(); output_format report_format(); output_format log_format(); long detect_memory_leak(); int random_seed(); } // namespace runtime_config } // namespace unit_test } // namespace boost //____________________________________________________________________________// #include <boost/test/detail/enable_warnings.hpp> // *************************************************************************** // Revision History : // // $Log$ // Revision 1.22 2005/12/14 04:58:30 rogeeff // new parameter --break_exec_path introduced // // Revision 1.21 2005/04/05 06:11:37 rogeeff // memory leak allocation point detection\nextra help with _WIN32_WINNT // // Revision 1.20 2005/02/21 10:18:30 rogeeff // random cla support // // Revision 1.19 2005/02/20 08:27:06 rogeeff // This a major update for Boost.Test framework. See release docs for complete list of fixes/updates // // *************************************************************************** #endif // BOOST_TEST_UNIT_TEST_PARAMETERS_HPP_071894GER <|endoftext|>
<commit_before>/** * \file * \brief ThreadControlBlock class header * * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. * * \date 2015-02-01 */ #ifndef INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ #define INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ #include "distortos/scheduler/RoundRobinQuantum.hpp" #include "distortos/scheduler/ThreadControlBlockList-types.hpp" #include "distortos/scheduler/MutexControlBlockList.hpp" #include "distortos/architecture/Stack.hpp" #include "distortos/SchedulingPolicy.hpp" #include "distortos/estd/TypeErasedFunctor.hpp" #include <functional> namespace distortos { namespace scheduler { class ThreadControlBlockList; /// ThreadControlBlock class is a simple description of a Thread class ThreadControlBlock { public: /// state of the thread enum class State : uint8_t { /// state in which thread is created, before being added to Scheduler New, /// thread is runnable Runnable, /// thread is sleeping Sleeping, /// thread is blocked on Semaphore BlockedOnSemaphore, /// thread is suspended Suspended, /// thread is terminated Terminated, /// thread is blocked on Mutex BlockedOnMutex, /// thread is blocked on ConditionVariable BlockedOnConditionVariable, }; /// reason of thread unblocking enum class UnblockReason : uint8_t { /// explicit request to unblock the thread - normal unblock UnblockRequest, /// timeout - unblock via software timer Timeout, }; /// type of object used as storage for ThreadControlBlockList elements - 3 pointers using Link = std::array<std::aligned_storage<sizeof(void*), alignof(void*)>::type, 3>; /// UnblockFunctor is a functor executed when unblocking the thread, it receives one parameter - a reference to /// ThreadControlBlock that is being unblocked using UnblockFunctor = estd::TypeErasedFunctor<void(ThreadControlBlock&)>; /** * \brief ThreadControlBlock constructor. * * \param [in] buffer is a pointer to stack's buffer * \param [in] size is the size of stack's buffer, bytes * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread */ ThreadControlBlock(void* buffer, size_t size, uint8_t priority, SchedulingPolicy schedulingPolicy); /** * \return effective priority of ThreadControlBlock */ uint8_t getEffectivePriority() const { return std::max(priority_, boostedPriority_); } /** * \return iterator to the element on the list, valid only when list_ != nullptr */ ThreadControlBlockListIterator getIterator() const { return iterator_; } /** * \return reference to internal storage for list link */ Link& getLink() { return link_; } /** * \return const reference to internal storage for list link */ const Link& getLink() const { return link_; } /** * \return pointer to list that has this object */ ThreadControlBlockList* getList() const { return list_; } /** * \return reference to list of mutex control blocks with enabled priority protocol owned by this thread */ MutexControlBlockList& getOwnedProtocolMutexControlBlocksList() { return ownedProtocolMutexControlBlocksList_; } /** * \return const reference to list of mutex control blocks with enabled priority protocol owned by this thread */ const MutexControlBlockList& getOwnedProtocolMutexControlBlocksList() const { return ownedProtocolMutexControlBlocksList_; } /** * \return priority of ThreadControlBlock */ uint8_t getPriority() const { return priority_; } /** * \return reference to internal RoundRobinQuantum object */ RoundRobinQuantum& getRoundRobinQuantum() { return roundRobinQuantum_; } /** * \return const reference to internal RoundRobinQuantum object */ const RoundRobinQuantum& getRoundRobinQuantum() const { return roundRobinQuantum_; } /** * \return scheduling policy of the thread */ SchedulingPolicy getSchedulingPolicy() const { return schedulingPolicy_; } /** * \return reference to internal Stack object */ architecture::Stack& getStack() { return stack_; } /** * \return const reference to internal Stack object */ const architecture::Stack& getStack() const { return stack_; } /** * \return current state of object */ State getState() const { return state_; } /** * \return reason of previous unblocking of the thread */ UnblockReason getUnblockReason() const { return unblockReason_; } /** * \brief Sets the iterator to the element on the list. * * \param [in] iterator is an iterator to the element on the list */ void setIterator(const ThreadControlBlockListIterator iterator) { iterator_ = iterator; } /** * \brief Sets the list that has this object. * * \param [in] list is a pointer to list that has this object */ void setList(ThreadControlBlockList* const list) { list_ = list; } /** * \brief Changes priority of thread. * * If the priority really changes, the position in the thread list is adjusted and context switch may be requested. * * \param [in] priority is the new priority of thread * \param [in] alwaysBehind selects the method of ordering when lowering the priority * - false - the thread is moved to the head of the group of threads with the new priority (default), * - true - the thread is moved to the tail of the group of threads with the new priority. */ void setPriority(uint8_t priority, bool alwaysBehind = {}); /** * \param [in] priorityInheritanceMutexControlBlock is a pointer to MutexControlBlock (with PriorityInheritance * protocol) that blocks this thread */ void setPriorityInheritanceMutexControlBlock(const synchronization::MutexControlBlock* const priorityInheritanceMutexControlBlock) { priorityInheritanceMutexControlBlock_ = priorityInheritanceMutexControlBlock; } /** * param [in] schedulingPolicy is the new scheduling policy of the thread */ void setSchedulingPolicy(SchedulingPolicy schedulingPolicy); /** * \param [in] state is the new state of object */ void setState(const State state) { state_ = state; } /** * \param [in] unblockReason is the new reason of unblocking of the thread */ void setUnblockReason(const UnblockReason unblockReason) { unblockReason_ = unblockReason; } /** * \brief Termination hook function of thread * * \attention This function should be called only by Scheduler::remove(). */ void terminationHook() { terminationHook_(); } /** * \brief Unblock hook function of thread * * Resets round-robin's quantum and sets unblock reason * * \attention This function should be called only by Scheduler::unblockInternal(). * * \param [in] unblockReason is the new reason of unblocking of the thread */ void unblockHook(UnblockReason unblockReason); /** * \brief Updates boosted priority of the thread. * * This function should be called after all operations involving this thread and a mutex with enabled priority * protocol. * * \param [in] boostedPriority is the initial boosted priority, this should be effective priority of the thread that * is about to be blocked on a mutex owned by this thread, default - 0 */ void updateBoostedPriority(uint8_t boostedPriority = {}); protected: /** * \brief ThreadControlBlock constructor. * * This constructor is meant for MainThreadControlBlock. * * \param [in] stack is an rvalue reference to stack of main() * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread */ ThreadControlBlock(architecture::Stack&& stack, uint8_t priority, SchedulingPolicy schedulingPolicy); /** * \brief ThreadControlBlock's destructor * * \note Polymorphic objects of ThreadControlBlock type must not be deleted via pointer/reference */ ~ThreadControlBlock() { } private: /** * \brief Thread runner function - entry point of threads. * * After return from actual thread function, thread is terminated, so this function never returns. * * \param [in] threadControlBlock is a reference to ThreadControlBlock object that is being run */ static void threadRunner(ThreadControlBlock& threadControlBlock) __attribute__ ((noreturn)); /** * \brief Repositions the thread on the list it's currently on. * * This function should be called when thread's effective priority changes. * * \attention list_ must not be nullptr * * \param [in] loweringBefore selects the method of ordering when lowering the priority (it must be false when the * priority is raised!): * - true - the thread is moved to the head of the group of threads with the new priority, this is accomplished by * temporarily boosting effective priority by 1, * - false - the thread is moved to the tail of the group of threads with the new priority. */ void reposition(bool loweringBefore); /** * \brief "Run" function of thread * * This should be overridden by derived classes. */ virtual void run() = 0; /** * \brief Termination hook function of thread * * This function is called after run() completes. * * This should be overridden by derived classes. */ virtual void terminationHook_() = 0; /// internal stack object architecture::Stack stack_; /// storage for list link Link link_; /// list of mutex control blocks with enabled priority protocol owned by this thread MutexControlBlockList ownedProtocolMutexControlBlocksList_; /// pointer to MutexControlBlock (with PriorityInheritance protocol) that blocks this thread const synchronization::MutexControlBlock* priorityInheritanceMutexControlBlock_; /// pointer to list that has this object ThreadControlBlockList* list_; /// iterator to the element on the list, valid only when list_ != nullptr ThreadControlBlockListIterator iterator_; /// thread's priority, 0 - lowest, UINT8_MAX - highest uint8_t priority_; /// thread's boosted priority, 0 - no boosting uint8_t boostedPriority_; /// round-robin quantum RoundRobinQuantum roundRobinQuantum_; /// scheduling policy of the thread SchedulingPolicy schedulingPolicy_; /// current state of object State state_; /// reason of previous unblocking of the thread UnblockReason unblockReason_; }; } // namespace scheduler } // namespace distortos #endif // INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ <commit_msg>ThreadControlBlock: remove ThreadControlBlock::setUnblockReason()<commit_after>/** * \file * \brief ThreadControlBlock class header * * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * 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/. * * \date 2015-02-01 */ #ifndef INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ #define INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ #include "distortos/scheduler/RoundRobinQuantum.hpp" #include "distortos/scheduler/ThreadControlBlockList-types.hpp" #include "distortos/scheduler/MutexControlBlockList.hpp" #include "distortos/architecture/Stack.hpp" #include "distortos/SchedulingPolicy.hpp" #include "distortos/estd/TypeErasedFunctor.hpp" #include <functional> namespace distortos { namespace scheduler { class ThreadControlBlockList; /// ThreadControlBlock class is a simple description of a Thread class ThreadControlBlock { public: /// state of the thread enum class State : uint8_t { /// state in which thread is created, before being added to Scheduler New, /// thread is runnable Runnable, /// thread is sleeping Sleeping, /// thread is blocked on Semaphore BlockedOnSemaphore, /// thread is suspended Suspended, /// thread is terminated Terminated, /// thread is blocked on Mutex BlockedOnMutex, /// thread is blocked on ConditionVariable BlockedOnConditionVariable, }; /// reason of thread unblocking enum class UnblockReason : uint8_t { /// explicit request to unblock the thread - normal unblock UnblockRequest, /// timeout - unblock via software timer Timeout, }; /// type of object used as storage for ThreadControlBlockList elements - 3 pointers using Link = std::array<std::aligned_storage<sizeof(void*), alignof(void*)>::type, 3>; /// UnblockFunctor is a functor executed when unblocking the thread, it receives one parameter - a reference to /// ThreadControlBlock that is being unblocked using UnblockFunctor = estd::TypeErasedFunctor<void(ThreadControlBlock&)>; /** * \brief ThreadControlBlock constructor. * * \param [in] buffer is a pointer to stack's buffer * \param [in] size is the size of stack's buffer, bytes * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread */ ThreadControlBlock(void* buffer, size_t size, uint8_t priority, SchedulingPolicy schedulingPolicy); /** * \return effective priority of ThreadControlBlock */ uint8_t getEffectivePriority() const { return std::max(priority_, boostedPriority_); } /** * \return iterator to the element on the list, valid only when list_ != nullptr */ ThreadControlBlockListIterator getIterator() const { return iterator_; } /** * \return reference to internal storage for list link */ Link& getLink() { return link_; } /** * \return const reference to internal storage for list link */ const Link& getLink() const { return link_; } /** * \return pointer to list that has this object */ ThreadControlBlockList* getList() const { return list_; } /** * \return reference to list of mutex control blocks with enabled priority protocol owned by this thread */ MutexControlBlockList& getOwnedProtocolMutexControlBlocksList() { return ownedProtocolMutexControlBlocksList_; } /** * \return const reference to list of mutex control blocks with enabled priority protocol owned by this thread */ const MutexControlBlockList& getOwnedProtocolMutexControlBlocksList() const { return ownedProtocolMutexControlBlocksList_; } /** * \return priority of ThreadControlBlock */ uint8_t getPriority() const { return priority_; } /** * \return reference to internal RoundRobinQuantum object */ RoundRobinQuantum& getRoundRobinQuantum() { return roundRobinQuantum_; } /** * \return const reference to internal RoundRobinQuantum object */ const RoundRobinQuantum& getRoundRobinQuantum() const { return roundRobinQuantum_; } /** * \return scheduling policy of the thread */ SchedulingPolicy getSchedulingPolicy() const { return schedulingPolicy_; } /** * \return reference to internal Stack object */ architecture::Stack& getStack() { return stack_; } /** * \return const reference to internal Stack object */ const architecture::Stack& getStack() const { return stack_; } /** * \return current state of object */ State getState() const { return state_; } /** * \return reason of previous unblocking of the thread */ UnblockReason getUnblockReason() const { return unblockReason_; } /** * \brief Sets the iterator to the element on the list. * * \param [in] iterator is an iterator to the element on the list */ void setIterator(const ThreadControlBlockListIterator iterator) { iterator_ = iterator; } /** * \brief Sets the list that has this object. * * \param [in] list is a pointer to list that has this object */ void setList(ThreadControlBlockList* const list) { list_ = list; } /** * \brief Changes priority of thread. * * If the priority really changes, the position in the thread list is adjusted and context switch may be requested. * * \param [in] priority is the new priority of thread * \param [in] alwaysBehind selects the method of ordering when lowering the priority * - false - the thread is moved to the head of the group of threads with the new priority (default), * - true - the thread is moved to the tail of the group of threads with the new priority. */ void setPriority(uint8_t priority, bool alwaysBehind = {}); /** * \param [in] priorityInheritanceMutexControlBlock is a pointer to MutexControlBlock (with PriorityInheritance * protocol) that blocks this thread */ void setPriorityInheritanceMutexControlBlock(const synchronization::MutexControlBlock* const priorityInheritanceMutexControlBlock) { priorityInheritanceMutexControlBlock_ = priorityInheritanceMutexControlBlock; } /** * param [in] schedulingPolicy is the new scheduling policy of the thread */ void setSchedulingPolicy(SchedulingPolicy schedulingPolicy); /** * \param [in] state is the new state of object */ void setState(const State state) { state_ = state; } /** * \brief Termination hook function of thread * * \attention This function should be called only by Scheduler::remove(). */ void terminationHook() { terminationHook_(); } /** * \brief Unblock hook function of thread * * Resets round-robin's quantum and sets unblock reason * * \attention This function should be called only by Scheduler::unblockInternal(). * * \param [in] unblockReason is the new reason of unblocking of the thread */ void unblockHook(UnblockReason unblockReason); /** * \brief Updates boosted priority of the thread. * * This function should be called after all operations involving this thread and a mutex with enabled priority * protocol. * * \param [in] boostedPriority is the initial boosted priority, this should be effective priority of the thread that * is about to be blocked on a mutex owned by this thread, default - 0 */ void updateBoostedPriority(uint8_t boostedPriority = {}); protected: /** * \brief ThreadControlBlock constructor. * * This constructor is meant for MainThreadControlBlock. * * \param [in] stack is an rvalue reference to stack of main() * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest * \param [in] schedulingPolicy is the scheduling policy of the thread */ ThreadControlBlock(architecture::Stack&& stack, uint8_t priority, SchedulingPolicy schedulingPolicy); /** * \brief ThreadControlBlock's destructor * * \note Polymorphic objects of ThreadControlBlock type must not be deleted via pointer/reference */ ~ThreadControlBlock() { } private: /** * \brief Thread runner function - entry point of threads. * * After return from actual thread function, thread is terminated, so this function never returns. * * \param [in] threadControlBlock is a reference to ThreadControlBlock object that is being run */ static void threadRunner(ThreadControlBlock& threadControlBlock) __attribute__ ((noreturn)); /** * \brief Repositions the thread on the list it's currently on. * * This function should be called when thread's effective priority changes. * * \attention list_ must not be nullptr * * \param [in] loweringBefore selects the method of ordering when lowering the priority (it must be false when the * priority is raised!): * - true - the thread is moved to the head of the group of threads with the new priority, this is accomplished by * temporarily boosting effective priority by 1, * - false - the thread is moved to the tail of the group of threads with the new priority. */ void reposition(bool loweringBefore); /** * \brief "Run" function of thread * * This should be overridden by derived classes. */ virtual void run() = 0; /** * \brief Termination hook function of thread * * This function is called after run() completes. * * This should be overridden by derived classes. */ virtual void terminationHook_() = 0; /// internal stack object architecture::Stack stack_; /// storage for list link Link link_; /// list of mutex control blocks with enabled priority protocol owned by this thread MutexControlBlockList ownedProtocolMutexControlBlocksList_; /// pointer to MutexControlBlock (with PriorityInheritance protocol) that blocks this thread const synchronization::MutexControlBlock* priorityInheritanceMutexControlBlock_; /// pointer to list that has this object ThreadControlBlockList* list_; /// iterator to the element on the list, valid only when list_ != nullptr ThreadControlBlockListIterator iterator_; /// thread's priority, 0 - lowest, UINT8_MAX - highest uint8_t priority_; /// thread's boosted priority, 0 - no boosting uint8_t boostedPriority_; /// round-robin quantum RoundRobinQuantum roundRobinQuantum_; /// scheduling policy of the thread SchedulingPolicy schedulingPolicy_; /// current state of object State state_; /// reason of previous unblocking of the thread UnblockReason unblockReason_; }; } // namespace scheduler } // namespace distortos #endif // INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: expl.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2006-06-19 21:50:15 $ * * 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 "expl.hxx" #include "shapes.hxx" #include "invader.hrc" #ifndef _SV_OUTDEV_HXX //autogen #include <vcl/outdev.hxx> #endif Explosion::Explosion(ResMgr* pRes) : ExplListe(0,1), pExpl1(0L), pExpl2(0L), pExpl3(0L) { pExpl1 = ImplLoadImage( EXPLOS1, pRes ); pExpl2 = ImplLoadImage( EXPLOS2, pRes ); pExpl3 = ImplLoadImage( EXPLOS3, pRes ); } Explosion::~Explosion() { delete pExpl1; delete pExpl2; delete pExpl3; } void Explosion::Paint(OutputDevice& rDev) { unsigned long i; for( i = 0; i < Count(); i++ ) { switch(GetMode(i)) { case EXPL1: rDev.DrawImage(GetPoint(i),*pExpl1); SetMode(i,EXPL2); break; case EXPL2: rDev.DrawImage(GetPoint(i),*pExpl2); SetMode(i,EXPL3); break; case EXPL3: rDev.DrawImage(GetPoint(i),*pExpl3); SetMode(i,EXPL4); break; case EXPL4: rDev.DrawImage(GetPoint(i),*pExpl2); SetMode(i,EXPL5); break; case EXPL5: rDev.DrawImage(GetPoint(i),*pExpl3); SetMode(i,EXPL6); break; case EXPL6: rDev.DrawImage(GetPoint(i),*pExpl2); SetMode(i,EXPL7); break; case EXPL7: rDev.DrawImage(GetPoint(i),*pExpl1); SetMode(i,EXPLNONE); break; case EXPLNONE: SetMode(i,EXPLDEL); break; case EXPL8: break; case EXPLDEL: break; } } // RemoveExpl(); } BOOL Explosion::RemoveExpl() { Expl_Impl* pWork; for(long i=Count()-1; i >= 0; i--) { if(GetMode(i) == EXPLDEL) { pWork = GetObject(i); Remove(pWork); delete pWork; } } if(Count()) return FALSE; else return TRUE; } void Explosion::ClearAll() { unsigned long i; for( i = 0; i < Count(); i++ ) delete GetObject(i); Clear(); } void Explosion::InsertExpl(Point& rPoint) { Expl_Impl* pWork = new Expl_Impl(); pWork->aPos = rPoint; pWork->eMode = EXPL1; Insert(pWork); } <commit_msg>INTEGRATION: CWS pchfix02 (1.3.28); FILE MERGED 2006/09/01 17:30:16 kaib 1.3.28.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: expl.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-09-17 15:54:45 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_goodies.hxx" #include "expl.hxx" #include "shapes.hxx" #include "invader.hrc" #ifndef _SV_OUTDEV_HXX //autogen #include <vcl/outdev.hxx> #endif Explosion::Explosion(ResMgr* pRes) : ExplListe(0,1), pExpl1(0L), pExpl2(0L), pExpl3(0L) { pExpl1 = ImplLoadImage( EXPLOS1, pRes ); pExpl2 = ImplLoadImage( EXPLOS2, pRes ); pExpl3 = ImplLoadImage( EXPLOS3, pRes ); } Explosion::~Explosion() { delete pExpl1; delete pExpl2; delete pExpl3; } void Explosion::Paint(OutputDevice& rDev) { unsigned long i; for( i = 0; i < Count(); i++ ) { switch(GetMode(i)) { case EXPL1: rDev.DrawImage(GetPoint(i),*pExpl1); SetMode(i,EXPL2); break; case EXPL2: rDev.DrawImage(GetPoint(i),*pExpl2); SetMode(i,EXPL3); break; case EXPL3: rDev.DrawImage(GetPoint(i),*pExpl3); SetMode(i,EXPL4); break; case EXPL4: rDev.DrawImage(GetPoint(i),*pExpl2); SetMode(i,EXPL5); break; case EXPL5: rDev.DrawImage(GetPoint(i),*pExpl3); SetMode(i,EXPL6); break; case EXPL6: rDev.DrawImage(GetPoint(i),*pExpl2); SetMode(i,EXPL7); break; case EXPL7: rDev.DrawImage(GetPoint(i),*pExpl1); SetMode(i,EXPLNONE); break; case EXPLNONE: SetMode(i,EXPLDEL); break; case EXPL8: break; case EXPLDEL: break; } } // RemoveExpl(); } BOOL Explosion::RemoveExpl() { Expl_Impl* pWork; for(long i=Count()-1; i >= 0; i--) { if(GetMode(i) == EXPLDEL) { pWork = GetObject(i); Remove(pWork); delete pWork; } } if(Count()) return FALSE; else return TRUE; } void Explosion::ClearAll() { unsigned long i; for( i = 0; i < Count(); i++ ) delete GetObject(i); Clear(); } void Explosion::InsertExpl(Point& rPoint) { Expl_Impl* pWork = new Expl_Impl(); pWork->aPos = rPoint; pWork->eMode = EXPL1; Insert(pWork); } <|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/net/url_fetcher.h" #include "base/compiler_specific.h" #include "base/string_util.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/net/url_request_context_getter.h" #include "googleurl/src/gurl.h" #include "net/base/load_flags.h" #include "net/base/io_buffer.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_context.h" static const int kBufferSize = 4096; bool URLFetcher::g_interception_enabled = false; class URLFetcher::Core : public base::RefCountedThreadSafe<URLFetcher::Core>, public URLRequest::Delegate { public: // For POST requests, set |content_type| to the MIME type of the content // and set |content| to the data to upload. |flags| are flags to apply to // the load operation--these should be one or more of the LOAD_* flags // defined in url_request.h. Core(URLFetcher* fetcher, const GURL& original_url, RequestType request_type, URLFetcher::Delegate* d); // Starts the load. It's important that this not happen in the constructor // because it causes the IO thread to begin AddRef()ing and Release()ing // us. If our caller hasn't had time to fully construct us and take a // reference, the IO thread could interrupt things, run a task, Release() // us, and destroy us, leaving the caller with an already-destroyed object // when construction finishes. void Start(); // Stops any in-progress load and ensures no callback will happen. It is // safe to call this multiple times. void Stop(); // URLRequest::Delegate implementations virtual void OnResponseStarted(URLRequest* request); virtual void OnReadCompleted(URLRequest* request, int bytes_read); URLFetcher::Delegate* delegate() const { return delegate_; } private: friend class base::RefCountedThreadSafe<URLFetcher::Core>; ~Core() {} // Wrapper functions that allow us to ensure actions happen on the right // thread. void StartURLRequest(); void CancelURLRequest(); void OnCompletedURLRequest(const URLRequestStatus& status); URLFetcher* fetcher_; // Corresponding fetcher object GURL original_url_; // The URL we were asked to fetch GURL url_; // The URL we eventually wound up at RequestType request_type_; // What type of request is this? URLFetcher::Delegate* delegate_; // Object to notify on completion MessageLoop* delegate_loop_; // Message loop of the creating thread URLRequest* request_; // The actual request this wraps int load_flags_; // Flags for the load operation int response_code_; // HTTP status code for the request std::string data_; // Results of the request scoped_refptr<net::IOBuffer> buffer_; // Read buffer scoped_refptr<URLRequestContextGetter> request_context_getter_; // Cookie/cache info for the request ResponseCookies cookies_; // Response cookies std::string extra_request_headers_;// Extra headers for the request, if any scoped_refptr<net::HttpResponseHeaders> response_headers_; std::string upload_content_; // HTTP POST payload std::string upload_content_type_; // MIME type of POST payload // The overload protection entry for this URL. This is used to // incrementally back off how rapidly we'll send requests to a particular // URL, to avoid placing too much demand on the remote resource. We update // this with the status of all requests as they return, and in turn use it // to determine how long to wait before making another request. URLFetcherProtectEntry* protect_entry_; // |num_retries_| indicates how many times we've failed to successfully // fetch this URL. Once this value exceeds the maximum number of retries // specified by the protection manager, we'll give up. int num_retries_; friend class URLFetcher; DISALLOW_COPY_AND_ASSIGN(Core); }; // static URLFetcher::Factory* URLFetcher::factory_ = NULL; URLFetcher::URLFetcher(const GURL& url, RequestType request_type, Delegate* d) : ALLOW_THIS_IN_INITIALIZER_LIST( core_(new Core(this, url, request_type, d))) { } URLFetcher::~URLFetcher() { core_->Stop(); } // static URLFetcher* URLFetcher::Create(int id, const GURL& url, RequestType request_type, Delegate* d) { return factory_ ? factory_->CreateURLFetcher(id, url, request_type, d) : new URLFetcher(url, request_type, d); } URLFetcher::Core::Core(URLFetcher* fetcher, const GURL& original_url, RequestType request_type, URLFetcher::Delegate* d) : fetcher_(fetcher), original_url_(original_url), request_type_(request_type), delegate_(d), delegate_loop_(MessageLoop::current()), request_(NULL), load_flags_(net::LOAD_NORMAL), response_code_(-1), buffer_(new net::IOBuffer(kBufferSize)), protect_entry_(URLFetcherProtectManager::GetInstance()->Register( original_url_.host())), num_retries_(0) { } void URLFetcher::Core::Start() { DCHECK(delegate_loop_); DCHECK(request_context_getter_) << "We need an URLRequestContext!"; ChromeThread::PostDelayedTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(this, &Core::StartURLRequest), protect_entry_->UpdateBackoff(URLFetcherProtectEntry::SEND)); } void URLFetcher::Core::Stop() { DCHECK_EQ(MessageLoop::current(), delegate_loop_); delegate_ = NULL; ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(this, &Core::CancelURLRequest)); } void URLFetcher::Core::OnResponseStarted(URLRequest* request) { DCHECK(request == request_); DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)); if (request_->status().is_success()) { response_code_ = request_->GetResponseCode(); response_headers_ = request_->response_headers(); } int bytes_read = 0; // Some servers may treat HEAD requests as GET requests. To free up the // network connection as soon as possible, signal that the request has // completed immediately, without trying to read any data back (all we care // about is the response code and headers, which we already have). if (request_->status().is_success() && (request_type_ != HEAD)) request_->Read(buffer_, kBufferSize, &bytes_read); OnReadCompleted(request_, bytes_read); } void URLFetcher::Core::OnReadCompleted(URLRequest* request, int bytes_read) { DCHECK(request == request_); DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)); url_ = request->url(); do { if (!request_->status().is_success() || bytes_read <= 0) break; data_.append(buffer_->data(), bytes_read); } while (request_->Read(buffer_, kBufferSize, &bytes_read)); if (request_->status().is_success()) request_->GetResponseCookies(&cookies_); // See comments re: HEAD requests in OnResponseStarted(). if (!request_->status().is_io_pending() || (request_type_ == HEAD)) { delegate_loop_->PostTask(FROM_HERE, NewRunnableMethod( this, &Core::OnCompletedURLRequest, request_->status())); delete request_; request_ = NULL; } } void URLFetcher::Core::StartURLRequest() { DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)); DCHECK(!request_); request_ = new URLRequest(original_url_, this); int flags = request_->load_flags() | load_flags_; if (!g_interception_enabled) { flags = flags | net::LOAD_DISABLE_INTERCEPT; } request_->set_load_flags(flags); request_->set_context(request_context_getter_->GetURLRequestContext()); switch (request_type_) { case GET: break; case POST: DCHECK(!upload_content_.empty()); DCHECK(!upload_content_type_.empty()); request_->set_method("POST"); if (!extra_request_headers_.empty()) extra_request_headers_ += "\r\n"; StringAppendF(&extra_request_headers_, "Content-Type: %s", upload_content_type_.c_str()); request_->AppendBytesToUpload(upload_content_.data(), static_cast<int>(upload_content_.size())); break; case HEAD: request_->set_method("HEAD"); break; default: NOTREACHED(); } if (!extra_request_headers_.empty()) request_->SetExtraRequestHeaders(extra_request_headers_); request_->Start(); } void URLFetcher::Core::CancelURLRequest() { DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)); if (request_) { request_->Cancel(); delete request_; request_ = NULL; } // Release the reference to the request context. There could be multiple // references to URLFetcher::Core at this point so it may take a while to // delete the object, but we cannot delay the destruction of the request // context. request_context_getter_ = NULL; } void URLFetcher::Core::OnCompletedURLRequest(const URLRequestStatus& status) { DCHECK(MessageLoop::current() == delegate_loop_); // Checks the response from server. if (response_code_ >= 500) { // When encountering a server error, we will send the request again // after backoff time. const int64 wait = protect_entry_->UpdateBackoff(URLFetcherProtectEntry::FAILURE); ++num_retries_; // Restarts the request if we still need to notify the delegate. if (delegate_) { if (num_retries_ <= protect_entry_->max_retries()) { ChromeThread::PostDelayedTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(this, &Core::StartURLRequest), wait); } else { delegate_->OnURLFetchComplete(fetcher_, url_, status, response_code_, cookies_, data_); } } } else { protect_entry_->UpdateBackoff(URLFetcherProtectEntry::SUCCESS); if (delegate_) delegate_->OnURLFetchComplete(fetcher_, url_, status, response_code_, cookies_, data_); } } void URLFetcher::set_upload_data(const std::string& upload_content_type, const std::string& upload_content) { core_->upload_content_type_ = upload_content_type; core_->upload_content_ = upload_content; } void URLFetcher::set_load_flags(int load_flags) { core_->load_flags_ = load_flags; } int URLFetcher::load_flags() const { return core_->load_flags_; } void URLFetcher::set_extra_request_headers( const std::string& extra_request_headers) { core_->extra_request_headers_ = extra_request_headers; } void URLFetcher::set_request_context( URLRequestContextGetter* request_context_getter) { core_->request_context_getter_ = request_context_getter; } net::HttpResponseHeaders* URLFetcher::response_headers() const { return core_->response_headers_; } void URLFetcher::Start() { core_->Start(); } const GURL& URLFetcher::url() const { return core_->url_; } URLFetcher::Delegate* URLFetcher::delegate() const { return core_->delegate(); } <commit_msg>Add instrumentation to track down a crash.<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/net/url_fetcher.h" #include "base/compiler_specific.h" #include "base/string_util.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/net/url_request_context_getter.h" #include "googleurl/src/gurl.h" #include "net/base/load_flags.h" #include "net/base/io_buffer.h" #include "net/http/http_response_headers.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_context.h" static const int kBufferSize = 4096; bool URLFetcher::g_interception_enabled = false; class URLFetcher::Core : public base::RefCountedThreadSafe<URLFetcher::Core>, public URLRequest::Delegate { public: // For POST requests, set |content_type| to the MIME type of the content // and set |content| to the data to upload. |flags| are flags to apply to // the load operation--these should be one or more of the LOAD_* flags // defined in url_request.h. Core(URLFetcher* fetcher, const GURL& original_url, RequestType request_type, URLFetcher::Delegate* d); // Starts the load. It's important that this not happen in the constructor // because it causes the IO thread to begin AddRef()ing and Release()ing // us. If our caller hasn't had time to fully construct us and take a // reference, the IO thread could interrupt things, run a task, Release() // us, and destroy us, leaving the caller with an already-destroyed object // when construction finishes. void Start(); // Stops any in-progress load and ensures no callback will happen. It is // safe to call this multiple times. void Stop(); // URLRequest::Delegate implementations virtual void OnResponseStarted(URLRequest* request); virtual void OnReadCompleted(URLRequest* request, int bytes_read); URLFetcher::Delegate* delegate() const { return delegate_; } private: friend class base::RefCountedThreadSafe<URLFetcher::Core>; ~Core() {} // Wrapper functions that allow us to ensure actions happen on the right // thread. void StartURLRequest(); void CancelURLRequest(); void OnCompletedURLRequest(const URLRequestStatus& status); URLFetcher* fetcher_; // Corresponding fetcher object GURL original_url_; // The URL we were asked to fetch GURL url_; // The URL we eventually wound up at RequestType request_type_; // What type of request is this? URLFetcher::Delegate* delegate_; // Object to notify on completion MessageLoop* delegate_loop_; // Message loop of the creating thread URLRequest* request_; // The actual request this wraps int load_flags_; // Flags for the load operation int response_code_; // HTTP status code for the request std::string data_; // Results of the request scoped_refptr<net::IOBuffer> buffer_; // Read buffer scoped_refptr<URLRequestContextGetter> request_context_getter_; // Cookie/cache info for the request ResponseCookies cookies_; // Response cookies std::string extra_request_headers_;// Extra headers for the request, if any scoped_refptr<net::HttpResponseHeaders> response_headers_; std::string upload_content_; // HTTP POST payload std::string upload_content_type_; // MIME type of POST payload // The overload protection entry for this URL. This is used to // incrementally back off how rapidly we'll send requests to a particular // URL, to avoid placing too much demand on the remote resource. We update // this with the status of all requests as they return, and in turn use it // to determine how long to wait before making another request. URLFetcherProtectEntry* protect_entry_; // |num_retries_| indicates how many times we've failed to successfully // fetch this URL. Once this value exceeds the maximum number of retries // specified by the protection manager, we'll give up. int num_retries_; // Temporary member variable to test whether requests are being started // after they have already been cancelled. // TODO(eroman): Remove this after done investigating 27074. bool was_cancelled_; friend class URLFetcher; DISALLOW_COPY_AND_ASSIGN(Core); }; // static URLFetcher::Factory* URLFetcher::factory_ = NULL; URLFetcher::URLFetcher(const GURL& url, RequestType request_type, Delegate* d) : ALLOW_THIS_IN_INITIALIZER_LIST( core_(new Core(this, url, request_type, d))) { } URLFetcher::~URLFetcher() { core_->Stop(); } // static URLFetcher* URLFetcher::Create(int id, const GURL& url, RequestType request_type, Delegate* d) { return factory_ ? factory_->CreateURLFetcher(id, url, request_type, d) : new URLFetcher(url, request_type, d); } URLFetcher::Core::Core(URLFetcher* fetcher, const GURL& original_url, RequestType request_type, URLFetcher::Delegate* d) : fetcher_(fetcher), original_url_(original_url), request_type_(request_type), delegate_(d), delegate_loop_(MessageLoop::current()), request_(NULL), load_flags_(net::LOAD_NORMAL), response_code_(-1), buffer_(new net::IOBuffer(kBufferSize)), protect_entry_(URLFetcherProtectManager::GetInstance()->Register( original_url_.host())), num_retries_(0), was_cancelled_(false) { } void URLFetcher::Core::Start() { DCHECK(delegate_loop_); CHECK(request_context_getter_) << "We need an URLRequestContext!"; ChromeThread::PostDelayedTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(this, &Core::StartURLRequest), protect_entry_->UpdateBackoff(URLFetcherProtectEntry::SEND)); } void URLFetcher::Core::Stop() { DCHECK_EQ(MessageLoop::current(), delegate_loop_); delegate_ = NULL; ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(this, &Core::CancelURLRequest)); } void URLFetcher::Core::OnResponseStarted(URLRequest* request) { DCHECK(request == request_); DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)); if (request_->status().is_success()) { response_code_ = request_->GetResponseCode(); response_headers_ = request_->response_headers(); } int bytes_read = 0; // Some servers may treat HEAD requests as GET requests. To free up the // network connection as soon as possible, signal that the request has // completed immediately, without trying to read any data back (all we care // about is the response code and headers, which we already have). if (request_->status().is_success() && (request_type_ != HEAD)) request_->Read(buffer_, kBufferSize, &bytes_read); OnReadCompleted(request_, bytes_read); } void URLFetcher::Core::OnReadCompleted(URLRequest* request, int bytes_read) { DCHECK(request == request_); DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)); url_ = request->url(); do { if (!request_->status().is_success() || bytes_read <= 0) break; data_.append(buffer_->data(), bytes_read); } while (request_->Read(buffer_, kBufferSize, &bytes_read)); if (request_->status().is_success()) request_->GetResponseCookies(&cookies_); // See comments re: HEAD requests in OnResponseStarted(). if (!request_->status().is_io_pending() || (request_type_ == HEAD)) { delegate_loop_->PostTask(FROM_HERE, NewRunnableMethod( this, &Core::OnCompletedURLRequest, request_->status())); delete request_; request_ = NULL; } } void URLFetcher::Core::StartURLRequest() { DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)); CHECK(!was_cancelled_); CHECK(request_context_getter_); CHECK(!request_); request_ = new URLRequest(original_url_, this); int flags = request_->load_flags() | load_flags_; if (!g_interception_enabled) { flags = flags | net::LOAD_DISABLE_INTERCEPT; } request_->set_load_flags(flags); request_->set_context(request_context_getter_->GetURLRequestContext()); switch (request_type_) { case GET: break; case POST: DCHECK(!upload_content_.empty()); DCHECK(!upload_content_type_.empty()); request_->set_method("POST"); if (!extra_request_headers_.empty()) extra_request_headers_ += "\r\n"; StringAppendF(&extra_request_headers_, "Content-Type: %s", upload_content_type_.c_str()); request_->AppendBytesToUpload(upload_content_.data(), static_cast<int>(upload_content_.size())); break; case HEAD: request_->set_method("HEAD"); break; default: NOTREACHED(); } if (!extra_request_headers_.empty()) request_->SetExtraRequestHeaders(extra_request_headers_); request_->Start(); } void URLFetcher::Core::CancelURLRequest() { DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO)); if (request_) { request_->Cancel(); delete request_; request_ = NULL; } // Release the reference to the request context. There could be multiple // references to URLFetcher::Core at this point so it may take a while to // delete the object, but we cannot delay the destruction of the request // context. request_context_getter_ = NULL; was_cancelled_ = true; } void URLFetcher::Core::OnCompletedURLRequest(const URLRequestStatus& status) { DCHECK(MessageLoop::current() == delegate_loop_); // Checks the response from server. if (response_code_ >= 500) { // When encountering a server error, we will send the request again // after backoff time. const int64 wait = protect_entry_->UpdateBackoff(URLFetcherProtectEntry::FAILURE); ++num_retries_; // Restarts the request if we still need to notify the delegate. if (delegate_) { if (num_retries_ <= protect_entry_->max_retries()) { ChromeThread::PostDelayedTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod(this, &Core::StartURLRequest), wait); } else { delegate_->OnURLFetchComplete(fetcher_, url_, status, response_code_, cookies_, data_); } } } else { protect_entry_->UpdateBackoff(URLFetcherProtectEntry::SUCCESS); if (delegate_) delegate_->OnURLFetchComplete(fetcher_, url_, status, response_code_, cookies_, data_); } } void URLFetcher::set_upload_data(const std::string& upload_content_type, const std::string& upload_content) { core_->upload_content_type_ = upload_content_type; core_->upload_content_ = upload_content; } void URLFetcher::set_load_flags(int load_flags) { core_->load_flags_ = load_flags; } int URLFetcher::load_flags() const { return core_->load_flags_; } void URLFetcher::set_extra_request_headers( const std::string& extra_request_headers) { core_->extra_request_headers_ = extra_request_headers; } void URLFetcher::set_request_context( URLRequestContextGetter* request_context_getter) { core_->request_context_getter_ = request_context_getter; } net::HttpResponseHeaders* URLFetcher::response_headers() const { return core_->response_headers_; } void URLFetcher::Start() { core_->Start(); } const GURL& URLFetcher::url() const { return core_->url_; } URLFetcher::Delegate* URLFetcher::delegate() const { return core_->delegate(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: pe_struc.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2004-02-04 12:41:22 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef LUIDL_PE_STRUC_HXX #define LUIDL_PE_STRUC_HXX // USED SERVICES // BASE CLASSES #include <s2_luidl/parsenv2.hxx> #include <s2_luidl/pestate.hxx> // COMPONENTS #include <s2_luidl/semnode.hxx> #include <ary/qualiname.hxx> // PARAMETERS namespace csi { namespace prl { class TNamespace; } } namespace csi { namespace uidl { class Struct; class StructElement; class PE_StructElement; class PE_Type; class PE_Struct : public UnoIDL_PE { public: PE_Struct(); virtual void EstablishContacts( UnoIDL_PE * io_pParentPE, ary::n22::Repository & io_rRepository, TokenProcessing_Result & o_rResult ); ~PE_Struct(); virtual void ProcessToken( const Token & i_rToken ); private: struct S_Work { S_Work(); void InitData(); void Prepare_PE_QualifiedName(); void Prepare_PE_Element(); void Data_Set_Name( const char * i_sName ); String sData_Name; bool bIsPreDeclaration; ary::idl::Ce_id nCurStruct; Dyn<PE_StructElement> pPE_Element; ary::idl::Ce_id nCurParsed_ElementRef; Dyn<PE_Type> pPE_Type; ary::idl::Type_id nCurParsed_Base; }; struct S_Stati; class PE_StructState; friend struct S_Stati; friend class PE_StructState; class PE_StructState : public ParseEnvState { public: protected: PE_StructState( PE_Struct & i_rStruct ) : rStruct(i_rStruct) {} void MoveState( ParseEnvState & i_rState ) const; void SetResult( E_TokenDone i_eDone, E_EnvStackAction i_eWhat2DoWithEnvStack, UnoIDL_PE * i_pParseEnv2Push = 0 ) const { rStruct.SetResult(i_eDone, i_eWhat2DoWithEnvStack, i_pParseEnv2Push); } S_Stati & Stati() const { return *rStruct.pStati; } S_Work & Work() const { return rStruct.aWork; } PE_Struct & PE() const { return rStruct; } private: virtual UnoIDL_PE & MyPE(); // DATA PE_Struct & rStruct; }; class State_None : public PE_StructState { public: State_None( PE_Struct & i_rStruct ) : PE_StructState(i_rStruct) {} }; class State_WaitForName : public PE_StructState { // -> Name public: State_WaitForName( PE_Struct & i_rStruct ) : PE_StructState(i_rStruct) {} virtual void Process_Identifier( const TokIdentifier & i_rToken ); }; class State_GotName : public PE_StructState { // -> : { ; public: State_GotName( PE_Struct & i_rStruct ) : PE_StructState(i_rStruct) {} virtual void Process_Punctuation( const TokPunctuation & i_rToken ); }; class State_WaitForBase : public PE_StructState { // -> Base public: State_WaitForBase( PE_Struct & i_rStruct ) : PE_StructState(i_rStruct) {} virtual void On_SubPE_Left(); }; class State_GotBase : public PE_StructState { // -> { public: State_GotBase( PE_Struct & i_rStruct ) : PE_StructState(i_rStruct) {} virtual void Process_Punctuation( const TokPunctuation & i_rToken ); }; class State_WaitForElement : public PE_StructState { // -> Typ } public: State_WaitForElement( PE_Struct & i_rStruct ) : PE_StructState(i_rStruct) {} virtual void Process_Identifier( const TokIdentifier & i_rToken ); virtual void Process_NameSeparator(); virtual void Process_BuiltInType( const TokBuiltInType & i_rToken ); virtual void Process_TypeModifier( const TokTypeModifier & i_rToken ); virtual void Process_Punctuation( const TokPunctuation & i_rToken ); }; class State_WaitForFinish : public PE_StructState { // -> ; public: State_WaitForFinish( PE_Struct & i_rStruct ) : PE_StructState(i_rStruct) {} virtual void Process_Punctuation( const TokPunctuation & i_rToken ); }; struct S_Stati { S_Stati( PE_Struct & io_rStruct ); void SetState( ParseEnvState & i_rNextState ) { pCurStatus = &i_rNextState; } State_None aNone; State_WaitForName aWaitForName; State_GotName aGotName; State_WaitForBase aWaitForBase; State_GotBase aGotBase; State_WaitForElement aWaitForElement; State_WaitForFinish aWaitForFinish; ParseEnvState * pCurStatus; }; virtual void InitData(); virtual void TransferData(); virtual void ReceiveData(); public: void store_Struct(); private: S_Stati & Stati() { return *pStati; } S_Work & Work() { return aWork; } // DATA S_Work aWork; Dyn<S_Stati> pStati; }; inline void PE_Struct::PE_StructState::MoveState( ParseEnvState & i_rState ) const { rStruct.Stati().SetState(i_rState); } } // namespace uidl } // namespace csi #endif <commit_msg>INTEGRATION: CWS adc9 (1.3.28); FILE MERGED 2004/11/09 17:31:07 np 1.3.28.1: #i33253#<commit_after>/************************************************************************* * * $RCSfile: pe_struc.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-11-15 13:44: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): _______________________________________ * * ************************************************************************/ #ifndef LUIDL_PE_STRUC_HXX #define LUIDL_PE_STRUC_HXX // USED SERVICES // BASE CLASSES #include <s2_luidl/parsenv2.hxx> #include <s2_luidl/pestate.hxx> // COMPONENTS #include <s2_luidl/semnode.hxx> #include <ary/qualiname.hxx> // PARAMETERS namespace csi { namespace prl { class TNamespace; } } namespace csi { namespace uidl { class Struct; class StructElement; class PE_StructElement; class PE_Type; class PE_Struct : public UnoIDL_PE { public: PE_Struct(); virtual void EstablishContacts( UnoIDL_PE * io_pParentPE, ary::n22::Repository & io_rRepository, TokenProcessing_Result & o_rResult ); ~PE_Struct(); virtual void ProcessToken( const Token & i_rToken ); private: struct S_Work { S_Work(); void InitData(); void Prepare_PE_QualifiedName(); void Prepare_PE_Element(); void Data_Set_Name( const char * i_sName ); void Data_Set_TemplateParam( const char * i_sTemplateParam ); String sData_Name; String sData_TemplateParam; bool bIsPreDeclaration; ary::idl::Ce_id nCurStruct; Dyn<PE_StructElement> pPE_Element; ary::idl::Ce_id nCurParsed_ElementRef; Dyn<PE_Type> pPE_Type; ary::idl::Type_id nCurParsed_Base; }; struct S_Stati; class PE_StructState; friend struct S_Stati; friend class PE_StructState; class PE_StructState : public ParseEnvState { public: protected: PE_StructState( PE_Struct & i_rStruct ) : rStruct(i_rStruct) {} void MoveState( ParseEnvState & i_rState ) const; void SetResult( E_TokenDone i_eDone, E_EnvStackAction i_eWhat2DoWithEnvStack, UnoIDL_PE * i_pParseEnv2Push = 0 ) const { rStruct.SetResult(i_eDone, i_eWhat2DoWithEnvStack, i_pParseEnv2Push); } S_Stati & Stati() const { return *rStruct.pStati; } S_Work & Work() const { return rStruct.aWork; } PE_Struct & PE() const { return rStruct; } private: virtual UnoIDL_PE & MyPE(); // DATA PE_Struct & rStruct; }; class State_None : public PE_StructState { public: State_None( PE_Struct & i_rStruct ) : PE_StructState(i_rStruct) {} }; class State_WaitForName : public PE_StructState { // -> Name public: State_WaitForName( PE_Struct & i_rStruct ) : PE_StructState(i_rStruct) {} virtual void Process_Identifier( const TokIdentifier & i_rToken ); }; class State_GotName : public PE_StructState { // -> : { ; < public: State_GotName( PE_Struct & i_rStruct ) : PE_StructState(i_rStruct) {} virtual void Process_Punctuation( const TokPunctuation & i_rToken ); }; class State_WaitForTemplateParam : public PE_StructState { // -> Template parameter identifier public: State_WaitForTemplateParam( PE_Struct & i_rStruct ) : PE_StructState(i_rStruct) {} virtual void Process_Identifier( const TokIdentifier & i_rToken ); }; class State_WaitForTemplateEnd : public PE_StructState { // -> > public: State_WaitForTemplateEnd( PE_Struct & i_rStruct ) : PE_StructState(i_rStruct) {} virtual void Process_Punctuation( const TokPunctuation & i_rToken ); }; class State_WaitForBase : public PE_StructState { // -> Base public: State_WaitForBase( PE_Struct & i_rStruct ) : PE_StructState(i_rStruct) {} virtual void On_SubPE_Left(); }; class State_GotBase : public PE_StructState { // -> { public: State_GotBase( PE_Struct & i_rStruct ) : PE_StructState(i_rStruct) {} virtual void Process_Punctuation( const TokPunctuation & i_rToken ); }; class State_WaitForElement : public PE_StructState { // -> Typ } public: State_WaitForElement( PE_Struct & i_rStruct ) : PE_StructState(i_rStruct) {} virtual void Process_Identifier( const TokIdentifier & i_rToken ); virtual void Process_NameSeparator(); virtual void Process_BuiltInType( const TokBuiltInType & i_rToken ); virtual void Process_TypeModifier( const TokTypeModifier & i_rToken ); virtual void Process_Punctuation( const TokPunctuation & i_rToken ); }; class State_WaitForFinish : public PE_StructState { // -> ; public: State_WaitForFinish( PE_Struct & i_rStruct ) : PE_StructState(i_rStruct) {} virtual void Process_Punctuation( const TokPunctuation & i_rToken ); }; struct S_Stati { S_Stati( PE_Struct & io_rStruct ); void SetState( ParseEnvState & i_rNextState ) { pCurStatus = &i_rNextState; } State_None aNone; State_WaitForName aWaitForName; State_GotName aGotName; State_WaitForTemplateParam aWaitForTemplateParam; State_WaitForTemplateEnd aWaitForTemplateEnd; State_WaitForBase aWaitForBase; State_GotBase aGotBase; State_WaitForElement aWaitForElement; State_WaitForFinish aWaitForFinish; ParseEnvState * pCurStatus; }; virtual void InitData(); virtual void TransferData(); virtual void ReceiveData(); public: void store_Struct(); private: S_Stati & Stati() { return *pStati; } S_Work & Work() { return aWork; } // DATA S_Work aWork; Dyn<S_Stati> pStati; }; inline void PE_Struct::PE_StructState::MoveState( ParseEnvState & i_rState ) const { rStruct.Stati().SetState(i_rState); } } // namespace uidl } // namespace csi #endif <|endoftext|>
<commit_before>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ // vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s /* * examples/charpoly.C * * Copyright (C) 2005, 2010 D. Saunders, C. Pernet, J-G. Dumas * * This file is part of LinBox. * * LinBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2 of * the License, or (at your option) any later version. * * LinBox 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 LinBox. If not, see * <http://www.gnu.org/licenses/>. */ /** \file examples/charpoly.C * @example examples/charpoly.C \brief Characteristic polynomial of matrix over Z or Zp. \ingroup examples */ #include <iostream> #include <iomanip> #include "linbox/util/timer.h" #include "linbox/field/modular-double.h" #include "linbox/field/unparametric.h" #include "linbox/blackbox/sparse.h" #include "linbox/blackbox/blas-blackbox.h" using namespace std; #include "linbox/solutions/charpoly.h" #include "linbox/ring/givaro-polynomial.h" using namespace LinBox; template <class Field, class Polynomial> std::ostream& printPolynomial (std::ostream& out, const Field &F, const Polynomial &v) { for (int i = v.size () - 1; i >= 0; i--) { F.write (out, v[i]); if (i > 0) out << " X^" << i << " + "; } return out; } template <class Field, class Polynomial> std::ostream& prettyprintIntegerPolynomial (std::ostream& out, const Field &F, const Polynomial &v) { size_t n = v.size()-1; if (n == 0) { F.write(out, v[0]); } else { if(v[n] != 0) { if (v[n] != 1) F.write(out, v[n]) << '*'; out << 'X'; if (n > 1) out << '^' << n; for (int i = n - 1; i > 0; i--) { if (v[i] != 0) { if (v[i] >0) out << " + "; if (v[i] != 1) F.write (out, v[i]) << '*'; out << 'X'; if (i > 1) out << '^' << i; } } if (v[0] != 0) { if (v[0] >0) out << " + "; F.write(out, v[0]); } } } return out; } template <class Field, class Factors, class Exponents> std::ostream& printFactorization (std::ostream& out, const Field &F, const Factors &f, const Exponents& exp) { typename Factors::const_iterator itf = f.begin(); typename Exponents::const_iterator ite = exp.begin(); for ( ; itf != f.end(); ++itf, ++ite) { prettyprintIntegerPolynomial(out << '(', F, *(*itf)) << ')'; if (*ite > 1) out << '^' << *ite; out << endl; } return out; } int main (int argc, char **argv) { commentator.setMaxDetailLevel (2); commentator.setMaxDepth (2); commentator.setReportStream (std::cerr); cout<<setprecision(8); cerr<<setprecision(8); if (argc < 2 || argc > 3) { cerr << "Usage: charpoly <matrix-file-in-SMS-format> [<p>]" << endl; return -1; } ifstream input (argv[1]); if (!input) { cerr << "Error opening matrix file " << argv[1] << endl; return -1; } if (argc == 2) { PID_integer ZZ; DenseMatrix<PID_integer > A (ZZ); A.read (input); typedef GivPolynomialRing<PID_integer,Dense> IntPolRing; IntPolRing::Element c_A; Timer tim; tim.clear();tim.start();charpoly (c_A, A, Method::Blackbox()); tim.stop(); cout << "Characteristic Polynomial is "; //printPolynomial (cout, ZZ, c_A) << endl; cout << tim << endl; #ifdef __LINBOX_HAVE_NTL cout << "Do you want a factorization (y/n) ? "; char tmp; cin >> tmp; if (tmp == 'y' || tmp == 'Y') { commentator.start("Integer Polynomial factorization by NTL", "NTLfac"); vector<IntPolRing::Element*> intFactors; vector<unsigned long> exp; IntPolRing IPD(ZZ); tim.start(); IPD.factor (intFactors, exp, c_A); tim.stop(); commentator.stop("done", NULL, "NTLfac"); printFactorization(cout << intFactors.size() << " integer polynomial factors:" << endl, ZZ, intFactors, exp) << endl; vector<IntPolRing::Element*>::const_iterator itf = intFactors.begin(); for ( ; itf != intFactors.end(); ++itf) delete *itf; cout << tim << endl; } #endif } if (argc == 3) { typedef Modular<double> Field; double q = atof(argv[2]); Field F(q); DenseMatrix<Field> B (F); B.read (input); cout << "B is " << B.rowdim() << " by " << B.coldim() << endl; GivPolynomialRing<Field,Dense>::Element c_B; Timer tim; tim.clear();tim.start(); charpoly (c_B, B); tim.stop(); cout << "Characteristic Polynomial is "; //printPolynomial (cout, F, c_B) << endl; cout << tim << endl; } return 0; } <commit_msg>LinBox::Timer<commit_after>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ // vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s /* * examples/charpoly.C * * Copyright (C) 2005, 2010 D. Saunders, C. Pernet, J-G. Dumas * * This file is part of LinBox. * * LinBox is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2 of * the License, or (at your option) any later version. * * LinBox 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 LinBox. If not, see * <http://www.gnu.org/licenses/>. */ /** \file examples/charpoly.C * @example examples/charpoly.C \brief Characteristic polynomial of matrix over Z or Zp. \ingroup examples */ #include <iostream> #include <iomanip> #include "linbox/util/timer.h" #include "linbox/field/modular-double.h" #include "linbox/field/unparametric.h" #include "linbox/blackbox/sparse.h" #include "linbox/blackbox/blas-blackbox.h" using namespace std; #include "linbox/solutions/charpoly.h" #include "linbox/ring/givaro-polynomial.h" using namespace LinBox; template <class Field, class Polynomial> std::ostream& printPolynomial (std::ostream& out, const Field &F, const Polynomial &v) { for (int i = v.size () - 1; i >= 0; i--) { F.write (out, v[i]); if (i > 0) out << " X^" << i << " + "; } return out; } template <class Field, class Polynomial> std::ostream& prettyprintIntegerPolynomial (std::ostream& out, const Field &F, const Polynomial &v) { size_t n = v.size()-1; if (n == 0) { F.write(out, v[0]); } else { if(v[n] != 0) { if (v[n] != 1) F.write(out, v[n]) << '*'; out << 'X'; if (n > 1) out << '^' << n; for (int i = n - 1; i > 0; i--) { if (v[i] != 0) { if (v[i] >0) out << " + "; if (v[i] != 1) F.write (out, v[i]) << '*'; out << 'X'; if (i > 1) out << '^' << i; } } if (v[0] != 0) { if (v[0] >0) out << " + "; F.write(out, v[0]); } } } return out; } template <class Field, class Factors, class Exponents> std::ostream& printFactorization (std::ostream& out, const Field &F, const Factors &f, const Exponents& exp) { typename Factors::const_iterator itf = f.begin(); typename Exponents::const_iterator ite = exp.begin(); for ( ; itf != f.end(); ++itf, ++ite) { prettyprintIntegerPolynomial(out << '(', F, *(*itf)) << ')'; if (*ite > 1) out << '^' << *ite; out << endl; } return out; } int main (int argc, char **argv) { commentator.setMaxDetailLevel (2); commentator.setMaxDepth (2); commentator.setReportStream (std::cerr); cout<<setprecision(8); cerr<<setprecision(8); if (argc < 2 || argc > 3) { cerr << "Usage: charpoly <matrix-file-in-SMS-format> [<p>]" << endl; return -1; } ifstream input (argv[1]); if (!input) { cerr << "Error opening matrix file " << argv[1] << endl; return -1; } if (argc == 2) { PID_integer ZZ; DenseMatrix<PID_integer > A (ZZ); A.read (input); typedef GivPolynomialRing<PID_integer,Dense> IntPolRing; IntPolRing::Element c_A; LinBox::Timer tim; tim.clear();tim.start();charpoly (c_A, A, Method::Blackbox()); tim.stop(); cout << "Characteristic Polynomial is "; //printPolynomial (cout, ZZ, c_A) << endl; cout << tim << endl; #ifdef __LINBOX_HAVE_NTL cout << "Do you want a factorization (y/n) ? "; char tmp; cin >> tmp; if (tmp == 'y' || tmp == 'Y') { commentator.start("Integer Polynomial factorization by NTL", "NTLfac"); vector<IntPolRing::Element*> intFactors; vector<unsigned long> exp; IntPolRing IPD(ZZ); tim.start(); IPD.factor (intFactors, exp, c_A); tim.stop(); commentator.stop("done", NULL, "NTLfac"); printFactorization(cout << intFactors.size() << " integer polynomial factors:" << endl, ZZ, intFactors, exp) << endl; vector<IntPolRing::Element*>::const_iterator itf = intFactors.begin(); for ( ; itf != intFactors.end(); ++itf) delete *itf; cout << tim << endl; } #endif } if (argc == 3) { typedef Modular<double> Field; double q = atof(argv[2]); Field F(q); DenseMatrix<Field> B (F); B.read (input); cout << "B is " << B.rowdim() << " by " << B.coldim() << endl; GivPolynomialRing<Field,Dense>::Element c_B; LinBox::Timer tim; tim.clear();tim.start(); charpoly (c_B, B); tim.stop(); cout << "Characteristic Polynomial is "; //printPolynomial (cout, F, c_B) << endl; cout << tim << endl; } return 0; } <|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 "vcl/svapp.hxx" #include "vcl/sysdata.hxx" #include "quartz/salvd.h" #ifdef MACOSX #include "osx/salinst.h" #include "osx/saldata.hxx" #include "osx/salframe.h" #else #include "headless/svpframe.hxx" #include "headless/svpgdi.hxx" #include "headless/svpinst.hxx" #include "headless/svpvd.hxx" #endif #include "quartz/salgdi.h" #include "quartz/utils.h" SalVirtualDevice* AquaSalInstance::CreateVirtualDevice( SalGraphics* pGraphics, long nDX, long nDY, sal_uInt16 nBitCount, const SystemGraphicsData *pData ) { // #i92075# can be called first in a thread SalData::ensureThreadAutoreleasePool(); #ifdef IOS if( pData ) return new AquaSalVirtualDevice( static_cast< AquaSalGraphics* >( pGraphics ), nDX, nDY, nBitCount, pData ); else { AquaSalVirtualDevice* pNew = new AquaSalVirtualDevice( NULL, nDX, nDY, nBitCount, NULL ); pNew->SetSize( nDX, nDY ); return pNew; } #else return new AquaSalVirtualDevice( static_cast< AquaSalGraphics* >( pGraphics ), nDX, nDY, nBitCount, pData ); #endif } AquaSalVirtualDevice::AquaSalVirtualDevice( AquaSalGraphics* pGraphic, long nDX, long nDY, sal_uInt16 nBitCount, const SystemGraphicsData *pData ) : mbGraphicsUsed( false ) , mxBitmapContext( NULL ) , mnBitmapDepth( 0 ) , mxLayer( NULL ) { SAL_INFO( "vcl.virdev", "AquaSalVirtualDevice::AquaSalVirtualDevice() this=" << this << " size=(" << nDX << "x" << nDY << ") bitcount=" << nBitCount << " pData=" << pData << " context=" << (pData ? pData->rCGContext : 0) ); if( pGraphic && pData && pData->rCGContext ) { // Create virtual device based on existing SystemGraphicsData // We ignore nDx and nDY, as the desired size comes from the SystemGraphicsData. // WTF does the above mean, SystemGraphicsData has no size field(s). mbForeignContext = true; // the mxContext is from pData (what "mxContext"? there is no such field anywhere in vcl;) mpGraphics = new AquaSalGraphics( /*pGraphic*/ ); if (nDX == 0) nDX = 1; if (nDY == 0) nDY = 1; mxLayer = CGLayerCreateWithContext( pData->rCGContext, CGSizeMake( nDX, nDY), NULL ); CG_TRACE( "CGLayerCreateWithContext(" << pData->rCGContext << "," << CGSizeMake( nDX, nDY) << ",NULL) = " << mxLayer ); mpGraphics->SetVirDevGraphics( mxLayer, pData->rCGContext ); } else { // create empty new virtual device mbForeignContext = false; // the mxContext is created within VCL mpGraphics = new AquaSalGraphics(); // never fails mnBitmapDepth = nBitCount; #ifdef MACOSX // inherit resolution from reference device if( pGraphic ) { AquaSalFrame* pFrame = pGraphic->getGraphicsFrame(); if( pFrame && AquaSalFrame::isAlive( pFrame ) ) { mpGraphics->setGraphicsFrame( pFrame ); mpGraphics->copyResolution( *pGraphic ); } } #endif if( nDX && nDY ) SetSize( nDX, nDY ); // NOTE: if SetSize does not succeed, we just ignore the nDX and nDY } } AquaSalVirtualDevice::~AquaSalVirtualDevice() { SAL_INFO( "vcl.virdev", "AquaSalVirtualDevice::~AquaSalVirtualDevice() this=" << this ); if( mpGraphics ) { mpGraphics->SetVirDevGraphics( NULL, NULL ); delete mpGraphics; mpGraphics = 0; } Destroy(); } void AquaSalVirtualDevice::Destroy() { SAL_INFO( "vcl.virdev", "AquaSalVirtualDevice::Destroy() this=" << this << " mbForeignContext=" << mbForeignContext ); if( mbForeignContext ) { // Do not delete mxContext that we have received from outside VCL mxLayer = NULL; return; } if( mxLayer ) { if( mpGraphics ) mpGraphics->SetVirDevGraphics( NULL, NULL ); CG_TRACE( "CGLayerRelease(" << mxLayer << ")" ); CGLayerRelease( mxLayer ); mxLayer = NULL; } if( mxBitmapContext ) { void* pRawData = CGBitmapContextGetData( mxBitmapContext ); rtl_freeMemory( pRawData ); CG_TRACE( "CGContextRelease(" << mxBitmapContext << ")" ); CGContextRelease( mxBitmapContext ); mxBitmapContext = NULL; } } SalGraphics* AquaSalVirtualDevice::AcquireGraphics() { if( mbGraphicsUsed || !mpGraphics ) return 0; mbGraphicsUsed = true; return mpGraphics; } void AquaSalVirtualDevice::ReleaseGraphics( SalGraphics* ) { mbGraphicsUsed = false; } bool AquaSalVirtualDevice::SetSize( long nDX, long nDY ) { SAL_INFO( "vcl.virdev", "AquaSalVirtualDevice::SetSize() this=" << this << " (" << nDX << "x" << nDY << ")" << " mbForeignContext=" << mbForeignContext ); if( mbForeignContext ) { // Do not delete/resize mxContext that we have received from outside VCL return true; } if( mxLayer ) { const CGSize aSize = CGLayerGetSize( mxLayer ); CG_TRACE( "CGlayerGetSize(" << mxLayer << ") = " << aSize ); if( (nDX == aSize.width) && (nDY == aSize.height) ) { // Yay, we do not have to do anything :) return true; } } Destroy(); // create a Quartz layer matching to the intended virdev usage CGContextRef xCGContext = NULL; if( mnBitmapDepth && (mnBitmapDepth < 16) ) { mnBitmapDepth = 8; // TODO: are 1bit vdevs worth it? const CGColorSpaceRef aCGColorSpace = GetSalData()->mxGraySpace; const CGBitmapInfo aCGBmpInfo = kCGImageAlphaNone; const int nBytesPerRow = (mnBitmapDepth * nDX + 7) / 8; void* pRawData = rtl_allocateMemory( nBytesPerRow * nDY ); mxBitmapContext = CGBitmapContextCreate( pRawData, nDX, nDY, mnBitmapDepth, nBytesPerRow, aCGColorSpace, aCGBmpInfo ); CG_TRACE( "CGBitmapContextCreate(" << nDX << "x" << nDY << "x" << mnBitmapDepth << ") = " << mxBitmapContext ); xCGContext = mxBitmapContext; } else { #ifdef MACOSX // default to a NSView target context AquaSalFrame* pSalFrame = mpGraphics->getGraphicsFrame(); if( !pSalFrame || !AquaSalFrame::isAlive( pSalFrame )) { if( !GetSalData()->maFrames.empty() ) { // get the first matching frame pSalFrame = *GetSalData()->maFrames.begin(); } else { // ensure we don't reuse a dead AquaSalFrame on the very // unlikely case of no other frame to use pSalFrame = NULL; } // update the frame reference mpGraphics->setGraphicsFrame( pSalFrame ); } if( pSalFrame ) { // #i91990# NSWindow* pNSWindow = pSalFrame->getNSWindow(); if ( pNSWindow ) { NSGraphicsContext* pNSContext = [NSGraphicsContext graphicsContextWithWindow: pNSWindow]; if( pNSContext ) xCGContext = reinterpret_cast<CGContextRef>([pNSContext graphicsPort]); } else { // fall back to a bitmap context mnBitmapDepth = 32; const CGColorSpaceRef aCGColorSpace = GetSalData()->mxRGBSpace; const CGBitmapInfo aCGBmpInfo = kCGImageAlphaNoneSkipFirst; const int nBytesPerRow = (mnBitmapDepth * nDX) / 8; void* pRawData = rtl_allocateMemory( nBytesPerRow * nDY ); mxBitmapContext = CGBitmapContextCreate( pRawData, nDX, nDY, 8, nBytesPerRow, aCGColorSpace, aCGBmpInfo ); xCGContext = mxBitmapContext; } } #else mnBitmapDepth = 32; const CGColorSpaceRef aCGColorSpace = GetSalData()->mxRGBSpace; const CGBitmapInfo aCGBmpInfo = kCGImageAlphaNoneSkipFirst; const int nBytesPerRow = (mnBitmapDepth * nDX) / 8; void* pRawData = rtl_allocateMemory( nBytesPerRow * nDY ); mxBitmapContext = CGBitmapContextCreate( pRawData, nDX, nDY, 8, nBytesPerRow, aCGColorSpace, aCGBmpInfo ); CG_TRACE( "CGBitmapContextCreate(" << nDX << "x" << nDY << "x8) = " << mxBitmapContext ); xCGContext = mxBitmapContext; #endif } SAL_WARN_IF( !xCGContext, "vcl.quartz", "No context" ); const CGSize aNewSize = { static_cast<CGFloat>(nDX), static_cast<CGFloat>(nDY) }; mxLayer = CGLayerCreateWithContext( xCGContext, aNewSize, NULL ); CG_TRACE( "CGLayerCreateWithContext(" << xCGContext << "," << aNewSize << ",NULL) = " << mxLayer ); if( mxLayer && mpGraphics ) { // get the matching Quartz context CGContextRef xDrawContext = CGLayerGetContext( mxLayer ); CG_TRACE( "CGLayerGetContext(" << mxLayer << ") = " << xDrawContext ); mpGraphics->SetVirDevGraphics( mxLayer, xDrawContext, mnBitmapDepth ); } return (mxLayer != NULL); } void AquaSalVirtualDevice::GetSize( long& rWidth, long& rHeight ) { if( mxLayer ) { const CGSize aSize = CGLayerGetSize( mxLayer ); rWidth = static_cast<long>(aSize.width); rHeight = static_cast<long>(aSize.height); CG_TRACE( "CGLayerGetSize(" << mxLayer << ") = " << aSize << "(" << rWidth << "x" << rHeight << ")" ); } else { rWidth = 0; rHeight = 0; } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Fill these buffers, too, with easily recognizable junk in dbgutil mode<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 "vcl/svapp.hxx" #include "vcl/sysdata.hxx" #include "quartz/salvd.h" #ifdef MACOSX #include "osx/salinst.h" #include "osx/saldata.hxx" #include "osx/salframe.h" #else #include "headless/svpframe.hxx" #include "headless/svpgdi.hxx" #include "headless/svpinst.hxx" #include "headless/svpvd.hxx" #endif #include "quartz/salgdi.h" #include "quartz/utils.h" SalVirtualDevice* AquaSalInstance::CreateVirtualDevice( SalGraphics* pGraphics, long nDX, long nDY, sal_uInt16 nBitCount, const SystemGraphicsData *pData ) { // #i92075# can be called first in a thread SalData::ensureThreadAutoreleasePool(); #ifdef IOS if( pData ) return new AquaSalVirtualDevice( static_cast< AquaSalGraphics* >( pGraphics ), nDX, nDY, nBitCount, pData ); else { AquaSalVirtualDevice* pNew = new AquaSalVirtualDevice( NULL, nDX, nDY, nBitCount, NULL ); pNew->SetSize( nDX, nDY ); return pNew; } #else return new AquaSalVirtualDevice( static_cast< AquaSalGraphics* >( pGraphics ), nDX, nDY, nBitCount, pData ); #endif } AquaSalVirtualDevice::AquaSalVirtualDevice( AquaSalGraphics* pGraphic, long nDX, long nDY, sal_uInt16 nBitCount, const SystemGraphicsData *pData ) : mbGraphicsUsed( false ) , mxBitmapContext( NULL ) , mnBitmapDepth( 0 ) , mxLayer( NULL ) { SAL_INFO( "vcl.virdev", "AquaSalVirtualDevice::AquaSalVirtualDevice() this=" << this << " size=(" << nDX << "x" << nDY << ") bitcount=" << nBitCount << " pData=" << pData << " context=" << (pData ? pData->rCGContext : 0) ); if( pGraphic && pData && pData->rCGContext ) { // Create virtual device based on existing SystemGraphicsData // We ignore nDx and nDY, as the desired size comes from the SystemGraphicsData. // WTF does the above mean, SystemGraphicsData has no size field(s). mbForeignContext = true; // the mxContext is from pData (what "mxContext"? there is no such field anywhere in vcl;) mpGraphics = new AquaSalGraphics( /*pGraphic*/ ); if (nDX == 0) nDX = 1; if (nDY == 0) nDY = 1; mxLayer = CGLayerCreateWithContext( pData->rCGContext, CGSizeMake( nDX, nDY), NULL ); CG_TRACE( "CGLayerCreateWithContext(" << pData->rCGContext << "," << CGSizeMake( nDX, nDY) << ",NULL) = " << mxLayer ); mpGraphics->SetVirDevGraphics( mxLayer, pData->rCGContext ); } else { // create empty new virtual device mbForeignContext = false; // the mxContext is created within VCL mpGraphics = new AquaSalGraphics(); // never fails mnBitmapDepth = nBitCount; #ifdef MACOSX // inherit resolution from reference device if( pGraphic ) { AquaSalFrame* pFrame = pGraphic->getGraphicsFrame(); if( pFrame && AquaSalFrame::isAlive( pFrame ) ) { mpGraphics->setGraphicsFrame( pFrame ); mpGraphics->copyResolution( *pGraphic ); } } #endif if( nDX && nDY ) SetSize( nDX, nDY ); // NOTE: if SetSize does not succeed, we just ignore the nDX and nDY } } AquaSalVirtualDevice::~AquaSalVirtualDevice() { SAL_INFO( "vcl.virdev", "AquaSalVirtualDevice::~AquaSalVirtualDevice() this=" << this ); if( mpGraphics ) { mpGraphics->SetVirDevGraphics( NULL, NULL ); delete mpGraphics; mpGraphics = 0; } Destroy(); } void AquaSalVirtualDevice::Destroy() { SAL_INFO( "vcl.virdev", "AquaSalVirtualDevice::Destroy() this=" << this << " mbForeignContext=" << mbForeignContext ); if( mbForeignContext ) { // Do not delete mxContext that we have received from outside VCL mxLayer = NULL; return; } if( mxLayer ) { if( mpGraphics ) mpGraphics->SetVirDevGraphics( NULL, NULL ); CG_TRACE( "CGLayerRelease(" << mxLayer << ")" ); CGLayerRelease( mxLayer ); mxLayer = NULL; } if( mxBitmapContext ) { void* pRawData = CGBitmapContextGetData( mxBitmapContext ); rtl_freeMemory( pRawData ); CG_TRACE( "CGContextRelease(" << mxBitmapContext << ")" ); CGContextRelease( mxBitmapContext ); mxBitmapContext = NULL; } } SalGraphics* AquaSalVirtualDevice::AcquireGraphics() { if( mbGraphicsUsed || !mpGraphics ) return 0; mbGraphicsUsed = true; return mpGraphics; } void AquaSalVirtualDevice::ReleaseGraphics( SalGraphics* ) { mbGraphicsUsed = false; } bool AquaSalVirtualDevice::SetSize( long nDX, long nDY ) { SAL_INFO( "vcl.virdev", "AquaSalVirtualDevice::SetSize() this=" << this << " (" << nDX << "x" << nDY << ")" << " mbForeignContext=" << mbForeignContext ); if( mbForeignContext ) { // Do not delete/resize mxContext that we have received from outside VCL return true; } if( mxLayer ) { const CGSize aSize = CGLayerGetSize( mxLayer ); CG_TRACE( "CGlayerGetSize(" << mxLayer << ") = " << aSize ); if( (nDX == aSize.width) && (nDY == aSize.height) ) { // Yay, we do not have to do anything :) return true; } } Destroy(); // create a Quartz layer matching to the intended virdev usage CGContextRef xCGContext = NULL; if( mnBitmapDepth && (mnBitmapDepth < 16) ) { mnBitmapDepth = 8; // TODO: are 1bit vdevs worth it? const CGColorSpaceRef aCGColorSpace = GetSalData()->mxGraySpace; const CGBitmapInfo aCGBmpInfo = kCGImageAlphaNone; const int nBytesPerRow = (mnBitmapDepth * nDX + 7) / 8; void* pRawData = rtl_allocateMemory( nBytesPerRow * nDY ); #ifdef DBG_UTIL for (ssize_t i = 0; i < nBytesPerRow * nDY; i++) ((sal_uInt8*)pRawData)[i] = (i & 0xFF); #endif mxBitmapContext = CGBitmapContextCreate( pRawData, nDX, nDY, mnBitmapDepth, nBytesPerRow, aCGColorSpace, aCGBmpInfo ); CG_TRACE( "CGBitmapContextCreate(" << nDX << "x" << nDY << "x" << mnBitmapDepth << ") = " << mxBitmapContext ); xCGContext = mxBitmapContext; } else { #ifdef MACOSX // default to a NSView target context AquaSalFrame* pSalFrame = mpGraphics->getGraphicsFrame(); if( !pSalFrame || !AquaSalFrame::isAlive( pSalFrame )) { if( !GetSalData()->maFrames.empty() ) { // get the first matching frame pSalFrame = *GetSalData()->maFrames.begin(); } else { // ensure we don't reuse a dead AquaSalFrame on the very // unlikely case of no other frame to use pSalFrame = NULL; } // update the frame reference mpGraphics->setGraphicsFrame( pSalFrame ); } if( pSalFrame ) { // #i91990# NSWindow* pNSWindow = pSalFrame->getNSWindow(); if ( pNSWindow ) { NSGraphicsContext* pNSContext = [NSGraphicsContext graphicsContextWithWindow: pNSWindow]; if( pNSContext ) xCGContext = reinterpret_cast<CGContextRef>([pNSContext graphicsPort]); } else { // fall back to a bitmap context mnBitmapDepth = 32; const CGColorSpaceRef aCGColorSpace = GetSalData()->mxRGBSpace; const CGBitmapInfo aCGBmpInfo = kCGImageAlphaNoneSkipFirst; const int nBytesPerRow = (mnBitmapDepth * nDX) / 8; void* pRawData = rtl_allocateMemory( nBytesPerRow * nDY ); #ifdef DBG_UTIL for (ssize_t i = 0; i < nBytesPerRow * nDY; i++) ((sal_uInt8*)pRawData)[i] = (i & 0xFF); #endif mxBitmapContext = CGBitmapContextCreate( pRawData, nDX, nDY, 8, nBytesPerRow, aCGColorSpace, aCGBmpInfo ); xCGContext = mxBitmapContext; } } #else mnBitmapDepth = 32; const CGColorSpaceRef aCGColorSpace = GetSalData()->mxRGBSpace; const CGBitmapInfo aCGBmpInfo = kCGImageAlphaNoneSkipFirst; const int nBytesPerRow = (mnBitmapDepth * nDX) / 8; void* pRawData = rtl_allocateMemory( nBytesPerRow * nDY ); #ifdef DBG_UTIL for (ssize_t i = 0; i < nBytesPerRow * nDY; i++) ((sal_uInt8*)pRawData)[i] = (i & 0xFF); #endif mxBitmapContext = CGBitmapContextCreate( pRawData, nDX, nDY, 8, nBytesPerRow, aCGColorSpace, aCGBmpInfo ); CG_TRACE( "CGBitmapContextCreate(" << nDX << "x" << nDY << "x8) = " << mxBitmapContext ); xCGContext = mxBitmapContext; #endif } SAL_WARN_IF( !xCGContext, "vcl.quartz", "No context" ); const CGSize aNewSize = { static_cast<CGFloat>(nDX), static_cast<CGFloat>(nDY) }; mxLayer = CGLayerCreateWithContext( xCGContext, aNewSize, NULL ); CG_TRACE( "CGLayerCreateWithContext(" << xCGContext << "," << aNewSize << ",NULL) = " << mxLayer ); if( mxLayer && mpGraphics ) { // get the matching Quartz context CGContextRef xDrawContext = CGLayerGetContext( mxLayer ); CG_TRACE( "CGLayerGetContext(" << mxLayer << ") = " << xDrawContext ); mpGraphics->SetVirDevGraphics( mxLayer, xDrawContext, mnBitmapDepth ); } return (mxLayer != NULL); } void AquaSalVirtualDevice::GetSize( long& rWidth, long& rHeight ) { if( mxLayer ) { const CGSize aSize = CGLayerGetSize( mxLayer ); rWidth = static_cast<long>(aSize.width); rHeight = static_cast<long>(aSize.height); CG_TRACE( "CGLayerGetSize(" << mxLayer << ") = " << aSize << "(" << rWidth << "x" << rHeight << ")" ); } else { rWidth = 0; rHeight = 0; } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * Copyright (c) 2007 MIPS Technologies, 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 copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black * Ali Saidi * Korey Sewell */ #ifndef __ARCH_MIPS_REGFILE_REGFILE_HH__ #define __ARCH_MIPS_REGFILE_REGFILE_HH__ #include "arch/mips/types.hh" #include "arch/mips/isa_traits.hh" #include "arch/mips/mt.hh" #include "arch/mips/regfile/misc_regfile.hh" #include "sim/faults.hh" class Checkpoint; class ThreadContext; using namespace MipsISA; void RegFile::clear() { miscRegFile.clear(); } void RegFile::reset(std::string core_name, ThreadID num_threads, unsigned num_vpes) { miscRegFile.reset(core_name, num_threads, num_vpes); } MiscReg RegFile::readMiscRegNoEffect(int miscReg, ThreadID tid = 0) { return miscRegFile.readRegNoEffect(miscReg, tid); } MiscReg RegFile::readMiscReg(int miscReg, ThreadContext *tc, ThreadID tid = 0) { return miscRegFile.readReg(miscReg, tc, tid); } void RegFile::setMiscRegNoEffect(int miscReg, const MiscReg &val, ThreadID tid = 0) { miscRegFile.setRegNoEffect(miscReg, val, tid); } void RegFile::setMiscReg(int miscReg, const MiscReg &val, ThreadContext *tc, ThreadID tid = 0) { miscRegFile.setReg(miscReg, val, tc, tid); } Addr RegFile::readPC() { return pc; } void RegFile::setPC(Addr val) { pc = val; } Addr RegFile::readNextPC() { return npc; } void RegFile::setNextPC(Addr val) { npc = val; } Addr RegFile::readNextNPC() { return nnpc; } void RegFile::setNextNPC(Addr val) { nnpc = val; } void RegFile::serialize(std::ostream &os) { miscRegFile.serialize(os); SERIALIZE_SCALAR(pc); SERIALIZE_SCALAR(npc); SERIALIZE_SCALAR(nnpc); } void RegFile::unserialize(Checkpoint *cp, const std::string &section) { miscRegFile.unserialize(cp, section); UNSERIALIZE_SCALAR(pc); UNSERIALIZE_SCALAR(npc); UNSERIALIZE_SCALAR(nnpc); } void MipsISA::copyRegs(ThreadContext *src, ThreadContext *dest) { panic("Copy Regs Not Implemented Yet\n"); } void MipsISA::copyMiscRegs(ThreadContext *src, ThreadContext *dest) { panic("Copy Misc. Regs Not Implemented Yet\n"); } <commit_msg>MIPS: Get rid of an orphaned MIPS .cc file.<commit_after><|endoftext|>
<commit_before>/* ** Copyright 2014 Centreon ** ** 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. ** ** For more information : contact@centreon.com */ #ifndef CCB_BAM_BOOL_AGGREGATE_HH # define CCB_BAM_BOOL_AGGREGATE_HH # include <vector> # include <string> # include "com/centreon/broker/bam/bool_value.hh" # include "com/centreon/broker/bam/metric_listener.hh" # include "com/centreon/broker/bam/bool_metric.hh" # include "com/centreon/broker/misc/shared_ptr.hh" # include "com/centreon/broker/io/stream.hh" # include "com/centreon/broker/namespace.hh" CCB_BEGIN() namespace bam { /** * @class bool_aggregate bool_aggregate.hh "com/centreon/broker/bam/bool_aggregate.hh" * @brief Evaluation of an aggregate of several metric. */ class bool_aggregate : public bool_value, public metric_listener { public: typedef misc::shared_ptr<bool_aggregate> ptr; static double min(std::vector<bool_metric::ptr> const& metrics); static double max(std::vector<bool_metric::ptr> const& metrics); static double avg(std::vector<bool_metric::ptr> const& metrics); static double sum(std::vector<bool_metric::ptr> const& metrics); static double count(std::vector<bool_metric::ptr> const& metrics); bool_aggregate( double (*aggregate_function) (std::vector<bool_metric::ptr> const&)); bool_aggregate(bool_aggregate const& right); ~bool_aggregate(); bool_aggregate& operator=(bool_aggregate const& right); bool child_has_update( computable* child, io::stream* visitor = NULL); void metric_update( misc::shared_ptr<storage::metric> const& m, io::stream* visitor = NULL); double value_hard(); double value_soft(); bool state_known() const; void add_boolean_metric(bool_metric::ptr metric); std::vector<bool_metric::ptr> const& get_boolean_metrics() const; private: double (*_aggregate_function)(std::vector<bool_metric::ptr> const&); std::vector<bool_metric::ptr> _bool_metrics; }; } CCB_END() #endif // !CCB_BAM_BOOL_AGGREGATE_HH <commit_msg>Bam: fix build error.<commit_after>/* ** Copyright 2014 Centreon ** ** 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. ** ** For more information : contact@centreon.com */ #ifndef CCB_BAM_BOOL_AGGREGATE_HH # define CCB_BAM_BOOL_AGGREGATE_HH # include <vector> # include <string> # include "com/centreon/broker/bam/bool_value.hh" # include "com/centreon/broker/bam/metric_listener.hh" # include "com/centreon/broker/bam/bool_metric.hh" # include "com/centreon/broker/misc/shared_ptr.hh" # include "com/centreon/broker/io/stream.hh" # include "com/centreon/broker/namespace.hh" CCB_BEGIN() namespace bam { /** * @class bool_aggregate bool_aggregate.hh "com/centreon/broker/bam/bool_aggregate.hh" * @brief Evaluation of an aggregate of several metric. */ class bool_aggregate : public bool_value { public: typedef misc::shared_ptr<bool_aggregate> ptr; static double min(std::vector<bool_metric::ptr> const& metrics); static double max(std::vector<bool_metric::ptr> const& metrics); static double avg(std::vector<bool_metric::ptr> const& metrics); static double sum(std::vector<bool_metric::ptr> const& metrics); static double count(std::vector<bool_metric::ptr> const& metrics); bool_aggregate( double (*aggregate_function) (std::vector<bool_metric::ptr> const&)); bool_aggregate(bool_aggregate const& right); ~bool_aggregate(); bool_aggregate& operator=(bool_aggregate const& right); bool child_has_update( computable* child, io::stream* visitor = NULL); double value_hard(); double value_soft(); bool state_known() const; void add_boolean_metric(bool_metric::ptr metric); std::vector<bool_metric::ptr> const& get_boolean_metrics() const; private: double (*_aggregate_function)(std::vector<bool_metric::ptr> const&); std::vector<bool_metric::ptr> _bool_metrics; }; } CCB_END() #endif // !CCB_BAM_BOOL_AGGREGATE_HH <|endoftext|>
<commit_before>/* Copyright 2015-2017 Philippe Tillet * * 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 <fstream> #include <memory> #include "triton/driver/module.h" #include "triton/driver/context.h" #include "triton/driver/error.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Verifier.h" #include "llvm/IR/IRPrintingPasses.h" #include "llvm/IR/Module.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/ExecutionEngine/ExecutionEngine.h" #include "llvm/ExecutionEngine/SectionMemoryManager.h" #include "llvm/Transforms/Utils/Cloning.h" namespace triton { namespace driver { /* ------------------------ */ // Base // /* ------------------------ */ void module::init_llvm() { static bool init = false; if(!init){ llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargets(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmParsers(); llvm::InitializeAllAsmPrinters(); init = true; } } module::module(driver::context* ctx, CUmodule mod, bool has_ownership) : polymorphic_resource(mod, has_ownership), ctx_(ctx) { } module::module(driver::context* ctx, cl_program mod, bool has_ownership) : polymorphic_resource(mod, has_ownership), ctx_(ctx) { } module::module(driver::context* ctx, host_module_t mod, bool has_ownership) : polymorphic_resource(mod, has_ownership), ctx_(ctx) { } driver::context* module::context() const { return ctx_; } module* module::create(driver::context* ctx, std::unique_ptr<llvm::Module> src) { switch(ctx->backend()){ case CUDA: return new cu_module(ctx, std::move(src)); case OpenCL: return new ocl_module(ctx, std::move(src)); case Host: return new host_module(ctx, std::move(src)); default: throw std::runtime_error("unknown backend"); } } void module::compile_llvm_module(std::unique_ptr<llvm::Module> module, const std::string& triple, const std::string &proc, std::string layout, llvm::SmallVectorImpl<char> &buffer, const std::string& features, file_type_t ft) { init_llvm(); // // debug // llvm::legacy::PassManager pm; // pm.add(llvm::createPrintModulePass(llvm::outs())); // pm.add(llvm::createVerifierPass()); // pm.run(*module); // create machine module->setTargetTriple(triple); std::string error; auto target = llvm::TargetRegistry::lookupTarget(module->getTargetTriple(), error); llvm::TargetOptions opt; opt.AllowFPOpFusion = llvm::FPOpFusion::Fast; opt.UnsafeFPMath = false; opt.NoInfsFPMath = false; opt.NoNaNsFPMath = true; llvm::TargetMachine *machine = target->createTargetMachine(module->getTargetTriple(), proc, features, opt, llvm::Reloc::PIC_, llvm::None, llvm::CodeGenOpt::Aggressive); // set data layout if(layout.empty()) module->setDataLayout(machine->createDataLayout()); else module->setDataLayout(layout); // emit machine code for (llvm::Function &f : module->functions()) f.addFnAttr(llvm::Attribute::AlwaysInline); llvm::legacy::PassManager pass; llvm::raw_svector_ostream stream(buffer); // convert triton file type to llvm file type auto ll_file_type = [&](module::file_type_t type){ if(type == Object) return llvm::TargetMachine::CGFT_ObjectFile; return llvm::TargetMachine::CGFT_AssemblyFile; }; // emit machine->addPassesToEmitFile(pass, stream, nullptr, ll_file_type(ft)); pass.run(*module); } /* ------------------------ */ // Host // /* ------------------------ */ host_module::host_module(driver::context * context, std::unique_ptr<llvm::Module> src): module(context, host_module_t(), true) { init_llvm(); // host info // std::string triple = llvm::sys::getDefaultTargetTriple(); // std::string cpu = llvm::sys::getHostCPUName(); // llvm::SmallVector<char, 0> buffer; // module::compile_llvm_module(src, triple, cpu, "", buffer, "", Assembly); // create kernel wrapper llvm::LLVMContext &ctx = src->getContext(); llvm::Type *void_ty = llvm::Type::getVoidTy(ctx); llvm::Type *args_ty = llvm::Type::getInt8PtrTy(ctx)->getPointerTo(); llvm::Type *int32_ty = llvm::Type::getInt32Ty(ctx); std::vector<llvm::Type*> tys = {args_ty, int32_ty, int32_ty, int32_ty}; llvm::FunctionType *main_ty = llvm::FunctionType::get(void_ty, tys, false); llvm::Function* main = llvm::Function::Create(main_ty, llvm::Function::ExternalLinkage, "main", &*src); llvm::Function* fn = src->getFunction("matmul"); llvm::FunctionType *fn_ty = fn->getFunctionType(); std::vector<llvm::Value*> fn_args(fn_ty->getNumParams()); std::vector<llvm::Value*> ptrs(fn_args.size() - 3); llvm::BasicBlock* entry = llvm::BasicBlock::Create(ctx, "entry", main); llvm::IRBuilder<> ir_builder(ctx); ir_builder.SetInsertPoint(entry); for(unsigned i = 0; i < ptrs.size(); i++) ptrs[i] = ir_builder.CreateGEP(main->arg_begin(), ir_builder.getInt32(i)); for(unsigned i = 0; i < ptrs.size(); i++){ llvm::Value* addr = ir_builder.CreateBitCast(ir_builder.CreateLoad(ptrs[i]), fn_ty->getParamType(i)->getPointerTo()); fn_args[i] = ir_builder.CreateLoad(addr); } fn_args[fn_args.size() - 3] = main->arg_begin() + 1; fn_args[fn_args.size() - 2] = main->arg_begin() + 2; fn_args[fn_args.size() - 1] = main->arg_begin() + 3; ir_builder.CreateCall(fn, fn_args); ir_builder.CreateRetVoid(); // create execution engine for(llvm::Function& fn: src->functions()) hst_->functions[fn.getName()] = &fn; llvm::EngineBuilder builder(std::move(src)); builder.setErrorStr(&hst_->error); builder.setMCJITMemoryManager(llvm::make_unique<llvm::SectionMemoryManager>()); builder.setOptLevel(llvm::CodeGenOpt::Aggressive); builder.setEngineKind(llvm::EngineKind::JIT); builder.setUseOrcMCJITReplacement(true); hst_->engine = builder.create(); } std::unique_ptr<buffer> host_module::symbol(const char *name) const { throw std::runtime_error("not implemented"); } /* ------------------------ */ // OpenCL // /* ------------------------ */ ocl_module::ocl_module(driver::context * context, std::unique_ptr<llvm::Module> src): module(context, cl_program(), true) { throw std::runtime_error("not supported"); // init_llvm(); // llvm::SmallVector<char, 0> buffer; // module::compile_llvm_module(src, "amdgcn-amd-amdhsa-amdgizcl", "gfx902", "", buffer, "code-object-v3", Object); // std::ofstream output("/tmp/tmp.o", std::ios::binary); // std::copy(buffer.begin(), buffer.end(), std::ostreambuf_iterator<char>(output)); // system("ld.lld-8 /tmp/tmp.o -shared -o /tmp/tmp.o"); // std::ifstream input("/tmp/tmp.o", std::ios::in | std::ios::binary ); // std::vector<unsigned char> in_buffer(std::istreambuf_iterator<char>(input), {}); // size_t sizes[] = {in_buffer.size()}; // const unsigned char* data[] = {(unsigned char*)in_buffer.data()}; // cl_int status; // cl_int err; // *cl_ = dispatch::clCreateProgramWithBinary(*context->cl(), 1, &*context->device()->cl(), sizes, data, &status, &err); // check(status); // check(err); // try{ // dispatch::clBuildProgram(*cl_, 1, &*context->device()->cl(), NULL, NULL, NULL); // } // catch(...){ // char log[2048]; // dispatch::clGetProgramBuildInfo(*cl_, *context->device()->cl(), CL_PROGRAM_BUILD_LOG, 1024, log, NULL); // throw; // } } std::unique_ptr<buffer> ocl_module::symbol(const char *name) const { throw std::runtime_error("not implemented"); } /* ------------------------ */ // CUDA // /* ------------------------ */ static bool find_and_replace(std::string& str, const std::string& begin, const std::string& end, const std::string& target){ size_t start_replace = str.find(begin); size_t end_replace = str.find(end, start_replace); if(start_replace == std::string::npos) return false; str.replace(start_replace, end_replace + 1 - start_replace, target); return true; } std::string cu_module::compile_llvm_module(std::unique_ptr<llvm::Module> module, driver::device* device) { // options auto options = llvm::cl::getRegisteredOptions(); // for(auto& opt: options) // std::cout << opt.getKey().str() << std::endl; auto* short_ptr = static_cast<llvm::cl::opt<bool>*>(options["nvptx-short-ptr"]); assert(short_ptr); short_ptr->setValue(true); // compute capability auto cc = ((driver::cu_device*)device)->compute_capability(); std::string sm = "sm_" + std::to_string(cc.first) + std::to_string(cc.second); // create llvm::SmallVector<char, 0> buffer; module::compile_llvm_module(std::move(module), "nvptx64-nvidia-cuda", sm, "", buffer, "ptx63", Assembly); std::string result(buffer.begin(), buffer.end()); int version; dispatch::cuDriverGetVersion(&version); int major = version / 1000; int minor = (version - major*1000) / 10; if(major < 10) throw std::runtime_error("Triton requires CUDA 10+"); if(minor >= 1) find_and_replace(result, ".version", "\n", ".version 6.4\n"); while(find_and_replace(result, "\t// begin inline asm", "\n", "")); while(find_and_replace(result, "\t// end inline asm", "\n", "")); return result; } cu_module::cu_module(driver::context * context, std::unique_ptr<llvm::Module> ll_module): cu_module(context, compile_llvm_module(std::move(ll_module), context->device())) { } cu_module::cu_module(driver::context * context, std::string const & source) : module(context, CUmodule(), true), source_(source){ cu_context::context_switcher ctx(*context); // std::cout << source << std::endl; // JIT compile source-code CUjit_option opt[] = {CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES, CU_JIT_ERROR_LOG_BUFFER}; unsigned int errbufsize = 8096; std::string errbuf(errbufsize, 0); void* optval[] = {(void*)(uintptr_t)errbufsize, (void*)errbuf.data()}; try{ dispatch::cuModuleLoadDataEx(&*cu_, source_.data(), 2, opt, optval); }catch(exception::cuda::base const &){ #ifdef TRITON_LOG_PTX_ERROR std::cerr << "Compilation Failed! Log: " << std::endl; std::cerr << errbuf << std::endl; #endif throw; } } std::unique_ptr<buffer> cu_module::symbol(const char *name) const{ CUdeviceptr handle; size_t size; dispatch::cuModuleGetGlobal_v2(&handle, &size, *cu_, name); std::unique_ptr<buffer> res(new cu_buffer(ctx_, size, handle, false)); return std::move(res); } } } <commit_msg>[DRIVER] Now always using PTXv6.4<commit_after>/* Copyright 2015-2017 Philippe Tillet * * 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 <fstream> #include <memory> #include "triton/driver/module.h" #include "triton/driver/context.h" #include "triton/driver/error.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Verifier.h" #include "llvm/IR/IRPrintingPasses.h" #include "llvm/IR/Module.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/ExecutionEngine/ExecutionEngine.h" #include "llvm/ExecutionEngine/SectionMemoryManager.h" #include "llvm/Transforms/Utils/Cloning.h" namespace triton { namespace driver { /* ------------------------ */ // Base // /* ------------------------ */ void module::init_llvm() { static bool init = false; if(!init){ llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargets(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmParsers(); llvm::InitializeAllAsmPrinters(); init = true; } } module::module(driver::context* ctx, CUmodule mod, bool has_ownership) : polymorphic_resource(mod, has_ownership), ctx_(ctx) { } module::module(driver::context* ctx, cl_program mod, bool has_ownership) : polymorphic_resource(mod, has_ownership), ctx_(ctx) { } module::module(driver::context* ctx, host_module_t mod, bool has_ownership) : polymorphic_resource(mod, has_ownership), ctx_(ctx) { } driver::context* module::context() const { return ctx_; } module* module::create(driver::context* ctx, std::unique_ptr<llvm::Module> src) { switch(ctx->backend()){ case CUDA: return new cu_module(ctx, std::move(src)); case OpenCL: return new ocl_module(ctx, std::move(src)); case Host: return new host_module(ctx, std::move(src)); default: throw std::runtime_error("unknown backend"); } } void module::compile_llvm_module(std::unique_ptr<llvm::Module> module, const std::string& triple, const std::string &proc, std::string layout, llvm::SmallVectorImpl<char> &buffer, const std::string& features, file_type_t ft) { init_llvm(); // // debug // llvm::legacy::PassManager pm; // pm.add(llvm::createPrintModulePass(llvm::outs())); // pm.add(llvm::createVerifierPass()); // pm.run(*module); // create machine module->setTargetTriple(triple); std::string error; auto target = llvm::TargetRegistry::lookupTarget(module->getTargetTriple(), error); llvm::TargetOptions opt; opt.AllowFPOpFusion = llvm::FPOpFusion::Fast; opt.UnsafeFPMath = false; opt.NoInfsFPMath = false; opt.NoNaNsFPMath = true; llvm::TargetMachine *machine = target->createTargetMachine(module->getTargetTriple(), proc, features, opt, llvm::Reloc::PIC_, llvm::None, llvm::CodeGenOpt::Aggressive); // set data layout if(layout.empty()) module->setDataLayout(machine->createDataLayout()); else module->setDataLayout(layout); // emit machine code for (llvm::Function &f : module->functions()) f.addFnAttr(llvm::Attribute::AlwaysInline); llvm::legacy::PassManager pass; llvm::raw_svector_ostream stream(buffer); // convert triton file type to llvm file type auto ll_file_type = [&](module::file_type_t type){ if(type == Object) return llvm::TargetMachine::CGFT_ObjectFile; return llvm::TargetMachine::CGFT_AssemblyFile; }; // emit machine->addPassesToEmitFile(pass, stream, nullptr, ll_file_type(ft)); pass.run(*module); } /* ------------------------ */ // Host // /* ------------------------ */ host_module::host_module(driver::context * context, std::unique_ptr<llvm::Module> src): module(context, host_module_t(), true) { init_llvm(); // host info // std::string triple = llvm::sys::getDefaultTargetTriple(); // std::string cpu = llvm::sys::getHostCPUName(); // llvm::SmallVector<char, 0> buffer; // module::compile_llvm_module(src, triple, cpu, "", buffer, "", Assembly); // create kernel wrapper llvm::LLVMContext &ctx = src->getContext(); llvm::Type *void_ty = llvm::Type::getVoidTy(ctx); llvm::Type *args_ty = llvm::Type::getInt8PtrTy(ctx)->getPointerTo(); llvm::Type *int32_ty = llvm::Type::getInt32Ty(ctx); std::vector<llvm::Type*> tys = {args_ty, int32_ty, int32_ty, int32_ty}; llvm::FunctionType *main_ty = llvm::FunctionType::get(void_ty, tys, false); llvm::Function* main = llvm::Function::Create(main_ty, llvm::Function::ExternalLinkage, "main", &*src); llvm::Function* fn = src->getFunction("matmul"); llvm::FunctionType *fn_ty = fn->getFunctionType(); std::vector<llvm::Value*> fn_args(fn_ty->getNumParams()); std::vector<llvm::Value*> ptrs(fn_args.size() - 3); llvm::BasicBlock* entry = llvm::BasicBlock::Create(ctx, "entry", main); llvm::IRBuilder<> ir_builder(ctx); ir_builder.SetInsertPoint(entry); for(unsigned i = 0; i < ptrs.size(); i++) ptrs[i] = ir_builder.CreateGEP(main->arg_begin(), ir_builder.getInt32(i)); for(unsigned i = 0; i < ptrs.size(); i++){ llvm::Value* addr = ir_builder.CreateBitCast(ir_builder.CreateLoad(ptrs[i]), fn_ty->getParamType(i)->getPointerTo()); fn_args[i] = ir_builder.CreateLoad(addr); } fn_args[fn_args.size() - 3] = main->arg_begin() + 1; fn_args[fn_args.size() - 2] = main->arg_begin() + 2; fn_args[fn_args.size() - 1] = main->arg_begin() + 3; ir_builder.CreateCall(fn, fn_args); ir_builder.CreateRetVoid(); // create execution engine for(llvm::Function& fn: src->functions()) hst_->functions[fn.getName()] = &fn; llvm::EngineBuilder builder(std::move(src)); builder.setErrorStr(&hst_->error); builder.setMCJITMemoryManager(llvm::make_unique<llvm::SectionMemoryManager>()); builder.setOptLevel(llvm::CodeGenOpt::Aggressive); builder.setEngineKind(llvm::EngineKind::JIT); builder.setUseOrcMCJITReplacement(true); hst_->engine = builder.create(); } std::unique_ptr<buffer> host_module::symbol(const char *name) const { throw std::runtime_error("not implemented"); } /* ------------------------ */ // OpenCL // /* ------------------------ */ ocl_module::ocl_module(driver::context * context, std::unique_ptr<llvm::Module> src): module(context, cl_program(), true) { throw std::runtime_error("not supported"); // init_llvm(); // llvm::SmallVector<char, 0> buffer; // module::compile_llvm_module(src, "amdgcn-amd-amdhsa-amdgizcl", "gfx902", "", buffer, "code-object-v3", Object); // std::ofstream output("/tmp/tmp.o", std::ios::binary); // std::copy(buffer.begin(), buffer.end(), std::ostreambuf_iterator<char>(output)); // system("ld.lld-8 /tmp/tmp.o -shared -o /tmp/tmp.o"); // std::ifstream input("/tmp/tmp.o", std::ios::in | std::ios::binary ); // std::vector<unsigned char> in_buffer(std::istreambuf_iterator<char>(input), {}); // size_t sizes[] = {in_buffer.size()}; // const unsigned char* data[] = {(unsigned char*)in_buffer.data()}; // cl_int status; // cl_int err; // *cl_ = dispatch::clCreateProgramWithBinary(*context->cl(), 1, &*context->device()->cl(), sizes, data, &status, &err); // check(status); // check(err); // try{ // dispatch::clBuildProgram(*cl_, 1, &*context->device()->cl(), NULL, NULL, NULL); // } // catch(...){ // char log[2048]; // dispatch::clGetProgramBuildInfo(*cl_, *context->device()->cl(), CL_PROGRAM_BUILD_LOG, 1024, log, NULL); // throw; // } } std::unique_ptr<buffer> ocl_module::symbol(const char *name) const { throw std::runtime_error("not implemented"); } /* ------------------------ */ // CUDA // /* ------------------------ */ static bool find_and_replace(std::string& str, const std::string& begin, const std::string& end, const std::string& target){ size_t start_replace = str.find(begin); size_t end_replace = str.find(end, start_replace); if(start_replace == std::string::npos) return false; str.replace(start_replace, end_replace + 1 - start_replace, target); return true; } std::string cu_module::compile_llvm_module(std::unique_ptr<llvm::Module> module, driver::device* device) { // options auto options = llvm::cl::getRegisteredOptions(); // for(auto& opt: options) // std::cout << opt.getKey().str() << std::endl; auto* short_ptr = static_cast<llvm::cl::opt<bool>*>(options["nvptx-short-ptr"]); assert(short_ptr); short_ptr->setValue(true); // compute capability auto cc = ((driver::cu_device*)device)->compute_capability(); std::string sm = "sm_" + std::to_string(cc.first) + std::to_string(cc.second); // create llvm::SmallVector<char, 0> buffer; module::compile_llvm_module(std::move(module), "nvptx64-nvidia-cuda", sm, "", buffer, "ptx63", Assembly); std::string result(buffer.begin(), buffer.end()); int version; dispatch::cuDriverGetVersion(&version); int major = version / 1000; // int minor = (version - major*1000) / 10; if(major < 10) throw std::runtime_error("Triton requires CUDA 10+"); find_and_replace(result, ".version", "\n", ".version 6.4\n"); while(find_and_replace(result, "\t// begin inline asm", "\n", "")); while(find_and_replace(result, "\t// end inline asm", "\n", "")); return result; } cu_module::cu_module(driver::context * context, std::unique_ptr<llvm::Module> ll_module): cu_module(context, compile_llvm_module(std::move(ll_module), context->device())) { } cu_module::cu_module(driver::context * context, std::string const & source) : module(context, CUmodule(), true), source_(source){ cu_context::context_switcher ctx(*context); // std::cout << source << std::endl; // JIT compile source-code CUjit_option opt[] = {CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES, CU_JIT_ERROR_LOG_BUFFER}; unsigned int errbufsize = 8096; std::string errbuf(errbufsize, 0); void* optval[] = {(void*)(uintptr_t)errbufsize, (void*)errbuf.data()}; try{ dispatch::cuModuleLoadDataEx(&*cu_, source_.data(), 2, opt, optval); }catch(exception::cuda::base const &){ #ifdef TRITON_LOG_PTX_ERROR std::cerr << "Compilation Failed! Log: " << std::endl; std::cerr << errbuf << std::endl; #endif throw; } } std::unique_ptr<buffer> cu_module::symbol(const char *name) const{ CUdeviceptr handle; size_t size; dispatch::cuModuleGetGlobal_v2(&handle, &size, *cu_, name); std::unique_ptr<buffer> res(new cu_buffer(ctx_, size, handle, false)); return std::move(res); } } } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RX マイコン、デバイス固有ヘッダー @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2018, 2022 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/io_utils.hpp" #if defined(SIG_RX63T) #include "RX63T/clock_profile.hpp" #include "RX63T/peripheral.hpp" #include "RX63T/system.hpp" #include "RX63T/power_mgr.hpp" #include "RX63T/icu.hpp" #include "RX63T/icu_mgr.hpp" #include "RX63T/port_map.hpp" #include "RX63T/port_map_mtu.hpp" #include "RX63T/port_map_gpt.hpp" #include "RX600/rx_dsp_inst.h" #elif defined(SIG_RX621) || defined(SIG_RX62N) #include "RX62x/clock_profile.hpp" #include "RX62x/peripheral.hpp" #include "RX62x/system.hpp" #include "RX62x/power_mgr.hpp" #include "RX62x/icu.hpp" #include "RX62x/icu_mgr.hpp" #include "RX62x/port_map.hpp" #include "RX62x/port_map_mtu.hpp" #include "RX600/rx_dsp_inst.h" #elif defined(SIG_RX24T) #include "RX24T/clock_profile.hpp" #include "RX24T/peripheral.hpp" #include "RX24T/system.hpp" #include "RX24T/power_mgr.hpp" #include "RX24T/icu.hpp" #include "RX24T/icu_mgr.hpp" #include "RX24T/port_map.hpp" #include "RX24T/port_map_mtu.hpp" #include "RX600/rx_dsp_inst.h" #elif defined(SIG_RX64M) #include "RX64M/clock_profile.hpp" #include "RX64M/peripheral.hpp" #include "RX600/system.hpp" #include "RX64M/power_mgr.hpp" #include "RX64M/icu.hpp" #include "RX64M/icu_mgr.hpp" #include "RX64M/port_map.hpp" #include "RX64M/port_map_sci.hpp" #include "RX64M/port_map_mtu.hpp" #include "RX64M/port_map_tpu.hpp" #include "RX600/rx_dsp_inst.h" #elif defined(SIG_RX71M) #include "RX71M/clock_profile.hpp" #include "RX64M/peripheral.hpp" #include "RX600/system.hpp" #include "RX64M/power_mgr.hpp" #include "RX64M/icu.hpp" #include "RX64M/icu_mgr.hpp" #include "RX64M/port_map.hpp" #include "RX64M/port_map_sci.hpp" #include "RX64M/port_map_mtu.hpp" #include "RX64M/port_map_tpu.hpp" #include "RX600/rx_dsp_inst.h" #elif defined(SIG_RX72M) #include "RX72M/clock_profile.hpp" #include "RX72M/peripheral.hpp" #include "RX600/system.hpp" #include "RX72M/power_mgr.hpp" #include "RX72M/icu.hpp" #include "RX72M/icu_mgr.hpp" #include "RX72M/port_map.hpp" #include "RX72M/port_map_mtu.hpp" #include "RX600/rx_dsp_inst.h" #elif defined(SIG_RX72N) #include "RX72N/clock_profile.hpp" #include "RX72N/peripheral.hpp" #include "RX600/system.hpp" #include "RX72N/power_mgr.hpp" #include "RX72N/icu.hpp" #include "RX72N/icu_mgr.hpp" #include "RX72N/port_map.hpp" #include "RX72N/port_map_sci.hpp" #include "RX72N/port_map_mtu.hpp" #include "RX72N/port_map_gptw.hpp" #include "RX72N/port_map_tpu.hpp" #include "RX72N/port_map_qspi.hpp" #include "RX72N/port_map_ether.hpp" #include "RX600/rx_dsp_inst.h" #elif defined(SIG_RX651) || defined(SIG_RX65N) #include "RX65x/clock_profile.hpp" #include "RX65x/peripheral.hpp" #include "RX600/system.hpp" #include "RX65x/power_mgr.hpp" #include "RX65x/icu.hpp" #include "RX65x/icu_mgr.hpp" #include "RX65x/port_map.hpp" #include "RX65x/port_map_mtu.hpp" #include "RX65x/port_map_tpu.hpp" #include "RX600/rx_dsp_inst.h" #elif defined(SIG_RX66T) #include "RX66T/clock_profile.hpp" #include "RX66T/peripheral.hpp" #include "RX600/system.hpp" #include "RX66T/power_mgr.hpp" #include "RX66T/icu.hpp" #include "RX66T/icu_mgr.hpp" #include "RX66T/port_map.hpp" #include "RX66T/port_map_mtu.hpp" #include "RX66T/port_map_gptw.hpp" #include "RX600/rx_dsp_inst.h" #elif defined(SIG_RX72T) #include "RX72T/clock_profile.hpp" #include "RX72T/peripheral.hpp" #include "RX600/system.hpp" #include "RX72T/power_mgr.hpp" #include "RX72T/icu.hpp" #include "RX72T/icu_mgr.hpp" #include "RX72T/port_map.hpp" #include "RX72T/port_map_sci.hpp" #include "RX72T/port_map_mtu.hpp" #include "RX72T/port_map_gptw.hpp" #include "RX600/rx_dsp_inst.h" #else #error "device.hpp: Requires SIG_XXX to be defined" #endif <commit_msg>Update: edit 'port_map_gpt.hpp' path<commit_after>#pragma once //=====================================================================// /*! @file @brief RX マイコン、デバイス固有ヘッダー @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2018, 2022 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/io_utils.hpp" #if defined(SIG_RX63T) #include "RX63T/clock_profile.hpp" #include "RX63T/peripheral.hpp" #include "RX63T/system.hpp" #include "RX63T/power_mgr.hpp" #include "RX63T/icu.hpp" #include "RX63T/icu_mgr.hpp" #include "RX63T/port_map.hpp" #include "RX63T/port_map_mtu.hpp" #include "RX63T/port_map_gpt.hpp" #include "RX600/rx_dsp_inst.h" #elif defined(SIG_RX621) || defined(SIG_RX62N) #include "RX62x/clock_profile.hpp" #include "RX62x/peripheral.hpp" #include "RX62x/system.hpp" #include "RX62x/power_mgr.hpp" #include "RX62x/icu.hpp" #include "RX62x/icu_mgr.hpp" #include "RX62x/port_map.hpp" #include "RX62x/port_map_mtu.hpp" #include "RX600/rx_dsp_inst.h" #elif defined(SIG_RX24T) #include "RX24T/clock_profile.hpp" #include "RX24T/peripheral.hpp" #include "RX24T/system.hpp" #include "RX24T/power_mgr.hpp" #include "RX24T/icu.hpp" #include "RX24T/icu_mgr.hpp" #include "RX24T/port_map.hpp" #include "RX24T/port_map_mtu.hpp" #include "RX24T/port_map_gpt.hpp" #include "RX600/rx_dsp_inst.h" #elif defined(SIG_RX64M) #include "RX64M/clock_profile.hpp" #include "RX64M/peripheral.hpp" #include "RX600/system.hpp" #include "RX64M/power_mgr.hpp" #include "RX64M/icu.hpp" #include "RX64M/icu_mgr.hpp" #include "RX64M/port_map.hpp" #include "RX64M/port_map_sci.hpp" #include "RX64M/port_map_mtu.hpp" #include "RX64M/port_map_gpt.hpp" #include "RX64M/port_map_tpu.hpp" #include "RX600/rx_dsp_inst.h" #elif defined(SIG_RX71M) #include "RX71M/clock_profile.hpp" #include "RX64M/peripheral.hpp" #include "RX600/system.hpp" #include "RX64M/power_mgr.hpp" #include "RX64M/icu.hpp" #include "RX64M/icu_mgr.hpp" #include "RX64M/port_map.hpp" #include "RX64M/port_map_sci.hpp" #include "RX64M/port_map_mtu.hpp" #include "RX64M/port_map_gpt.hpp" #include "RX64M/port_map_tpu.hpp" #include "RX600/rx_dsp_inst.h" #elif defined(SIG_RX72M) #include "RX72M/clock_profile.hpp" #include "RX72M/peripheral.hpp" #include "RX600/system.hpp" #include "RX72M/power_mgr.hpp" #include "RX72M/icu.hpp" #include "RX72M/icu_mgr.hpp" #include "RX72M/port_map.hpp" #include "RX72M/port_map_mtu.hpp" #include "RX600/rx_dsp_inst.h" #elif defined(SIG_RX72N) #include "RX72N/clock_profile.hpp" #include "RX72N/peripheral.hpp" #include "RX600/system.hpp" #include "RX72N/power_mgr.hpp" #include "RX72N/icu.hpp" #include "RX72N/icu_mgr.hpp" #include "RX72N/port_map.hpp" #include "RX72N/port_map_sci.hpp" #include "RX72N/port_map_mtu.hpp" #include "RX72N/port_map_gptw.hpp" #include "RX72N/port_map_tpu.hpp" #include "RX72N/port_map_qspi.hpp" #include "RX72N/port_map_ether.hpp" #include "RX600/rx_dsp_inst.h" #elif defined(SIG_RX651) || defined(SIG_RX65N) #include "RX65x/clock_profile.hpp" #include "RX65x/peripheral.hpp" #include "RX600/system.hpp" #include "RX65x/power_mgr.hpp" #include "RX65x/icu.hpp" #include "RX65x/icu_mgr.hpp" #include "RX65x/port_map.hpp" #include "RX65x/port_map_mtu.hpp" #include "RX65x/port_map_tpu.hpp" #include "RX600/rx_dsp_inst.h" #elif defined(SIG_RX66T) #include "RX66T/clock_profile.hpp" #include "RX66T/peripheral.hpp" #include "RX600/system.hpp" #include "RX66T/power_mgr.hpp" #include "RX66T/icu.hpp" #include "RX66T/icu_mgr.hpp" #include "RX66T/port_map.hpp" #include "RX66T/port_map_mtu.hpp" #include "RX66T/port_map_gptw.hpp" #include "RX600/rx_dsp_inst.h" #elif defined(SIG_RX72T) #include "RX72T/clock_profile.hpp" #include "RX72T/peripheral.hpp" #include "RX600/system.hpp" #include "RX72T/power_mgr.hpp" #include "RX72T/icu.hpp" #include "RX72T/icu_mgr.hpp" #include "RX72T/port_map.hpp" #include "RX72T/port_map_sci.hpp" #include "RX72T/port_map_mtu.hpp" #include "RX72T/port_map_gptw.hpp" #include "RX600/rx_dsp_inst.h" #else #error "device.hpp: Requires SIG_XXX to be defined" #endif <|endoftext|>
<commit_before>/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | Copyright (c) 2012-2015 The Swoole Group | +----------------------------------------------------------------------+ | 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 | | license@swoole.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tianfeng Han <mikan.tenny@gmail.com> | +----------------------------------------------------------------------+ */ #include "php_swoole.h" #ifdef SW_COROUTINE #include "swoole_coroutine.h" #endif using namespace swoole; enum swoole_timer_type { SW_TIMER_TICK, SW_TIMER_AFTER, }; typedef struct _swTimer_callback { int type; int interval; zval* callback; zend_fcall_info_cache *fci_cache; zval* data; zval _callback; zend_fcall_info_cache _fci_cache; zval _data; } swTimer_callback; static int php_swoole_del_timer(swTimer_node *tnode); void php_swoole_clear_all_timer() { if (!SwooleG.timer.map) { return; } uint64_t timer_id; //kill user process while (1) { swTimer_node *tnode = (swTimer_node *) swHashMap_each_int(SwooleG.timer.map, &timer_id); if (tnode == NULL) { break; } if (tnode->type != SW_TIMER_TYPE_PHP) { continue; } php_swoole_del_timer(tnode); swTimer_del(&SwooleG.timer, tnode); } } long php_swoole_add_timer(long ms, zval *callback, zval *param, int persistent) { if (ms <= 0) { swoole_php_fatal_error(E_WARNING, "Timer must be greater than 0"); return SW_ERR; } // no server || user worker || task process with async mode if (!SwooleG.serv || swIsUserWorker() || (swIsTaskWorker() && SwooleG.serv->task_enable_coroutine)) { php_swoole_check_reactor(); } swTimer_callback *cb = (swTimer_callback *) emalloc(sizeof(swTimer_callback)); char *func_name = NULL; if (!sw_zend_is_callable_ex(callback, NULL, 0, &func_name, NULL, &cb->_fci_cache, NULL)) { swoole_php_fatal_error(E_ERROR, "function '%s' is not callable", func_name); return SW_ERR; } efree(func_name); cb->_callback = *callback; cb->callback = &cb->_callback; cb->fci_cache = &cb->_fci_cache; if (param) { cb->_data = *param; cb->data = &cb->_data; } else { cb->data = NULL; } swTimerCallback timer_func; if (persistent) { cb->type = SW_TIMER_TICK; timer_func = php_swoole_onInterval; } else { cb->type = SW_TIMER_AFTER; timer_func = php_swoole_onTimeout; } Z_TRY_ADDREF_P(cb->callback); if (cb->data) { Z_TRY_ADDREF_P(cb->data); } swTimer_node *tnode = swTimer_add(&SwooleG.timer, ms, persistent, cb, timer_func); if (tnode == NULL) { swoole_php_fatal_error(E_WARNING, "add timer failed."); return SW_ERR; } else { tnode->type = SW_TIMER_TYPE_PHP; return tnode->id; } } static int php_swoole_del_timer(swTimer_node *tnode) { swTimer_callback *cb = (swTimer_callback *) tnode->data; if (!cb) { return SW_ERR; } if (cb->callback) { zval_ptr_dtor(cb->callback); } if (cb->data) { zval_ptr_dtor(cb->data); } efree(cb); return SW_OK; } void php_swoole_onTimeout(swTimer *timer, swTimer_node *tnode) { swTimer_callback *cb = (swTimer_callback *) tnode->data; zval args[1]; int argc = 0; if (cb->data) { argc = 1; args[0] = *cb->data; } if (SwooleG.enable_coroutine) { if (PHPCoroutine::create(cb->fci_cache, argc, args) < 0) { swoole_php_fatal_error(E_WARNING, "create onTimer coroutine error."); } } else { zval _retval, *retval = &_retval; if (sw_call_user_function_fast_ex(NULL, cb->fci_cache, retval, argc, args) == FAILURE) { swoole_php_fatal_error(E_WARNING, "onTimeout handler error."); } zval_ptr_dtor(retval); } php_swoole_del_timer(tnode); if (UNEXPECTED(EG(exception))) { zend_exception_error(EG(exception), E_ERROR); } } void php_swoole_onInterval(swTimer *timer, swTimer_node *tnode) { swTimer_callback *cb = (swTimer_callback *) tnode->data; zval args[2]; ZVAL_LONG(&args[0], tnode->id); int argc = 1; if (cb->data) { argc = 2; Z_TRY_ADDREF_P(cb->data); args[1] = *cb->data; } if (SwooleG.enable_coroutine) { if (PHPCoroutine::create(cb->fci_cache, argc, args) < 0) { swoole_php_fatal_error(E_WARNING, "create onInterval coroutine error."); return; } } else { zval _retval, *retval = &_retval; if (sw_call_user_function_fast_ex(NULL, cb->fci_cache, retval, argc, args) == FAILURE) { swoole_php_fatal_error(E_WARNING, "onInterval handler error."); } zval_ptr_dtor(retval); } if (tnode->remove) { php_swoole_del_timer(tnode); } if (UNEXPECTED(EG(exception))) { zend_exception_error(EG(exception), E_ERROR); } } PHP_FUNCTION(swoole_timer_tick) { zend_long after_ms; zval *callback; zval *param = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "lz|z", &after_ms, &callback, &param) == FAILURE) { RETURN_FALSE; } long timer_id = php_swoole_add_timer(after_ms, callback, param, 1); if (timer_id < 0) { RETURN_FALSE; } else { RETURN_LONG(timer_id); } } PHP_FUNCTION(swoole_timer_after) { long after_ms; zval *callback; zval *param = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "lz|z", &after_ms, &callback, &param) == FAILURE) { RETURN_FALSE; } long timer_id = php_swoole_add_timer(after_ms, callback, param, 0); if (timer_id < 0) { RETURN_FALSE; } else { RETURN_LONG(timer_id); } } PHP_FUNCTION(swoole_timer_clear) { if (!SwooleG.timer.initialized) { swoole_php_error(E_WARNING, "no timer"); RETURN_FALSE; } long id; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &id) == FAILURE) { RETURN_FALSE; } swTimer_node *tnode = swTimer_get(&SwooleG.timer, id); if (tnode == NULL) { swoole_php_error(E_WARNING, "timer#%ld is not found.", id); RETURN_FALSE; } if (tnode->remove) { RETURN_FALSE; } //current timer, cannot remove here. if (SwooleG.timer._current_id > 0 && tnode->id == SwooleG.timer._current_id) { tnode->remove = 1; RETURN_TRUE; } //remove timer if (php_swoole_del_timer(tnode) < 0) { RETURN_FALSE; } if (swTimer_del(&SwooleG.timer, tnode) == SW_FALSE) { RETURN_FALSE; } else { RETURN_TRUE; } } PHP_FUNCTION(swoole_timer_exists) { if (!SwooleG.timer.set) { swoole_php_error(E_WARNING, "no timer"); RETURN_FALSE; } long id; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &id) == FAILURE) { RETURN_FALSE; } swTimer_node *tnode = swTimer_get(&SwooleG.timer, id); if (tnode == NULL) { RETURN_FALSE; } if (tnode->remove) { RETURN_FALSE; } RETURN_TRUE; } <commit_msg>fixed #2342<commit_after>/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | Copyright (c) 2012-2015 The Swoole Group | +----------------------------------------------------------------------+ | 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 | | license@swoole.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tianfeng Han <mikan.tenny@gmail.com> | +----------------------------------------------------------------------+ */ #include "php_swoole.h" #ifdef SW_COROUTINE #include "swoole_coroutine.h" #endif using namespace swoole; enum swoole_timer_type { SW_TIMER_TICK, SW_TIMER_AFTER, }; typedef struct _swTimer_callback { int type; int interval; zval* callback; zend_fcall_info_cache *fci_cache; zval* data; zval _callback; zend_fcall_info_cache _fci_cache; zval _data; } swTimer_callback; static int php_swoole_del_timer(swTimer_node *tnode); void php_swoole_clear_all_timer() { if (!SwooleG.timer.map) { return; } uint64_t timer_id; //kill user process while (1) { swTimer_node *tnode = (swTimer_node *) swHashMap_each_int(SwooleG.timer.map, &timer_id); if (tnode == NULL) { break; } if (tnode->type != SW_TIMER_TYPE_PHP) { continue; } php_swoole_del_timer(tnode); swTimer_del(&SwooleG.timer, tnode); } } long php_swoole_add_timer(long ms, zval *callback, zval *param, int persistent) { if (ms <= 0) { swoole_php_fatal_error(E_WARNING, "Timer must be greater than 0"); return SW_ERR; } // no server || user worker || task process with async mode if (!SwooleG.serv || swIsUserWorker() || (swIsTaskWorker() && SwooleG.serv->task_enable_coroutine)) { php_swoole_check_reactor(); } swTimer_callback *cb = (swTimer_callback *) emalloc(sizeof(swTimer_callback)); char *func_name = NULL; if (!sw_zend_is_callable_ex(callback, NULL, 0, &func_name, NULL, &cb->_fci_cache, NULL)) { swoole_php_fatal_error(E_ERROR, "function '%s' is not callable", func_name); return SW_ERR; } efree(func_name); cb->_callback = *callback; cb->callback = &cb->_callback; cb->fci_cache = &cb->_fci_cache; if (param) { cb->_data = *param; cb->data = &cb->_data; } else { cb->data = NULL; } swTimerCallback timer_func; if (persistent) { cb->type = SW_TIMER_TICK; timer_func = php_swoole_onInterval; } else { cb->type = SW_TIMER_AFTER; timer_func = php_swoole_onTimeout; } Z_TRY_ADDREF_P(cb->callback); if (cb->data) { Z_TRY_ADDREF_P(cb->data); } swTimer_node *tnode = swTimer_add(&SwooleG.timer, ms, persistent, cb, timer_func); if (tnode == NULL) { swoole_php_fatal_error(E_WARNING, "add timer failed."); return SW_ERR; } else { tnode->type = SW_TIMER_TYPE_PHP; return tnode->id; } } static int php_swoole_del_timer(swTimer_node *tnode) { swTimer_callback *cb = (swTimer_callback *) tnode->data; if (!cb) { return SW_ERR; } if (cb->callback) { zval_ptr_dtor(cb->callback); } if (cb->data) { zval_ptr_dtor(cb->data); } efree(cb); return SW_OK; } void php_swoole_onTimeout(swTimer *timer, swTimer_node *tnode) { swTimer_callback *cb = (swTimer_callback *) tnode->data; zval args[1]; int argc = 0; if (cb->data) { argc = 1; args[0] = *cb->data; } if (SwooleG.enable_coroutine) { if (PHPCoroutine::create(cb->fci_cache, argc, args) < 0) { swoole_php_fatal_error(E_WARNING, "create onTimer coroutine error."); } } else { zval _retval, *retval = &_retval; if (sw_call_user_function_fast_ex(NULL, cb->fci_cache, retval, argc, args) == FAILURE) { swoole_php_fatal_error(E_WARNING, "onTimeout handler error."); } zval_ptr_dtor(retval); } php_swoole_del_timer(tnode); if (UNEXPECTED(EG(exception))) { zend_exception_error(EG(exception), E_ERROR); } } void php_swoole_onInterval(swTimer *timer, swTimer_node *tnode) { swTimer_callback *cb = (swTimer_callback *) tnode->data; zval args[2]; ZVAL_LONG(&args[0], tnode->id); int argc = 1; if (cb->data) { argc = 2; args[1] = *cb->data; } if (SwooleG.enable_coroutine) { if (PHPCoroutine::create(cb->fci_cache, argc, args) < 0) { swoole_php_fatal_error(E_WARNING, "create onInterval coroutine error."); return; } } else { zval _retval, *retval = &_retval; if (sw_call_user_function_fast_ex(NULL, cb->fci_cache, retval, argc, args) == FAILURE) { swoole_php_fatal_error(E_WARNING, "onInterval handler error."); } zval_ptr_dtor(retval); } if (tnode->remove) { php_swoole_del_timer(tnode); } if (UNEXPECTED(EG(exception))) { zend_exception_error(EG(exception), E_ERROR); } } PHP_FUNCTION(swoole_timer_tick) { zend_long after_ms; zval *callback; zval *param = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "lz|z", &after_ms, &callback, &param) == FAILURE) { RETURN_FALSE; } long timer_id = php_swoole_add_timer(after_ms, callback, param, 1); if (timer_id < 0) { RETURN_FALSE; } else { RETURN_LONG(timer_id); } } PHP_FUNCTION(swoole_timer_after) { long after_ms; zval *callback; zval *param = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "lz|z", &after_ms, &callback, &param) == FAILURE) { RETURN_FALSE; } long timer_id = php_swoole_add_timer(after_ms, callback, param, 0); if (timer_id < 0) { RETURN_FALSE; } else { RETURN_LONG(timer_id); } } PHP_FUNCTION(swoole_timer_clear) { if (!SwooleG.timer.initialized) { swoole_php_error(E_WARNING, "no timer"); RETURN_FALSE; } long id; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &id) == FAILURE) { RETURN_FALSE; } swTimer_node *tnode = swTimer_get(&SwooleG.timer, id); if (tnode == NULL) { swoole_php_error(E_WARNING, "timer#%ld is not found.", id); RETURN_FALSE; } if (tnode->remove) { RETURN_FALSE; } //current timer, cannot remove here. if (SwooleG.timer._current_id > 0 && tnode->id == SwooleG.timer._current_id) { tnode->remove = 1; RETURN_TRUE; } //remove timer if (php_swoole_del_timer(tnode) < 0) { RETURN_FALSE; } if (swTimer_del(&SwooleG.timer, tnode) == SW_FALSE) { RETURN_FALSE; } else { RETURN_TRUE; } } PHP_FUNCTION(swoole_timer_exists) { if (!SwooleG.timer.set) { swoole_php_error(E_WARNING, "no timer"); RETURN_FALSE; } long id; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &id) == FAILURE) { RETURN_FALSE; } swTimer_node *tnode = swTimer_get(&SwooleG.timer, id); if (tnode == NULL) { RETURN_FALSE; } if (tnode->remove) { RETURN_FALSE; } RETURN_TRUE; } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vvasielv@cern.ch> //------------------------------------------------------------------------------ #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclBase.h" #include "clang/AST/PrettyPrinter.h" using namespace clang; namespace cling { Transaction::~Transaction() { if (hasNestedTransactions()) for (size_t i = 0; i < m_NestedTransactions->size(); ++i) delete (*m_NestedTransactions)[i]; } void Transaction::append(DelayCallInfo DCI) { // for (const_iterator I = decls_begin(), E = decls_end(); I != E; ++I) { // if (DGR.isNull() || (*I).getAsOpaquePtr() == DGR.getAsOpaquePtr()) // return; // } // register the wrapper if any. if (getState() == kCommitting) { // We are committing and getting enw decls in. // Move them into a sub transaction that will be processed // recursively at the end of of commitTransaction. Transaction* subTransactionWhileCommitting = 0; if (hasNestedTransactions() && m_NestedTransactions->back()->getState() == kCollecting) subTransactionWhileCommitting = m_NestedTransactions->back(); else { // FIXME: is this correct (Axel says "yes") CompilationOptions Opts(getCompilationOpts()); Opts.DeclarationExtraction = 0; Opts.ValuePrinting = CompilationOptions::VPDisabled; Opts.ResultEvaluation = 0; Opts.DynamicScoping = 0; subTransactionWhileCommitting = new Transaction(Opts, getModule()); addNestedTransaction(subTransactionWhileCommitting); } subTransactionWhileCommitting->append(DCI); return; } assert(getState() == kCollecting || getState() == kCompleted); bool checkForWrapper = !m_WrapperFD; assert(checkForWrapper = true && "Check for wrappers with asserts"); if (checkForWrapper && DCI.m_DGR.isSingleDecl()) { if (FunctionDecl* FD = dyn_cast<FunctionDecl>(DCI.m_DGR.getSingleDecl())) if (utils::Analyze::IsWrapper(FD)) { assert(!m_WrapperFD && "Two wrappers in one transaction?"); m_WrapperFD = FD; } } if (!m_DeclQueue) m_DeclQueue.reset(new DeclQueue()); m_DeclQueue->push_back(DCI); } void Transaction::append(clang::DeclGroupRef DGR) { append(DelayCallInfo(DGR, kCCIHandleTopLevelDecl)); } void Transaction::append(Decl* D) { append(DeclGroupRef(D)); } void Transaction::dump() const { if (!size()) return; ASTContext& C = getFirstDecl().getSingleDecl()->getASTContext(); PrintingPolicy Policy = C.getPrintingPolicy(); Policy.DumpSourceManager = &C.getSourceManager(); print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true); } void Transaction::dumpPretty() const { if (!size()) return; ASTContext* C = 0; if (m_WrapperFD) C = &(m_WrapperFD->getASTContext()); if (!getFirstDecl().isNull()) C = &(getFirstDecl().getSingleDecl()->getASTContext()); PrintingPolicy Policy(C->getLangOpts()); print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true); } void Transaction::print(llvm::raw_ostream& Out, const PrintingPolicy& Policy, unsigned Indent, bool PrintInstantiation) const { int nestedT = 0; for (const_iterator I = decls_begin(), E = decls_end(); I != E; ++I) { if (I->m_DGR.isNull()) { assert(hasNestedTransactions() && "DGR is null even if no nesting?"); // print the nested decl Out<< "\n"; Out<<"+====================================================+\n"; Out<<" Nested Transaction" << nestedT << " \n"; Out<<"+====================================================+\n"; (*m_NestedTransactions)[nestedT++]->print(Out, Policy, Indent, PrintInstantiation); Out<< "\n"; Out<<"+====================================================+\n"; Out<<" End Transaction" << nestedT << " \n"; Out<<"+====================================================+\n"; } for (DeclGroupRef::const_iterator J = I->m_DGR.begin(), L = I->m_DGR.end(); J != L; ++J) if (*J) (*J)->print(Out, Policy, Indent, PrintInstantiation); else Out << "<<NULL DECL>>"; } } void Transaction::printStructure(size_t nindent) const { static const char* const stateNames[] = { "Collecting", "RolledBack", "RolledBackWithErrors", "Committing", "Committed" }; std::string indent(nindent, ' '); llvm::errs() << indent << "Transaction @" << this << ": \n"; for (const_nested_iterator I = nested_begin(), E = nested_end(); I != E; ++I) { (*I)->printStructure(nindent + 1); } llvm::errs() << indent << " state: " << stateNames[getState()] << ", " << size() << " decl groups, " << m_NestedTransactions->size() << " nested transactions\n" << indent << " wrapper: " << m_WrapperFD << ", parent: " << m_Parent << ", next: " << m_Next << "\n"; } } // end namespace cling <commit_msg>Remove unused code. Move the relevant comments at the right place.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <vvasielv@cern.ch> //------------------------------------------------------------------------------ #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclBase.h" #include "clang/AST/PrettyPrinter.h" using namespace clang; namespace cling { Transaction::~Transaction() { if (hasNestedTransactions()) for (size_t i = 0; i < m_NestedTransactions->size(); ++i) delete (*m_NestedTransactions)[i]; } void Transaction::append(DelayCallInfo DCI) { if (getState() == kCommitting) { // We are committing and getting enw decls in. // Move them into a sub transaction that will be processed // recursively at the end of of commitTransaction. Transaction* subTransactionWhileCommitting = 0; if (hasNestedTransactions() && m_NestedTransactions->back()->getState() == kCollecting) subTransactionWhileCommitting = m_NestedTransactions->back(); else { // FIXME: is this correct (Axel says "yes") CompilationOptions Opts(getCompilationOpts()); Opts.DeclarationExtraction = 0; Opts.ValuePrinting = CompilationOptions::VPDisabled; Opts.ResultEvaluation = 0; Opts.DynamicScoping = 0; subTransactionWhileCommitting = new Transaction(Opts, getModule()); addNestedTransaction(subTransactionWhileCommitting); } subTransactionWhileCommitting->append(DCI); return; } assert(getState() == kCollecting || getState() == kCompleted); bool checkForWrapper = !m_WrapperFD; assert(checkForWrapper = true && "Check for wrappers with asserts"); // register the wrapper if any. if (checkForWrapper && DCI.m_DGR.isSingleDecl()) { if (FunctionDecl* FD = dyn_cast<FunctionDecl>(DCI.m_DGR.getSingleDecl())) if (utils::Analyze::IsWrapper(FD)) { assert(!m_WrapperFD && "Two wrappers in one transaction?"); m_WrapperFD = FD; } } // Lazy create the container on first append. if (!m_DeclQueue) m_DeclQueue.reset(new DeclQueue()); m_DeclQueue->push_back(DCI); } void Transaction::append(clang::DeclGroupRef DGR) { append(DelayCallInfo(DGR, kCCIHandleTopLevelDecl)); } void Transaction::append(Decl* D) { append(DeclGroupRef(D)); } void Transaction::dump() const { if (!size()) return; ASTContext& C = getFirstDecl().getSingleDecl()->getASTContext(); PrintingPolicy Policy = C.getPrintingPolicy(); Policy.DumpSourceManager = &C.getSourceManager(); print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true); } void Transaction::dumpPretty() const { if (!size()) return; ASTContext* C = 0; if (m_WrapperFD) C = &(m_WrapperFD->getASTContext()); if (!getFirstDecl().isNull()) C = &(getFirstDecl().getSingleDecl()->getASTContext()); PrintingPolicy Policy(C->getLangOpts()); print(llvm::errs(), Policy, /*Indent*/0, /*PrintInstantiation*/true); } void Transaction::print(llvm::raw_ostream& Out, const PrintingPolicy& Policy, unsigned Indent, bool PrintInstantiation) const { int nestedT = 0; for (const_iterator I = decls_begin(), E = decls_end(); I != E; ++I) { if (I->m_DGR.isNull()) { assert(hasNestedTransactions() && "DGR is null even if no nesting?"); // print the nested decl Out<< "\n"; Out<<"+====================================================+\n"; Out<<" Nested Transaction" << nestedT << " \n"; Out<<"+====================================================+\n"; (*m_NestedTransactions)[nestedT++]->print(Out, Policy, Indent, PrintInstantiation); Out<< "\n"; Out<<"+====================================================+\n"; Out<<" End Transaction" << nestedT << " \n"; Out<<"+====================================================+\n"; } for (DeclGroupRef::const_iterator J = I->m_DGR.begin(), L = I->m_DGR.end(); J != L; ++J) if (*J) (*J)->print(Out, Policy, Indent, PrintInstantiation); else Out << "<<NULL DECL>>"; } } void Transaction::printStructure(size_t nindent) const { static const char* const stateNames[] = { "Collecting", "RolledBack", "RolledBackWithErrors", "Committing", "Committed" }; std::string indent(nindent, ' '); llvm::errs() << indent << "Transaction @" << this << ": \n"; for (const_nested_iterator I = nested_begin(), E = nested_end(); I != E; ++I) { (*I)->printStructure(nindent + 1); } llvm::errs() << indent << " state: " << stateNames[getState()] << ", " << size() << " decl groups, " << m_NestedTransactions->size() << " nested transactions\n" << indent << " wrapper: " << m_WrapperFD << ", parent: " << m_Parent << ", next: " << m_Next << "\n"; } } // end namespace cling <|endoftext|>
<commit_before>#include "gc/gc.hpp" #include "builtin/tuple.hpp" #include "vm.hpp" #include "vm/object_utils.hpp" #include "objectmemory.hpp" #include "builtin/fixnum.hpp" #include "builtin/compactlookuptable.hpp" #include <stdarg.h> #include <iostream> #include <stdint.h> namespace rubinius { Tuple* Tuple::bounds_exceeded_error(STATE, const char* method, int index) { std::ostringstream msg; msg << method; msg << ": index " << index << " out of bounds for size " << num_fields(); Exception::object_bounds_exceeded_error(state, msg.str().c_str()); return 0; } /* The Tuple#at primitive. */ Object* Tuple::at_prim(STATE, Fixnum* index_obj) { native_int index = index_obj->to_native(); if(index < 0 || num_fields() <= index) { return bounds_exceeded_error(state, "Tuple::at_prim", index); } return field[index]; } Object* Tuple::put(STATE, native_int idx, Object* val) { assert(idx >= 0 && idx < num_fields()); this->field[idx] = val; if(val->reference_p()) write_barrier(state, val); return val; } /* The Tuple#put primitive. */ Object* Tuple::put_prim(STATE, Fixnum* index, Object* val) { native_int idx = index->to_native(); if(idx < 0 || num_fields() <= idx) { return bounds_exceeded_error(state, "Tuple::put_prim", idx); } this->field[idx] = val; if(val->reference_p()) write_barrier(state, val); return val; } /* The Tuple#fields primitive. */ Object* Tuple::fields_prim(STATE) { return Integer::from(state, num_fields()); } Tuple* Tuple::create(STATE, native_int fields) { assert(fields >= 0 && fields < INT32_MAX); // Fast path using GC optimized tuple creation Tuple* tup = state->vm()->new_young_tuple_dirty(fields); if(likely(tup)) { for(native_int i = 0; i < fields; i++) { tup->field[i] = cNil; } return tup; } // Slow path. size_t bytes; tup = state->vm()->new_object_variable<Tuple>(G(tuple), fields, bytes); if(unlikely(!tup)) { Exception::memory_error(state); } tup->full_size_ = bytes; return tup; } Tuple* Tuple::allocate(STATE, Fixnum* fields) { native_int size = fields->to_native(); if(size < 0) { Exception::argument_error(state, "negative tuple size"); } else if(size > INT32_MAX) { Exception::argument_error(state, "too large tuple size"); } return create(state, fields->to_native()); } Tuple* Tuple::from(STATE, native_int fields, ...) { assert(fields >= 0); va_list ar; Tuple* tup = create(state, fields); va_start(ar, fields); for(native_int i = 0; i < fields; i++) { Object *obj = va_arg(ar, Object*); // fields equals size so bounds checking is unecessary tup->field[i] = obj; if(obj->reference_p()) tup->write_barrier(state, obj); } va_end(ar); return tup; } Tuple* Tuple::copy_from(STATE, Tuple* other, Fixnum* start, Fixnum *length, Fixnum* dest) { native_int osize = other->num_fields(); native_int size = this->num_fields(); int src_start = start->to_native(); int dst_start = dest->to_native(); int len = length->to_native(); // left end should be within range if(src_start < 0 || src_start > osize) { return other->bounds_exceeded_error(state, "Tuple::copy_from", src_start); } if(dst_start < 0 || dst_start > size) { return bounds_exceeded_error(state, "Tuple::copy_from", dst_start); } // length can not be negative and must fit in src/dest if(len < 0) { return other->bounds_exceeded_error(state, "Tuple::copy_from", len); } if((src_start + len) > osize) { return other->bounds_exceeded_error(state, "Tuple::copy_from", src_start + len); } if(len > (size - dst_start)) { return bounds_exceeded_error(state, "Tuple::copy_from", len); } // A memmove within the tuple if(other == this) { // No movement, no work! if(src_start == dst_start) return this; // right shift if(src_start < dst_start) { for(native_int dest_idx = dst_start + len - 1, src_idx = src_start + len - 1; src_idx >= src_start; src_idx--, dest_idx--) { this->field[dest_idx] = this->field[src_idx]; } } else { // left shift for(native_int dest_idx = dst_start, src_idx = src_start; src_idx < src_start + len; src_idx++, dest_idx++) { this->field[dest_idx] = this->field[src_idx]; } } } else { for(native_int src = src_start, dst = dst_start; src < (src_start + len); ++src, ++dst) { // Since we have carefully checked the bounds we don't need // to do it in at/put Object *obj = other->field[src]; this->field[dst] = obj; // but this is necessary to keep the GC happy if(obj->reference_p()) write_barrier(state, obj); } } return this; } Fixnum* Tuple::delete_inplace(STATE, Fixnum *start, Fixnum *length, Object *obj) { int size = this->num_fields(); int len = length->to_native(); int lend = start->to_native(); int rend = lend + len; if(size == 0 || len == 0) return Fixnum::from(0); if(lend < 0 || lend >= size) { return force_as<Fixnum>(bounds_exceeded_error(state, "Tuple::delete_inplace", lend)); } if(rend < 0 || rend > size) { return force_as<Fixnum>(bounds_exceeded_error(state, "Tuple::delete_inplace", rend)); } int i = lend; while(i < rend) { if(this->at(state,i) == obj) { int j = i; ++i; while(i < rend) { Object *val = this->field[i]; if(val != obj) { // no need to set write_barrier since it's already // referenced to this object this->field[j] = val; ++j; } ++i; } // cleanup all the bins after i = j; while(i < rend) { this->field[i] = cNil; ++i; } return Fixnum::from(rend-j); } ++i; } return Fixnum::from(0); } /** @todo Add some error checking/handling and * evaluate corner cases, and add tests... --rue */ Tuple* Tuple::lshift_inplace(STATE, Fixnum* shift) { native_int size = this->num_fields(); const int start = shift->to_native(); assert(start >= 0); if(start > 0) { native_int i = 0; native_int j = start; while(j < size) { this->field[i++] = this->field[j++]; } while(i < size) { this->field[i++] = cNil; } } return this; } Object* Tuple::reverse(STATE, Fixnum* o_start, Fixnum* o_total) { native_int start = o_start->to_native(); native_int total = o_total->to_native(); if(total <= 0 || start < 0 || start >= num_fields()) return this; native_int end = start + total - 1; if(end >= num_fields()) end = num_fields() - 1; Object** pos1 = field + start; Object** pos2 = field + end; register Object* tmp; while(pos1 < pos2) { tmp = *pos1; *pos1++ = *pos2; *pos2-- = tmp; } return this; } // @todo performance primitive; could be replaced with Ruby Tuple* Tuple::pattern(STATE, Fixnum* size, Object* val) { native_int cnt = size->to_native(); if(cnt < 0) { Exception::argument_error(state, "negative tuple size"); } else if (cnt > INT32_MAX) { Exception::argument_error(state, "too large tuple size"); } Tuple* tuple = Tuple::create(state, cnt); // val is referend size times, we only need to hit the write // barrier once if(val->reference_p()) tuple->write_barrier(state, val); for(native_int i = 0; i < cnt; i++) { // bounds checking is covered because we instantiated the tuple // in this method tuple->field[i] = val; } return tuple; } Tuple* Tuple::tuple_dup(STATE) { native_int fields = num_fields(); Tuple* tup = state->vm()->new_young_tuple_dirty(fields); if(likely(tup)) { for(native_int i = 0; i < fields; i++) { Object *obj = field[i]; // fields equals size so bounds checking is unecessary tup->field[i] = obj; // Because tup is promised to be a young object, // we can elide the write barrier usage. } return tup; } // Otherwise, use slower creation path that might create // a mature object. tup = create(state, fields); for(native_int i = 0; i < fields; i++) { Object *obj = field[i]; // fields equals size so bounds checking is unecessary tup->field[i] = obj; if(obj->reference_p()) tup->write_barrier(state, obj); } return tup; } size_t Tuple::Info::object_size(const ObjectHeader* obj) { return force_as<Tuple>(obj)->full_size_; } void Tuple::Info::mark(Object* obj, ObjectMark& mark) { Object* tmp; Tuple* tup = as<Tuple>(obj); for(native_int i = 0; i < tup->num_fields(); i++) { tmp = mark.call(tup->field[i]); if(tmp) mark.set(obj, &tup->field[i], tmp); } } void Tuple::Info::show(STATE, Object* self, int level) { Tuple* tup = as<Tuple>(self); native_int size = tup->num_fields(); native_int stop = size < 6 ? size : 6; if(size == 0) { class_info(state, self, true); return; } class_info(state, self); std::cout << ": " << size << std::endl; ++level; for(native_int i = 0; i < stop; i++) { indent(level); Object* obj = tup->at(state, i); if(obj == tup) { class_info(state, self, true); } else { obj->show(state, level); } } if(tup->num_fields() > stop) ellipsis(level); close_body(level); } void Tuple::Info::show_simple(STATE, Object* self, int level) { Tuple* tup = as<Tuple>(self); native_int size = tup->num_fields(); native_int stop = size < 6 ? size : 6; if(size == 0) { class_info(state, self, true); return; } class_info(state, self); std::cout << ": " << size << std::endl; ++level; for(native_int i = 0; i < stop; i++) { indent(level); Object* obj = tup->at(state, i); if(Tuple* t = try_as<Tuple>(obj)) { class_info(state, self); std::cout << ": " << t->num_fields() << ">" << std::endl; } else { obj->show_simple(state, level); } } if(tup->num_fields() > stop) ellipsis(level); close_body(level); } } <commit_msg>Use rubinius::bug instead of assertions<commit_after>#include "gc/gc.hpp" #include "builtin/tuple.hpp" #include "vm.hpp" #include "vm/object_utils.hpp" #include "objectmemory.hpp" #include "builtin/fixnum.hpp" #include "builtin/compactlookuptable.hpp" #include <stdarg.h> #include <iostream> #include <stdint.h> namespace rubinius { Tuple* Tuple::bounds_exceeded_error(STATE, const char* method, int index) { std::ostringstream msg; msg << method; msg << ": index " << index << " out of bounds for size " << num_fields(); Exception::object_bounds_exceeded_error(state, msg.str().c_str()); return 0; } /* The Tuple#at primitive. */ Object* Tuple::at_prim(STATE, Fixnum* index_obj) { native_int index = index_obj->to_native(); if(index < 0 || num_fields() <= index) { return bounds_exceeded_error(state, "Tuple::at_prim", index); } return field[index]; } Object* Tuple::put(STATE, native_int idx, Object* val) { if(idx < 0 || idx >= num_fields()) { rubinius::bug("Invalid tuple index"); } this->field[idx] = val; if(val->reference_p()) write_barrier(state, val); return val; } /* The Tuple#put primitive. */ Object* Tuple::put_prim(STATE, Fixnum* index, Object* val) { native_int idx = index->to_native(); if(idx < 0 || num_fields() <= idx) { return bounds_exceeded_error(state, "Tuple::put_prim", idx); } this->field[idx] = val; if(val->reference_p()) write_barrier(state, val); return val; } /* The Tuple#fields primitive. */ Object* Tuple::fields_prim(STATE) { return Integer::from(state, num_fields()); } Tuple* Tuple::create(STATE, native_int fields) { if(fields < 0 || fields >= INT32_MAX) { rubinius::bug("Invalid tuple size"); } // Fast path using GC optimized tuple creation Tuple* tup = state->vm()->new_young_tuple_dirty(fields); if(likely(tup)) { for(native_int i = 0; i < fields; i++) { tup->field[i] = cNil; } return tup; } // Slow path. size_t bytes; tup = state->vm()->new_object_variable<Tuple>(G(tuple), fields, bytes); if(unlikely(!tup)) { Exception::memory_error(state); } tup->full_size_ = bytes; return tup; } Tuple* Tuple::allocate(STATE, Fixnum* fields) { native_int size = fields->to_native(); if(size < 0) { Exception::argument_error(state, "negative tuple size"); } else if(size > INT32_MAX) { Exception::argument_error(state, "too large tuple size"); } return create(state, fields->to_native()); } Tuple* Tuple::from(STATE, native_int fields, ...) { if(fields < 0 || fields >= INT32_MAX) { rubinius::bug("Invalid tuple size"); } va_list ar; Tuple* tup = create(state, fields); va_start(ar, fields); for(native_int i = 0; i < fields; i++) { Object *obj = va_arg(ar, Object*); // fields equals size so bounds checking is unecessary tup->field[i] = obj; if(obj->reference_p()) tup->write_barrier(state, obj); } va_end(ar); return tup; } Tuple* Tuple::copy_from(STATE, Tuple* other, Fixnum* start, Fixnum *length, Fixnum* dest) { native_int osize = other->num_fields(); native_int size = this->num_fields(); int src_start = start->to_native(); int dst_start = dest->to_native(); int len = length->to_native(); // left end should be within range if(src_start < 0 || src_start > osize) { return other->bounds_exceeded_error(state, "Tuple::copy_from", src_start); } if(dst_start < 0 || dst_start > size) { return bounds_exceeded_error(state, "Tuple::copy_from", dst_start); } // length can not be negative and must fit in src/dest if(len < 0) { return other->bounds_exceeded_error(state, "Tuple::copy_from", len); } if((src_start + len) > osize) { return other->bounds_exceeded_error(state, "Tuple::copy_from", src_start + len); } if(len > (size - dst_start)) { return bounds_exceeded_error(state, "Tuple::copy_from", len); } // A memmove within the tuple if(other == this) { // No movement, no work! if(src_start == dst_start) return this; // right shift if(src_start < dst_start) { for(native_int dest_idx = dst_start + len - 1, src_idx = src_start + len - 1; src_idx >= src_start; src_idx--, dest_idx--) { this->field[dest_idx] = this->field[src_idx]; } } else { // left shift for(native_int dest_idx = dst_start, src_idx = src_start; src_idx < src_start + len; src_idx++, dest_idx++) { this->field[dest_idx] = this->field[src_idx]; } } } else { for(native_int src = src_start, dst = dst_start; src < (src_start + len); ++src, ++dst) { // Since we have carefully checked the bounds we don't need // to do it in at/put Object *obj = other->field[src]; this->field[dst] = obj; // but this is necessary to keep the GC happy if(obj->reference_p()) write_barrier(state, obj); } } return this; } Fixnum* Tuple::delete_inplace(STATE, Fixnum *start, Fixnum *length, Object *obj) { int size = this->num_fields(); int len = length->to_native(); int lend = start->to_native(); int rend = lend + len; if(size == 0 || len == 0) return Fixnum::from(0); if(lend < 0 || lend >= size) { return force_as<Fixnum>(bounds_exceeded_error(state, "Tuple::delete_inplace", lend)); } if(rend < 0 || rend > size) { return force_as<Fixnum>(bounds_exceeded_error(state, "Tuple::delete_inplace", rend)); } int i = lend; while(i < rend) { if(this->at(state,i) == obj) { int j = i; ++i; while(i < rend) { Object *val = this->field[i]; if(val != obj) { // no need to set write_barrier since it's already // referenced to this object this->field[j] = val; ++j; } ++i; } // cleanup all the bins after i = j; while(i < rend) { this->field[i] = cNil; ++i; } return Fixnum::from(rend-j); } ++i; } return Fixnum::from(0); } /** @todo Add some error checking/handling and * evaluate corner cases, and add tests... --rue */ Tuple* Tuple::lshift_inplace(STATE, Fixnum* shift) { native_int size = this->num_fields(); const int start = shift->to_native(); assert(start >= 0); if(start > 0) { native_int i = 0; native_int j = start; while(j < size) { this->field[i++] = this->field[j++]; } while(i < size) { this->field[i++] = cNil; } } return this; } Object* Tuple::reverse(STATE, Fixnum* o_start, Fixnum* o_total) { native_int start = o_start->to_native(); native_int total = o_total->to_native(); if(total <= 0 || start < 0 || start >= num_fields()) return this; native_int end = start + total - 1; if(end >= num_fields()) end = num_fields() - 1; Object** pos1 = field + start; Object** pos2 = field + end; register Object* tmp; while(pos1 < pos2) { tmp = *pos1; *pos1++ = *pos2; *pos2-- = tmp; } return this; } // @todo performance primitive; could be replaced with Ruby Tuple* Tuple::pattern(STATE, Fixnum* size, Object* val) { native_int cnt = size->to_native(); if(cnt < 0) { Exception::argument_error(state, "negative tuple size"); } else if (cnt > INT32_MAX) { Exception::argument_error(state, "too large tuple size"); } Tuple* tuple = Tuple::create(state, cnt); // val is referend size times, we only need to hit the write // barrier once if(val->reference_p()) tuple->write_barrier(state, val); for(native_int i = 0; i < cnt; i++) { // bounds checking is covered because we instantiated the tuple // in this method tuple->field[i] = val; } return tuple; } Tuple* Tuple::tuple_dup(STATE) { native_int fields = num_fields(); Tuple* tup = state->vm()->new_young_tuple_dirty(fields); if(likely(tup)) { for(native_int i = 0; i < fields; i++) { Object *obj = field[i]; // fields equals size so bounds checking is unecessary tup->field[i] = obj; // Because tup is promised to be a young object, // we can elide the write barrier usage. } return tup; } // Otherwise, use slower creation path that might create // a mature object. tup = create(state, fields); for(native_int i = 0; i < fields; i++) { Object *obj = field[i]; // fields equals size so bounds checking is unecessary tup->field[i] = obj; if(obj->reference_p()) tup->write_barrier(state, obj); } return tup; } size_t Tuple::Info::object_size(const ObjectHeader* obj) { return force_as<Tuple>(obj)->full_size_; } void Tuple::Info::mark(Object* obj, ObjectMark& mark) { Object* tmp; Tuple* tup = as<Tuple>(obj); for(native_int i = 0; i < tup->num_fields(); i++) { tmp = mark.call(tup->field[i]); if(tmp) mark.set(obj, &tup->field[i], tmp); } } void Tuple::Info::show(STATE, Object* self, int level) { Tuple* tup = as<Tuple>(self); native_int size = tup->num_fields(); native_int stop = size < 6 ? size : 6; if(size == 0) { class_info(state, self, true); return; } class_info(state, self); std::cout << ": " << size << std::endl; ++level; for(native_int i = 0; i < stop; i++) { indent(level); Object* obj = tup->at(state, i); if(obj == tup) { class_info(state, self, true); } else { obj->show(state, level); } } if(tup->num_fields() > stop) ellipsis(level); close_body(level); } void Tuple::Info::show_simple(STATE, Object* self, int level) { Tuple* tup = as<Tuple>(self); native_int size = tup->num_fields(); native_int stop = size < 6 ? size : 6; if(size == 0) { class_info(state, self, true); return; } class_info(state, self); std::cout << ": " << size << std::endl; ++level; for(native_int i = 0; i < stop; i++) { indent(level); Object* obj = tup->at(state, i); if(Tuple* t = try_as<Tuple>(obj)) { class_info(state, self); std::cout << ": " << t->num_fields() << ">" << std::endl; } else { obj->show_simple(state, level); } } if(tup->num_fields() > stop) ellipsis(level); close_body(level); } } <|endoftext|>
<commit_before>/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "lpc_nuvoton.hpp" #include "lpc_interface.hpp" #include <cstdint> #include <memory> #include <utility> namespace blobs { std::unique_ptr<LpcMapperInterface> LpcMapperNuvoton::createNuvotonMapper() { /* NOTE: Considered making one factory for both types. */ return std::make_unique<LpcMapperNuvoton>(); } std::pair<std::uint32_t, std::uint32_t> LpcMapperNuvoton::mapWindow(std::uint32_t address, std::uint32_t length) { return std::make_pair(0, 0); } } // namespace blobs <commit_msg>lpc_nuvoton: add mapping implementation<commit_after>/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "lpc_nuvoton.hpp" #include "lpc_interface.hpp" #include <fcntl.h> #include <sys/mman.h> #include <unistd.h> #include <cinttypes> #include <cstdint> #include <cstdio> #include <memory> #include <utility> namespace blobs { using std::uint16_t; using std::uint32_t; using std::uint8_t; std::unique_ptr<LpcMapperInterface> LpcMapperNuvoton::createNuvotonMapper() { /* NOTE: Considered making one factory for both types. */ return std::make_unique<LpcMapperNuvoton>(); } /* * The host buffer address is configured by host through * SuperIO. On BMC side the max memory can be mapped is 4kB with the caveat that * first byte of the buffer is reserved as host/BMC semaphore and not usable as * shared memory. * * Mapper returns success for (addr, len) where (addr & 0x7) == 4 and len <= * (4096 - 4). Otherwise, mapper returns either * - WindowOffset = 4 and WindowSize = len - 4 if (addr & 0x7) == 0 * - WindowSize = 0 means that the region cannot be mapped otherwise */ std::pair<std::uint32_t, std::uint32_t> LpcMapperNuvoton::mapWindow(std::uint32_t address, std::uint32_t length) { /* We reserve the first 4 bytes from the mapped region; the first byte * is shared semaphore, and the number of 4 is for alignment. */ const uint32_t bmcMapReserveBytes = 4; const uint32_t bmcMapMaxSizeBytes = 4 * 1024 - bmcMapReserveBytes; if (length <= bmcMapReserveBytes) { std::fprintf(stderr, "window size %" PRIx32 " too small to map.\n", length); return std::make_pair(0, 0); } if (length > bmcMapMaxSizeBytes) { std::fprintf(stderr, "window size %" PRIx32 " not supported. Max size 4k.\n", length); length = bmcMapMaxSizeBytes; } /* If host requested region starts at an aligned address, return offset of 4 * bytes so as to skip the semaphore register. */ uint32_t windowOffset = bmcMapReserveBytes; uint32_t windowSize = length; const uint32_t addressOffset = address & 0x7; if (addressOffset == 0) { std::fprintf(stderr, "Map address offset should be 4 for Nuvoton.\n"); return std::make_pair(0, 0); } else if (addressOffset != bmcMapReserveBytes) { std::fprintf(stderr, "Map address offset should be 4 for Nuvoton.\n"); return std::make_pair(0, 0); } /* TODO: need a kernel driver to handle mapping configuration. * Until then program the register through /dev/mem. */ int fd; if ((fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1) { std::fprintf(stderr, "Failed to open /dev/mem\n"); close(fd); return std::make_pair(0, 0); } const uint32_t bmcMapConfigBaseAddr = 0xc0001000; const uint32_t bmcMapConfigWindowSizeOffset = 0x7; const uint32_t bmcMapConfigWindowBaseOffset = 0xa; const uint8_t bmcWindowSizeValue = 0xc; // 4k const uint16_t bmcWindowBaseValue = 0x8000; // BMC phyAddr from 0xc0008000 auto mapBasePtr = reinterpret_cast<uint8_t*>( mmap(nullptr, getpagesize(), PROT_READ | PROT_WRITE, MAP_SHARED, fd, bmcMapConfigBaseAddr)); uint8_t* bmcWindowSize = mapBasePtr + bmcMapConfigWindowSizeOffset; uint16_t* bmcWindowBase = reinterpret_cast<uint16_t*>(mapBasePtr + bmcMapConfigWindowBaseOffset); *bmcWindowSize = bmcWindowSizeValue; *bmcWindowBase = bmcWindowBaseValue; munmap(mapBasePtr, getpagesize()); close(fd); return std::make_pair(windowOffset, windowSize); } } // namespace blobs <|endoftext|>
<commit_before>/// (c) Koheron #include "pubsub.hpp" #include "kserver_session.hpp" namespace kserver { template<uint32_t channel, uint32_t event, typename... Tp> void PubSub::emit(Tp&&... args) { static_assert(channel < channels_count, "Invalid channel"); for (auto const& sid : subscribers.get(channel)) session_manager.get_session(sid).send( std::make_tuple(0U, // RESERVED channel, event, args...) ); } template<uint32_t channel, uint32_t event> void PubSub::emit_cstr(const char *str) { static_assert(channel < channels_count, "Invalid channel"); auto string = std::string(str); uint32_t len = string.size() + 1; // Including '\0' auto array = serialize(std::make_tuple(0U, channel, event, len)); std::vector<char> data(array.begin(), array.end()); std::copy(string.begin(), string.end(), std::back_inserter(data)); data.push_back('\0'); for (auto const& sid : subscribers.get(channel)) session_manager.get_session(sid).send(data); } } // namespace kserver <commit_msg>Fix pubsub (#147)<commit_after>/// (c) Koheron #include "pubsub.hpp" #include "kserver_session.hpp" namespace kserver { template<uint32_t channel, uint32_t event, typename... Tp> void PubSub::emit(Tp&&... args) { static_assert(channel < channels_count, "Invalid channel"); for (auto const& sid : subscribers.get(channel)) session_manager.get_session(sid).send( std::make_tuple(0U, // RESERVED channel, event, args...) ); } template<uint32_t channel, uint32_t event> void PubSub::emit_cstr(const char *str) { static_assert(channel < channels_count, "Invalid channel"); auto string = std::string(str); uint32_t len = string.size() + 1; // Including '\0' auto array = serialize(std::make_tuple(0U, channel, event, len)); std::vector<char> data(array.begin(), array.end()); std::copy(string.begin(), string.end(), std::back_inserter(data)); data.push_back('\0'); for (auto const& sid : subscribers.get(channel)) session_manager.get_session(sid).send_array(data.data(), data.size()); } } // namespace kserver <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: pageproperties.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2004-11-26 15:07:54 $ * * 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 _SDR_PROPERTIES_PAGEPROPERTIES_HXX #define _SDR_PROPERTIES_PAGEPROPERTIES_HXX #ifndef _SDR_PROPERTIES_EMPTYPROPERTIES_HXX #include <svx/sdr/properties/emptyproperties.hxx> #endif ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace properties { class PageProperties : public EmptyProperties { protected: // create a new object specific itemset with object specific ranges. virtual SfxItemSet& CreateObjectSpecificItemSet(SfxItemPool& pPool); // Do the ItemChange, may do special handling virtual void ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem = 0); public: // basic constructor PageProperties(SdrObject& rObj); // constructor for copying, but using new object PageProperties(const PageProperties& rProps, SdrObject& rObj); // destructor virtual ~PageProperties(); // Clone() operator, normally just calls the local copy constructor virtual BaseProperties& Clone(SdrObject& rObj) const; // get itemset. Overloaded here to allow creating the empty itemset // without asserting virtual const SfxItemSet& GetObjectItemSet() const; // get the installed StyleSheet virtual SfxStyleSheet* GetStyleSheet() const; // clear single item virtual void ClearObjectItem(const sal_uInt16 nWhich = 0); }; } // end of namespace properties } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// #endif //_SDR_PROPERTIES_PAGEPROPERTIES_HXX // eof <commit_msg>INTEGRATION: CWS ooo19126 (1.3.550); FILE MERGED 2005/09/05 14:18:34 rt 1.3.550.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pageproperties.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 20:08:45 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SDR_PROPERTIES_PAGEPROPERTIES_HXX #define _SDR_PROPERTIES_PAGEPROPERTIES_HXX #ifndef _SDR_PROPERTIES_EMPTYPROPERTIES_HXX #include <svx/sdr/properties/emptyproperties.hxx> #endif ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace properties { class PageProperties : public EmptyProperties { protected: // create a new object specific itemset with object specific ranges. virtual SfxItemSet& CreateObjectSpecificItemSet(SfxItemPool& pPool); // Do the ItemChange, may do special handling virtual void ItemChange(const sal_uInt16 nWhich, const SfxPoolItem* pNewItem = 0); public: // basic constructor PageProperties(SdrObject& rObj); // constructor for copying, but using new object PageProperties(const PageProperties& rProps, SdrObject& rObj); // destructor virtual ~PageProperties(); // Clone() operator, normally just calls the local copy constructor virtual BaseProperties& Clone(SdrObject& rObj) const; // get itemset. Overloaded here to allow creating the empty itemset // without asserting virtual const SfxItemSet& GetObjectItemSet() const; // get the installed StyleSheet virtual SfxStyleSheet* GetStyleSheet() const; // clear single item virtual void ClearObjectItem(const sal_uInt16 nWhich = 0); }; } // end of namespace properties } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// #endif //_SDR_PROPERTIES_PAGEPROPERTIES_HXX // eof <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Manasij Mukherjee <manasij7479@gmail.com> // author: Vassil Vassilev <vvasilev@cern.ch> // // 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 "AutoloadingTransform.h" #include "cling/Interpreter/Transaction.h" #include "clang/AST/DeclVisitor.h" using namespace clang; namespace cling { class DeclFixer : public DeclVisitor<DeclFixer> { public: void VisitEnumDecl(EnumDecl* ED) { 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); } } }; void AutoloadingTransform::Transform() { const Transaction* T = getTransaction(); DeclFixer visitor; 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) { if (!(*J)->hasAttr<AnnotateAttr>()) continue; visitor.Visit(*J); //FIXME: Enable when safe ! // if ( (*J)->hasAttr<AnnotateAttr>() /*FIXME: && CorrectCallbackLoaded() how ? */ ) // clang::Decl::castToDeclContext(*J)->setHasExternalLexicalStorage(); } } } } // end namespace cling <commit_msg>Decend into DeclContexts in general.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Manasij Mukherjee <manasij7479@gmail.com> // author: Vassil Vassilev <vvasilev@cern.ch> // // 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 "AutoloadingTransform.h" #include "cling/Interpreter/Transaction.h" #include "clang/AST/DeclVisitor.h" using namespace clang; namespace cling { class DeclFixer : public DeclVisitor<DeclFixer> { public: void VisitDecl(Decl* D) { if (DeclContext* DC = dyn_cast<DeclContext>(D)) for (auto Child : DC->decls()) Visit(Child); } void VisitEnumDecl(EnumDecl* ED) { 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); } } }; void AutoloadingTransform::Transform() { const Transaction* T = getTransaction(); DeclFixer visitor; 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) { if (!(*J)->hasAttr<AnnotateAttr>()) continue; visitor.Visit(*J); //FIXME: Enable when safe ! // if ( (*J)->hasAttr<AnnotateAttr>() /*FIXME: && CorrectCallbackLoaded() how ? */ ) // clang::Decl::castToDeclContext(*J)->setHasExternalLexicalStorage(); } } } } // end namespace cling <|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 <svx/ShapeTypeHandler.hxx> #include <svx/SvxShapeTypes.hxx> #include <svx/AccessibleShapeInfo.hxx> #include <com/sun/star/drawing/XShapeDescriptor.hpp> #include <osl/mutex.hxx> #include <vcl/svapp.hxx> #include <svx/dialmgr.hxx> #include <svx/unoshape.hxx> #include <svx/svdoashp.hxx> #include "svx/unoapi.hxx" #include "svx/svdstr.hrc" using namespace ::com::sun::star; using namespace ::com::sun::star::accessibility; namespace accessibility { // Pointer to the shape type handler singleton. ShapeTypeHandler* ShapeTypeHandler::instance = NULL; // Create an empty reference to an accessible object. AccessibleShape* CreateEmptyShapeReference ( const AccessibleShapeInfo& /*rShapeInfo*/, const AccessibleShapeTreeInfo& /*rShapeTreeInfo*/, ShapeTypeId /*nId*/) { return NULL; } ShapeTypeHandler& ShapeTypeHandler::Instance() { // Using double check pattern to make sure that exactly one instance of // the shape type handler is instantiated. if (instance == NULL) { SolarMutexGuard aGuard; if (instance == NULL) { // Create the single instance of the shape type handler. instance = new ShapeTypeHandler; // Register the basic SVX shape types. RegisterDrawShapeTypes (); } } return *instance; } /** The given service name is first transformed into a slot id that identifies the place of the type descriptor. From that descriptor the shape type id is returned. */ ShapeTypeId ShapeTypeHandler::GetTypeId (const OUString& aServiceName) const { tServiceNameToSlotId::iterator I (maServiceNameToSlotId.find (aServiceName)); if (I != maServiceNameToSlotId.end()) { return maShapeTypeDescriptorList[I->second].mnShapeTypeId; } else return -1; } /** Extract the specified shape's service name and forward the request to the appropriate method. */ ShapeTypeId ShapeTypeHandler::GetTypeId (const uno::Reference<drawing::XShape>& rxShape) const { uno::Reference<drawing::XShapeDescriptor> xDescriptor (rxShape, uno::UNO_QUERY); if (xDescriptor.is()) return GetTypeId (xDescriptor->getShapeType()); else return -1; } /** This factory method determines the type descriptor for the type of the given shape, then calls the descriptor's create function, and finally initializes the new object. */ AccessibleShape* ShapeTypeHandler::CreateAccessibleObject ( const AccessibleShapeInfo& rShapeInfo, const AccessibleShapeTreeInfo& rShapeTreeInfo) const { ShapeTypeId nSlotId (GetSlotId (rShapeInfo.mxShape)); AccessibleShape* pShape = maShapeTypeDescriptorList[nSlotId].maCreateFunction ( rShapeInfo, rShapeTreeInfo, maShapeTypeDescriptorList[nSlotId].mnShapeTypeId); return pShape; } /** Create the single instance of this class and initialize its list of type descriptors with an entry of an unknown type. */ ShapeTypeHandler::ShapeTypeHandler() : maShapeTypeDescriptorList (1) { // Make sure that at least the UNKNOWN entry is present. // Resize the list, if necessary, so that the new type can be inserted. maShapeTypeDescriptorList[0].mnShapeTypeId = UNKNOWN_SHAPE_TYPE; maShapeTypeDescriptorList[0].msServiceName = "UNKNOWN_SHAPE_TYPE"; maShapeTypeDescriptorList[0].maCreateFunction = CreateEmptyShapeReference; maServiceNameToSlotId[maShapeTypeDescriptorList[0].msServiceName] = 0; } ShapeTypeHandler::~ShapeTypeHandler() { // Because this class is a singleton and the only instance, whose // destructor has just been called, is pointed to from instance, // we reset the static variable instance, so that further calls to // getInstance do not return an undefined object but create a new // singleton. instance = NULL; } bool ShapeTypeHandler::AddShapeTypeList (int nDescriptorCount, ShapeTypeDescriptor aDescriptorList[]) { SolarMutexGuard aGuard; // Determine first id of new type descriptor(s). int nFirstId = maShapeTypeDescriptorList.size(); // Resize the list, if necessary, so that the types can be inserted. maShapeTypeDescriptorList.resize (nFirstId + nDescriptorCount); for (int i=0; i<nDescriptorCount; i++) { #if OSL_DEBUG_LEVEL > 0 ShapeTypeId nId (aDescriptorList[i].mnShapeTypeId); (void)nId; #endif // Fill Type descriptor. maShapeTypeDescriptorList[nFirstId+i].mnShapeTypeId = aDescriptorList[i].mnShapeTypeId; maShapeTypeDescriptorList[nFirstId+i].msServiceName = aDescriptorList[i].msServiceName; maShapeTypeDescriptorList[nFirstId+i].maCreateFunction = aDescriptorList[i].maCreateFunction; // Update inverse mapping from service name to the descriptor's position. maServiceNameToSlotId[aDescriptorList[i].msServiceName] = nFirstId+i; } return true; } long ShapeTypeHandler::GetSlotId (const OUString& aServiceName) const { tServiceNameToSlotId::iterator I (maServiceNameToSlotId.find (aServiceName)); if (I != maServiceNameToSlotId.end()) return I->second; else return 0; } // Extract the given shape's service name and forward request to appropriate // method. long ShapeTypeHandler::GetSlotId (const uno::Reference<drawing::XShape>& rxShape) const { uno::Reference<drawing::XShapeDescriptor> xDescriptor (rxShape, uno::UNO_QUERY); if (xDescriptor.is()) return GetSlotId (xDescriptor->getShapeType()); else return 0; } /// get the accessible base name for an object OUString ShapeTypeHandler::CreateAccessibleBaseName (const uno::Reference<drawing::XShape>& rxShape) throw (::com::sun::star::uno::RuntimeException) { sal_Int32 nResourceId; OUString sName; switch (ShapeTypeHandler::Instance().GetTypeId (rxShape)) { // case DRAWING_3D_POLYGON: was removed in original code in // AccessibleShape::CreateAccessibleBaseName. See issue 11190 for details. // Id can be removed from SvxShapeTypes.hxx as well. case DRAWING_3D_CUBE: nResourceId = STR_ObjNameSingulCube3d; break; case DRAWING_3D_EXTRUDE: nResourceId = STR_ObjNameSingulExtrude3d; break; case DRAWING_3D_LATHE: nResourceId = STR_ObjNameSingulLathe3d; break; case DRAWING_3D_SCENE: nResourceId = STR_ObjNameSingulScene3d; break; case DRAWING_3D_SPHERE: nResourceId = STR_ObjNameSingulSphere3d; break; case DRAWING_CAPTION: nResourceId = STR_ObjNameSingulCAPTION; break; case DRAWING_CLOSED_BEZIER: nResourceId = STR_ObjNameSingulPATHFILL; break; case DRAWING_CLOSED_FREEHAND: nResourceId = STR_ObjNameSingulFREEFILL; break; case DRAWING_CONNECTOR: nResourceId = STR_ObjNameSingulEDGE; break; case DRAWING_CONTROL: nResourceId = STR_ObjNameSingulUno; break; case DRAWING_ELLIPSE: nResourceId = STR_ObjNameSingulCIRCE; break; case DRAWING_GROUP: nResourceId = STR_ObjNameSingulGRUP; break; case DRAWING_LINE: nResourceId = STR_ObjNameSingulLINE; break; case DRAWING_MEASURE: nResourceId = STR_ObjNameSingulMEASURE; break; case DRAWING_OPEN_BEZIER: nResourceId = STR_ObjNameSingulPATHLINE; break; case DRAWING_OPEN_FREEHAND: nResourceId = STR_ObjNameSingulFREELINE; break; case DRAWING_PAGE: nResourceId = STR_ObjNameSingulPAGE; break; case DRAWING_POLY_LINE: nResourceId = STR_ObjNameSingulPLIN; break; case DRAWING_POLY_LINE_PATH: nResourceId = STR_ObjNameSingulPLIN; break; case DRAWING_POLY_POLYGON: nResourceId = STR_ObjNameSingulPOLY; break; case DRAWING_POLY_POLYGON_PATH: nResourceId = STR_ObjNameSingulPOLY; break; case DRAWING_RECTANGLE: nResourceId = STR_ObjNameSingulRECT; break; case DRAWING_CUSTOM: { nResourceId = STR_ObjNameSingulCUSTOMSHAPE; SvxShape* pShape = SvxShape::getImplementation( rxShape ); if (pShape) { SdrObject *pSdrObj = pShape->GetSdrObject(); if (pSdrObj) { if(pSdrObj->ISA(SdrObjCustomShape)) { SdrObjCustomShape* pCustomShape = static_cast<SdrObjCustomShape*>(pSdrObj); if(pCustomShape) { if (pCustomShape->IsTextPath()) nResourceId = STR_ObjNameSingulFONTWORK; else { nResourceId = -1; sName = pCustomShape->GetCustomShapeName(); } } } } } break; } case DRAWING_TEXT: nResourceId = STR_ObjNameSingulTEXT; break; default: nResourceId = -1; sName = "UnknownAccessibleShape"; uno::Reference<drawing::XShapeDescriptor> xDescriptor (rxShape, uno::UNO_QUERY); if (xDescriptor.is()) sName += ": " + xDescriptor->getShapeType(); break; } if (nResourceId != -1) { SolarMutexGuard aGuard; sName = OUString (SVX_RESSTR((unsigned short)nResourceId)); } return sName; } } // end of namespace accessibility /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>coverity#1308547 Uncaught exception<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 <svx/ShapeTypeHandler.hxx> #include <svx/SvxShapeTypes.hxx> #include <svx/AccessibleShapeInfo.hxx> #include <com/sun/star/drawing/XShapeDescriptor.hpp> #include <osl/mutex.hxx> #include <vcl/svapp.hxx> #include <svx/dialmgr.hxx> #include <svx/unoshape.hxx> #include <svx/svdoashp.hxx> #include "svx/unoapi.hxx" #include "svx/svdstr.hrc" using namespace ::com::sun::star; using namespace ::com::sun::star::accessibility; namespace accessibility { // Pointer to the shape type handler singleton. ShapeTypeHandler* ShapeTypeHandler::instance = NULL; // Create an empty reference to an accessible object. AccessibleShape* CreateEmptyShapeReference ( const AccessibleShapeInfo& /*rShapeInfo*/, const AccessibleShapeTreeInfo& /*rShapeTreeInfo*/, ShapeTypeId /*nId*/) { return NULL; } ShapeTypeHandler& ShapeTypeHandler::Instance() { // Using double check pattern to make sure that exactly one instance of // the shape type handler is instantiated. if (instance == NULL) { SolarMutexGuard aGuard; if (instance == NULL) { // Create the single instance of the shape type handler. instance = new ShapeTypeHandler; // Register the basic SVX shape types. RegisterDrawShapeTypes (); } } return *instance; } /** The given service name is first transformed into a slot id that identifies the place of the type descriptor. From that descriptor the shape type id is returned. */ ShapeTypeId ShapeTypeHandler::GetTypeId (const OUString& aServiceName) const { tServiceNameToSlotId::iterator I (maServiceNameToSlotId.find (aServiceName)); if (I != maServiceNameToSlotId.end()) { return maShapeTypeDescriptorList[I->second].mnShapeTypeId; } else return -1; } /** Extract the specified shape's service name and forward the request to the appropriate method. */ ShapeTypeId ShapeTypeHandler::GetTypeId (const uno::Reference<drawing::XShape>& rxShape) const { uno::Reference<drawing::XShapeDescriptor> xDescriptor (rxShape, uno::UNO_QUERY); if (xDescriptor.is()) return GetTypeId (xDescriptor->getShapeType()); else return -1; } /** This factory method determines the type descriptor for the type of the given shape, then calls the descriptor's create function, and finally initializes the new object. */ AccessibleShape* ShapeTypeHandler::CreateAccessibleObject ( const AccessibleShapeInfo& rShapeInfo, const AccessibleShapeTreeInfo& rShapeTreeInfo) const { ShapeTypeId nSlotId (GetSlotId (rShapeInfo.mxShape)); AccessibleShape* pShape = maShapeTypeDescriptorList[nSlotId].maCreateFunction ( rShapeInfo, rShapeTreeInfo, maShapeTypeDescriptorList[nSlotId].mnShapeTypeId); return pShape; } /** Create the single instance of this class and initialize its list of type descriptors with an entry of an unknown type. */ ShapeTypeHandler::ShapeTypeHandler() : maShapeTypeDescriptorList (1) { // Make sure that at least the UNKNOWN entry is present. // Resize the list, if necessary, so that the new type can be inserted. maShapeTypeDescriptorList[0].mnShapeTypeId = UNKNOWN_SHAPE_TYPE; maShapeTypeDescriptorList[0].msServiceName = "UNKNOWN_SHAPE_TYPE"; maShapeTypeDescriptorList[0].maCreateFunction = CreateEmptyShapeReference; maServiceNameToSlotId[maShapeTypeDescriptorList[0].msServiceName] = 0; } ShapeTypeHandler::~ShapeTypeHandler() { // Because this class is a singleton and the only instance, whose // destructor has just been called, is pointed to from instance, // we reset the static variable instance, so that further calls to // getInstance do not return an undefined object but create a new // singleton. instance = NULL; } bool ShapeTypeHandler::AddShapeTypeList (int nDescriptorCount, ShapeTypeDescriptor aDescriptorList[]) { SolarMutexGuard aGuard; // Determine first id of new type descriptor(s). int nFirstId = maShapeTypeDescriptorList.size(); // Resize the list, if necessary, so that the types can be inserted. maShapeTypeDescriptorList.resize (nFirstId + nDescriptorCount); for (int i=0; i<nDescriptorCount; i++) { #if OSL_DEBUG_LEVEL > 0 ShapeTypeId nId (aDescriptorList[i].mnShapeTypeId); (void)nId; #endif // Fill Type descriptor. maShapeTypeDescriptorList[nFirstId+i].mnShapeTypeId = aDescriptorList[i].mnShapeTypeId; maShapeTypeDescriptorList[nFirstId+i].msServiceName = aDescriptorList[i].msServiceName; maShapeTypeDescriptorList[nFirstId+i].maCreateFunction = aDescriptorList[i].maCreateFunction; // Update inverse mapping from service name to the descriptor's position. maServiceNameToSlotId[aDescriptorList[i].msServiceName] = nFirstId+i; } return true; } long ShapeTypeHandler::GetSlotId (const OUString& aServiceName) const { tServiceNameToSlotId::iterator I (maServiceNameToSlotId.find (aServiceName)); if (I != maServiceNameToSlotId.end()) return I->second; else return 0; } // Extract the given shape's service name and forward request to appropriate // method. long ShapeTypeHandler::GetSlotId (const uno::Reference<drawing::XShape>& rxShape) const { uno::Reference<drawing::XShapeDescriptor> xDescriptor (rxShape, uno::UNO_QUERY); if (xDescriptor.is()) return GetSlotId (xDescriptor->getShapeType()); else return 0; } /// get the accessible base name for an object OUString ShapeTypeHandler::CreateAccessibleBaseName (const uno::Reference<drawing::XShape>& rxShape) throw (::com::sun::star::uno::RuntimeException, std::exception) { sal_Int32 nResourceId; OUString sName; switch (ShapeTypeHandler::Instance().GetTypeId (rxShape)) { // case DRAWING_3D_POLYGON: was removed in original code in // AccessibleShape::CreateAccessibleBaseName. See issue 11190 for details. // Id can be removed from SvxShapeTypes.hxx as well. case DRAWING_3D_CUBE: nResourceId = STR_ObjNameSingulCube3d; break; case DRAWING_3D_EXTRUDE: nResourceId = STR_ObjNameSingulExtrude3d; break; case DRAWING_3D_LATHE: nResourceId = STR_ObjNameSingulLathe3d; break; case DRAWING_3D_SCENE: nResourceId = STR_ObjNameSingulScene3d; break; case DRAWING_3D_SPHERE: nResourceId = STR_ObjNameSingulSphere3d; break; case DRAWING_CAPTION: nResourceId = STR_ObjNameSingulCAPTION; break; case DRAWING_CLOSED_BEZIER: nResourceId = STR_ObjNameSingulPATHFILL; break; case DRAWING_CLOSED_FREEHAND: nResourceId = STR_ObjNameSingulFREEFILL; break; case DRAWING_CONNECTOR: nResourceId = STR_ObjNameSingulEDGE; break; case DRAWING_CONTROL: nResourceId = STR_ObjNameSingulUno; break; case DRAWING_ELLIPSE: nResourceId = STR_ObjNameSingulCIRCE; break; case DRAWING_GROUP: nResourceId = STR_ObjNameSingulGRUP; break; case DRAWING_LINE: nResourceId = STR_ObjNameSingulLINE; break; case DRAWING_MEASURE: nResourceId = STR_ObjNameSingulMEASURE; break; case DRAWING_OPEN_BEZIER: nResourceId = STR_ObjNameSingulPATHLINE; break; case DRAWING_OPEN_FREEHAND: nResourceId = STR_ObjNameSingulFREELINE; break; case DRAWING_PAGE: nResourceId = STR_ObjNameSingulPAGE; break; case DRAWING_POLY_LINE: nResourceId = STR_ObjNameSingulPLIN; break; case DRAWING_POLY_LINE_PATH: nResourceId = STR_ObjNameSingulPLIN; break; case DRAWING_POLY_POLYGON: nResourceId = STR_ObjNameSingulPOLY; break; case DRAWING_POLY_POLYGON_PATH: nResourceId = STR_ObjNameSingulPOLY; break; case DRAWING_RECTANGLE: nResourceId = STR_ObjNameSingulRECT; break; case DRAWING_CUSTOM: { nResourceId = STR_ObjNameSingulCUSTOMSHAPE; SvxShape* pShape = SvxShape::getImplementation( rxShape ); if (pShape) { SdrObject *pSdrObj = pShape->GetSdrObject(); if (pSdrObj) { if(pSdrObj->ISA(SdrObjCustomShape)) { SdrObjCustomShape* pCustomShape = static_cast<SdrObjCustomShape*>(pSdrObj); if(pCustomShape) { if (pCustomShape->IsTextPath()) nResourceId = STR_ObjNameSingulFONTWORK; else { nResourceId = -1; sName = pCustomShape->GetCustomShapeName(); } } } } } break; } case DRAWING_TEXT: nResourceId = STR_ObjNameSingulTEXT; break; default: nResourceId = -1; sName = "UnknownAccessibleShape"; uno::Reference<drawing::XShapeDescriptor> xDescriptor (rxShape, uno::UNO_QUERY); if (xDescriptor.is()) sName += ": " + xDescriptor->getShapeType(); break; } if (nResourceId != -1) { SolarMutexGuard aGuard; sName = OUString (SVX_RESSTR((unsigned short)nResourceId)); } return sName; } } // end of namespace accessibility /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SvXMLAutoCorrectExport.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2005-09-08 22:24:31 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SV_XMLAUTOCORRECTEXPORT_HXX #define _SV_XMLAUTOCORRECTEXPORT_HXX #ifndef _XMLOFF_XMLICTXT_HXX #include <xmloff/xmlictxt.hxx> #endif #ifndef _XMLOFF_XMLEXP_HXX #include <xmloff/xmlexp.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _MySVXACORR_HXX #include "svxacorr.hxx" #endif class SvXMLAutoCorrectExport : public SvXMLExport { private: const SvxAutocorrWordList *pAutocorr_List; public: // #110680# SvXMLAutoCorrectExport( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory, const SvxAutocorrWordList * pNewAutocorr_List, const rtl::OUString &rFileName, com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler> &rHandler); virtual ~SvXMLAutoCorrectExport ( void ) {} sal_uInt32 exportDoc(enum ::xmloff::token::XMLTokenEnum eClass); void _ExportAutoStyles() {} void _ExportMasterStyles () {} void _ExportContent() {} }; class SvStringsISortDtor; class SvXMLExceptionListExport : public SvXMLExport { private: const SvStringsISortDtor & rList; public: // #110680# SvXMLExceptionListExport( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory, const SvStringsISortDtor &rNewList, const rtl::OUString &rFileName, com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler> &rHandler); virtual ~SvXMLExceptionListExport ( void ) {} sal_uInt32 exportDoc(enum ::xmloff::token::XMLTokenEnum eClass); void _ExportAutoStyles() {} void _ExportMasterStyles () {} void _ExportContent() {} }; #endif <commit_msg>INTEGRATION: CWS vgbugs07 (1.7.876); FILE MERGED 2007/06/04 13:26:47 vg 1.7.876.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SvXMLAutoCorrectExport.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2007-06-27 17:53:08 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SV_XMLAUTOCORRECTEXPORT_HXX #define _SV_XMLAUTOCORRECTEXPORT_HXX #ifndef _XMLOFF_XMLICTXT_HXX #include <xmloff/xmlictxt.hxx> #endif #ifndef _XMLOFF_XMLEXP_HXX #include <xmloff/xmlexp.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _MySVXACORR_HXX #include <svx/svxacorr.hxx> #endif class SvXMLAutoCorrectExport : public SvXMLExport { private: const SvxAutocorrWordList *pAutocorr_List; public: // #110680# SvXMLAutoCorrectExport( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory, const SvxAutocorrWordList * pNewAutocorr_List, const rtl::OUString &rFileName, com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler> &rHandler); virtual ~SvXMLAutoCorrectExport ( void ) {} sal_uInt32 exportDoc(enum ::xmloff::token::XMLTokenEnum eClass); void _ExportAutoStyles() {} void _ExportMasterStyles () {} void _ExportContent() {} }; class SvStringsISortDtor; class SvXMLExceptionListExport : public SvXMLExport { private: const SvStringsISortDtor & rList; public: // #110680# SvXMLExceptionListExport( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory, const SvStringsISortDtor &rNewList, const rtl::OUString &rFileName, com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler> &rHandler); virtual ~SvXMLExceptionListExport ( void ) {} sal_uInt32 exportDoc(enum ::xmloff::token::XMLTokenEnum eClass); void _ExportAutoStyles() {} void _ExportMasterStyles () {} void _ExportContent() {} }; #endif <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // \index{otb::LabelMapToVectorDataFilter} // // // This class vectorizes a LabelObject to a VectorData. // // LabelMapToVectorDataFilter converts a LabelMap to a // VectorData where all the pixels get the attribute value of the label object they belong. // It uses the class otbLabelObjectToPolygonFunctor wich follows a finite states machine described in: // // "An algorithm for the rapid computation of boundaries of run-length // encoded regions", Francis K. H. Queck, in Pattern Recognition 33 // (2000), p 1637-1649. // // This filter converts label object to polygons. // Software Guide : EndLatex #include "otbImageFileReader.h" #include "otbVectorDataFileWriter.h" #include "otbVectorData.h" #include "otbVectorDataProjectionFilter.h" #include <fstream> #include <iostream> #include "otbImage.h" #include "otbLabelMapToVectorDataFilter.h" #include "otbAttributesMapLabelObject.h" #include "itkLabelImageToLabelMapFilter.h" int main(int argc, char * argv[]) { /** Use the labelObjecttopolygon functor (not thread safe) only polygon conversion is available yet*/ if ( argc != 3 ) { std::cerr << "Usage: " << argv[0]; std::cerr << " inputImageFile outputVectorfile(shp)" << std::endl; return EXIT_FAILURE; } const char * infname = argv[1]; const char * outfname = argv[2]; // Software Guide : BeginLatex // // The image types are now defined using pixel types and // dimension. The input image is defined as an \doxygen{itk}{Image}, // the output is a \doxygen{otb}{VectorData}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const unsigned int Dimension = 2; typedef unsigned short LabelType; typedef otb::Image<LabelType,Dimension> LabeledImageType; typedef otb::VectorData<double,2> VectorDataType; // Software Guide : EndCodeSnippet // We instantiate reader and writer types typedef otb::ImageFileReader<LabeledImageType> LabeledReaderType; typedef otb::VectorDataFileWriter<VectorDataType> WriterType; // Label map typedef // Software Guide : BeginLatex // // The Attribute Label Map is // instantiated using the image pixel types as template parameters. // The LabelObjectToPolygonFunctor is instantiated with LabelObjectType and PolygonType // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::AttributesMapLabelObject<LabelType,Dimension,double> LabelObjectType; typedef itk::LabelMap<LabelObjectType> LabelMapType; typedef itk::LabelImageToLabelMapFilter<LabeledImageType,LabelMapType> LabelMapFilterType; typedef otb::Polygon<double> PolygonType; typedef otb::Functor::LabelObjectToPolygonFunctor<LabelObjectType,PolygonType> FunctorType; // Software Guide : EndCodeSnippet typedef VectorDataType::DataNodeType DataNodeType; typedef otb::VectorDataProjectionFilter<VectorDataType,VectorDataType> VectorDataFilterType; LabeledReaderType::Pointer lreader = LabeledReaderType::New(); WriterType::Pointer writer = WriterType::New(); // Software Guide : BeginLatex // // Now the input image is set and a name is given to the output image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet lreader->SetFileName(infname); writer->SetFileName(outfname); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Then, the input image is converted to a map of label objects. // Here each whyte region connected regions are converted. So the background is define all zero pixels. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet LabelMapFilterType::Pointer labelMapFilter = LabelMapFilterType::New(); labelMapFilter->SetInput(lreader->GetOutput()); labelMapFilter->SetBackgroundValue(itk::NumericTraits<LabelType>::min()); labelMapFilter->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Then, the \doxygen{otb}{LabelMapToVectorDataFilter} is instantiated. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::LabelMapToVectorDataFilter< LabelMapType , VectorDataType > LabelMapToVectorDataFilterType; LabelMapToVectorDataFilterType::Pointer MyFilter = LabelMapToVectorDataFilterType::New(); MyFilter->SetInput(labelMapFilter->GetOutput()); MyFilter->Update(); MyFilter->GetOutput()->SetProjectionRef(lreader->GetOutput()->GetProjectionRef()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The output can be passed to a writer. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet writer->SetInput( MyFilter->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The invocation of the \code{Update()} method on the writer triggers the // execution of the pipeline. It is recommended to place update calls in a // \code{try/catch} block in case errors occur and exceptions are thrown. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet try { writer->Update(); return EXIT_SUCCESS; } catch ( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; } // Software Guide : EndCodeSnippet catch ( ... ) { std::cout << "Unknown exception !" << std::endl; return EXIT_FAILURE; } } <commit_msg>DOC:LabelMaptoVectorData example v0<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // \index{otb::LabelMapToVectorDataFilter} // // // This class vectorizes a LabelObject to a VectorData. // // LabelMapToVectorDataFilter converts a LabelMap to a // VectorData where all the pixels get the attribute value of the label object they belong. // It uses the class otbLabelObjectToPolygonFunctor wich follows a finite states machine described in: // // "An algorithm for the rapid computation of boundaries of run-length // encoded regions", Francis K. H. Queck, in Pattern Recognition 33 // (2000), p 1637-1649. // // Only polygon conversion is available yet. // Software Guide : EndLatex #include "otbImageFileReader.h" #include "otbVectorDataFileWriter.h" #include "otbVectorData.h" #include "otbVectorDataProjectionFilter.h" #include <fstream> #include <iostream> #include "otbImage.h" #include "otbLabelMapToVectorDataFilter.h" #include "otbAttributesMapLabelObject.h" #include "itkLabelImageToLabelMapFilter.h" int main(int argc, char * argv[]) { /** Use the labelObjecttopolygon functor (not thread safe) only polygon conversion is available yet*/ if ( argc != 3 ) { std::cerr << "Usage: " << argv[0]; std::cerr << " inputImageFile outputVectorfile(shp)" << std::endl; return EXIT_FAILURE; } const char * infname = argv[1]; const char * outfname = argv[2]; // Software Guide : BeginLatex // // The image types are defined using pixel types and // dimension. The input image is defined as an \doxygen{itk}{Image}, // the output is a \doxygen{otb}{VectorData}. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet const unsigned int Dimension = 2; typedef unsigned short LabelType; typedef otb::Image<LabelType,Dimension> LabeledImageType; typedef otb::VectorData<double,2> VectorDataType; // Software Guide : EndCodeSnippet // We instantiate reader and writer types typedef otb::ImageFileReader<LabeledImageType> LabeledReaderType; typedef otb::VectorDataFileWriter<VectorDataType> WriterType; // Label map typedef // Software Guide : BeginLatex // // The Attribute Label Map is // instantiated using the image pixel types as template parameters. // The LabelObjectToPolygonFunctor is instantiated with LabelObjectType and PolygonType. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::AttributesMapLabelObject<LabelType,Dimension,double> LabelObjectType; typedef itk::LabelMap<LabelObjectType> LabelMapType; typedef itk::LabelImageToLabelMapFilter<LabeledImageType,LabelMapType> LabelMapFilterType; typedef otb::Polygon<double> PolygonType; typedef otb::Functor::LabelObjectToPolygonFunctor<LabelObjectType,PolygonType> FunctorType; // Software Guide : EndCodeSnippet typedef VectorDataType::DataNodeType DataNodeType; typedef otb::VectorDataProjectionFilter<VectorDataType,VectorDataType> VectorDataFilterType; LabeledReaderType::Pointer lreader = LabeledReaderType::New(); WriterType::Pointer writer = WriterType::New(); // Software Guide : BeginLatex // Now the reader and writer are instantiated and // the input image is set and a name is given to the output image. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet lreader->SetFileName(infname); writer->SetFileName(outfname); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Then, the input image is converted to a map of label objects. // Here each white region connected regions are converted. So the background is define all zero pixels. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet LabelMapFilterType::Pointer labelMapFilter = LabelMapFilterType::New(); labelMapFilter->SetInput(lreader->GetOutput()); labelMapFilter->SetBackgroundValue(itk::NumericTraits<LabelType>::min()); labelMapFilter->Update(); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Then, the \doxygen{otb}{LabelMapToVectorDataFilter} is instantiated. This is // the main filter which proceed the vectorization. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef otb::LabelMapToVectorDataFilter< LabelMapType , VectorDataType > LabelMapToVectorDataFilterType; LabelMapToVectorDataFilterType::Pointer MyFilter = LabelMapToVectorDataFilterType::New(); MyFilter->SetInput(labelMapFilter->GetOutput()); MyFilter->Update(); MyFilter->GetOutput()->SetProjectionRef(lreader->GetOutput()->GetProjectionRef()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The output can be passed to a writer. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet writer->SetInput( MyFilter->GetOutput()); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // The invocation of the \code{Update()} method on the writer triggers the // execution of the pipeline. As usualn, it is recommended to place update calls in a // \code{try/catch} block in case errors occur and exceptions are thrown. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet try { writer->Update(); return EXIT_SUCCESS; } catch ( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; } // Software Guide : EndCodeSnippet catch ( ... ) { std::cout << "Unknown exception !" << std::endl; return EXIT_FAILURE; } } <|endoftext|>
<commit_before>#include "Globals.h" #include "Application.h" #include "ModuleAudio.h" #pragma comment( lib, "3DEngine/SDL_mixer/libx86/SDL2_mixer.lib" ) ModuleAudio::ModuleAudio( bool start_enabled) : Module(start_enabled), music(NULL) {} // Destructor ModuleAudio::~ModuleAudio() {} // Called before render is available bool ModuleAudio::Init() { LOG("Loading Audio Mixer"); bool ret = true; SDL_Init(0); if(SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) { LOG("SDL_INIT_AUDIO could not initialize! SDL_Error: %s\n", SDL_GetError()); ret = false; } // load support for the OGG format int flags = MIX_INIT_OGG; int init = Mix_Init(flags); if((init & flags) != flags) { LOG("Could not initialize Mixer lib. Mix_Init: %s", Mix_GetError()); ret = false; } //Initialize SDL_mixer if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) { LOG("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError()); ret = false; } return true; } // Called before quitting bool ModuleAudio::CleanUp() { LOG("Freeing sound FX, closing Mixer and Audio subsystem"); if(music != NULL) { Mix_FreeMusic(music); } std::vector<Mix_Chunk*>::iterator item; for(item = fx.begin(); item != fx.end(); item++) { Mix_FreeChunk((*item)); } fx.clear(); Mix_CloseAudio(); Mix_Quit(); SDL_QuitSubSystem(SDL_INIT_AUDIO); return true; } // Play a music file bool ModuleAudio::PlayMusic(const char* path, float fade_time) { bool ret = true; if(music != NULL) { if(fade_time > 0.0f) { Mix_FadeOutMusic((int) (fade_time * 1000.0f)); } else { Mix_HaltMusic(); } // this call blocks until fade out is done Mix_FreeMusic(music); } music = Mix_LoadMUS(path); if(music == NULL) { LOG("Cannot load music %s. Mix_GetError(): %s\n", path, Mix_GetError()); ret = false; } else { if(fade_time > 0.0f) { if(Mix_FadeInMusic(music, -1, (int) (fade_time * 1000.0f)) < 0) { LOG("Cannot fade in music %s. Mix_GetError(): %s", path, Mix_GetError()); ret = false; } } else { if(Mix_PlayMusic(music, -1) < 0) { LOG("Cannot play in music %s. Mix_GetError(): %s", path, Mix_GetError()); ret = false; } } } LOG("Successfully playing %s", path); return ret; } // Load WAV unsigned int ModuleAudio::LoadFx(const char* path) { unsigned int ret = 0; Mix_Chunk* chunk = Mix_LoadWAV(path); if(chunk == NULL) { LOG("Cannot load wav %s. Mix_GetError(): %s", path, Mix_GetError()); } else { fx.push_back(chunk); ret = fx.size(); } return ret; } // Play WAV bool ModuleAudio::PlayFx(unsigned int id, int repeat) { bool ret = false; Mix_Chunk* chunk = NULL; if(fx.at(id-1, chunk) == true) { Mix_PlayChannel(-1, chunk, repeat); ret = true; } return ret; }<commit_msg>audio done<commit_after>#include "Globals.h" #include "Application.h" #include "ModuleAudio.h" #pragma comment( lib, "3DEngine/SDL_mixer/libx86/SDL2_mixer.lib" ) ModuleAudio::ModuleAudio( bool start_enabled) : Module(start_enabled), music(NULL) {} // Destructor ModuleAudio::~ModuleAudio() {} // Called before render is available bool ModuleAudio::Init() { LOG("Loading Audio Mixer"); bool ret = true; SDL_Init(0); if(SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) { LOG("SDL_INIT_AUDIO could not initialize! SDL_Error: %s\n", SDL_GetError()); ret = false; } // load support for the OGG format int flags = MIX_INIT_OGG; int init = Mix_Init(flags); if((init & flags) != flags) { LOG("Could not initialize Mixer lib. Mix_Init: %s", Mix_GetError()); ret = false; } //Initialize SDL_mixer if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) { LOG("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError()); ret = false; } return true; } // Called before quitting bool ModuleAudio::CleanUp() { LOG("Freeing sound FX, closing Mixer and Audio subsystem"); if(music != NULL) { Mix_FreeMusic(music); } std::vector<Mix_Chunk*>::iterator item; for(item = fx.begin(); item != fx.end(); item++) { Mix_FreeChunk((*item)); } fx.clear(); Mix_CloseAudio(); Mix_Quit(); SDL_QuitSubSystem(SDL_INIT_AUDIO); return true; } // Play a music file bool ModuleAudio::PlayMusic(const char* path, float fade_time) { bool ret = true; if(music != NULL) { if(fade_time > 0.0f) { Mix_FadeOutMusic((int) (fade_time * 1000.0f)); } else { Mix_HaltMusic(); } // this call blocks until fade out is done Mix_FreeMusic(music); } music = Mix_LoadMUS(path); if(music == NULL) { LOG("Cannot load music %s. Mix_GetError(): %s\n", path, Mix_GetError()); ret = false; } else { if(fade_time > 0.0f) { if(Mix_FadeInMusic(music, -1, (int) (fade_time * 1000.0f)) < 0) { LOG("Cannot fade in music %s. Mix_GetError(): %s", path, Mix_GetError()); ret = false; } } else { if(Mix_PlayMusic(music, -1) < 0) { LOG("Cannot play in music %s. Mix_GetError(): %s", path, Mix_GetError()); ret = false; } } } LOG("Successfully playing %s", path); return ret; } // Load WAV unsigned int ModuleAudio::LoadFx(const char* path) { unsigned int ret = 0; Mix_Chunk* chunk = Mix_LoadWAV(path); if(chunk == NULL) { LOG("Cannot load wav %s. Mix_GetError(): %s", path, Mix_GetError()); } else { fx.push_back(chunk); ret = fx.size(); } return ret; } // Play WAV bool ModuleAudio::PlayFx(unsigned int id, int repeat) { bool ret = false; if (id > 0 && id <= fx.size()) { Mix_PlayChannel(-1, fx[id - 1], repeat); ret = true; } return ret; }<|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////////// // // Copyright (c) 2002 Stanislav Shwartsman // Written by Stanislav Shwartsman <gate@fidonet.org.il> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #define NEED_CPU_REG_SHORTCUTS 1 #include "bochs.h" #define LOG_THIS BX_CPU_THIS_PTR #if BX_SUPPORT_3DNOW #include "softfloat.h" static void prepare_softfloat_status_word (softfloat_status_word_t &status_word, int rounding_mode) { status.float_precision = 32; status.float_detect_tininess = float_tininess_before_rounding; status.float_exception_flags = 0; // clear exceptions before execution status.float_nan_handling_mode = float_first_operand_nan; status.float_rounding_mode = rounding_mode; status.flush_underflow_to_zero = 0; } void BX_CPU_C::PFPNACC_PqQq(bxInstruction_c *i) { BX_PANIC(("PFPNACC_PqQq: 3DNow! instruction still not implemented")); } /* 0F 0F /r 0C */ void BX_CPU_C::PI2FW_PqQq(bxInstruction_c *i) { BxPackedMmxRegister result, op; /* op is a register or memory reference */ if (i->modC0()) { op = BX_READ_MMX_REG(i->rm()); } else { /* pointer, segment address pair */ read_virtual_qword(i->seg(), RMAddr(i), (Bit64u *) &op); } softfloat_status_word_t status_word; prepare_softfloat_status_word(status_word, float_round_to_zero); MMXUD0(result) = int32_to_float32((Bit32s)(MMXSW0(op)), status_word); MMXUD1(result) = int32_to_float32((Bit32s)(MMXSW2(op)), status_word); /* now write result back to destination */ BX_WRITE_MMX_REG(i->nnn(), result); } /* 0F 0F /r 0D */ void BX_CPU_C::PI2FD_PqQq(bxInstruction_c *i) { BxPackedMmxRegister result, op; /* op is a register or memory reference */ if (i->modC0()) { op = BX_READ_MMX_REG(i->rm()); } else { /* pointer, segment address pair */ read_virtual_qword(i->seg(), RMAddr(i), (Bit64u *) &op); } softfloat_status_word_t status_word; prepare_softfloat_status_word(status_word, float_round_to_zero); MMXUD0(result) = int32_to_float32(MMXSD0(op), status_word); MMXUD1(result) = int32_to_float32(MMXSD1(op), status_word); /* now write result back to destination */ BX_WRITE_MMX_REG(i->nnn(), result); } void BX_CPU_C::PF2IW_PqQq(bxInstruction_c *i) { BX_PANIC(("PF2IW_PqQq: 3DNow! instruction still not implemented")); } /* 0F 0F /r 1D */ void BX_CPU_C::PF2ID_PqQq(bxInstruction_c *i) { BxPackedMmxRegister result, op; /* op is a register or memory reference */ if (i->modC0()) { op = BX_READ_MMX_REG(i->rm()); } else { /* pointer, segment address pair */ read_virtual_qword(i->seg(), RMAddr(i), (Bit64u *) &op); } softfloat_status_word_t status_word; prepare_softfloat_status_word(status_word, float_round_to_zero); MMXSD0(result) = float32_to_int32_round_to_zero(MMXUD0(op), status_word); MMXSD1(result) = float32_to_int32_round_to_zero(MMXUD1(op), status_word); /* now write result back to destination */ BX_WRITE_MMX_REG(i->nnn(), result); } void BX_CPU_C::PFNACC_PqQq(bxInstruction_c *i) { BX_PANIC(("PFNACC_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFCMPGE_PqQq(bxInstruction_c *i) { BX_PANIC(("PFCMPGE_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFMIN_PqQq(bxInstruction_c *i) { BX_PANIC(("PFMIN_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFRCP_PqQq(bxInstruction_c *i) { BX_PANIC(("PFRCP_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFRSQRT_PqQq(bxInstruction_c *i) { BX_PANIC(("PFRSQRT_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFSUB_PqQq(bxInstruction_c *i) { BX_PANIC(("PFSUB_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFADD_PqQq(bxInstruction_c *i) { BX_PANIC(("PFADD_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFCMPGT_PqQq(bxInstruction_c *i) { BX_PANIC(("PFCMPGT_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFMAX_PqQq(bxInstruction_c *i) { BX_PANIC(("PFMAX_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFRCPIT1_PqQq(bxInstruction_c *i) { BX_PANIC(("PFRCPIT1_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFRSQIT1_PqQq(bxInstruction_c *i) { BX_PANIC(("PFRSQIT1_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFSUBR_PqQq(bxInstruction_c *i) { BX_PANIC(("PFSUBR_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFACC_PqQq(bxInstruction_c *i) { BX_PANIC(("PFACC_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFCMPEQ_PqQq(bxInstruction_c *i) { BX_PANIC(("PFCMPEQ_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFMUL_PqQq(bxInstruction_c *i) { BX_PANIC(("PFMUL_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFRCPIT2_PqQq(bxInstruction_c *i) { BX_PANIC(("PFRCPIT2_PqQq: 3DNow! instruction still not implemented")); } /* 0F 0F /r B7 */ void BX_CPU_C::PMULHRW_PqQq(bxInstruction_c *i) { BX_CPU_THIS_PTR prepareMMX(); BxPackedMmxRegister op1 = BX_READ_MMX_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_MMX_REG(i->rm()); } else { /* pointer, segment address pair */ read_virtual_qword(i->seg(), RMAddr(i), (Bit64u *) &op2); } Bit32s product1 = Bit32s(MMXSW0(op1)) * Bit32s(MMXSW0(op2)) + 0x8000; Bit32s product2 = Bit32s(MMXSW1(op1)) * Bit32s(MMXSW1(op2)) + 0x8000; Bit32s product3 = Bit32s(MMXSW2(op1)) * Bit32s(MMXSW2(op2)) + 0x8000; Bit32s product4 = Bit32s(MMXSW3(op1)) * Bit32s(MMXSW3(op2)) + 0x8000; MMXUW0(result) = Bit16u(product1 >> 16); MMXUW1(result) = Bit16u(product2 >> 16); MMXUW2(result) = Bit16u(product3 >> 16); MMXUW3(result) = Bit16u(product4 >> 16); /* now write result back to destination */ BX_WRITE_MMX_REG(i->nnn(), result); } /* 0F 0F /r BB */ void BX_CPU_C::PSWAPD_PqQq(bxInstruction_c *i) { BX_CPU_THIS_PTR prepareMMX(); BxPackedMmxRegister result, op; /* op is a register or memory reference */ if (i->modC0()) { op = BX_READ_MMX_REG(i->rm()); } else { /* pointer, segment address pair */ read_virtual_qword(i->seg(), RMAddr(i), (Bit64u *) &op); } MMXUD0(result) = MMXUD1(op); MMXUD1(result) = MMXUD0(op); /* now write result back to destination */ BX_WRITE_MMX_REG(i->nnn(), result); } #endif <commit_msg><commit_after>///////////////////////////////////////////////////////////////////////// // // Copyright (c) 2002 Stanislav Shwartsman // Written by Stanislav Shwartsman <gate@fidonet.org.il> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #define NEED_CPU_REG_SHORTCUTS 1 #include "bochs.h" #define LOG_THIS BX_CPU_THIS_PTR #if BX_SUPPORT_3DNOW #include "softfloat.h" static void prepare_softfloat_status_word (softfloat_status_word_t &status, int rounding_mode) { status.float_precision = 32; status.float_detect_tininess = float_tininess_before_rounding; status.float_exception_flags = 0; // clear exceptions before execution status.float_nan_handling_mode = float_first_operand_nan; status.float_rounding_mode = rounding_mode; status.flush_underflow_to_zero = 0; } void BX_CPU_C::PFPNACC_PqQq(bxInstruction_c *i) { BX_PANIC(("PFPNACC_PqQq: 3DNow! instruction still not implemented")); } /* 0F 0F /r 0C */ void BX_CPU_C::PI2FW_PqQq(bxInstruction_c *i) { BxPackedMmxRegister result, op; /* op is a register or memory reference */ if (i->modC0()) { op = BX_READ_MMX_REG(i->rm()); } else { /* pointer, segment address pair */ read_virtual_qword(i->seg(), RMAddr(i), (Bit64u *) &op); } softfloat_status_word_t status_word; prepare_softfloat_status_word(status_word, float_round_to_zero); MMXUD0(result) = int32_to_float32((Bit32s)(MMXSW0(op)), status_word); MMXUD1(result) = int32_to_float32((Bit32s)(MMXSW2(op)), status_word); /* now write result back to destination */ BX_WRITE_MMX_REG(i->nnn(), result); } /* 0F 0F /r 0D */ void BX_CPU_C::PI2FD_PqQq(bxInstruction_c *i) { BxPackedMmxRegister result, op; /* op is a register or memory reference */ if (i->modC0()) { op = BX_READ_MMX_REG(i->rm()); } else { /* pointer, segment address pair */ read_virtual_qword(i->seg(), RMAddr(i), (Bit64u *) &op); } softfloat_status_word_t status_word; prepare_softfloat_status_word(status_word, float_round_to_zero); MMXUD0(result) = int32_to_float32(MMXSD0(op), status_word); MMXUD1(result) = int32_to_float32(MMXSD1(op), status_word); /* now write result back to destination */ BX_WRITE_MMX_REG(i->nnn(), result); } void BX_CPU_C::PF2IW_PqQq(bxInstruction_c *i) { BX_PANIC(("PF2IW_PqQq: 3DNow! instruction still not implemented")); } /* 0F 0F /r 1D */ void BX_CPU_C::PF2ID_PqQq(bxInstruction_c *i) { BxPackedMmxRegister result, op; /* op is a register or memory reference */ if (i->modC0()) { op = BX_READ_MMX_REG(i->rm()); } else { /* pointer, segment address pair */ read_virtual_qword(i->seg(), RMAddr(i), (Bit64u *) &op); } softfloat_status_word_t status_word; prepare_softfloat_status_word(status_word, float_round_to_zero); MMXSD0(result) = float32_to_int32_round_to_zero(MMXUD0(op), status_word); MMXSD1(result) = float32_to_int32_round_to_zero(MMXUD1(op), status_word); /* now write result back to destination */ BX_WRITE_MMX_REG(i->nnn(), result); } void BX_CPU_C::PFNACC_PqQq(bxInstruction_c *i) { BX_PANIC(("PFNACC_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFCMPGE_PqQq(bxInstruction_c *i) { BX_PANIC(("PFCMPGE_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFMIN_PqQq(bxInstruction_c *i) { BX_PANIC(("PFMIN_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFRCP_PqQq(bxInstruction_c *i) { BX_PANIC(("PFRCP_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFRSQRT_PqQq(bxInstruction_c *i) { BX_PANIC(("PFRSQRT_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFSUB_PqQq(bxInstruction_c *i) { BX_PANIC(("PFSUB_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFADD_PqQq(bxInstruction_c *i) { BX_PANIC(("PFADD_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFCMPGT_PqQq(bxInstruction_c *i) { BX_PANIC(("PFCMPGT_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFMAX_PqQq(bxInstruction_c *i) { BX_PANIC(("PFMAX_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFRCPIT1_PqQq(bxInstruction_c *i) { BX_PANIC(("PFRCPIT1_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFRSQIT1_PqQq(bxInstruction_c *i) { BX_PANIC(("PFRSQIT1_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFSUBR_PqQq(bxInstruction_c *i) { BX_PANIC(("PFSUBR_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFACC_PqQq(bxInstruction_c *i) { BX_PANIC(("PFACC_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFCMPEQ_PqQq(bxInstruction_c *i) { BX_PANIC(("PFCMPEQ_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFMUL_PqQq(bxInstruction_c *i) { BX_PANIC(("PFMUL_PqQq: 3DNow! instruction still not implemented")); } void BX_CPU_C::PFRCPIT2_PqQq(bxInstruction_c *i) { BX_PANIC(("PFRCPIT2_PqQq: 3DNow! instruction still not implemented")); } /* 0F 0F /r B7 */ void BX_CPU_C::PMULHRW_PqQq(bxInstruction_c *i) { BX_CPU_THIS_PTR prepareMMX(); BxPackedMmxRegister op1 = BX_READ_MMX_REG(i->nnn()), op2, result; /* op2 is a register or memory reference */ if (i->modC0()) { op2 = BX_READ_MMX_REG(i->rm()); } else { /* pointer, segment address pair */ read_virtual_qword(i->seg(), RMAddr(i), (Bit64u *) &op2); } Bit32s product1 = Bit32s(MMXSW0(op1)) * Bit32s(MMXSW0(op2)) + 0x8000; Bit32s product2 = Bit32s(MMXSW1(op1)) * Bit32s(MMXSW1(op2)) + 0x8000; Bit32s product3 = Bit32s(MMXSW2(op1)) * Bit32s(MMXSW2(op2)) + 0x8000; Bit32s product4 = Bit32s(MMXSW3(op1)) * Bit32s(MMXSW3(op2)) + 0x8000; MMXUW0(result) = Bit16u(product1 >> 16); MMXUW1(result) = Bit16u(product2 >> 16); MMXUW2(result) = Bit16u(product3 >> 16); MMXUW3(result) = Bit16u(product4 >> 16); /* now write result back to destination */ BX_WRITE_MMX_REG(i->nnn(), result); } /* 0F 0F /r BB */ void BX_CPU_C::PSWAPD_PqQq(bxInstruction_c *i) { BX_CPU_THIS_PTR prepareMMX(); BxPackedMmxRegister result, op; /* op is a register or memory reference */ if (i->modC0()) { op = BX_READ_MMX_REG(i->rm()); } else { /* pointer, segment address pair */ read_virtual_qword(i->seg(), RMAddr(i), (Bit64u *) &op); } MMXUD0(result) = MMXUD1(op); MMXUD1(result) = MMXUD0(op); /* now write result back to destination */ BX_WRITE_MMX_REG(i->nnn(), result); } #endif <|endoftext|>
<commit_before> /* * Copyright 2010 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrResourceCache.h" #include "GrResource.h" GrResourceEntry::GrResourceEntry(const GrResourceKey& key, GrResource* resource) : fKey(key), fResource(resource) { fLockCount = 0; fPrev = fNext = NULL; // we assume ownership of the resource, and will unref it when we die GrAssert(resource); } GrResourceEntry::~GrResourceEntry() { fResource->unref(); } #if GR_DEBUG void GrResourceEntry::validate() const { GrAssert(fLockCount >= 0); GrAssert(fResource); fResource->validate(); } #endif /////////////////////////////////////////////////////////////////////////////// GrResourceCache::GrResourceCache(int maxCount, size_t maxBytes) : fMaxCount(maxCount), fMaxBytes(maxBytes) { fEntryCount = 0; fUnlockedEntryCount = 0; fEntryBytes = 0; fClientDetachedCount = 0; fClientDetachedBytes = 0; fHead = fTail = NULL; fPurging = false; } GrResourceCache::~GrResourceCache() { GrAutoResourceCacheValidate atcv(this); this->removeAll(); } void GrResourceCache::getLimits(int* maxResources, size_t* maxResourceBytes) const{ if (maxResources) { *maxResources = fMaxCount; } if (maxResourceBytes) { *maxResourceBytes = fMaxBytes; } } void GrResourceCache::setLimits(int maxResources, size_t maxResourceBytes) { bool smaller = (maxResources < fMaxCount) || (maxResourceBytes < fMaxBytes); fMaxCount = maxResources; fMaxBytes = maxResourceBytes; if (smaller) { this->purgeAsNeeded(); } } void GrResourceCache::internalDetach(GrResourceEntry* entry, bool clientDetach) { GrResourceEntry* prev = entry->fPrev; GrResourceEntry* next = entry->fNext; if (prev) { prev->fNext = next; } else { fHead = next; } if (next) { next->fPrev = prev; } else { fTail = prev; } if (!entry->isLocked()) { --fUnlockedEntryCount; } // update our stats if (clientDetach) { fClientDetachedCount += 1; fClientDetachedBytes += entry->resource()->sizeInBytes(); } else { fEntryCount -= 1; fEntryBytes -= entry->resource()->sizeInBytes(); } } void GrResourceCache::attachToHead(GrResourceEntry* entry, bool clientReattach) { entry->fPrev = NULL; entry->fNext = fHead; if (fHead) { fHead->fPrev = entry; } fHead = entry; if (NULL == fTail) { fTail = entry; } if (!entry->isLocked()) { ++fUnlockedEntryCount; } // update our stats if (clientReattach) { fClientDetachedCount -= 1; fClientDetachedBytes -= entry->resource()->sizeInBytes(); } else { fEntryCount += 1; fEntryBytes += entry->resource()->sizeInBytes(); } } class GrResourceCache::Key { typedef GrResourceEntry T; const GrResourceKey& fKey; public: Key(const GrResourceKey& key) : fKey(key) {} uint32_t getHash() const { return fKey.hashIndex(); } static bool LT(const T& entry, const Key& key) { return entry.key() < key.fKey; } static bool EQ(const T& entry, const Key& key) { return entry.key() == key.fKey; } #if GR_DEBUG static uint32_t GetHash(const T& entry) { return entry.key().hashIndex(); } static bool LT(const T& a, const T& b) { return a.key() < b.key(); } static bool EQ(const T& a, const T& b) { return a.key() == b.key(); } #endif }; GrResourceEntry* GrResourceCache::findAndLock(const GrResourceKey& key, LockType type) { GrAutoResourceCacheValidate atcv(this); GrResourceEntry* entry = fCache.find(key); if (entry) { this->internalDetach(entry, false); // mark the entry as "busy" so it doesn't get purged // do this between detach and attach for locked count tracking if (kNested_LockType == type || !entry->isLocked()) { entry->lock(); } this->attachToHead(entry, false); } return entry; } GrResourceEntry* GrResourceCache::createAndLock(const GrResourceKey& key, GrResource* resource) { // we don't expect to create new resources during a purge. In theory // this could cause purgeAsNeeded() into an infinite loop (e.g. // each resource destroyed creates and locks 2 resources and // unlocks 1 thereby causing a new purge). GrAssert(!fPurging); GrAutoResourceCacheValidate atcv(this); GrResourceEntry* entry = new GrResourceEntry(key, resource); // mark the entry as "busy" so it doesn't get purged // do this before attach for locked count tracking entry->lock(); this->attachToHead(entry, false); fCache.insert(key, entry); #if GR_DUMP_TEXTURE_UPLOAD GrPrintf("--- add resource to cache %p, count=%d bytes= %d %d\n", entry, fEntryCount, resource->sizeInBytes(), fEntryBytes); #endif this->purgeAsNeeded(); return entry; } void GrResourceCache::detach(GrResourceEntry* entry) { internalDetach(entry, true); fCache.remove(entry->fKey, entry); } void GrResourceCache::reattachAndUnlock(GrResourceEntry* entry) { attachToHead(entry, true); fCache.insert(entry->key(), entry); unlock(entry); } void GrResourceCache::unlock(GrResourceEntry* entry) { GrAutoResourceCacheValidate atcv(this); GrAssert(entry); GrAssert(entry->isLocked()); GrAssert(fCache.find(entry->key())); entry->unlock(); if (!entry->isLocked()) { ++fUnlockedEntryCount; } this->purgeAsNeeded(); } /** * Destroying a resource may potentially trigger the unlock of additional * resources which in turn will trigger a nested purge. We block the nested * purge using the fPurging variable. However, the initial purge will keep * looping until either all resources in the cache are unlocked or we've met * the budget. There is an assertion in createAndLock to check against a * resource's destructor inserting new resources into the cache. If these * new resources were unlocked before purgeAsNeeded completed it could * potentially make purgeAsNeeded loop infinitely. */ void GrResourceCache::purgeAsNeeded() { if (!fPurging) { fPurging = true; bool withinBudget = false; do { GrAutoResourceCacheValidate atcv(this); GrResourceEntry* entry = fTail; while (entry && fUnlockedEntryCount) { if (fEntryCount <= fMaxCount && fEntryBytes <= fMaxBytes) { withinBudget = true; break; } GrResourceEntry* prev = entry->fPrev; if (!entry->isLocked()) { // remove from our cache fCache.remove(entry->fKey, entry); // remove from our llist this->internalDetach(entry, false); #if GR_DUMP_TEXTURE_UPLOAD GrPrintf("--- ~resource from cache %p [%d %d]\n", entry->resource(), entry->resource()->width(), entry->resource()->height()); #endif delete entry; } entry = prev; } } while (!withinBudget && fUnlockedEntryCount); fPurging = false; } } void GrResourceCache::removeAll() { GrAssert(!fClientDetachedCount); GrAssert(!fClientDetachedBytes); GrResourceEntry* entry = fHead; while (entry) { GrAssert(!entry->isLocked()); GrResourceEntry* next = entry->fNext; delete entry; entry = next; } fCache.removeAll(); fHead = fTail = NULL; fEntryCount = 0; fEntryBytes = 0; fUnlockedEntryCount = 0; } /////////////////////////////////////////////////////////////////////////////// #if GR_DEBUG static int countMatches(const GrResourceEntry* head, const GrResourceEntry* target) { const GrResourceEntry* entry = head; int count = 0; while (entry) { if (target == entry) { count += 1; } entry = entry->next(); } return count; } #if GR_DEBUG static bool both_zero_or_nonzero(int count, size_t bytes) { return (count == 0 && bytes == 0) || (count > 0 && bytes > 0); } #endif void GrResourceCache::validate() const { GrAssert(!fHead == !fTail); GrAssert(both_zero_or_nonzero(fEntryCount, fEntryBytes)); GrAssert(both_zero_or_nonzero(fClientDetachedCount, fClientDetachedBytes)); GrAssert(fClientDetachedBytes <= fEntryBytes); GrAssert(fClientDetachedCount <= fEntryCount); GrAssert((fEntryCount - fClientDetachedCount) == fCache.count()); fCache.validate(); GrResourceEntry* entry = fHead; int count = 0; int unlockCount = 0; size_t bytes = 0; while (entry) { entry->validate(); GrAssert(fCache.find(entry->key())); count += 1; bytes += entry->resource()->sizeInBytes(); if (!entry->isLocked()) { unlockCount += 1; } entry = entry->fNext; } GrAssert(count == fEntryCount - fClientDetachedCount); GrAssert(bytes == fEntryBytes - fClientDetachedBytes); GrAssert(unlockCount == fUnlockedEntryCount); count = 0; for (entry = fTail; entry; entry = entry->fPrev) { count += 1; } GrAssert(count == fEntryCount - fClientDetachedCount); for (int i = 0; i < count; i++) { int matches = countMatches(fHead, fCache.getArray()[i]); GrAssert(1 == matches); } } #endif <commit_msg>Fix GrResourceCache::removeAll when one resource holds a lock on another<commit_after> /* * Copyright 2010 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrResourceCache.h" #include "GrResource.h" GrResourceEntry::GrResourceEntry(const GrResourceKey& key, GrResource* resource) : fKey(key), fResource(resource) { fLockCount = 0; fPrev = fNext = NULL; // we assume ownership of the resource, and will unref it when we die GrAssert(resource); } GrResourceEntry::~GrResourceEntry() { fResource->unref(); } #if GR_DEBUG void GrResourceEntry::validate() const { GrAssert(fLockCount >= 0); GrAssert(fResource); fResource->validate(); } #endif /////////////////////////////////////////////////////////////////////////////// GrResourceCache::GrResourceCache(int maxCount, size_t maxBytes) : fMaxCount(maxCount), fMaxBytes(maxBytes) { fEntryCount = 0; fUnlockedEntryCount = 0; fEntryBytes = 0; fClientDetachedCount = 0; fClientDetachedBytes = 0; fHead = fTail = NULL; fPurging = false; } GrResourceCache::~GrResourceCache() { GrAutoResourceCacheValidate atcv(this); this->removeAll(); } void GrResourceCache::getLimits(int* maxResources, size_t* maxResourceBytes) const{ if (maxResources) { *maxResources = fMaxCount; } if (maxResourceBytes) { *maxResourceBytes = fMaxBytes; } } void GrResourceCache::setLimits(int maxResources, size_t maxResourceBytes) { bool smaller = (maxResources < fMaxCount) || (maxResourceBytes < fMaxBytes); fMaxCount = maxResources; fMaxBytes = maxResourceBytes; if (smaller) { this->purgeAsNeeded(); } } void GrResourceCache::internalDetach(GrResourceEntry* entry, bool clientDetach) { GrResourceEntry* prev = entry->fPrev; GrResourceEntry* next = entry->fNext; if (prev) { prev->fNext = next; } else { fHead = next; } if (next) { next->fPrev = prev; } else { fTail = prev; } if (!entry->isLocked()) { --fUnlockedEntryCount; } // update our stats if (clientDetach) { fClientDetachedCount += 1; fClientDetachedBytes += entry->resource()->sizeInBytes(); } else { fEntryCount -= 1; fEntryBytes -= entry->resource()->sizeInBytes(); } } void GrResourceCache::attachToHead(GrResourceEntry* entry, bool clientReattach) { entry->fPrev = NULL; entry->fNext = fHead; if (fHead) { fHead->fPrev = entry; } fHead = entry; if (NULL == fTail) { fTail = entry; } if (!entry->isLocked()) { ++fUnlockedEntryCount; } // update our stats if (clientReattach) { fClientDetachedCount -= 1; fClientDetachedBytes -= entry->resource()->sizeInBytes(); } else { fEntryCount += 1; fEntryBytes += entry->resource()->sizeInBytes(); } } class GrResourceCache::Key { typedef GrResourceEntry T; const GrResourceKey& fKey; public: Key(const GrResourceKey& key) : fKey(key) {} uint32_t getHash() const { return fKey.hashIndex(); } static bool LT(const T& entry, const Key& key) { return entry.key() < key.fKey; } static bool EQ(const T& entry, const Key& key) { return entry.key() == key.fKey; } #if GR_DEBUG static uint32_t GetHash(const T& entry) { return entry.key().hashIndex(); } static bool LT(const T& a, const T& b) { return a.key() < b.key(); } static bool EQ(const T& a, const T& b) { return a.key() == b.key(); } #endif }; GrResourceEntry* GrResourceCache::findAndLock(const GrResourceKey& key, LockType type) { GrAutoResourceCacheValidate atcv(this); GrResourceEntry* entry = fCache.find(key); if (entry) { this->internalDetach(entry, false); // mark the entry as "busy" so it doesn't get purged // do this between detach and attach for locked count tracking if (kNested_LockType == type || !entry->isLocked()) { entry->lock(); } this->attachToHead(entry, false); } return entry; } GrResourceEntry* GrResourceCache::createAndLock(const GrResourceKey& key, GrResource* resource) { // we don't expect to create new resources during a purge. In theory // this could cause purgeAsNeeded() into an infinite loop (e.g. // each resource destroyed creates and locks 2 resources and // unlocks 1 thereby causing a new purge). GrAssert(!fPurging); GrAutoResourceCacheValidate atcv(this); GrResourceEntry* entry = new GrResourceEntry(key, resource); // mark the entry as "busy" so it doesn't get purged // do this before attach for locked count tracking entry->lock(); this->attachToHead(entry, false); fCache.insert(key, entry); #if GR_DUMP_TEXTURE_UPLOAD GrPrintf("--- add resource to cache %p, count=%d bytes= %d %d\n", entry, fEntryCount, resource->sizeInBytes(), fEntryBytes); #endif this->purgeAsNeeded(); return entry; } void GrResourceCache::detach(GrResourceEntry* entry) { GrAutoResourceCacheValidate atcv(this); internalDetach(entry, true); fCache.remove(entry->fKey, entry); } void GrResourceCache::reattachAndUnlock(GrResourceEntry* entry) { attachToHead(entry, true); fCache.insert(entry->key(), entry); unlock(entry); } void GrResourceCache::unlock(GrResourceEntry* entry) { GrAutoResourceCacheValidate atcv(this); GrAssert(entry); GrAssert(entry->isLocked()); GrAssert(fCache.find(entry->key())); entry->unlock(); if (!entry->isLocked()) { ++fUnlockedEntryCount; } this->purgeAsNeeded(); } /** * Destroying a resource may potentially trigger the unlock of additional * resources which in turn will trigger a nested purge. We block the nested * purge using the fPurging variable. However, the initial purge will keep * looping until either all resources in the cache are unlocked or we've met * the budget. There is an assertion in createAndLock to check against a * resource's destructor inserting new resources into the cache. If these * new resources were unlocked before purgeAsNeeded completed it could * potentially make purgeAsNeeded loop infinitely. */ void GrResourceCache::purgeAsNeeded() { if (!fPurging) { fPurging = true; bool withinBudget = false; do { GrResourceEntry* entry = fTail; while (entry && fUnlockedEntryCount) { GrAutoResourceCacheValidate atcv(this); if (fEntryCount <= fMaxCount && fEntryBytes <= fMaxBytes) { withinBudget = true; break; } GrResourceEntry* prev = entry->fPrev; if (!entry->isLocked()) { // remove from our cache fCache.remove(entry->fKey, entry); // remove from our llist this->internalDetach(entry, false); #if GR_DUMP_TEXTURE_UPLOAD GrPrintf("--- ~resource from cache %p [%d %d]\n", entry->resource(), entry->resource()->width(), entry->resource()->height()); #endif delete entry; } entry = prev; } } while (!withinBudget && fUnlockedEntryCount); fPurging = false; } } void GrResourceCache::removeAll() { GrAutoResourceCacheValidate atcv(this); GrAssert(!fClientDetachedCount); GrAssert(!fClientDetachedBytes); GrResourceEntry* entry = fHead; // we can have one GrResource holding a lock on another // so we don't want to just do a simple loop kicking each // entry out. Instead change the budget and purge. int savedMaxBytes = fMaxBytes; int savedMaxCount = fMaxCount; fMaxBytes = -1; fMaxCount = 0; this->purgeAsNeeded(); GrAssert(!fCache.count()); GrAssert(!fUnlockedEntryCount); GrAssert(!fEntryCount); GrAssert(!fEntryBytes); GrAssert(NULL == fHead); GrAssert(NULL == fTail); fMaxBytes = savedMaxBytes; fMaxCount = savedMaxCount; } /////////////////////////////////////////////////////////////////////////////// #if GR_DEBUG static int countMatches(const GrResourceEntry* head, const GrResourceEntry* target) { const GrResourceEntry* entry = head; int count = 0; while (entry) { if (target == entry) { count += 1; } entry = entry->next(); } return count; } #if GR_DEBUG static bool both_zero_or_nonzero(int count, size_t bytes) { return (count == 0 && bytes == 0) || (count > 0 && bytes > 0); } #endif void GrResourceCache::validate() const { GrAssert(!fHead == !fTail); GrAssert(both_zero_or_nonzero(fEntryCount, fEntryBytes)); GrAssert(both_zero_or_nonzero(fClientDetachedCount, fClientDetachedBytes)); GrAssert(fClientDetachedBytes <= fEntryBytes); GrAssert(fClientDetachedCount <= fEntryCount); GrAssert((fEntryCount - fClientDetachedCount) == fCache.count()); fCache.validate(); GrResourceEntry* entry = fHead; int count = 0; int unlockCount = 0; size_t bytes = 0; while (entry) { entry->validate(); GrAssert(fCache.find(entry->key())); count += 1; bytes += entry->resource()->sizeInBytes(); if (!entry->isLocked()) { unlockCount += 1; } entry = entry->fNext; } GrAssert(count == fEntryCount - fClientDetachedCount); GrAssert(bytes == fEntryBytes - fClientDetachedBytes); GrAssert(unlockCount == fUnlockedEntryCount); count = 0; for (entry = fTail; entry; entry = entry->fPrev) { count += 1; } GrAssert(count == fEntryCount - fClientDetachedCount); for (int i = 0; i < count; i++) { int matches = countMatches(fHead, fCache.getArray()[i]); GrAssert(1 == matches); } } #endif <|endoftext|>
<commit_before>/** extra.hpp - Support file for writing LV2 plugins in C++ Copyright (C) 2012 Michael Fisher <mfisher31@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307 USA */ /** @extra.hpp C++ convenience header for the LV2 extra extensions. This covers extensions that aren't in the LV2 Specification officially */ #ifndef LV2_XXX_HPP #define LV2_XXX_HPP #include <lv2mm/types.hpp> namespace LV2 { /** The fixed buffer size extension. A host that supports this will always call the plugin's run() function with the same @c sample_count parameter, which will be equal to the value returned by I::get_buffer_size(). The actual type that your plugin class will inherit when you use this mixin is the internal struct template I. @ingroup pluginmixins */ LV2MM_MIXIN_CLASS FixedBufSize { /** This is the type that your plugin class will inherit when you use the FixedBufSize mixin. The public and protected members defined here will be available in your plugin class. */ LV2MM_MIXIN_DERIVED { I() : m_buffer_size(0) { } /** @internal */ static void map_feature_handlers(FeatureHandlerMap& hmap) { hmap["http://tapas.affenbande.org/lv2/ext/fixed-buffersize"] = &I<Derived>::handle_feature; } /** @internal */ static void handle_feature(void* instance, void* data) { Derived* d = reinterpret_cast<Derived*>(instance); I<Derived>* fe = static_cast<I<Derived>*>(d); fe->m_buffer_size = *reinterpret_cast<uint32_t*>(data); if (LV2MM_DEBUG) { std::clog<<" [LV2::FixedBufSize] Host set buffer size to " <<fe->m_buffer_size<<std::endl; } fe->m_ok = true; } bool check_ok() { if (LV2MM_DEBUG) { std::clog<<" [LV2::FixedBufSize] Validation " <<(this->m_ok ? "succeeded" : "failed")<<"."<<std::endl; } return this->m_ok; } protected: /** This returns the buffer size that the host has promised to use. If the host does not support this extension this function will return 0. */ uint32_t get_buffer_size() const { return m_buffer_size; } uint32_t m_buffer_size; }; }; /** The fixed power-of-2 buffer size extension. This works just like FixedBufSize with the additional requirement that the buffer size must be a power of 2. The actual type that your plugin class will inherit when you use this mixin is the internal struct template I. @ingroup pluginmixins */ LV2MM_MIXIN_CLASS FixedP2BufSize { /** This is the type that your plugin class will inherit when you use the FixedP2BufSize mixin. The public and protected members defined here will be available in your plugin class. */ LV2MM_MIXIN_DERIVED { I() : m_buffer_size(0) { } /** @internal */ static void map_feature_handlers(FeatureHandlerMap& hmap) { hmap["http://tapas.affenbande.org/lv2/ext/power-of-two-buffersize"] = &I<Derived>::handle_feature; } /** @internal */ static void handle_feature(void* instance, void* data) { Derived* d = reinterpret_cast<Derived*>(instance); I<Derived>* fe = static_cast<I<Derived>*>(d); fe->m_buffer_size = *reinterpret_cast<uint32_t*>(data); if (LV2MM_DEBUG) { std::clog<<" [LV2::FixedP2BufSize] Host set buffer size to " <<fe->m_buffer_size<<std::endl; } fe->m_ok = true; } bool check_ok() { if (LV2MM_DEBUG) { std::clog<<" [LV2::FixedP2BufSize] Validation " <<(this->m_ok ? "succeeded" : "failed")<<"."<<std::endl; } return this->m_ok; } protected: /** This returns the buffer size that the host has promised to use. If the host does not support this extension this function will return 0. */ uint32_t get_buffer_size() const { return m_buffer_size; } uint32_t m_buffer_size; }; }; /** The save/restore extension. The actual type that your plugin class will inherit when you use this mixin is the internal struct template I. @ingroup pluginmixins */ LV2MM_MIXIN_CLASS SaveRestore { /** This is the type that your plugin class will inherit when you use the SaveRestore mixin. The public and protected members defined here will be available in your plugin class. */ LV2MM_MIXIN_DERIVED { /** @internal */ static void map_feature_handlers(FeatureHandlerMap& hmap) { hmap[LV2_SAVERESTORE_URI] = &I<Derived>::handle_feature; } /** @internal */ static void handle_feature(void* instance, void* data) { Derived* d = reinterpret_cast<Derived*>(instance); I<Derived>* fe = static_cast<I<Derived>*>(d); fe->m_ok = true; } bool check_ok() { if (LV2MM_DEBUG) { std::clog<<" [LV2::SaveRestore] Validation " <<(this->m_ok ? "succeeded" : "failed")<<"."<<std::endl; } return this->m_ok; } /** @internal */ static const void* extension_data(const char* uri) { if (!std::strcmp(uri, LV2_SAVERESTORE_URI)) { static LV2SR_Descriptor srdesc = { &I<Derived>::_save, &I<Derived>::_restore }; return &srdesc; } return 0; } /** This function is called by the host when it wants to save the current state of the plugin. You should override it. @param directory A filesystem path to a directory where the plugin should write any files it creates while saving. @param files A pointer to a NULL-terminated array of @c LV2SR_File pointers. The plugin should set @c *files to point to the first element in a dynamically allocated array of @c LV2SR_File pointers to (also dynamically allocated) @c LV2SR_File objects, listing the files to which the internal state of the plugin instance has been saved. These objects, and the array, will be freed by the host. */ char* save(const char* directory, LV2SR_File*** files) { return 0; } /** This function is called by the host when it wants to restore the plugin to a previous state. You should override it. @param files An array of pointers to @c LV2SR_File objects, listing the files from which the internal state of the plugin instance should be restored. */ char* restore(const LV2SR_File** files) { return 0; } protected: /** @internal Static callback wrapper. */ static char* _save(LV2_Handle h, const char* directory, LV2SR_File*** files) { if (LV2MM_DEBUG) { std::clog<<"[LV2::SaveRestore] Host called save().\n" <<" directory: \""<<directory<<"\""<<std::endl; } return reinterpret_cast<Derived*>(h)->save(directory, files); } /** @internal Static callback wrapper. */ static char* _restore(LV2_Handle h, const LV2SR_File** files) { if (LV2MM_DEBUG) { std::clog<<"[LV2::SaveRestore] Host called restore().\n" <<" Files:\n"; for (LV2SR_File const** f = files; (*f) != 0; ++f) std::clog<<" \""<<(*f)->name<<"\" -> \""<<(*f)->path<<"\"\n"; std::clog<<std::flush; } return reinterpret_cast<Derived*>(h)->restore(files); } }; }; /** @internal The message context extension. Experimental and unsupported. Don't use it. The actual type that your plugin class will inherit when you use this mixin is the internal struct template I. @ingroup pluginmixins */ LV2MM_MIXIN_CLASS MsgContext { /** This is the type that your plugin class will inherit when you use the MsgContext mixin. The public and protected members defined here will be available in your plugin class. */ LV2MM_MIXIN_DERIVED { /** @internal */ static void map_feature_handlers(FeatureHandlerMap& hmap) { hmap[LV2_CONTEXT_MESSAGE] = &I<Derived>::handle_feature; } /** @internal */ static void handle_feature(void* instance, void* data) { Derived* d = reinterpret_cast<Derived*>(instance); I<Derived>* fe = static_cast<I<Derived>*>(d); fe->m_ok = true; } bool check_ok() { if (LV2MM_DEBUG) { std::clog<<" [LV2::MsgContext] Validation " <<(this->m_ok ? "succeeded" : "failed")<<"."<<std::endl; } return this->m_ok; } /** @internal */ static const void* extension_data(const char* uri) { if (!std::strcmp(uri, LV2_CONTEXT_MESSAGE)) { static LV2_Blocking_Context desc = { &I<Derived>::_blocking_run, &I<Derived>::_connect_port }; return &desc; } return 0; } /** @internal This is called by the host when the plugin's message context is executed. Experimental and unsupported. Don't use it. */ bool blocking_run(uint8_t* outputs_written) { return false; } protected: /** @internal Static callback wrapper. */ static bool _blocking_run(LV2_Handle h, uint8_t* outputs_written) { if (LV2MM_DEBUG) std::clog<<"[LV2::MsgContext] Host called blocking_run()."<<std::endl; return reinterpret_cast<Derived*>(h)->blocking_run(outputs_written); } /** @internal Static callback wrapper. */ static void _connect_port(LV2_Handle h, uint32_t port, void* buffer) { reinterpret_cast<Derived*>(h)->connect_port(port, buffer); } }; }; } /* namespace LV2 */ #endif /* LV2_XXX_HPP */ <commit_msg>Disable extra.hpp unless LV2MM_EXTRA_ENABLED is defined<commit_after>/** extra.hpp - Support file for writing LV2 plugins in C++ Copyright (C) 2012 Michael Fisher <mfisher31@gmail.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307 USA */ /** @extra.hpp C++ convenience header for the LV2 extra extensions. This covers extensions that aren't in the LV2 Specification officially, Many of these are more than likely broken. */ #ifndef LV2_EXTRA_HPP #define LV2_EXTRA_HPP #if defined (LV2MM_EXTRA_ENABLED) #include <lv2mm/types.hpp> namespace LV2 { /** @internal A mixin that allows easy sending of OSC from GUI to plugin. The actual type that your plugin class will inherit when you use this mixin is the internal struct template I. Do NOT use this. It may change in the future. @ingroup guimixins */ LV2MM_MIXIN_CLASS WriteOSC { /** This is the type that your plugin or GUI class will inherit when you use the WriteOSC mixin. The public and protected members defined here will be available in your plugin class. */ LV2MM_MIXIN_DERIVED { I() : m_osc_type(0) { m_buffer = lv2_event_buffer_new(sizeof(LV2_Event) + 256, 0); } bool check_ok() { Derived* d = static_cast<Derived*>(this); m_osc_type = d-> uri_to_id(LV2_EVENT_URI, "http://lv2plug.in/ns/ext/osc#OscEvent"); m_event_buffer_format = d-> uri_to_id(LV2_UI_URI, "http://lv2plug.in/ns/extensions/ui#Events"); return !Required || (m_osc_type && m_event_buffer_format); } protected: bool write_osc(uint32_t port, const char* path, const char* types, ...) { if (m_osc_type == 0) return false; // XXX handle all sizes here - this is dangerous lv2_event_buffer_reset(m_buffer, 0, m_buffer->data); LV2_Event_Iterator iter; lv2_event_begin(&iter, m_buffer); va_list ap; va_start(ap, types); uint32_t size = lv2_osc_event_vsize(path, types, ap); va_end(ap); if (!size) return false; va_start(ap, types); bool success = lv2_osc_buffer_vappend(&iter, 0, 0, m_osc_type, path, types, size, ap); va_end(ap); if (success) { static_cast<Derived*>(this)-> write(port, m_buffer->header_size + m_buffer->capacity, m_event_buffer_format, m_buffer); return true; } return false; } uint32_t m_osc_type; uint32_t m_event_buffer_format; LV2_Event_Buffer* m_buffer; }; }; /** Preset GUI extension - the host will tell the GUI what presets are available and which one of them is currently active, the GUI can request saving and using presets. The actual type that your plugin class will inherit when you use this mixin is the internal struct template I. @ingroup guimixins */ LV2MM_MIXIN_CLASS Presets { /** This is the type that your plugin or GUI class will inherit when you use the Presets mixin. The public and protected members defined here will be available in your plugin class. */ LV2MM_MIXIN_DERIVED { I() : m_hdesc(0), m_host_support(false) { } /** @internal */ static void map_feature_handlers(FeatureHandlerMap& hmap) { hmap[LV2_UI_PRESETS_URI] = &I<Derived>::handle_feature; } /** @internal */ static void handle_feature(void* instance, void* data) { Derived* d = reinterpret_cast<Derived*>(instance); I<Derived>* e = static_cast<I<Derived>*>(d); e->m_hdesc = static_cast<LV2UI_Presets_Feature*>(data); e->m_ok = (e->m_hdesc != 0); e->m_host_support = (e->m_hdesc != 0); } bool check_ok() { if (LV2MM_DEBUG) { std::clog<<" [LV2::Presets] Validation " <<(this->m_ok ? "succeeded" : "failed")<<"."<<std::endl; } return this->m_ok; } /** This is called by the host to let the GUI know that a new preset has been added or renamed. @param number The number of the added preset. @param name The name of the added preset. */ void preset_added(uint32_t number, char const* name) { } /** This is called by the host to let the GUI know that a previously existing preset has been removed. @param number The number of the removed preset. */ void preset_removed(uint32_t number) { } /** This is called by the host to let the GUI know that all previously existing presets have been removed. */ void presets_cleared() { } /** This is called by the host to let the GUI know that the current preset has changed. If the number is equal to @c LV2_UI_PRESETS_NOPRESET there is no current preset. @param number The number of the active preset, or LV2_UI_PRESETS_NOPRESET if there is no active preset. */ void current_preset_changed(uint32_t number) { } /** @internal Returns the plugin descriptor for this extension. */ static void const* extension_data(char const* uri) { static LV2UI_Presets_GDesc desc = { &_preset_added, &_preset_removed, &_presets_cleared, &_current_preset_changed }; if (!std::strcmp(uri, LV2_UI_PRESETS_URI)) return &desc; return 0; } protected: /** You can call this to request that the host changes the current preset to @c preset. */ void change_preset(uint32_t preset) { if (m_hdesc) { if (LV2MM_DEBUG) { std::clog<<"[LV2::Presets] change_preset("<<preset<<")" <<std::endl; } m_hdesc->change_preset(static_cast<Derived*>(this)->controller(), preset); } else if (LV2MM_DEBUG) { std::clog<<"[LV2::Presets] change_preset("<<preset<<")" <<" --- Function not provided by host!"<<std::endl; } } /** You can call this to request that the host saves the current state of the plugin instance to a preset with the given number and name. */ void save_preset(uint32_t preset, char const* name) { if (m_hdesc) { if (LV2MM_DEBUG) { std::clog<<"[LV2::Presets] save_preset("<<preset<<", \"" <<name<<"\")"<<std::endl; } m_hdesc->save_preset(static_cast<Derived*>(this)->controller(), preset, name); } else if (LV2MM_DEBUG) { std::clog<<"[LV2::Presets] save_preset("<<preset<<", \"" <<name<<"\")" <<" --- Function not provided by host!"<<std::endl; } } /** Returns @c true if the host supports the Preset feature, @c false if it does not. */ bool host_supports_presets() const { return m_host_support; } private: static void _preset_added(LV2UI_Handle gui, uint32_t number, char const* name) { if (LV2MM_DEBUG) { std::clog<<"[LV2::Presets] Host called preset_added(" <<number<<", \""<<name<<"\")."<<std::endl; } static_cast<Derived*>(gui)->preset_added(number, name); } static void _preset_removed(LV2UI_Handle gui, uint32_t number) { if (LV2MM_DEBUG) { std::clog<<"[LV2::Presets] Host called preset_removed(" <<number<<")."<<std::endl; } static_cast<Derived*>(gui)->preset_removed(number); } static void _presets_cleared(LV2UI_Handle gui) { if (LV2MM_DEBUG) { std::clog<<"[LV2::Presets] Host called presets_cleared()." <<std::endl; } static_cast<Derived*>(gui)->presets_cleared(); } static void _current_preset_changed(LV2UI_Handle gui, uint32_t number) { if (LV2MM_DEBUG) { std::clog<<"[LV2::Presets] Host called current_preset_changed(" <<number<<")."<<std::endl; } static_cast<Derived*>(gui)->current_preset_changed(number); } LV2UI_Presets_Feature* m_hdesc; bool m_host_support; }; }; /** The fixed buffer size extension. A host that supports this will always call the plugin's run() function with the same @c sample_count parameter, which will be equal to the value returned by I::get_buffer_size(). The actual type that your plugin class will inherit when you use this mixin is the internal struct template I. @ingroup pluginmixins */ LV2MM_MIXIN_CLASS FixedBufSize { /** This is the type that your plugin class will inherit when you use the FixedBufSize mixin. The public and protected members defined here will be available in your plugin class. */ LV2MM_MIXIN_DERIVED { I() : m_buffer_size(0) { } /** @internal */ static void map_feature_handlers(FeatureHandlerMap& hmap) { hmap["http://tapas.affenbande.org/lv2/ext/fixed-buffersize"] = &I<Derived>::handle_feature; } /** @internal */ static void handle_feature(void* instance, void* data) { Derived* d = reinterpret_cast<Derived*>(instance); I<Derived>* fe = static_cast<I<Derived>*>(d); fe->m_buffer_size = *reinterpret_cast<uint32_t*>(data); if (LV2MM_DEBUG) { std::clog<<" [LV2::FixedBufSize] Host set buffer size to " <<fe->m_buffer_size<<std::endl; } fe->m_ok = true; } bool check_ok() { if (LV2MM_DEBUG) { std::clog<<" [LV2::FixedBufSize] Validation " <<(this->m_ok ? "succeeded" : "failed")<<"."<<std::endl; } return this->m_ok; } protected: /** This returns the buffer size that the host has promised to use. If the host does not support this extension this function will return 0. */ uint32_t get_buffer_size() const { return m_buffer_size; } uint32_t m_buffer_size; }; }; /** The fixed power-of-2 buffer size extension. This works just like FixedBufSize with the additional requirement that the buffer size must be a power of 2. The actual type that your plugin class will inherit when you use this mixin is the internal struct template I. @ingroup pluginmixins */ LV2MM_MIXIN_CLASS FixedP2BufSize { /** This is the type that your plugin class will inherit when you use the FixedP2BufSize mixin. The public and protected members defined here will be available in your plugin class. */ LV2MM_MIXIN_DERIVED { I() : m_buffer_size(0) { } /** @internal */ static void map_feature_handlers(FeatureHandlerMap& hmap) { hmap["http://tapas.affenbande.org/lv2/ext/power-of-two-buffersize"] = &I<Derived>::handle_feature; } /** @internal */ static void handle_feature(void* instance, void* data) { Derived* d = reinterpret_cast<Derived*>(instance); I<Derived>* fe = static_cast<I<Derived>*>(d); fe->m_buffer_size = *reinterpret_cast<uint32_t*>(data); if (LV2MM_DEBUG) { std::clog<<" [LV2::FixedP2BufSize] Host set buffer size to " <<fe->m_buffer_size<<std::endl; } fe->m_ok = true; } bool check_ok() { if (LV2MM_DEBUG) { std::clog<<" [LV2::FixedP2BufSize] Validation " <<(this->m_ok ? "succeeded" : "failed")<<"."<<std::endl; } return this->m_ok; } protected: /** This returns the buffer size that the host has promised to use. If the host does not support this extension this function will return 0. */ uint32_t get_buffer_size() const { return m_buffer_size; } uint32_t m_buffer_size; }; }; /** The save/restore extension. The actual type that your plugin class will inherit when you use this mixin is the internal struct template I. @ingroup pluginmixins */ LV2MM_MIXIN_CLASS SaveRestore { /** This is the type that your plugin class will inherit when you use the SaveRestore mixin. The public and protected members defined here will be available in your plugin class. */ LV2MM_MIXIN_DERIVED { /** @internal */ static void map_feature_handlers(FeatureHandlerMap& hmap) { hmap[LV2_SAVERESTORE_URI] = &I<Derived>::handle_feature; } /** @internal */ static void handle_feature(void* instance, void* data) { Derived* d = reinterpret_cast<Derived*>(instance); I<Derived>* fe = static_cast<I<Derived>*>(d); fe->m_ok = true; } bool check_ok() { if (LV2MM_DEBUG) { std::clog<<" [LV2::SaveRestore] Validation " <<(this->m_ok ? "succeeded" : "failed")<<"."<<std::endl; } return this->m_ok; } /** @internal */ static const void* extension_data(const char* uri) { if (!std::strcmp(uri, LV2_SAVERESTORE_URI)) { static LV2SR_Descriptor srdesc = { &I<Derived>::_save, &I<Derived>::_restore }; return &srdesc; } return 0; } /** This function is called by the host when it wants to save the current state of the plugin. You should override it. @param directory A filesystem path to a directory where the plugin should write any files it creates while saving. @param files A pointer to a NULL-terminated array of @c LV2SR_File pointers. The plugin should set @c *files to point to the first element in a dynamically allocated array of @c LV2SR_File pointers to (also dynamically allocated) @c LV2SR_File objects, listing the files to which the internal state of the plugin instance has been saved. These objects, and the array, will be freed by the host. */ char* save(const char* directory, LV2SR_File*** files) { return 0; } /** This function is called by the host when it wants to restore the plugin to a previous state. You should override it. @param files An array of pointers to @c LV2SR_File objects, listing the files from which the internal state of the plugin instance should be restored. */ char* restore(const LV2SR_File** files) { return 0; } protected: /** @internal Static callback wrapper. */ static char* _save(LV2_Handle h, const char* directory, LV2SR_File*** files) { if (LV2MM_DEBUG) { std::clog<<"[LV2::SaveRestore] Host called save().\n" <<" directory: \""<<directory<<"\""<<std::endl; } return reinterpret_cast<Derived*>(h)->save(directory, files); } /** @internal Static callback wrapper. */ static char* _restore(LV2_Handle h, const LV2SR_File** files) { if (LV2MM_DEBUG) { std::clog<<"[LV2::SaveRestore] Host called restore().\n" <<" Files:\n"; for (LV2SR_File const** f = files; (*f) != 0; ++f) std::clog<<" \""<<(*f)->name<<"\" -> \""<<(*f)->path<<"\"\n"; std::clog<<std::flush; } return reinterpret_cast<Derived*>(h)->restore(files); } }; }; /** @internal The message context extension. Experimental and unsupported. Don't use it. The actual type that your plugin class will inherit when you use this mixin is the internal struct template I. @ingroup pluginmixins */ LV2MM_MIXIN_CLASS MsgContext { /** This is the type that your plugin class will inherit when you use the MsgContext mixin. The public and protected members defined here will be available in your plugin class. */ LV2MM_MIXIN_DERIVED { /** @internal */ static void map_feature_handlers(FeatureHandlerMap& hmap) { hmap[LV2_CONTEXT_MESSAGE] = &I<Derived>::handle_feature; } /** @internal */ static void handle_feature(void* instance, void* data) { Derived* d = reinterpret_cast<Derived*>(instance); I<Derived>* fe = static_cast<I<Derived>*>(d); fe->m_ok = true; } bool check_ok() { if (LV2MM_DEBUG) { std::clog<<" [LV2::MsgContext] Validation " <<(this->m_ok ? "succeeded" : "failed")<<"."<<std::endl; } return this->m_ok; } /** @internal */ static const void* extension_data(const char* uri) { if (!std::strcmp(uri, LV2_CONTEXT_MESSAGE)) { static LV2_Blocking_Context desc = { &I<Derived>::_blocking_run, &I<Derived>::_connect_port }; return &desc; } return 0; } /** @internal This is called by the host when the plugin's message context is executed. Experimental and unsupported. Don't use it. */ bool blocking_run(uint8_t* outputs_written) { return false; } protected: /** @internal Static callback wrapper. */ static bool _blocking_run(LV2_Handle h, uint8_t* outputs_written) { if (LV2MM_DEBUG) std::clog<<"[LV2::MsgContext] Host called blocking_run()."<<std::endl; return reinterpret_cast<Derived*>(h)->blocking_run(outputs_written); } /** @internal Static callback wrapper. */ static void _connect_port(LV2_Handle h, uint32_t port, void* buffer) { reinterpret_cast<Derived*>(h)->connect_port(port, buffer); } }; }; } /* namespace LV2 */ #endif #endif /* LV2_EXTRA_HPP */ <|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 <vcl/svapp.hxx> #include "svx/connctrl.hxx" #include "svx/dlgutil.hxx" #include <svx/dialmgr.hxx> #include <svx/sdr/contact/displayinfo.hxx> #include <svx/sdr/contact/objectcontactofobjlistpainter.hxx> #include <svx/svdmark.hxx> #include <svx/svdoedge.hxx> #include <svx/svdpage.hxx> #include <svx/svdview.hxx> #include <svx/sxelditm.hxx> #include <svx/sxmkitm.hxx> #include <vcl/builder.hxx> SvxXConnectionPreview::SvxXConnectionPreview( Window* pParent, WinBits nStyle) : Control(pParent, nStyle) , pEdgeObj(NULL) , pObjList(NULL) , pView(NULL) { SetMapMode( MAP_100TH_MM ); SetStyles(); } extern "C" SAL_DLLPUBLIC_EXPORT Window* SAL_CALL makeSvxXConnectionPreview(Window *pParent, VclBuilder::stringmap &rMap) { WinBits nWinStyle = 0; OString sBorder = VclBuilder::extractCustomProperty(rMap); if (!sBorder.isEmpty()) nWinStyle |= WB_BORDER; return new SvxXConnectionPreview(pParent, nWinStyle); } SvxXConnectionPreview::~SvxXConnectionPreview() { delete pObjList; } void SvxXConnectionPreview::Resize() { Control::Resize(); AdaptSize(); Invalidate(); } Size SvxXConnectionPreview::GetOptimalSize() const { return LogicToPixel(Size(118 , 121), MapMode(MAP_APPFONT)); } void SvxXConnectionPreview::AdaptSize() { // Adapt size if( pObjList ) { SetMapMode( MAP_100TH_MM ); OutputDevice* pOD = pView->GetFirstOutputDevice(); // GetWin( 0 ); Rectangle aRect = pObjList->GetAllObjBoundRect(); MapMode aMapMode = GetMapMode(); aMapMode.SetMapUnit( pOD->GetMapMode().GetMapUnit() ); SetMapMode( aMapMode ); MapMode aDisplayMap( aMapMode ); Point aNewPos; Size aNewSize; const Size aWinSize = PixelToLogic( GetOutputSizePixel(), aDisplayMap ); const long nWidth = aWinSize.Width(); const long nHeight = aWinSize.Height(); double fRectWH = (double) aRect.GetWidth() / aRect.GetHeight(); double fWinWH = (double) nWidth / nHeight; // Adapt bitmap to Thumb size (not here!) if ( fRectWH < fWinWH) { aNewSize.Width() = (long) ( (double) nHeight * fRectWH ); aNewSize.Height()= nHeight; } else { aNewSize.Width() = nWidth; aNewSize.Height()= (long) ( (double) nWidth / fRectWH ); } Fraction aFrac1( aWinSize.Width(), aRect.GetWidth() ); Fraction aFrac2( aWinSize.Height(), aRect.GetHeight() ); Fraction aMinFrac( aFrac1 <= aFrac2 ? aFrac1 : aFrac2 ); // Implement MapMode aDisplayMap.SetScaleX( aMinFrac ); aDisplayMap.SetScaleY( aMinFrac ); // Centering aNewPos.X() = ( nWidth - aNewSize.Width() ) >> 1; aNewPos.Y() = ( nHeight - aNewSize.Height() ) >> 1; aDisplayMap.SetOrigin( LogicToLogic( aNewPos, aMapMode, aDisplayMap ) ); SetMapMode( aDisplayMap ); // Origin aNewPos = aDisplayMap.GetOrigin(); aNewPos -= Point( aRect.TopLeft().X(), aRect.TopLeft().Y() ); aDisplayMap.SetOrigin( aNewPos ); SetMapMode( aDisplayMap ); Point aPos; MouseEvent aMEvt( aPos, 1, 0, MOUSE_RIGHT ); MouseButtonDown( aMEvt ); } } void SvxXConnectionPreview::Construct() { DBG_ASSERT( pView, "No valid view is passed on! "); const SdrMarkList& rMarkList = pView->GetMarkedObjectList(); sal_uIntPtr nMarkCount = rMarkList.GetMarkCount(); if( nMarkCount >= 1 ) { bool bFound = false; const SdrObject* pObj = rMarkList.GetMark(0)->GetMarkedSdrObj(); for( sal_uInt16 i = 0; i < nMarkCount && !bFound; i++ ) { pObj = rMarkList.GetMark( i )->GetMarkedSdrObj(); sal_uInt32 nInv = pObj->GetObjInventor(); sal_uInt16 nId = pObj->GetObjIdentifier(); if( nInv == SdrInventor && nId == OBJ_EDGE ) { bFound = true; SdrEdgeObj* pTmpEdgeObj = (SdrEdgeObj*) pObj; pEdgeObj = (SdrEdgeObj*) pTmpEdgeObj->Clone(); SdrObjConnection& rConn1 = (SdrObjConnection&)pEdgeObj->GetConnection( true ); SdrObjConnection& rConn2 = (SdrObjConnection&)pEdgeObj->GetConnection( false ); rConn1 = pTmpEdgeObj->GetConnection( true ); rConn2 = pTmpEdgeObj->GetConnection( false ); SdrObject* pTmpObj1 = pTmpEdgeObj->GetConnectedNode( true ); SdrObject* pTmpObj2 = pTmpEdgeObj->GetConnectedNode( false ); // potential memory leak here (!). Create SdrObjList only when there is // not yet one. if(!pObjList) { pObjList = new SdrObjList( pView->GetModel(), NULL ); } if( pTmpObj1 ) { SdrObject* pObj1 = pTmpObj1->Clone(); pObjList->InsertObject( pObj1 ); pEdgeObj->ConnectToNode( true, pObj1 ); } if( pTmpObj2 ) { SdrObject* pObj2 = pTmpObj2->Clone(); pObjList->InsertObject( pObj2 ); pEdgeObj->ConnectToNode( false, pObj2 ); } pObjList->InsertObject( pEdgeObj ); } } } if( !pEdgeObj ) pEdgeObj = new SdrEdgeObj(); AdaptSize(); } void SvxXConnectionPreview::Paint( const Rectangle& ) { if( pObjList ) { // #110094# // This will not work anymore. To not start at Adam and Eve, i will // ATM not try to change all this stuff to really using an own model // and a view. I will just try to provide a mechanism to paint such // objects without own model and without a page/view with the new // mechanism. // New stuff: Use a ObjectContactOfObjListPainter. sdr::contact::SdrObjectVector aObjectVector; for(sal_uInt32 a(0L); a < pObjList->GetObjCount(); a++) { SdrObject* pObject = pObjList->GetObj(a); DBG_ASSERT(pObject, "SvxXConnectionPreview::Paint: Corrupt ObjectList (!)"); aObjectVector.push_back(pObject); } sdr::contact::ObjectContactOfObjListPainter aPainter(*this, aObjectVector, 0); sdr::contact::DisplayInfo aDisplayInfo; // do processing aPainter.ProcessDisplay(aDisplayInfo); } } void SvxXConnectionPreview::SetAttributes( const SfxItemSet& rInAttrs ) { pEdgeObj->SetMergedItemSetAndBroadcast(rInAttrs); Invalidate(); } // Get number of lines which are offset based on the preview object sal_uInt16 SvxXConnectionPreview::GetLineDeltaAnz() { const SfxItemSet& rSet = pEdgeObj->GetMergedItemSet(); sal_uInt16 nCount(0); if(SFX_ITEM_DONTCARE != rSet.GetItemState(SDRATTR_EDGELINEDELTAANZ)) nCount = ((const SdrEdgeLineDeltaAnzItem&)rSet.Get(SDRATTR_EDGELINEDELTAANZ)).GetValue(); return nCount; } void SvxXConnectionPreview::MouseButtonDown( const MouseEvent& rMEvt ) { bool bZoomIn = rMEvt.IsLeft() && !rMEvt.IsShift(); bool bZoomOut = rMEvt.IsRight() || rMEvt.IsShift(); bool bCtrl = rMEvt.IsMod1(); if( bZoomIn || bZoomOut ) { MapMode aMapMode = GetMapMode(); Fraction aXFrac = aMapMode.GetScaleX(); Fraction aYFrac = aMapMode.GetScaleY(); Fraction* pMultFrac; if( bZoomIn ) { if( bCtrl ) pMultFrac = new Fraction( 3, 2 ); else pMultFrac = new Fraction( 11, 10 ); } else { if( bCtrl ) pMultFrac = new Fraction( 2, 3 ); else pMultFrac = new Fraction( 10, 11 ); } aXFrac *= *pMultFrac; aYFrac *= *pMultFrac; if( (double)aXFrac > 0.001 && (double)aXFrac < 1000.0 && (double)aYFrac > 0.001 && (double)aYFrac < 1000.0 ) { aMapMode.SetScaleX( aXFrac ); aMapMode.SetScaleY( aYFrac ); SetMapMode( aMapMode ); Size aOutSize( GetOutputSize() ); Point aPt( aMapMode.GetOrigin() ); long nX = (long)( ( (double)aOutSize.Width() - ( (double)aOutSize.Width() * (double)*pMultFrac ) ) / 2.0 + 0.5 ); long nY = (long)( ( (double)aOutSize.Height() - ( (double)aOutSize.Height() * (double)*pMultFrac ) ) / 2.0 + 0.5 ); aPt.X() += nX; aPt.Y() += nY; aMapMode.SetOrigin( aPt ); SetMapMode( aMapMode ); Invalidate(); } delete pMultFrac; } } void SvxXConnectionPreview::SetStyles() { const StyleSettings& rStyles = Application::GetSettings().GetStyleSettings(); SetDrawMode( GetSettings().GetStyleSettings().GetHighContrastMode() ? OUTPUT_DRAWMODE_CONTRAST : OUTPUT_DRAWMODE_COLOR ); SetBackground( Wallpaper( Color( rStyles.GetFieldColor() ) ) ); } void SvxXConnectionPreview::DataChanged( const DataChangedEvent& rDCEvt ) { Control::DataChanged( rDCEvt ); if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) ) { SetStyles(); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>coverity#708829 Unused pointer value<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 <vcl/svapp.hxx> #include "svx/connctrl.hxx" #include "svx/dlgutil.hxx" #include <svx/dialmgr.hxx> #include <svx/sdr/contact/displayinfo.hxx> #include <svx/sdr/contact/objectcontactofobjlistpainter.hxx> #include <svx/svdmark.hxx> #include <svx/svdoedge.hxx> #include <svx/svdpage.hxx> #include <svx/svdview.hxx> #include <svx/sxelditm.hxx> #include <svx/sxmkitm.hxx> #include <vcl/builder.hxx> SvxXConnectionPreview::SvxXConnectionPreview( Window* pParent, WinBits nStyle) : Control(pParent, nStyle) , pEdgeObj(NULL) , pObjList(NULL) , pView(NULL) { SetMapMode( MAP_100TH_MM ); SetStyles(); } extern "C" SAL_DLLPUBLIC_EXPORT Window* SAL_CALL makeSvxXConnectionPreview(Window *pParent, VclBuilder::stringmap &rMap) { WinBits nWinStyle = 0; OString sBorder = VclBuilder::extractCustomProperty(rMap); if (!sBorder.isEmpty()) nWinStyle |= WB_BORDER; return new SvxXConnectionPreview(pParent, nWinStyle); } SvxXConnectionPreview::~SvxXConnectionPreview() { delete pObjList; } void SvxXConnectionPreview::Resize() { Control::Resize(); AdaptSize(); Invalidate(); } Size SvxXConnectionPreview::GetOptimalSize() const { return LogicToPixel(Size(118 , 121), MapMode(MAP_APPFONT)); } void SvxXConnectionPreview::AdaptSize() { // Adapt size if( pObjList ) { SetMapMode( MAP_100TH_MM ); OutputDevice* pOD = pView->GetFirstOutputDevice(); // GetWin( 0 ); Rectangle aRect = pObjList->GetAllObjBoundRect(); MapMode aMapMode = GetMapMode(); aMapMode.SetMapUnit( pOD->GetMapMode().GetMapUnit() ); SetMapMode( aMapMode ); MapMode aDisplayMap( aMapMode ); Point aNewPos; Size aNewSize; const Size aWinSize = PixelToLogic( GetOutputSizePixel(), aDisplayMap ); const long nWidth = aWinSize.Width(); const long nHeight = aWinSize.Height(); double fRectWH = (double) aRect.GetWidth() / aRect.GetHeight(); double fWinWH = (double) nWidth / nHeight; // Adapt bitmap to Thumb size (not here!) if ( fRectWH < fWinWH) { aNewSize.Width() = (long) ( (double) nHeight * fRectWH ); aNewSize.Height()= nHeight; } else { aNewSize.Width() = nWidth; aNewSize.Height()= (long) ( (double) nWidth / fRectWH ); } Fraction aFrac1( aWinSize.Width(), aRect.GetWidth() ); Fraction aFrac2( aWinSize.Height(), aRect.GetHeight() ); Fraction aMinFrac( aFrac1 <= aFrac2 ? aFrac1 : aFrac2 ); // Implement MapMode aDisplayMap.SetScaleX( aMinFrac ); aDisplayMap.SetScaleY( aMinFrac ); // Centering aNewPos.X() = ( nWidth - aNewSize.Width() ) >> 1; aNewPos.Y() = ( nHeight - aNewSize.Height() ) >> 1; aDisplayMap.SetOrigin( LogicToLogic( aNewPos, aMapMode, aDisplayMap ) ); SetMapMode( aDisplayMap ); // Origin aNewPos = aDisplayMap.GetOrigin(); aNewPos -= Point( aRect.TopLeft().X(), aRect.TopLeft().Y() ); aDisplayMap.SetOrigin( aNewPos ); SetMapMode( aDisplayMap ); Point aPos; MouseEvent aMEvt( aPos, 1, 0, MOUSE_RIGHT ); MouseButtonDown( aMEvt ); } } void SvxXConnectionPreview::Construct() { DBG_ASSERT( pView, "No valid view is passed on! "); const SdrMarkList& rMarkList = pView->GetMarkedObjectList(); sal_uIntPtr nMarkCount = rMarkList.GetMarkCount(); if( nMarkCount >= 1 ) { bool bFound = false; for( sal_uInt16 i = 0; i < nMarkCount && !bFound; i++ ) { const SdrObject* pObj = rMarkList.GetMark( i )->GetMarkedSdrObj(); sal_uInt32 nInv = pObj->GetObjInventor(); sal_uInt16 nId = pObj->GetObjIdentifier(); if( nInv == SdrInventor && nId == OBJ_EDGE ) { bFound = true; SdrEdgeObj* pTmpEdgeObj = (SdrEdgeObj*) pObj; pEdgeObj = (SdrEdgeObj*) pTmpEdgeObj->Clone(); SdrObjConnection& rConn1 = (SdrObjConnection&)pEdgeObj->GetConnection( true ); SdrObjConnection& rConn2 = (SdrObjConnection&)pEdgeObj->GetConnection( false ); rConn1 = pTmpEdgeObj->GetConnection( true ); rConn2 = pTmpEdgeObj->GetConnection( false ); SdrObject* pTmpObj1 = pTmpEdgeObj->GetConnectedNode( true ); SdrObject* pTmpObj2 = pTmpEdgeObj->GetConnectedNode( false ); // potential memory leak here (!). Create SdrObjList only when there is // not yet one. if(!pObjList) { pObjList = new SdrObjList( pView->GetModel(), NULL ); } if( pTmpObj1 ) { SdrObject* pObj1 = pTmpObj1->Clone(); pObjList->InsertObject( pObj1 ); pEdgeObj->ConnectToNode( true, pObj1 ); } if( pTmpObj2 ) { SdrObject* pObj2 = pTmpObj2->Clone(); pObjList->InsertObject( pObj2 ); pEdgeObj->ConnectToNode( false, pObj2 ); } pObjList->InsertObject( pEdgeObj ); } } } if( !pEdgeObj ) pEdgeObj = new SdrEdgeObj(); AdaptSize(); } void SvxXConnectionPreview::Paint( const Rectangle& ) { if( pObjList ) { // #110094# // This will not work anymore. To not start at Adam and Eve, i will // ATM not try to change all this stuff to really using an own model // and a view. I will just try to provide a mechanism to paint such // objects without own model and without a page/view with the new // mechanism. // New stuff: Use a ObjectContactOfObjListPainter. sdr::contact::SdrObjectVector aObjectVector; for(sal_uInt32 a(0L); a < pObjList->GetObjCount(); a++) { SdrObject* pObject = pObjList->GetObj(a); DBG_ASSERT(pObject, "SvxXConnectionPreview::Paint: Corrupt ObjectList (!)"); aObjectVector.push_back(pObject); } sdr::contact::ObjectContactOfObjListPainter aPainter(*this, aObjectVector, 0); sdr::contact::DisplayInfo aDisplayInfo; // do processing aPainter.ProcessDisplay(aDisplayInfo); } } void SvxXConnectionPreview::SetAttributes( const SfxItemSet& rInAttrs ) { pEdgeObj->SetMergedItemSetAndBroadcast(rInAttrs); Invalidate(); } // Get number of lines which are offset based on the preview object sal_uInt16 SvxXConnectionPreview::GetLineDeltaAnz() { const SfxItemSet& rSet = pEdgeObj->GetMergedItemSet(); sal_uInt16 nCount(0); if(SFX_ITEM_DONTCARE != rSet.GetItemState(SDRATTR_EDGELINEDELTAANZ)) nCount = ((const SdrEdgeLineDeltaAnzItem&)rSet.Get(SDRATTR_EDGELINEDELTAANZ)).GetValue(); return nCount; } void SvxXConnectionPreview::MouseButtonDown( const MouseEvent& rMEvt ) { bool bZoomIn = rMEvt.IsLeft() && !rMEvt.IsShift(); bool bZoomOut = rMEvt.IsRight() || rMEvt.IsShift(); bool bCtrl = rMEvt.IsMod1(); if( bZoomIn || bZoomOut ) { MapMode aMapMode = GetMapMode(); Fraction aXFrac = aMapMode.GetScaleX(); Fraction aYFrac = aMapMode.GetScaleY(); Fraction* pMultFrac; if( bZoomIn ) { if( bCtrl ) pMultFrac = new Fraction( 3, 2 ); else pMultFrac = new Fraction( 11, 10 ); } else { if( bCtrl ) pMultFrac = new Fraction( 2, 3 ); else pMultFrac = new Fraction( 10, 11 ); } aXFrac *= *pMultFrac; aYFrac *= *pMultFrac; if( (double)aXFrac > 0.001 && (double)aXFrac < 1000.0 && (double)aYFrac > 0.001 && (double)aYFrac < 1000.0 ) { aMapMode.SetScaleX( aXFrac ); aMapMode.SetScaleY( aYFrac ); SetMapMode( aMapMode ); Size aOutSize( GetOutputSize() ); Point aPt( aMapMode.GetOrigin() ); long nX = (long)( ( (double)aOutSize.Width() - ( (double)aOutSize.Width() * (double)*pMultFrac ) ) / 2.0 + 0.5 ); long nY = (long)( ( (double)aOutSize.Height() - ( (double)aOutSize.Height() * (double)*pMultFrac ) ) / 2.0 + 0.5 ); aPt.X() += nX; aPt.Y() += nY; aMapMode.SetOrigin( aPt ); SetMapMode( aMapMode ); Invalidate(); } delete pMultFrac; } } void SvxXConnectionPreview::SetStyles() { const StyleSettings& rStyles = Application::GetSettings().GetStyleSettings(); SetDrawMode( GetSettings().GetStyleSettings().GetHighContrastMode() ? OUTPUT_DRAWMODE_CONTRAST : OUTPUT_DRAWMODE_COLOR ); SetBackground( Wallpaper( Color( rStyles.GetFieldColor() ) ) ); } void SvxXConnectionPreview::DataChanged( const DataChangedEvent& rDCEvt ) { Control::DataChanged( rDCEvt ); if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) ) { SetStyles(); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: slidepersist.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2008-01-17 08:06:00 $ * * 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 <boost/bind.hpp> #include "oox/ppt/timenode.hxx" #include "oox/ppt/pptshape.hxx" #include "oox/ppt/slidepersist.hxx" #include "oox/core/namespaces.hxx" #include "tokens.hxx" #include <com/sun/star/style/XStyle.hpp> #include <com/sun/star/style/XStyleFamiliesSupplier.hpp> #include <com/sun/star/container/XNamed.hpp> #include <com/sun/star/beans/XMultiPropertySet.hpp> #include <com/sun/star/animations/XAnimationNodeSupplier.hpp> using namespace ::com::sun::star; using namespace ::oox::core; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::drawing; using namespace ::com::sun::star::container; using namespace ::com::sun::star::animations; namespace oox { namespace ppt { SlidePersist::SlidePersist( sal_Bool bMaster, sal_Bool bNotes, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& rxPage, oox::drawingml::ShapePtr pShapesPtr, const drawingml::TextListStylePtr & pDefaultTextStyle ) : mpDrawingPtr( new oox::vml::Drawing ) , mxPage( rxPage ) , maShapesPtr( pShapesPtr ) , mnLayoutValueToken( 0 ) , mbMaster( bMaster ) , mbNotes ( bNotes ) , maDefaultTextStylePtr( pDefaultTextStyle ) , maTitleTextStylePtr( new oox::drawingml::TextListStyle ) , maBodyTextStylePtr( new oox::drawingml::TextListStyle ) , maNotesTextStylePtr( new oox::drawingml::TextListStyle ) , maOtherTextStylePtr( new oox::drawingml::TextListStyle ) { } SlidePersist::~SlidePersist() { } sal_Int16 SlidePersist::getLayoutFromValueToken() { sal_Int16 nLayout = 20; // 20 == blanc (so many magic numbers :-( the description at com.sun.star.presentation.DrawPage.Layout does not help) switch( mnLayoutValueToken ) { case XML_blank: nLayout = 20; break; case XML_chart: nLayout = 2; break; case XML_chartAndTx: nLayout = 7; break; case XML_clipArtAndTx: nLayout = 9; break; case XML_clipArtAndVertTx: nLayout = 24; break; case XML_fourObj: nLayout = 18; break; case XML_obj: nLayout = 11; break; case XML_objAndTx: nLayout = 13; break; case XML_objOverTx: nLayout = 14; break; case XML_tbl: nLayout = 8; break; case XML_title: nLayout = 0; break; case XML_titleOnly: nLayout = 19; break; case XML_twoObj: case XML_twoColTx: nLayout = 3; break; case XML_twoObjAndTx: nLayout = 15; break; case XML_twoObjOverTx: nLayout = 16; break; case XML_tx: nLayout = 1; break; case XML_txAndChart: nLayout = 4; break; case XML_txAndClipArt: nLayout = 6; break; case XML_txAndMedia: nLayout = 6; break; case XML_txAndObj: nLayout = 10; break; case XML_txAndTwoObj: nLayout = 12; break; case XML_txOverObj: nLayout = 17; break; case XML_vertTitleAndTx: nLayout = 22; break; case XML_vertTitleAndTxOverChart: nLayout = 21; break; case XML_vertTx: nLayout = 23; break; case XML_twoTxTwoObj: case XML_twoObjAndObj: case XML_objTx: case XML_picTx: case XML_secHead: case XML_objOnly: case XML_objAndTwoObj: case XML_mediaAndTx: case XML_dgm: case XML_cust: default: nLayout = 20; } return nLayout; } void SlidePersist::createXShapes( const oox::core::XmlFilterBase& rFilterBase, Reference< frame::XModel > xModel ) { applyTextStyles( xModel ); Reference< XShapes > xShapes( getPage(), UNO_QUERY ); std::vector< oox::drawingml::ShapePtr >& rShapes( maShapesPtr->getChilds() ); std::vector< oox::drawingml::ShapePtr >::iterator aShapesIter( rShapes.begin() ); while( aShapesIter != rShapes.end() ) { std::vector< oox::drawingml::ShapePtr >& rChilds( (*aShapesIter++)->getChilds() ); std::vector< oox::drawingml::ShapePtr >::iterator aChildIter( rChilds.begin() ); while( aChildIter != rChilds.end() ) { PPTShape* pPPTShape = dynamic_cast< PPTShape* >( (*aChildIter).get() ); if ( pPPTShape ) pPPTShape->addShape( rFilterBase, xModel, *this, getTheme(), getShapeMap(), xShapes, NULL ); else (*aChildIter)->addShape( rFilterBase, xModel, getTheme(), getShapeMap(), xShapes, NULL ); aChildIter++; } } Reference< XAnimationNodeSupplier > xNodeSupplier( getPage(), UNO_QUERY); if( xNodeSupplier.is() ) { Reference< XAnimationNode > xNode( xNodeSupplier->getAnimationNode() ); if( xNode.is() && !maTimeNodeList.empty() ) { SlidePersistPtr pSlidePtr( shared_from_this() ); TimeNodePtr pNode(maTimeNodeList.front()); OSL_ENSURE( pNode, "pNode" ); pNode->setNode( xModel, xNode, pSlidePtr ); } } } void SlidePersist::createBackground( const oox::core::XmlFilterBase& rFilterBase ) { if ( mpBackgroundPropertiesPtr ) { try { PropertyMap aPropMap; static const rtl::OUString sBackground( RTL_CONSTASCII_USTRINGPARAM( "Background" ) ); uno::Reference< beans::XPropertySet > xPagePropSet( mxPage, uno::UNO_QUERY_THROW ); uno::Reference< beans::XPropertySet > xPropertySet( aPropMap.makePropertySet() ); mpBackgroundPropertiesPtr->pushToPropSet( rFilterBase, xPropertySet ); xPagePropSet->setPropertyValue( sBackground, Any( xPropertySet ) ); } catch( Exception ) { } } } void setTextStyle( Reference< beans::XPropertySet >& rxPropSet, oox::drawingml::TextListStylePtr& pTextListStylePtr, int nLevel ) { ::oox::drawingml::TextParagraphPropertiesPtr pTextParagraphPropertiesPtr( pTextListStylePtr->getListStyle()[ nLevel ] ); if( pTextParagraphPropertiesPtr == NULL ) { // no properties. return return; } ::oox::drawingml::TextCharacterPropertiesPtr pTextCharacterPropertiesPtr( pTextParagraphPropertiesPtr->getTextCharacterProperties() ); if( pTextCharacterPropertiesPtr == NULL ) { // no properties. return return; } PropertyMap& rParagraphProperties( pTextParagraphPropertiesPtr->getTextParagraphPropertyMap() ); PropertyMap& rCharacterProperties( pTextCharacterPropertiesPtr->getTextCharacterPropertyMap() ); int i; Sequence< rtl::OUString > aNames; Sequence< Any > aValues; rParagraphProperties.makeSequence( aNames, aValues ); for( i = 0; i < aNames.getLength(); i++ ) rxPropSet->setPropertyValue( aNames[ i ], aValues[ i ] ); rCharacterProperties.makeSequence( aNames, aValues ); for( i = 0; i < aNames.getLength(); i++ ) rxPropSet->setPropertyValue( aNames[ i ], aValues[ i ] ); } void SlidePersist::applyTextStyles( Reference< frame::XModel > xModel ) { if ( mbMaster ) { try { Reference< style::XStyleFamiliesSupplier > aXStyleFamiliesSupplier( xModel, UNO_QUERY_THROW ); Reference< container::XNameAccess > aXNameAccess( aXStyleFamiliesSupplier->getStyleFamilies() ); Reference< container::XNamed > aXNamed( mxPage, UNO_QUERY_THROW ); if ( aXNameAccess.is() && aXNamed.is() ) { oox::drawingml::TextListStylePtr pTextListStylePtr; rtl::OUString aStyle; rtl::OUString aFamily; const rtl::OUString sOutline( RTL_CONSTASCII_USTRINGPARAM( "outline1" ) ); const rtl::OUString sTitle( RTL_CONSTASCII_USTRINGPARAM( "title" ) ); const rtl::OUString sStandard( RTL_CONSTASCII_USTRINGPARAM( "standard" ) ); const rtl::OUString sSubtitle( RTL_CONSTASCII_USTRINGPARAM( "subtitle" ) ); for( int i = 0; i < 4; i++ ) // todo: aggregation of bodystyle (subtitle) { switch( i ) { case 0 : // title style { pTextListStylePtr = maTitleTextStylePtr; aStyle = sTitle; aFamily= aXNamed->getName(); break; } case 1 : // body style { pTextListStylePtr = maBodyTextStylePtr; aStyle = sOutline; aFamily= aXNamed->getName(); break; } case 3 : // notes style { pTextListStylePtr = maNotesTextStylePtr; aStyle = sTitle; aFamily= aXNamed->getName(); break; } case 4 : // standard style { pTextListStylePtr = maOtherTextStylePtr; aStyle = sStandard; aFamily = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "graphics" ) ); break; } case 5 : // subtitle { pTextListStylePtr = maBodyTextStylePtr; aStyle = sSubtitle; aFamily = aXNamed->getName(); break; } } Reference< container::XNameAccess > xFamilies; if ( aXNameAccess->hasByName( aFamily ) ) { if( aXNameAccess->getByName( aFamily ) >>= xFamilies ) { if ( xFamilies->hasByName( aStyle ) ) { Reference< style::XStyle > aXStyle; if ( xFamilies->getByName( aStyle ) >>= aXStyle ) { Reference< beans::XPropertySet > xPropSet( aXStyle, UNO_QUERY_THROW ); setTextStyle( xPropSet, maDefaultTextStylePtr, 0 ); setTextStyle( xPropSet, pTextListStylePtr, 0 ); for ( int nLevel = 1; nLevel < 5; nLevel++ ) { if ( i == 1 /* BodyStyle */ ) { sal_Char pOutline[ 9 ] = "outline1"; pOutline[ 7 ] = static_cast< sal_Char >( '1' + i ); rtl::OUString sOutlineStyle( rtl::OUString::createFromAscii( pOutline ) ); if ( xFamilies->hasByName( sOutlineStyle ) ) { xFamilies->getByName( sOutlineStyle ) >>= aXStyle; if( aXStyle.is() ) xPropSet = Reference< beans::XPropertySet >( aXStyle, UNO_QUERY_THROW ); } } setTextStyle( xPropSet, maDefaultTextStylePtr, nLevel ); setTextStyle( xPropSet, pTextListStylePtr, nLevel ); } } } } } } } } catch( Exception& ) { } } } } } <commit_msg>INTEGRATION: CWS xmlfilter03_DEV300 (1.2.4); FILE MERGED 2008/02/14 18:48:00 sj 1.2.4.3: completet gradient/tile fill 2008/02/04 13:32:48 dr 1.2.4.2: rework of fragment handler/context handler base classes 2008/02/01 09:55:19 dr 1.2.4.1: addShape() code cleanup, started xlsx drawing import<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: slidepersist.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2008-03-05 18:49:57 $ * * 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 <boost/bind.hpp> #include "oox/ppt/timenode.hxx" #include "oox/ppt/pptshape.hxx" #include "oox/ppt/slidepersist.hxx" #include "oox/core/namespaces.hxx" #include "tokens.hxx" #include <com/sun/star/style/XStyle.hpp> #include <com/sun/star/style/XStyleFamiliesSupplier.hpp> #include <com/sun/star/container/XNamed.hpp> #include <com/sun/star/beans/XMultiPropertySet.hpp> #include <com/sun/star/animations/XAnimationNodeSupplier.hpp> using namespace ::com::sun::star; using namespace ::oox::core; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::drawing; using namespace ::com::sun::star::container; using namespace ::com::sun::star::animations; namespace oox { namespace ppt { SlidePersist::SlidePersist( sal_Bool bMaster, sal_Bool bNotes, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage >& rxPage, oox::drawingml::ShapePtr pShapesPtr, const drawingml::TextListStylePtr & pDefaultTextStyle ) : mpDrawingPtr( new oox::vml::Drawing ) , mxPage( rxPage ) , maShapesPtr( pShapesPtr ) , mnLayoutValueToken( 0 ) , mbMaster( bMaster ) , mbNotes ( bNotes ) , maDefaultTextStylePtr( pDefaultTextStyle ) , maTitleTextStylePtr( new oox::drawingml::TextListStyle ) , maBodyTextStylePtr( new oox::drawingml::TextListStyle ) , maNotesTextStylePtr( new oox::drawingml::TextListStyle ) , maOtherTextStylePtr( new oox::drawingml::TextListStyle ) { } SlidePersist::~SlidePersist() { } sal_Int16 SlidePersist::getLayoutFromValueToken() { sal_Int16 nLayout = 20; // 20 == blanc (so many magic numbers :-( the description at com.sun.star.presentation.DrawPage.Layout does not help) switch( mnLayoutValueToken ) { case XML_blank: nLayout = 20; break; case XML_chart: nLayout = 2; break; case XML_chartAndTx: nLayout = 7; break; case XML_clipArtAndTx: nLayout = 9; break; case XML_clipArtAndVertTx: nLayout = 24; break; case XML_fourObj: nLayout = 18; break; case XML_obj: nLayout = 11; break; case XML_objAndTx: nLayout = 13; break; case XML_objOverTx: nLayout = 14; break; case XML_tbl: nLayout = 8; break; case XML_title: nLayout = 0; break; case XML_titleOnly: nLayout = 19; break; case XML_twoObj: case XML_twoColTx: nLayout = 3; break; case XML_twoObjAndTx: nLayout = 15; break; case XML_twoObjOverTx: nLayout = 16; break; case XML_tx: nLayout = 1; break; case XML_txAndChart: nLayout = 4; break; case XML_txAndClipArt: nLayout = 6; break; case XML_txAndMedia: nLayout = 6; break; case XML_txAndObj: nLayout = 10; break; case XML_txAndTwoObj: nLayout = 12; break; case XML_txOverObj: nLayout = 17; break; case XML_vertTitleAndTx: nLayout = 22; break; case XML_vertTitleAndTxOverChart: nLayout = 21; break; case XML_vertTx: nLayout = 23; break; case XML_twoTxTwoObj: case XML_twoObjAndObj: case XML_objTx: case XML_picTx: case XML_secHead: case XML_objOnly: case XML_objAndTwoObj: case XML_mediaAndTx: case XML_dgm: case XML_cust: default: nLayout = 20; } return nLayout; } void SlidePersist::createXShapes( const oox::core::XmlFilterBase& rFilterBase ) { applyTextStyles( rFilterBase ); Reference< XShapes > xShapes( getPage(), UNO_QUERY ); std::vector< oox::drawingml::ShapePtr >& rShapes( maShapesPtr->getChilds() ); std::vector< oox::drawingml::ShapePtr >::iterator aShapesIter( rShapes.begin() ); while( aShapesIter != rShapes.end() ) { std::vector< oox::drawingml::ShapePtr >& rChilds( (*aShapesIter++)->getChilds() ); std::vector< oox::drawingml::ShapePtr >::iterator aChildIter( rChilds.begin() ); while( aChildIter != rChilds.end() ) { PPTShape* pPPTShape = dynamic_cast< PPTShape* >( (*aChildIter).get() ); if ( pPPTShape ) pPPTShape->addShape( rFilterBase, *this, getTheme(), xShapes, 0, &getShapeMap() ); else (*aChildIter)->addShape( rFilterBase, getTheme(), xShapes, 0, &getShapeMap() ); aChildIter++; } } Reference< XAnimationNodeSupplier > xNodeSupplier( getPage(), UNO_QUERY); if( xNodeSupplier.is() ) { Reference< XAnimationNode > xNode( xNodeSupplier->getAnimationNode() ); if( xNode.is() && !maTimeNodeList.empty() ) { SlidePersistPtr pSlidePtr( shared_from_this() ); TimeNodePtr pNode(maTimeNodeList.front()); OSL_ENSURE( pNode, "pNode" ); pNode->setNode( rFilterBase.getModel(), xNode, pSlidePtr ); } } } void SlidePersist::createBackground( const oox::core::XmlFilterBase& rFilterBase ) { if ( mpBackgroundPropertiesPtr ) { try { PropertyMap aPropMap; static const rtl::OUString sBackground( RTL_CONSTASCII_USTRINGPARAM( "Background" ) ); uno::Reference< beans::XPropertySet > xPagePropSet( mxPage, uno::UNO_QUERY_THROW ); uno::Reference< beans::XPropertySet > xPropertySet( aPropMap.makePropertySet() ); mpBackgroundPropertiesPtr->pushToPropSet( rFilterBase, xPropertySet, 0 ); xPagePropSet->setPropertyValue( sBackground, Any( xPropertySet ) ); } catch( Exception ) { } } } void setTextStyle( Reference< beans::XPropertySet >& rxPropSet, oox::drawingml::TextListStylePtr& pTextListStylePtr, int nLevel ) { ::oox::drawingml::TextParagraphPropertiesPtr pTextParagraphPropertiesPtr( pTextListStylePtr->getListStyle()[ nLevel ] ); if( pTextParagraphPropertiesPtr == NULL ) { // no properties. return return; } ::oox::drawingml::TextCharacterPropertiesPtr pTextCharacterPropertiesPtr( pTextParagraphPropertiesPtr->getTextCharacterProperties() ); if( pTextCharacterPropertiesPtr == NULL ) { // no properties. return return; } PropertyMap& rParagraphProperties( pTextParagraphPropertiesPtr->getTextParagraphPropertyMap() ); PropertyMap& rCharacterProperties( pTextCharacterPropertiesPtr->getTextCharacterPropertyMap() ); int i; Sequence< rtl::OUString > aNames; Sequence< Any > aValues; rParagraphProperties.makeSequence( aNames, aValues ); for( i = 0; i < aNames.getLength(); i++ ) rxPropSet->setPropertyValue( aNames[ i ], aValues[ i ] ); rCharacterProperties.makeSequence( aNames, aValues ); for( i = 0; i < aNames.getLength(); i++ ) rxPropSet->setPropertyValue( aNames[ i ], aValues[ i ] ); } void SlidePersist::applyTextStyles( const oox::core::XmlFilterBase& rFilterBase ) { if ( mbMaster ) { try { Reference< style::XStyleFamiliesSupplier > aXStyleFamiliesSupplier( rFilterBase.getModel(), UNO_QUERY_THROW ); Reference< container::XNameAccess > aXNameAccess( aXStyleFamiliesSupplier->getStyleFamilies() ); Reference< container::XNamed > aXNamed( mxPage, UNO_QUERY_THROW ); if ( aXNameAccess.is() && aXNamed.is() ) { oox::drawingml::TextListStylePtr pTextListStylePtr; rtl::OUString aStyle; rtl::OUString aFamily; const rtl::OUString sOutline( RTL_CONSTASCII_USTRINGPARAM( "outline1" ) ); const rtl::OUString sTitle( RTL_CONSTASCII_USTRINGPARAM( "title" ) ); const rtl::OUString sStandard( RTL_CONSTASCII_USTRINGPARAM( "standard" ) ); const rtl::OUString sSubtitle( RTL_CONSTASCII_USTRINGPARAM( "subtitle" ) ); for( int i = 0; i < 4; i++ ) // todo: aggregation of bodystyle (subtitle) { switch( i ) { case 0 : // title style { pTextListStylePtr = maTitleTextStylePtr; aStyle = sTitle; aFamily= aXNamed->getName(); break; } case 1 : // body style { pTextListStylePtr = maBodyTextStylePtr; aStyle = sOutline; aFamily= aXNamed->getName(); break; } case 3 : // notes style { pTextListStylePtr = maNotesTextStylePtr; aStyle = sTitle; aFamily= aXNamed->getName(); break; } case 4 : // standard style { pTextListStylePtr = maOtherTextStylePtr; aStyle = sStandard; aFamily = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "graphics" ) ); break; } case 5 : // subtitle { pTextListStylePtr = maBodyTextStylePtr; aStyle = sSubtitle; aFamily = aXNamed->getName(); break; } } Reference< container::XNameAccess > xFamilies; if ( aXNameAccess->hasByName( aFamily ) ) { if( aXNameAccess->getByName( aFamily ) >>= xFamilies ) { if ( xFamilies->hasByName( aStyle ) ) { Reference< style::XStyle > aXStyle; if ( xFamilies->getByName( aStyle ) >>= aXStyle ) { Reference< beans::XPropertySet > xPropSet( aXStyle, UNO_QUERY_THROW ); setTextStyle( xPropSet, maDefaultTextStylePtr, 0 ); setTextStyle( xPropSet, pTextListStylePtr, 0 ); for ( int nLevel = 1; nLevel < 5; nLevel++ ) { if ( i == 1 /* BodyStyle */ ) { sal_Char pOutline[ 9 ] = "outline1"; pOutline[ 7 ] = static_cast< sal_Char >( '1' + i ); rtl::OUString sOutlineStyle( rtl::OUString::createFromAscii( pOutline ) ); if ( xFamilies->hasByName( sOutlineStyle ) ) { xFamilies->getByName( sOutlineStyle ) >>= aXStyle; if( aXStyle.is() ) xPropSet = Reference< beans::XPropertySet >( aXStyle, UNO_QUERY_THROW ); } } setTextStyle( xPropSet, maDefaultTextStylePtr, nLevel ); setTextStyle( xPropSet, pTextListStylePtr, nLevel ); } } } } } } } } catch( Exception& ) { } } } } } <|endoftext|>
<commit_before><commit_msg>On init of DbCellControl, load value from Model<commit_after><|endoftext|>
<commit_before>/* * Copyright 2014 Cloudius Systems */ #ifndef SSTRING_HH_ #define SSTRING_HH_ #include <stdint.h> #include <algorithm> #include <string> #include <cstring> #include <stdexcept> #include <initializer_list> #include <iostream> #include <functional> #include <cstdio> #include <experimental/string_view> #include "core/temporary_buffer.hh" template <typename char_type, typename size_type, size_type max_size> class basic_sstring { union contents { struct external_type { char_type* str; size_type size; int8_t pad; } external; struct internal_type { char_type str[max_size]; int8_t size; } internal; static_assert(sizeof(external_type) <= sizeof(internal_type), "max_size too small"); static_assert(max_size <= 127, "max_size too large"); } u; bool is_internal() const noexcept { return u.internal.size >= 0; } bool is_external() const noexcept { return !is_internal(); } const char_type* str() const { return is_internal() ? u.internal.str : u.external.str; } char_type* str() { return is_internal() ? u.internal.str : u.external.str; } public: struct initialized_later {}; basic_sstring() noexcept { u.internal.size = 0; u.internal.str[0] = '\0'; } basic_sstring(const basic_sstring& x) { if (x.is_internal()) { u.internal = x.u.internal; } else { u.internal.size = -1; u.external.str = reinterpret_cast<char_type*>(std::malloc(x.u.external.size + 1)); if (!u.external.str) { throw std::bad_alloc(); } std::copy(x.u.external.str, x.u.external.str + x.u.external.size + 1, u.external.str); u.external.size = x.u.external.size; } } basic_sstring(basic_sstring&& x) noexcept { u = x.u; x.u.internal.size = 0; x.u.internal.str[0] = '\0'; } basic_sstring(initialized_later, size_t size) { if (size_type(size) != size) { throw std::overflow_error("sstring overflow"); } if (size + 1 <= sizeof(u.internal.str)) { u.internal.str[size] = '\0'; u.internal.size = size; } else { u.internal.size = -1; u.external.str = reinterpret_cast<char_type*>(std::malloc(size + 1)); if (!u.external.str) { throw std::bad_alloc(); } u.external.size = size; u.external.str[size] = '\0'; } } basic_sstring(const char_type* x, size_t size) { if (size_type(size) != size) { throw std::overflow_error("sstring overflow"); } if (size + 1 <= sizeof(u.internal.str)) { std::copy(x, x + size, u.internal.str); u.internal.str[size] = '\0'; u.internal.size = size; } else { u.internal.size = -1; u.external.str = reinterpret_cast<char_type*>(std::malloc(size + 1)); if (!u.external.str) { throw std::bad_alloc(); } u.external.size = size; std::copy(x, x + size, u.external.str); u.external.str[size] = '\0'; } } basic_sstring(const char* x) : basic_sstring(reinterpret_cast<const char_type*>(x), std::strlen(x)) {} basic_sstring(std::basic_string<char_type>& x) : basic_sstring(x.c_str(), x.size()) {} basic_sstring(std::initializer_list<char_type> x) : basic_sstring(x.begin(), x.end() - x.begin()) {} basic_sstring(const char_type* b, const char_type* e) : basic_sstring(b, e - b) {} basic_sstring(const std::basic_string<char_type>& s) : basic_sstring(s.data(), s.size()) {} ~basic_sstring() noexcept { if (is_external()) { std::free(u.external.str); } } basic_sstring& operator=(const basic_sstring& x) { basic_sstring tmp(x); swap(tmp); return *this; } basic_sstring& operator=(basic_sstring&& x) noexcept { if (this != &x) { swap(x); x.reset(); } return *this; } operator std::string() const { return { str(), size() }; } size_t size() const noexcept { return is_internal() ? u.internal.size : u.external.size; } bool empty() const noexcept { return u.internal.size == 0; } void reset() noexcept { if (is_external()) { std::free(u.external.str); } u.internal.size = 0; u.internal.str[0] = '\0'; } temporary_buffer<char_type> release() && { if (is_external()) { auto ptr = u.external.str; auto size = u.external.size; u.external.str = nullptr; u.external.size = 0; return temporary_buffer<char_type>(ptr, size, make_free_deleter(ptr)); } else { auto buf = temporary_buffer<char_type>(u.internal.size); std::copy(u.internal.str, u.internal.str + u.internal.size, buf.get_write()); u.internal.size = 0; u.internal.str[0] = '\0'; return buf; } } void swap(basic_sstring& x) noexcept { contents tmp; tmp = x.u; x.u = u; u = tmp; } const char_type* c_str() const { return str(); } const char_type* begin() const { return str(); } const char_type* end() const { return str() + size(); } char_type* begin() { return str(); } char_type* end() { return str() + size(); } bool operator==(const basic_sstring& x) const { return size() == x.size() && std::equal(begin(), end(), x.begin()); } bool operator!=(const basic_sstring& x) const { return !operator==(x); } basic_sstring operator+(const basic_sstring& x) const { basic_sstring ret(initialized_later(), size() + x.size()); std::copy(begin(), end(), ret.begin()); std::copy(x.begin(), x.end(), ret.begin() + size()); return ret; } basic_sstring& operator+=(const basic_sstring& x) { return *this = *this + x; } char_type& operator[](size_type pos) { return str()[pos]; } const char_type& operator[](size_type pos) const { return str()[pos]; } operator std::experimental::string_view() const { return std::experimental::string_view(str(), size()); } }; template <size_t N> static inline size_t str_len(const char(&s)[N]) { return N - 1; } template <size_t N> static inline const char* str_begin(const char(&s)[N]) { return s; } template <size_t N> static inline const char* str_end(const char(&s)[N]) { return str_begin(s) + str_len(s); } template <typename char_type, typename size_type, size_type max_size> static inline const char_type* str_begin(const basic_sstring<char_type, size_type, max_size>& s) { return s.begin(); } template <typename char_type, typename size_type, size_type max_size> static inline const char_type* str_end(const basic_sstring<char_type, size_type, max_size>& s) { return s.end(); } template <typename char_type, typename size_type, size_type max_size> static inline size_type str_len(const basic_sstring<char_type, size_type, max_size>& s) { return s.size(); } template <typename First, typename Second, typename... Tail> static inline const size_t str_len(const First& first, const Second& second, const Tail&... tail) { return str_len(first) + str_len(second, tail...); } template <typename char_type, typename size_type, size_type max_size> inline void swap(basic_sstring<char_type, size_type, max_size>& x, basic_sstring<char_type, size_type, max_size>& y) noexcept { return x.swap(y); } template <typename char_type, typename size_type, size_type max_size, typename char_traits> inline std::basic_ostream<char_type, char_traits>& operator<<(std::basic_ostream<char_type, char_traits>& os, const basic_sstring<char_type, size_type, max_size>& s) { return os.write(s.begin(), s.size()); } namespace std { template <typename char_type, typename size_type, size_type max_size> struct hash<basic_sstring<char_type, size_type, max_size>> { size_t operator()(const basic_sstring<char_type, size_type, max_size>& s) const { return std::hash<std::experimental::string_view>()(s); } }; } using sstring = basic_sstring<char, uint32_t, 15>; static inline char* copy_str_to(char* dst) { return dst; } template <typename Head, typename... Tail> static inline char* copy_str_to(char* dst, const Head& head, const Tail&... tail) { return copy_str_to(std::copy(str_begin(head), str_end(head), dst), tail...); } template <typename String = sstring, typename... Args> static String make_sstring(Args&&... args) { String ret(sstring::initialized_later(), str_len(args...)); copy_str_to(ret.begin(), args...); return ret; } template <typename T, typename String = sstring, typename for_enable_if = void*> String to_sstring(T value, for_enable_if); template <typename T> inline sstring to_sstring_sprintf(T value, const char* fmt) { char tmp[sizeof(value) * 3 + 3]; auto len = std::sprintf(tmp, fmt, value); return sstring(tmp, len); } template <typename string_type = sstring> inline string_type to_sstring(int value, void* = nullptr) { return to_sstring_sprintf(value, "%d"); } template <typename string_type = sstring> inline string_type to_sstring(unsigned value, void* = nullptr) { return to_sstring_sprintf(value, "%u"); } template <typename string_type = sstring> inline string_type to_sstring(long value, void* = nullptr) { return to_sstring_sprintf(value, "%ld"); } template <typename string_type = sstring> inline string_type to_sstring(unsigned long value, void* = nullptr) { return to_sstring_sprintf(value, "%lu"); } template <typename string_type = sstring> inline string_type to_sstring(long long value, void* = nullptr) { return to_sstring_sprintf(value, "%lld"); } template <typename string_type = sstring> inline string_type to_sstring(unsigned long long value, void* = nullptr) { return to_sstring_sprintf(value, "%llu"); } template <typename string_type = sstring> inline string_type to_sstring(float value, void* = nullptr) { return to_sstring_sprintf(value, "%f"); } template <typename string_type = sstring> inline string_type to_sstring(double value, void* = nullptr) { return to_sstring_sprintf(value, "%f"); } template <typename string_type = sstring> inline string_type to_sstring(long double value, void* = nullptr) { return to_sstring_sprintf(value, "%Lf"); } template <typename string_type = sstring> inline string_type to_sstring(const char* value, void* = nullptr) { return string_type(value); } template <typename string_type = sstring> inline string_type to_sstring(sstring value, void* = nullptr) { return value; } template <typename string_type = sstring> static string_type to_sstring(const temporary_buffer<char>& buf) { return string_type(buf.get(), buf.size()); } template <typename T> inline std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { bool first = true; os << "{"; for (auto&& elem : v) { if (!first) { os << ", "; } else { first = false; } os << elem; } os << "}"; return os; } #endif /* SSTRING_HH_ */ <commit_msg>sstring: add standard member typedefs<commit_after>/* * Copyright 2014 Cloudius Systems */ #ifndef SSTRING_HH_ #define SSTRING_HH_ #include <stdint.h> #include <algorithm> #include <string> #include <cstring> #include <stdexcept> #include <initializer_list> #include <iostream> #include <functional> #include <cstdio> #include <experimental/string_view> #include "core/temporary_buffer.hh" template <typename char_type, typename Size, Size max_size> class basic_sstring { union contents { struct external_type { char_type* str; Size size; int8_t pad; } external; struct internal_type { char_type str[max_size]; int8_t size; } internal; static_assert(sizeof(external_type) <= sizeof(internal_type), "max_size too small"); static_assert(max_size <= 127, "max_size too large"); } u; bool is_internal() const noexcept { return u.internal.size >= 0; } bool is_external() const noexcept { return !is_internal(); } const char_type* str() const { return is_internal() ? u.internal.str : u.external.str; } char_type* str() { return is_internal() ? u.internal.str : u.external.str; } public: using value_type = char_type; using traits_type = std::char_traits<char_type>; using allocator_type = std::allocator<char_type>; using reference = char_type&; using const_reference = const char_type&; using pointer = char_type*; using const_pointer = const char_type*; using iterator = char_type*; using const_iterator = const char_type*; // FIXME: add reverse_iterator and friend using difference_type = ssize_t; // std::make_signed_t<Size> can be too small using size_type = Size; public: struct initialized_later {}; basic_sstring() noexcept { u.internal.size = 0; u.internal.str[0] = '\0'; } basic_sstring(const basic_sstring& x) { if (x.is_internal()) { u.internal = x.u.internal; } else { u.internal.size = -1; u.external.str = reinterpret_cast<char_type*>(std::malloc(x.u.external.size + 1)); if (!u.external.str) { throw std::bad_alloc(); } std::copy(x.u.external.str, x.u.external.str + x.u.external.size + 1, u.external.str); u.external.size = x.u.external.size; } } basic_sstring(basic_sstring&& x) noexcept { u = x.u; x.u.internal.size = 0; x.u.internal.str[0] = '\0'; } basic_sstring(initialized_later, size_t size) { if (size_type(size) != size) { throw std::overflow_error("sstring overflow"); } if (size + 1 <= sizeof(u.internal.str)) { u.internal.str[size] = '\0'; u.internal.size = size; } else { u.internal.size = -1; u.external.str = reinterpret_cast<char_type*>(std::malloc(size + 1)); if (!u.external.str) { throw std::bad_alloc(); } u.external.size = size; u.external.str[size] = '\0'; } } basic_sstring(const char_type* x, size_t size) { if (size_type(size) != size) { throw std::overflow_error("sstring overflow"); } if (size + 1 <= sizeof(u.internal.str)) { std::copy(x, x + size, u.internal.str); u.internal.str[size] = '\0'; u.internal.size = size; } else { u.internal.size = -1; u.external.str = reinterpret_cast<char_type*>(std::malloc(size + 1)); if (!u.external.str) { throw std::bad_alloc(); } u.external.size = size; std::copy(x, x + size, u.external.str); u.external.str[size] = '\0'; } } basic_sstring(const char* x) : basic_sstring(reinterpret_cast<const char_type*>(x), std::strlen(x)) {} basic_sstring(std::basic_string<char_type>& x) : basic_sstring(x.c_str(), x.size()) {} basic_sstring(std::initializer_list<char_type> x) : basic_sstring(x.begin(), x.end() - x.begin()) {} basic_sstring(const char_type* b, const char_type* e) : basic_sstring(b, e - b) {} basic_sstring(const std::basic_string<char_type>& s) : basic_sstring(s.data(), s.size()) {} ~basic_sstring() noexcept { if (is_external()) { std::free(u.external.str); } } basic_sstring& operator=(const basic_sstring& x) { basic_sstring tmp(x); swap(tmp); return *this; } basic_sstring& operator=(basic_sstring&& x) noexcept { if (this != &x) { swap(x); x.reset(); } return *this; } operator std::string() const { return { str(), size() }; } size_t size() const noexcept { return is_internal() ? u.internal.size : u.external.size; } bool empty() const noexcept { return u.internal.size == 0; } void reset() noexcept { if (is_external()) { std::free(u.external.str); } u.internal.size = 0; u.internal.str[0] = '\0'; } temporary_buffer<char_type> release() && { if (is_external()) { auto ptr = u.external.str; auto size = u.external.size; u.external.str = nullptr; u.external.size = 0; return temporary_buffer<char_type>(ptr, size, make_free_deleter(ptr)); } else { auto buf = temporary_buffer<char_type>(u.internal.size); std::copy(u.internal.str, u.internal.str + u.internal.size, buf.get_write()); u.internal.size = 0; u.internal.str[0] = '\0'; return buf; } } void swap(basic_sstring& x) noexcept { contents tmp; tmp = x.u; x.u = u; u = tmp; } const char_type* c_str() const { return str(); } const char_type* begin() const { return str(); } const char_type* end() const { return str() + size(); } char_type* begin() { return str(); } char_type* end() { return str() + size(); } bool operator==(const basic_sstring& x) const { return size() == x.size() && std::equal(begin(), end(), x.begin()); } bool operator!=(const basic_sstring& x) const { return !operator==(x); } basic_sstring operator+(const basic_sstring& x) const { basic_sstring ret(initialized_later(), size() + x.size()); std::copy(begin(), end(), ret.begin()); std::copy(x.begin(), x.end(), ret.begin() + size()); return ret; } basic_sstring& operator+=(const basic_sstring& x) { return *this = *this + x; } char_type& operator[](size_type pos) { return str()[pos]; } const char_type& operator[](size_type pos) const { return str()[pos]; } operator std::experimental::string_view() const { return std::experimental::string_view(str(), size()); } }; template <size_t N> static inline size_t str_len(const char(&s)[N]) { return N - 1; } template <size_t N> static inline const char* str_begin(const char(&s)[N]) { return s; } template <size_t N> static inline const char* str_end(const char(&s)[N]) { return str_begin(s) + str_len(s); } template <typename char_type, typename size_type, size_type max_size> static inline const char_type* str_begin(const basic_sstring<char_type, size_type, max_size>& s) { return s.begin(); } template <typename char_type, typename size_type, size_type max_size> static inline const char_type* str_end(const basic_sstring<char_type, size_type, max_size>& s) { return s.end(); } template <typename char_type, typename size_type, size_type max_size> static inline size_type str_len(const basic_sstring<char_type, size_type, max_size>& s) { return s.size(); } template <typename First, typename Second, typename... Tail> static inline const size_t str_len(const First& first, const Second& second, const Tail&... tail) { return str_len(first) + str_len(second, tail...); } template <typename char_type, typename size_type, size_type max_size> inline void swap(basic_sstring<char_type, size_type, max_size>& x, basic_sstring<char_type, size_type, max_size>& y) noexcept { return x.swap(y); } template <typename char_type, typename size_type, size_type max_size, typename char_traits> inline std::basic_ostream<char_type, char_traits>& operator<<(std::basic_ostream<char_type, char_traits>& os, const basic_sstring<char_type, size_type, max_size>& s) { return os.write(s.begin(), s.size()); } namespace std { template <typename char_type, typename size_type, size_type max_size> struct hash<basic_sstring<char_type, size_type, max_size>> { size_t operator()(const basic_sstring<char_type, size_type, max_size>& s) const { return std::hash<std::experimental::string_view>()(s); } }; } using sstring = basic_sstring<char, uint32_t, 15>; static inline char* copy_str_to(char* dst) { return dst; } template <typename Head, typename... Tail> static inline char* copy_str_to(char* dst, const Head& head, const Tail&... tail) { return copy_str_to(std::copy(str_begin(head), str_end(head), dst), tail...); } template <typename String = sstring, typename... Args> static String make_sstring(Args&&... args) { String ret(sstring::initialized_later(), str_len(args...)); copy_str_to(ret.begin(), args...); return ret; } template <typename T, typename String = sstring, typename for_enable_if = void*> String to_sstring(T value, for_enable_if); template <typename T> inline sstring to_sstring_sprintf(T value, const char* fmt) { char tmp[sizeof(value) * 3 + 3]; auto len = std::sprintf(tmp, fmt, value); return sstring(tmp, len); } template <typename string_type = sstring> inline string_type to_sstring(int value, void* = nullptr) { return to_sstring_sprintf(value, "%d"); } template <typename string_type = sstring> inline string_type to_sstring(unsigned value, void* = nullptr) { return to_sstring_sprintf(value, "%u"); } template <typename string_type = sstring> inline string_type to_sstring(long value, void* = nullptr) { return to_sstring_sprintf(value, "%ld"); } template <typename string_type = sstring> inline string_type to_sstring(unsigned long value, void* = nullptr) { return to_sstring_sprintf(value, "%lu"); } template <typename string_type = sstring> inline string_type to_sstring(long long value, void* = nullptr) { return to_sstring_sprintf(value, "%lld"); } template <typename string_type = sstring> inline string_type to_sstring(unsigned long long value, void* = nullptr) { return to_sstring_sprintf(value, "%llu"); } template <typename string_type = sstring> inline string_type to_sstring(float value, void* = nullptr) { return to_sstring_sprintf(value, "%f"); } template <typename string_type = sstring> inline string_type to_sstring(double value, void* = nullptr) { return to_sstring_sprintf(value, "%f"); } template <typename string_type = sstring> inline string_type to_sstring(long double value, void* = nullptr) { return to_sstring_sprintf(value, "%Lf"); } template <typename string_type = sstring> inline string_type to_sstring(const char* value, void* = nullptr) { return string_type(value); } template <typename string_type = sstring> inline string_type to_sstring(sstring value, void* = nullptr) { return value; } template <typename string_type = sstring> static string_type to_sstring(const temporary_buffer<char>& buf) { return string_type(buf.get(), buf.size()); } template <typename T> inline std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { bool first = true; os << "{"; for (auto&& elem : v) { if (!first) { os << ", "; } else { first = false; } os << elem; } os << "}"; return os; } #endif /* SSTRING_HH_ */ <|endoftext|>
<commit_before>//===-- MSP430RegisterInfo.cpp - MSP430 Register Information --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the MSP430 implementation of the TargetRegisterInfo class. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "msp430-reg-info" #include "MSP430RegisterInfo.h" #include "MSP430.h" #include "MSP430MachineFunctionInfo.h" #include "MSP430TargetMachine.h" #include "llvm/ADT/BitVector.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/IR/Function.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #define GET_REGINFO_TARGET_DESC #include "MSP430GenRegisterInfo.inc" using namespace llvm; // FIXME: Provide proper call frame setup / destroy opcodes. MSP430RegisterInfo::MSP430RegisterInfo(MSP430TargetMachine &tm, const TargetInstrInfo &tii) : MSP430GenRegisterInfo(MSP430::PCW), TM(tm), TII(tii) { StackAlign = TM.getFrameLowering()->getStackAlignment(); } const uint16_t* MSP430RegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const { const TargetFrameLowering *TFI = MF->getTarget().getFrameLowering(); const Function* F = MF->getFunction(); static const uint16_t CalleeSavedRegs[] = { MSP430::FPW, MSP430::R5W, MSP430::R6W, MSP430::R7W, MSP430::R8W, MSP430::R9W, MSP430::R10W, MSP430::R11W, 0 }; static const uint16_t CalleeSavedRegsFP[] = { MSP430::R5W, MSP430::R6W, MSP430::R7W, MSP430::R8W, MSP430::R9W, MSP430::R10W, MSP430::R11W, 0 }; static const uint16_t CalleeSavedRegsIntr[] = { MSP430::FPW, MSP430::R5W, MSP430::R6W, MSP430::R7W, MSP430::R8W, MSP430::R9W, MSP430::R10W, MSP430::R11W, MSP430::R12W, MSP430::R13W, MSP430::R14W, MSP430::R15W, 0 }; static const uint16_t CalleeSavedRegsIntrFP[] = { MSP430::R5W, MSP430::R6W, MSP430::R7W, MSP430::R8W, MSP430::R9W, MSP430::R10W, MSP430::R11W, MSP430::R12W, MSP430::R13W, MSP430::R14W, MSP430::R15W, 0 }; if (TFI->hasFP(*MF)) return (F->getCallingConv() == CallingConv::MSP430_INTR ? CalleeSavedRegsIntrFP : CalleeSavedRegsFP); else return (F->getCallingConv() == CallingConv::MSP430_INTR ? CalleeSavedRegsIntr : CalleeSavedRegs); } BitVector MSP430RegisterInfo::getReservedRegs(const MachineFunction &MF) const { BitVector Reserved(getNumRegs()); const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering(); // Mark 4 special registers with subregisters as reserved. Reserved.set(MSP430::PCB); Reserved.set(MSP430::SPB); Reserved.set(MSP430::SRB); Reserved.set(MSP430::CGB); Reserved.set(MSP430::PCW); Reserved.set(MSP430::SPW); Reserved.set(MSP430::SRW); Reserved.set(MSP430::CGW); // Mark frame pointer as reserved if needed. if (TFI->hasFP(MF)) Reserved.set(MSP430::FPW); return Reserved; } const TargetRegisterClass * MSP430RegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind) const { return &MSP430::GR16RegClass; } void MSP430RegisterInfo:: eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const { const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering(); if (!TFI->hasReservedCallFrame(MF)) { // If the stack pointer can be changed after prologue, turn the // adjcallstackup instruction into a 'sub SPW, <amt>' and the // adjcallstackdown instruction into 'add SPW, <amt>' // TODO: consider using push / pop instead of sub + store / add MachineInstr *Old = I; uint64_t Amount = Old->getOperand(0).getImm(); if (Amount != 0) { // We need to keep the stack aligned properly. To do this, we round the // amount of space needed for the outgoing arguments up to the next // alignment boundary. Amount = (Amount+StackAlign-1)/StackAlign*StackAlign; MachineInstr *New = 0; if (Old->getOpcode() == TII.getCallFrameSetupOpcode()) { New = BuildMI(MF, Old->getDebugLoc(), TII.get(MSP430::SUB16ri), MSP430::SPW) .addReg(MSP430::SPW).addImm(Amount); } else { assert(Old->getOpcode() == TII.getCallFrameDestroyOpcode()); // factor out the amount the callee already popped. uint64_t CalleeAmt = Old->getOperand(1).getImm(); Amount -= CalleeAmt; if (Amount) New = BuildMI(MF, Old->getDebugLoc(), TII.get(MSP430::ADD16ri), MSP430::SPW) .addReg(MSP430::SPW).addImm(Amount); } if (New) { // The SRW implicit def is dead. New->getOperand(3).setIsDead(); // Replace the pseudo instruction with a new instruction... MBB.insert(I, New); } } } else if (I->getOpcode() == TII.getCallFrameDestroyOpcode()) { // If we are performing frame pointer elimination and if the callee pops // something off the stack pointer, add it back. if (uint64_t CalleeAmt = I->getOperand(1).getImm()) { MachineInstr *Old = I; MachineInstr *New = BuildMI(MF, Old->getDebugLoc(), TII.get(MSP430::SUB16ri), MSP430::SPW).addReg(MSP430::SPW).addImm(CalleeAmt); // The SRW implicit def is dead. New->getOperand(3).setIsDead(); MBB.insert(I, New); } } MBB.erase(I); } void MSP430RegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj, unsigned FIOperandNum, RegScavenger *RS) const { assert(SPAdj == 0 && "Unexpected"); unsigned i = 0; MachineInstr &MI = *II; MachineBasicBlock &MBB = *MI.getParent(); MachineFunction &MF = *MBB.getParent(); const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering(); DebugLoc dl = MI.getDebugLoc(); int FrameIndex = MI.getOperand(FIOperandNum).getIndex(); unsigned BasePtr = (TFI->hasFP(MF) ? MSP430::FPW : MSP430::SPW); int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex); // Skip the saved PC Offset += 2; if (!TFI->hasFP(MF)) Offset += MF.getFrameInfo()->getStackSize(); else Offset += 2; // Skip the saved FPW // Fold imm into offset Offset += MI.getOperand(FIOperandNum + 1).getImm(); if (MI.getOpcode() == MSP430::ADD16ri) { // This is actually "load effective address" of the stack slot // instruction. We have only two-address instructions, thus we need to // expand it into mov + add MI.setDesc(TII.get(MSP430::MOV16rr)); MI.getOperand(FIOperandNum).ChangeToRegister(BasePtr, false); if (Offset == 0) return; // We need to materialize the offset via add instruction. unsigned DstReg = MI.getOperand(0).getReg(); if (Offset < 0) BuildMI(MBB, llvm::next(II), dl, TII.get(MSP430::SUB16ri), DstReg) .addReg(DstReg).addImm(-Offset); else BuildMI(MBB, llvm::next(II), dl, TII.get(MSP430::ADD16ri), DstReg) .addReg(DstReg).addImm(Offset); return; } MI.getOperand(FIOperandNum).ChangeToRegister(BasePtr, false); MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Offset); } unsigned MSP430RegisterInfo::getFrameRegister(const MachineFunction &MF) const { const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering(); return TFI->hasFP(MF) ? MSP430::FPW : MSP430::SPW; } <commit_msg>Remove unused variable, which should have been removed with r174083.<commit_after>//===-- MSP430RegisterInfo.cpp - MSP430 Register Information --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the MSP430 implementation of the TargetRegisterInfo class. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "msp430-reg-info" #include "MSP430RegisterInfo.h" #include "MSP430.h" #include "MSP430MachineFunctionInfo.h" #include "MSP430TargetMachine.h" #include "llvm/ADT/BitVector.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/IR/Function.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #define GET_REGINFO_TARGET_DESC #include "MSP430GenRegisterInfo.inc" using namespace llvm; // FIXME: Provide proper call frame setup / destroy opcodes. MSP430RegisterInfo::MSP430RegisterInfo(MSP430TargetMachine &tm, const TargetInstrInfo &tii) : MSP430GenRegisterInfo(MSP430::PCW), TM(tm), TII(tii) { StackAlign = TM.getFrameLowering()->getStackAlignment(); } const uint16_t* MSP430RegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const { const TargetFrameLowering *TFI = MF->getTarget().getFrameLowering(); const Function* F = MF->getFunction(); static const uint16_t CalleeSavedRegs[] = { MSP430::FPW, MSP430::R5W, MSP430::R6W, MSP430::R7W, MSP430::R8W, MSP430::R9W, MSP430::R10W, MSP430::R11W, 0 }; static const uint16_t CalleeSavedRegsFP[] = { MSP430::R5W, MSP430::R6W, MSP430::R7W, MSP430::R8W, MSP430::R9W, MSP430::R10W, MSP430::R11W, 0 }; static const uint16_t CalleeSavedRegsIntr[] = { MSP430::FPW, MSP430::R5W, MSP430::R6W, MSP430::R7W, MSP430::R8W, MSP430::R9W, MSP430::R10W, MSP430::R11W, MSP430::R12W, MSP430::R13W, MSP430::R14W, MSP430::R15W, 0 }; static const uint16_t CalleeSavedRegsIntrFP[] = { MSP430::R5W, MSP430::R6W, MSP430::R7W, MSP430::R8W, MSP430::R9W, MSP430::R10W, MSP430::R11W, MSP430::R12W, MSP430::R13W, MSP430::R14W, MSP430::R15W, 0 }; if (TFI->hasFP(*MF)) return (F->getCallingConv() == CallingConv::MSP430_INTR ? CalleeSavedRegsIntrFP : CalleeSavedRegsFP); else return (F->getCallingConv() == CallingConv::MSP430_INTR ? CalleeSavedRegsIntr : CalleeSavedRegs); } BitVector MSP430RegisterInfo::getReservedRegs(const MachineFunction &MF) const { BitVector Reserved(getNumRegs()); const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering(); // Mark 4 special registers with subregisters as reserved. Reserved.set(MSP430::PCB); Reserved.set(MSP430::SPB); Reserved.set(MSP430::SRB); Reserved.set(MSP430::CGB); Reserved.set(MSP430::PCW); Reserved.set(MSP430::SPW); Reserved.set(MSP430::SRW); Reserved.set(MSP430::CGW); // Mark frame pointer as reserved if needed. if (TFI->hasFP(MF)) Reserved.set(MSP430::FPW); return Reserved; } const TargetRegisterClass * MSP430RegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind) const { return &MSP430::GR16RegClass; } void MSP430RegisterInfo:: eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const { const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering(); if (!TFI->hasReservedCallFrame(MF)) { // If the stack pointer can be changed after prologue, turn the // adjcallstackup instruction into a 'sub SPW, <amt>' and the // adjcallstackdown instruction into 'add SPW, <amt>' // TODO: consider using push / pop instead of sub + store / add MachineInstr *Old = I; uint64_t Amount = Old->getOperand(0).getImm(); if (Amount != 0) { // We need to keep the stack aligned properly. To do this, we round the // amount of space needed for the outgoing arguments up to the next // alignment boundary. Amount = (Amount+StackAlign-1)/StackAlign*StackAlign; MachineInstr *New = 0; if (Old->getOpcode() == TII.getCallFrameSetupOpcode()) { New = BuildMI(MF, Old->getDebugLoc(), TII.get(MSP430::SUB16ri), MSP430::SPW) .addReg(MSP430::SPW).addImm(Amount); } else { assert(Old->getOpcode() == TII.getCallFrameDestroyOpcode()); // factor out the amount the callee already popped. uint64_t CalleeAmt = Old->getOperand(1).getImm(); Amount -= CalleeAmt; if (Amount) New = BuildMI(MF, Old->getDebugLoc(), TII.get(MSP430::ADD16ri), MSP430::SPW) .addReg(MSP430::SPW).addImm(Amount); } if (New) { // The SRW implicit def is dead. New->getOperand(3).setIsDead(); // Replace the pseudo instruction with a new instruction... MBB.insert(I, New); } } } else if (I->getOpcode() == TII.getCallFrameDestroyOpcode()) { // If we are performing frame pointer elimination and if the callee pops // something off the stack pointer, add it back. if (uint64_t CalleeAmt = I->getOperand(1).getImm()) { MachineInstr *Old = I; MachineInstr *New = BuildMI(MF, Old->getDebugLoc(), TII.get(MSP430::SUB16ri), MSP430::SPW).addReg(MSP430::SPW).addImm(CalleeAmt); // The SRW implicit def is dead. New->getOperand(3).setIsDead(); MBB.insert(I, New); } } MBB.erase(I); } void MSP430RegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II, int SPAdj, unsigned FIOperandNum, RegScavenger *RS) const { assert(SPAdj == 0 && "Unexpected"); MachineInstr &MI = *II; MachineBasicBlock &MBB = *MI.getParent(); MachineFunction &MF = *MBB.getParent(); const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering(); DebugLoc dl = MI.getDebugLoc(); int FrameIndex = MI.getOperand(FIOperandNum).getIndex(); unsigned BasePtr = (TFI->hasFP(MF) ? MSP430::FPW : MSP430::SPW); int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex); // Skip the saved PC Offset += 2; if (!TFI->hasFP(MF)) Offset += MF.getFrameInfo()->getStackSize(); else Offset += 2; // Skip the saved FPW // Fold imm into offset Offset += MI.getOperand(FIOperandNum + 1).getImm(); if (MI.getOpcode() == MSP430::ADD16ri) { // This is actually "load effective address" of the stack slot // instruction. We have only two-address instructions, thus we need to // expand it into mov + add MI.setDesc(TII.get(MSP430::MOV16rr)); MI.getOperand(FIOperandNum).ChangeToRegister(BasePtr, false); if (Offset == 0) return; // We need to materialize the offset via add instruction. unsigned DstReg = MI.getOperand(0).getReg(); if (Offset < 0) BuildMI(MBB, llvm::next(II), dl, TII.get(MSP430::SUB16ri), DstReg) .addReg(DstReg).addImm(-Offset); else BuildMI(MBB, llvm::next(II), dl, TII.get(MSP430::ADD16ri), DstReg) .addReg(DstReg).addImm(Offset); return; } MI.getOperand(FIOperandNum).ChangeToRegister(BasePtr, false); MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Offset); } unsigned MSP430RegisterInfo::getFrameRegister(const MachineFunction &MF) const { const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering(); return TFI->hasFP(MF) ? MSP430::FPW : MSP430::SPW; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: callnk.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: fme $ $Date: 2002-09-09 09:26:48 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PRECOMPILED #include "core_pch.hxx" #endif #pragma hdrstop #ifndef _HINTIDS_HXX #include <hintids.hxx> #endif #ifndef _COM_SUN_STAR_I18N_SCRIPTTYPE_HDL_ #include <com/sun/star/i18n/ScriptType.hdl> #endif #ifndef _FMTCNTNT_HXX //autogen #include <fmtcntnt.hxx> #endif #ifndef _TXATBASE_HXX //autogen #include <txatbase.hxx> #endif #ifndef _FRMATR_HXX #include <frmatr.hxx> #endif #ifndef _VISCRS_HXX #include <viscrs.hxx> #endif #ifndef _CALLNK_HXX #include <callnk.hxx> #endif #ifndef _CRSRSH_HXX #include <crsrsh.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _FRMFMT_HXX #include <frmfmt.hxx> #endif #ifndef _TXTFRM_HXX #include <txtfrm.hxx> #endif #ifndef _NDTXT_HXX #include <ndtxt.hxx> #endif #ifndef _FLYFRM_HXX #include <flyfrm.hxx> #endif #ifndef _BREAKIT_HXX #include <breakit.hxx> #endif SwCallLink::SwCallLink( SwCrsrShell & rSh, ULONG nAktNode, xub_StrLen nAktCntnt, BYTE nAktNdTyp, long nLRPos ) : rShell( rSh ), nNode( nAktNode ), nCntnt( nAktCntnt ), nNdTyp( nAktNdTyp ), nLeftFrmPos( nLRPos ) { } SwCallLink::SwCallLink( SwCrsrShell & rSh ) : rShell( rSh ) { // SPoint-Werte vom aktuellen Cursor merken SwPaM* pCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr(); SwNode& rNd = pCrsr->GetPoint()->nNode.GetNode(); nNode = rNd.GetIndex(); nCntnt = pCrsr->GetPoint()->nContent.GetIndex(); nNdTyp = rNd.GetNodeType(); if( ND_TEXTNODE & nNdTyp ) nLeftFrmPos = SwCallLink::GetFrm( (SwTxtNode&)rNd, nCntnt, !rShell.ActionPend() ); else { nLeftFrmPos = 0; // eine Sonderbehandlung fuer die SwFeShell: diese setzt beim Loeschen // der Kopf-/Fusszeile, Fussnoten den Cursor auf NULL (Node + Content) // steht der Cursor auf keinem CntntNode, wird sich das im NdType // gespeichert. if( ND_CONTENTNODE & nNdTyp ) nNdTyp = 0; } } SwCallLink::~SwCallLink() { if( !nNdTyp || !rShell.bCallChgLnk ) // siehe ctor return ; // wird ueber Nodes getravellt, Formate ueberpruefen und im neuen // Node wieder anmelden SwPaM* pCurCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr(); SwCntntNode * pCNd = pCurCrsr->GetCntntNode(); if( !pCNd ) return; xub_StrLen nCmp, nAktCntnt = pCurCrsr->GetPoint()->nContent.GetIndex(); USHORT nNdWhich = pCNd->GetNodeType(); ULONG nAktNode = pCurCrsr->GetPoint()->nNode.GetIndex(); // melde die Shell beim akt. Node als abhaengig an, dadurch koennen // alle Attribut-Aenderungen ueber den Link weiter gemeldet werden. pCNd->Add( &rShell ); if( nNdTyp != nNdWhich || nNode != nAktNode ) { /* immer, wenn zwischen Nodes gesprungen wird, kann es * vorkommen, das neue Attribute gelten; die Text-Attribute. * Es muesste also festgestellt werden, welche Attribute * jetzt gelten; das kann auch gleich der Handler machen */ rShell.CallChgLnk(); } else if( rShell.aChgLnk.IsSet() && ND_TEXTNODE == nNdWhich && nCntnt != nAktCntnt ) { // nur wenn mit Left/right getravellt, dann Text-Hints pruefen // und sich nicht der Frame geaendert hat (Spalten!) if( nLeftFrmPos == SwCallLink::GetFrm( (SwTxtNode&)*pCNd, nAktCntnt, !rShell.ActionPend() ) && (( nCmp = nCntnt ) + 1 == nAktCntnt || // Right nCntnt -1 == ( nCmp = nAktCntnt )) ) // Left { if( nCmp == nAktCntnt && pCurCrsr->HasMark() ) // left & Sele ++nCmp; if ( ((SwTxtNode*)pCNd)->HasHints() ) { const SwpHints &rHts = ((SwTxtNode*)pCNd)->GetSwpHints(); USHORT n; xub_StrLen nStart; const xub_StrLen *pEnd; for( n = 0; n < rHts.Count(); n++ ) { const SwTxtAttr* pHt = rHts[ n ]; pEnd = pHt->GetEnd(); nStart = *pHt->GetStart(); // nur Start oder Start und Ende gleich, dann immer // beim Ueberlaufen von Start callen if( ( !pEnd || ( nStart == *pEnd ) ) && ( nStart == nCntnt || nStart == nAktCntnt) ) { rShell.CallChgLnk(); return; } // hat das Attribut einen Bereich und dieser nicht leer else if( pEnd && nStart < *pEnd && // dann teste, ob ueber Start/Ende getravellt wurde ( nStart == nCmp || ( pHt->DontExpand() ? nCmp == *pEnd-1 : nCmp == *pEnd ) )) { rShell.CallChgLnk(); return; } nStart = 0; } } if( pBreakIt->xBreak.is() ) { const String& rTxt = ((SwTxtNode*)pCNd)->GetTxt(); if( !nCmp || pBreakIt->xBreak->getScriptType( rTxt, nCmp ) != pBreakIt->xBreak->getScriptType( rTxt, nCmp - 1 )) { rShell.CallChgLnk(); return; } } } else /* wenn mit Home/End/.. mehr als 1 Zeichen getravellt, dann * immer den ChgLnk rufen, denn es kann hier nicht * festgestellt werden, was sich geaendert; etwas kann * veraendert sein. */ rShell.CallChgLnk(); } const SwFrm* pFrm; const SwFlyFrm *pFlyFrm; if( !rShell.ActionPend() && 0 != ( pFrm = pCNd->GetFrm(0,0,FALSE) ) && 0 != ( pFlyFrm = pFrm->FindFlyFrm() ) && !rShell.IsTableMode() ) { const SwNodeIndex* pIndex = pFlyFrm->GetFmt()->GetCntnt().GetCntntIdx(); ASSERT( pIndex, "Fly ohne Cntnt" ); const SwNode& rStNd = pIndex->GetNode(); if( rStNd.EndOfSectionNode()->StartOfSectionIndex() > nNode || nNode > rStNd.EndOfSectionIndex() ) rShell.GetFlyMacroLnk().Call( (void*)pFlyFrm->GetFmt() ); } } long SwCallLink::GetFrm( SwTxtNode& rNd, xub_StrLen nCntPos, BOOL bCalcFrm ) { SwTxtFrm* pFrm = (SwTxtFrm*)rNd.GetFrm(0,0,bCalcFrm), *pNext = pFrm; if ( pFrm && !pFrm->IsHiddenNow() ) { if( pFrm->HasFollow() ) while( 0 != ( pNext = (SwTxtFrm*)pFrm->GetFollow() ) && nCntPos >= pNext->GetOfst() ) pFrm = pNext; return pFrm->Frm().Left(); } return 0; } /*---------------------------------------------------------------------*/ //SwChgLinkFlag::SwChgLinkFlag( SwCrsrShell& rShell ) // : rCrsrShell( rShell ), bOldFlag( rShell.bCallChgLnk ), nLeftFrmPos( 0 ) //{ // rCrsrShell.bCallChgLnk = FALSE; // if( bOldFlag && !rCrsrShell.pTblCrsr ) // { // SwNode* pNd = rCrsrShell.pCurCrsr->GetNode(); // if( ND_TEXTNODE & pNd->GetNodeType() ) // nLeftFrmPos = SwCallLink::GetFrm( (SwTxtNode&)*pNd, // rCrsrShell.pCurCrsr->GetPoint()->nContent.GetIndex(), // !rCrsrShell.ActionPend() ); // } //} //SwChgLinkFlag::~SwChgLinkFlag() //{ // rCrsrShell.bCallChgLnk = bOldFlag; // if( bOldFlag && !rCrsrShell.pTblCrsr ) // { // // die Spalten Ueberwachung brauchen wir immer!!! // SwNode* pNd = rCrsrShell.pCurCrsr->GetNode(); // if( ND_TEXTNODE & pNd->GetNodeType() && // nLeftFrmPos != SwCallLink::GetFrm( (SwTxtNode&)*pNd, // rCrsrShell.pCurCrsr->GetPoint()->nContent.GetIndex(), // !rCrsrShell.ActionPend() )) // { // /* immer, wenn zwischen Frames gesprungen wird, gelten // * neue Attribute. Es muesste also festgestellt werden, welche // * Attribute jetzt gelten; das kann gleich der Handler machen. // * Diesen direkt rufen !!! // */ // rCrsrShell.aChgLnk.Call( &rCrsrShell ); // rCrsrShell.bChgCallFlag = FALSE; // Flag zuruecksetzen // } // } //} <commit_msg>INTEGRATION: CWS os8 (1.5.142); FILE MERGED 2003/04/03 07:09:39 os 1.5.142.1: #108583# precompiled headers removed<commit_after>/************************************************************************* * * $RCSfile: callnk.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: vg $ $Date: 2003-04-17 13:44:07 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _HINTIDS_HXX #include <hintids.hxx> #endif #ifndef _COM_SUN_STAR_I18N_SCRIPTTYPE_HDL_ #include <com/sun/star/i18n/ScriptType.hdl> #endif #ifndef _FMTCNTNT_HXX //autogen #include <fmtcntnt.hxx> #endif #ifndef _TXATBASE_HXX //autogen #include <txatbase.hxx> #endif #ifndef _FRMATR_HXX #include <frmatr.hxx> #endif #ifndef _VISCRS_HXX #include <viscrs.hxx> #endif #ifndef _CALLNK_HXX #include <callnk.hxx> #endif #ifndef _CRSRSH_HXX #include <crsrsh.hxx> #endif #ifndef _DOC_HXX #include <doc.hxx> #endif #ifndef _FRMFMT_HXX #include <frmfmt.hxx> #endif #ifndef _TXTFRM_HXX #include <txtfrm.hxx> #endif #ifndef _NDTXT_HXX #include <ndtxt.hxx> #endif #ifndef _FLYFRM_HXX #include <flyfrm.hxx> #endif #ifndef _BREAKIT_HXX #include <breakit.hxx> #endif SwCallLink::SwCallLink( SwCrsrShell & rSh, ULONG nAktNode, xub_StrLen nAktCntnt, BYTE nAktNdTyp, long nLRPos ) : rShell( rSh ), nNode( nAktNode ), nCntnt( nAktCntnt ), nNdTyp( nAktNdTyp ), nLeftFrmPos( nLRPos ) { } SwCallLink::SwCallLink( SwCrsrShell & rSh ) : rShell( rSh ) { // SPoint-Werte vom aktuellen Cursor merken SwPaM* pCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr(); SwNode& rNd = pCrsr->GetPoint()->nNode.GetNode(); nNode = rNd.GetIndex(); nCntnt = pCrsr->GetPoint()->nContent.GetIndex(); nNdTyp = rNd.GetNodeType(); if( ND_TEXTNODE & nNdTyp ) nLeftFrmPos = SwCallLink::GetFrm( (SwTxtNode&)rNd, nCntnt, !rShell.ActionPend() ); else { nLeftFrmPos = 0; // eine Sonderbehandlung fuer die SwFeShell: diese setzt beim Loeschen // der Kopf-/Fusszeile, Fussnoten den Cursor auf NULL (Node + Content) // steht der Cursor auf keinem CntntNode, wird sich das im NdType // gespeichert. if( ND_CONTENTNODE & nNdTyp ) nNdTyp = 0; } } SwCallLink::~SwCallLink() { if( !nNdTyp || !rShell.bCallChgLnk ) // siehe ctor return ; // wird ueber Nodes getravellt, Formate ueberpruefen und im neuen // Node wieder anmelden SwPaM* pCurCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr(); SwCntntNode * pCNd = pCurCrsr->GetCntntNode(); if( !pCNd ) return; xub_StrLen nCmp, nAktCntnt = pCurCrsr->GetPoint()->nContent.GetIndex(); USHORT nNdWhich = pCNd->GetNodeType(); ULONG nAktNode = pCurCrsr->GetPoint()->nNode.GetIndex(); // melde die Shell beim akt. Node als abhaengig an, dadurch koennen // alle Attribut-Aenderungen ueber den Link weiter gemeldet werden. pCNd->Add( &rShell ); if( nNdTyp != nNdWhich || nNode != nAktNode ) { /* immer, wenn zwischen Nodes gesprungen wird, kann es * vorkommen, das neue Attribute gelten; die Text-Attribute. * Es muesste also festgestellt werden, welche Attribute * jetzt gelten; das kann auch gleich der Handler machen */ rShell.CallChgLnk(); } else if( rShell.aChgLnk.IsSet() && ND_TEXTNODE == nNdWhich && nCntnt != nAktCntnt ) { // nur wenn mit Left/right getravellt, dann Text-Hints pruefen // und sich nicht der Frame geaendert hat (Spalten!) if( nLeftFrmPos == SwCallLink::GetFrm( (SwTxtNode&)*pCNd, nAktCntnt, !rShell.ActionPend() ) && (( nCmp = nCntnt ) + 1 == nAktCntnt || // Right nCntnt -1 == ( nCmp = nAktCntnt )) ) // Left { if( nCmp == nAktCntnt && pCurCrsr->HasMark() ) // left & Sele ++nCmp; if ( ((SwTxtNode*)pCNd)->HasHints() ) { const SwpHints &rHts = ((SwTxtNode*)pCNd)->GetSwpHints(); USHORT n; xub_StrLen nStart; const xub_StrLen *pEnd; for( n = 0; n < rHts.Count(); n++ ) { const SwTxtAttr* pHt = rHts[ n ]; pEnd = pHt->GetEnd(); nStart = *pHt->GetStart(); // nur Start oder Start und Ende gleich, dann immer // beim Ueberlaufen von Start callen if( ( !pEnd || ( nStart == *pEnd ) ) && ( nStart == nCntnt || nStart == nAktCntnt) ) { rShell.CallChgLnk(); return; } // hat das Attribut einen Bereich und dieser nicht leer else if( pEnd && nStart < *pEnd && // dann teste, ob ueber Start/Ende getravellt wurde ( nStart == nCmp || ( pHt->DontExpand() ? nCmp == *pEnd-1 : nCmp == *pEnd ) )) { rShell.CallChgLnk(); return; } nStart = 0; } } if( pBreakIt->xBreak.is() ) { const String& rTxt = ((SwTxtNode*)pCNd)->GetTxt(); if( !nCmp || pBreakIt->xBreak->getScriptType( rTxt, nCmp ) != pBreakIt->xBreak->getScriptType( rTxt, nCmp - 1 )) { rShell.CallChgLnk(); return; } } } else /* wenn mit Home/End/.. mehr als 1 Zeichen getravellt, dann * immer den ChgLnk rufen, denn es kann hier nicht * festgestellt werden, was sich geaendert; etwas kann * veraendert sein. */ rShell.CallChgLnk(); } const SwFrm* pFrm; const SwFlyFrm *pFlyFrm; if( !rShell.ActionPend() && 0 != ( pFrm = pCNd->GetFrm(0,0,FALSE) ) && 0 != ( pFlyFrm = pFrm->FindFlyFrm() ) && !rShell.IsTableMode() ) { const SwNodeIndex* pIndex = pFlyFrm->GetFmt()->GetCntnt().GetCntntIdx(); ASSERT( pIndex, "Fly ohne Cntnt" ); const SwNode& rStNd = pIndex->GetNode(); if( rStNd.EndOfSectionNode()->StartOfSectionIndex() > nNode || nNode > rStNd.EndOfSectionIndex() ) rShell.GetFlyMacroLnk().Call( (void*)pFlyFrm->GetFmt() ); } } long SwCallLink::GetFrm( SwTxtNode& rNd, xub_StrLen nCntPos, BOOL bCalcFrm ) { SwTxtFrm* pFrm = (SwTxtFrm*)rNd.GetFrm(0,0,bCalcFrm), *pNext = pFrm; if ( pFrm && !pFrm->IsHiddenNow() ) { if( pFrm->HasFollow() ) while( 0 != ( pNext = (SwTxtFrm*)pFrm->GetFollow() ) && nCntPos >= pNext->GetOfst() ) pFrm = pNext; return pFrm->Frm().Left(); } return 0; } /*---------------------------------------------------------------------*/ //SwChgLinkFlag::SwChgLinkFlag( SwCrsrShell& rShell ) // : rCrsrShell( rShell ), bOldFlag( rShell.bCallChgLnk ), nLeftFrmPos( 0 ) //{ // rCrsrShell.bCallChgLnk = FALSE; // if( bOldFlag && !rCrsrShell.pTblCrsr ) // { // SwNode* pNd = rCrsrShell.pCurCrsr->GetNode(); // if( ND_TEXTNODE & pNd->GetNodeType() ) // nLeftFrmPos = SwCallLink::GetFrm( (SwTxtNode&)*pNd, // rCrsrShell.pCurCrsr->GetPoint()->nContent.GetIndex(), // !rCrsrShell.ActionPend() ); // } //} //SwChgLinkFlag::~SwChgLinkFlag() //{ // rCrsrShell.bCallChgLnk = bOldFlag; // if( bOldFlag && !rCrsrShell.pTblCrsr ) // { // // die Spalten Ueberwachung brauchen wir immer!!! // SwNode* pNd = rCrsrShell.pCurCrsr->GetNode(); // if( ND_TEXTNODE & pNd->GetNodeType() && // nLeftFrmPos != SwCallLink::GetFrm( (SwTxtNode&)*pNd, // rCrsrShell.pCurCrsr->GetPoint()->nContent.GetIndex(), // !rCrsrShell.ActionPend() )) // { // /* immer, wenn zwischen Frames gesprungen wird, gelten // * neue Attribute. Es muesste also festgestellt werden, welche // * Attribute jetzt gelten; das kann gleich der Handler machen. // * Diesen direkt rufen !!! // */ // rCrsrShell.aChgLnk.Call( &rCrsrShell ); // rCrsrShell.bChgCallFlag = FALSE; // Flag zuruecksetzen // } // } //} <|endoftext|>
<commit_before><commit_msg>WaE: private field 'nSttLineNum' is not used<commit_after><|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 <viewopt.hxx> #include <SwPortionHandler.hxx> #include <inftxt.hxx> #include <porexp.hxx> sal_Int32 SwExpandPortion::GetCrsrOfst( const sal_uInt16 nOfst ) const { return SwLinePortion::GetCrsrOfst( nOfst ); } bool SwExpandPortion::GetExpTxt( const SwTxtSizeInfo&, OUString &rTxt ) const { rTxt = OUString(); // Nicht etwa: return 0 != rTxt.Len(); // Weil: leere Felder ersetzen CH_TXTATR gegen einen Leerstring return true; } void SwExpandPortion::HandlePortion( SwPortionHandler& rPH ) const { rPH.Special( GetLen(), OUString(), GetWhichPor() ); } SwPosSize SwExpandPortion::GetTxtSize( const SwTxtSizeInfo &rInf ) const { SwTxtSlot aDiffTxt( &rInf, this, false, false ); return rInf.GetTxtSize(); } // 5010: Exp und Tabs bool SwExpandPortion::Format( SwTxtFormatInfo &rInf ) { SwTxtSlot aDiffTxt( &rInf, this, true, false ); const sal_Int32 nFullLen = rInf.GetLen(); // So komisch es aussieht, die Abfrage auf GetLen() muss wegen der // ExpandPortions _hinter_ aDiffTxt (vgl. SoftHyphs) // false returnen wegen SetFull ... if( !nFullLen ) { // nicht Init(), weil wir Hoehe und Ascent brauchen Width(0); return false; } return SwTxtPortion::Format( rInf ); } void SwExpandPortion::Paint( const SwTxtPaintInfo &rInf ) const { SwTxtSlot aDiffTxt( &rInf, this, true, true ); const SwFont aOldFont = *rInf.GetFont(); if( GetJoinBorderWithPrev() ) const_cast<SwTxtPaintInfo&>(rInf).GetFont()->SetLeftBorder(0); if( GetJoinBorderWithNext() ) const_cast<SwTxtPaintInfo&>(rInf).GetFont()->SetRightBorder(0); rInf.DrawBackBrush( *this ); rInf.DrawBorder( *this ); // do we have to repaint a post it portion? if( rInf.OnWin() && pPortion && !pPortion->Width() ) pPortion->PrePaint( rInf, this ); // The contents of field portions is not considered during the // calculation of the directions. Therefore we let vcl handle // the calculation by removing the BIDI_STRONG_FLAG temporarily. SwLayoutModeModifier aLayoutModeModifier( *rInf.GetOut() ); aLayoutModeModifier.SetAuto(); // ST2 if ( rInf.GetSmartTags() || rInf.GetGrammarCheckList() ) rInf.DrawMarkedText( *this, rInf.GetLen(), false, false, 0 != rInf.GetSmartTags(), 0 != rInf.GetGrammarCheckList() ); else rInf.DrawText( *this, rInf.GetLen(), false ); if( GetJoinBorderWithPrev() || GetJoinBorderWithNext() ) *const_cast<SwTxtPaintInfo&>(rInf).GetFont() = aOldFont; } SwLinePortion *SwBlankPortion::Compress() { return this; } // 5497: Es gibt schon Gemeinheiten auf der Welt... // Wenn eine Zeile voll mit HardBlanks ist und diese ueberlaeuft, // dann duerfen keine Underflows generiert werden! // Komplikationen bei Flys... sal_uInt16 SwBlankPortion::MayUnderflow( const SwTxtFormatInfo &rInf, sal_Int32 nIdx, bool bUnderflow ) const { if( rInf.StopUnderflow() ) return 0; const SwLinePortion *pPos = rInf.GetRoot(); if( pPos->GetPortion() ) pPos = pPos->GetPortion(); while( pPos && pPos->IsBlankPortion() ) pPos = pPos->GetPortion(); if( !pPos || !rInf.GetIdx() || ( !pPos->GetLen() && pPos == rInf.GetRoot() ) ) return 0; // Nur noch BlankPortions unterwegs // Wenn vor uns ein Blank ist, brauchen wir kein Underflow ausloesen, // wenn hinter uns ein Blank ist, brauchen wir kein Underflow weiterreichen if (bUnderflow && nIdx + 1 < rInf.GetTxt().getLength() && CH_BLANK == rInf.GetTxt()[nIdx + 1]) return 0; if( nIdx && !((SwTxtFormatInfo&)rInf).GetFly() ) { while( pPos && !pPos->IsFlyPortion() ) pPos = pPos->GetPortion(); if( !pPos ) { //Hier wird ueberprueft, ob es in dieser Zeile noch sinnvolle Umbrueche //gibt, Blanks oder Felder etc., wenn nicht, kein Underflow. //Wenn Flys im Spiel sind, lassen wir das Underflow trotzdem zu. sal_Int32 nBlank = nIdx; while( --nBlank > rInf.GetLineStart() ) { const sal_Unicode cCh = rInf.GetChar( nBlank ); if( CH_BLANK == cCh || (( CH_TXTATR_BREAKWORD == cCh || CH_TXTATR_INWORD == cCh ) && rInf.HasHint( nBlank ) ) ) break; } if( nBlank <= rInf.GetLineStart() ) return 0; } } sal_Unicode cCh; if( nIdx < 2 || CH_BLANK == (cCh = rInf.GetChar( nIdx - 1 )) ) return 1; if( CH_BREAK == cCh ) return 0; return 2; } // Format end of Line void SwBlankPortion::FormatEOL( SwTxtFormatInfo &rInf ) { sal_uInt16 nMay = MayUnderflow( rInf, rInf.GetIdx() - nLineLength, true ); if( nMay ) { if( nMay > 1 ) { if( rInf.GetLast() == this ) rInf.SetLast( FindPrevPortion( rInf.GetRoot() ) ); rInf.X( rInf.X() - PrtWidth() ); rInf.SetIdx( rInf.GetIdx() - GetLen() ); } Truncate(); rInf.SetUnderflow( this ); if( rInf.GetLast()->IsKernPortion() ) rInf.SetUnderflow( rInf.GetLast() ); } } // 7771: Underflows weiterreichen und selbst ausloesen! bool SwBlankPortion::Format( SwTxtFormatInfo &rInf ) { const bool bFull = rInf.IsUnderflow() || SwExpandPortion::Format( rInf ); if( bFull && MayUnderflow( rInf, rInf.GetIdx(), rInf.IsUnderflow() ) ) { Truncate(); rInf.SetUnderflow( this ); if( rInf.GetLast()->IsKernPortion() ) rInf.SetUnderflow( rInf.GetLast() ); } return bFull; } void SwBlankPortion::Paint( const SwTxtPaintInfo &rInf ) const { if( !bMulti ) // No gray background for multiportion brackets rInf.DrawViewOpt( *this, POR_BLANK ); SwExpandPortion::Paint( rInf ); } bool SwBlankPortion::GetExpTxt( const SwTxtSizeInfo&, OUString &rTxt ) const { rTxt = OUString(cChar); return true; } void SwBlankPortion::HandlePortion( SwPortionHandler& rPH ) const { rPH.Special( GetLen(), OUString( cChar ), GetWhichPor() ); } SwPostItsPortion::SwPostItsPortion( bool bScrpt ) : bScript( bScrpt ) { nLineLength = 1; SetWhichPor( POR_POSTITS ); } void SwPostItsPortion::Paint( const SwTxtPaintInfo &rInf ) const { if( rInf.OnWin() && Width() ) rInf.DrawPostIts( *this, IsScript() ); } sal_uInt16 SwPostItsPortion::GetViewWidth( const SwTxtSizeInfo &rInf ) const { // Nicht zu fassen: PostIts sind immer zu sehen. return rInf.OnWin() ? (sal_uInt16)rInf.GetOpt().GetPostItsWidth( rInf.GetOut() ) : 0; } bool SwPostItsPortion::Format( SwTxtFormatInfo &rInf ) { const bool bRet = SwLinePortion::Format( rInf ); // 32749: PostIts sollen keine Auswirkung auf Zeilenhoehe etc. haben SetAscent( 1 ); Height( 1 ); return bRet; } bool SwPostItsPortion::GetExpTxt( const SwTxtSizeInfo &rInf, OUString &rTxt ) const { if( rInf.OnWin() && rInf.GetOpt().IsPostIts() ) rTxt = OUString(' '); else rTxt = OUString(); return true; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Remove unneeded cast<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 <viewopt.hxx> #include <SwPortionHandler.hxx> #include <inftxt.hxx> #include <porexp.hxx> sal_Int32 SwExpandPortion::GetCrsrOfst( const sal_uInt16 nOfst ) const { return SwLinePortion::GetCrsrOfst( nOfst ); } bool SwExpandPortion::GetExpTxt( const SwTxtSizeInfo&, OUString &rTxt ) const { rTxt = OUString(); // Nicht etwa: return 0 != rTxt.Len(); // Weil: leere Felder ersetzen CH_TXTATR gegen einen Leerstring return true; } void SwExpandPortion::HandlePortion( SwPortionHandler& rPH ) const { rPH.Special( GetLen(), OUString(), GetWhichPor() ); } SwPosSize SwExpandPortion::GetTxtSize( const SwTxtSizeInfo &rInf ) const { SwTxtSlot aDiffTxt( &rInf, this, false, false ); return rInf.GetTxtSize(); } // 5010: Exp und Tabs bool SwExpandPortion::Format( SwTxtFormatInfo &rInf ) { SwTxtSlot aDiffTxt( &rInf, this, true, false ); const sal_Int32 nFullLen = rInf.GetLen(); // So komisch es aussieht, die Abfrage auf GetLen() muss wegen der // ExpandPortions _hinter_ aDiffTxt (vgl. SoftHyphs) // false returnen wegen SetFull ... if( !nFullLen ) { // nicht Init(), weil wir Hoehe und Ascent brauchen Width(0); return false; } return SwTxtPortion::Format( rInf ); } void SwExpandPortion::Paint( const SwTxtPaintInfo &rInf ) const { SwTxtSlot aDiffTxt( &rInf, this, true, true ); const SwFont aOldFont = *rInf.GetFont(); if( GetJoinBorderWithPrev() ) const_cast<SwTxtPaintInfo&>(rInf).GetFont()->SetLeftBorder(0); if( GetJoinBorderWithNext() ) const_cast<SwTxtPaintInfo&>(rInf).GetFont()->SetRightBorder(0); rInf.DrawBackBrush( *this ); rInf.DrawBorder( *this ); // do we have to repaint a post it portion? if( rInf.OnWin() && pPortion && !pPortion->Width() ) pPortion->PrePaint( rInf, this ); // The contents of field portions is not considered during the // calculation of the directions. Therefore we let vcl handle // the calculation by removing the BIDI_STRONG_FLAG temporarily. SwLayoutModeModifier aLayoutModeModifier( *rInf.GetOut() ); aLayoutModeModifier.SetAuto(); // ST2 if ( rInf.GetSmartTags() || rInf.GetGrammarCheckList() ) rInf.DrawMarkedText( *this, rInf.GetLen(), false, false, 0 != rInf.GetSmartTags(), 0 != rInf.GetGrammarCheckList() ); else rInf.DrawText( *this, rInf.GetLen(), false ); if( GetJoinBorderWithPrev() || GetJoinBorderWithNext() ) *const_cast<SwTxtPaintInfo&>(rInf).GetFont() = aOldFont; } SwLinePortion *SwBlankPortion::Compress() { return this; } // 5497: Es gibt schon Gemeinheiten auf der Welt... // Wenn eine Zeile voll mit HardBlanks ist und diese ueberlaeuft, // dann duerfen keine Underflows generiert werden! // Komplikationen bei Flys... sal_uInt16 SwBlankPortion::MayUnderflow( const SwTxtFormatInfo &rInf, sal_Int32 nIdx, bool bUnderflow ) const { if( rInf.StopUnderflow() ) return 0; const SwLinePortion *pPos = rInf.GetRoot(); if( pPos->GetPortion() ) pPos = pPos->GetPortion(); while( pPos && pPos->IsBlankPortion() ) pPos = pPos->GetPortion(); if( !pPos || !rInf.GetIdx() || ( !pPos->GetLen() && pPos == rInf.GetRoot() ) ) return 0; // Nur noch BlankPortions unterwegs // Wenn vor uns ein Blank ist, brauchen wir kein Underflow ausloesen, // wenn hinter uns ein Blank ist, brauchen wir kein Underflow weiterreichen if (bUnderflow && nIdx + 1 < rInf.GetTxt().getLength() && CH_BLANK == rInf.GetTxt()[nIdx + 1]) return 0; if( nIdx && !((SwTxtFormatInfo&)rInf).GetFly() ) { while( pPos && !pPos->IsFlyPortion() ) pPos = pPos->GetPortion(); if( !pPos ) { //Hier wird ueberprueft, ob es in dieser Zeile noch sinnvolle Umbrueche //gibt, Blanks oder Felder etc., wenn nicht, kein Underflow. //Wenn Flys im Spiel sind, lassen wir das Underflow trotzdem zu. sal_Int32 nBlank = nIdx; while( --nBlank > rInf.GetLineStart() ) { const sal_Unicode cCh = rInf.GetChar( nBlank ); if( CH_BLANK == cCh || (( CH_TXTATR_BREAKWORD == cCh || CH_TXTATR_INWORD == cCh ) && rInf.HasHint( nBlank ) ) ) break; } if( nBlank <= rInf.GetLineStart() ) return 0; } } sal_Unicode cCh; if( nIdx < 2 || CH_BLANK == (cCh = rInf.GetChar( nIdx - 1 )) ) return 1; if( CH_BREAK == cCh ) return 0; return 2; } // Format end of Line void SwBlankPortion::FormatEOL( SwTxtFormatInfo &rInf ) { sal_uInt16 nMay = MayUnderflow( rInf, rInf.GetIdx() - nLineLength, true ); if( nMay ) { if( nMay > 1 ) { if( rInf.GetLast() == this ) rInf.SetLast( FindPrevPortion( rInf.GetRoot() ) ); rInf.X( rInf.X() - PrtWidth() ); rInf.SetIdx( rInf.GetIdx() - GetLen() ); } Truncate(); rInf.SetUnderflow( this ); if( rInf.GetLast()->IsKernPortion() ) rInf.SetUnderflow( rInf.GetLast() ); } } // 7771: Underflows weiterreichen und selbst ausloesen! bool SwBlankPortion::Format( SwTxtFormatInfo &rInf ) { const bool bFull = rInf.IsUnderflow() || SwExpandPortion::Format( rInf ); if( bFull && MayUnderflow( rInf, rInf.GetIdx(), rInf.IsUnderflow() ) ) { Truncate(); rInf.SetUnderflow( this ); if( rInf.GetLast()->IsKernPortion() ) rInf.SetUnderflow( rInf.GetLast() ); } return bFull; } void SwBlankPortion::Paint( const SwTxtPaintInfo &rInf ) const { if( !bMulti ) // No gray background for multiportion brackets rInf.DrawViewOpt( *this, POR_BLANK ); SwExpandPortion::Paint( rInf ); } bool SwBlankPortion::GetExpTxt( const SwTxtSizeInfo&, OUString &rTxt ) const { rTxt = OUString(cChar); return true; } void SwBlankPortion::HandlePortion( SwPortionHandler& rPH ) const { rPH.Special( GetLen(), OUString( cChar ), GetWhichPor() ); } SwPostItsPortion::SwPostItsPortion( bool bScrpt ) : bScript( bScrpt ) { nLineLength = 1; SetWhichPor( POR_POSTITS ); } void SwPostItsPortion::Paint( const SwTxtPaintInfo &rInf ) const { if( rInf.OnWin() && Width() ) rInf.DrawPostIts( *this, IsScript() ); } sal_uInt16 SwPostItsPortion::GetViewWidth( const SwTxtSizeInfo &rInf ) const { // Nicht zu fassen: PostIts sind immer zu sehen. return rInf.OnWin() ? rInf.GetOpt().GetPostItsWidth( rInf.GetOut() ) : 0; } bool SwPostItsPortion::Format( SwTxtFormatInfo &rInf ) { const bool bRet = SwLinePortion::Format( rInf ); // 32749: PostIts sollen keine Auswirkung auf Zeilenhoehe etc. haben SetAscent( 1 ); Height( 1 ); return bRet; } bool SwPostItsPortion::GetExpTxt( const SwTxtSizeInfo &rInf, OUString &rTxt ) const { if( rInf.OnWin() && rInf.GetOpt().IsPostIts() ) rTxt = OUString(' '); else rTxt = OUString(); return true; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: tablepg.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: svesik $ $Date: 2004-04-21 10:01:45 $ * * 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 _SWTABLEPG_HXX #define _SWTABLEPG_HXX #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _IMAGEBTN_HXX //autogen #include <vcl/imagebtn.hxx> #endif #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _ACTCTRL_HXX #include <actctrl.hxx> #endif #include "prcntfld.hxx" #include "swtypes.hxx" class SwTabCols; class SwWrtShell; class SwTableRep; struct TColumn { SwTwips nWidth; BOOL bVisible; }; class SwFormatTablePage : public SfxTabPage { FixedLine aOptionsFL; FixedText aNameFT; TableNameEdit aNameED; FixedText aWidthFT; PercentField aWidthMF; CheckBox aRelWidthCB; FixedLine aPosFL; RadioButton aFullBtn; RadioButton aLeftBtn; RadioButton aFromLeftBtn; RadioButton aRightBtn; RadioButton aCenterBtn; RadioButton aFreeBtn; FixedLine aDistFL; FixedText aLeftFT; PercentField aLeftMF; FixedText aRightFT; PercentField aRightMF; FixedText aTopFT; MetricField aTopMF; FixedText aBottomFT; MetricField aBottomMF; FixedLine aPropertiesFL; FixedText aTextDirectionFT; ListBox aTextDirectionLB; SwTableRep* pTblData; SwTwips nSaveWidth; SwTwips nMinTableWidth; USHORT nOldAlign; BOOL bModified; BOOL bFull:1; BOOL bHtmlMode : 1; void Init(); void ModifyHdl( Edit* pEdit ); DECL_LINK( AutoClickHdl, CheckBox * ); DECL_LINK( RelWidthClickHdl, CheckBox * ); DECL_LINK( RightModifyHdl, MetricField * ); DECL_LINK( UpDownLoseFocusHdl, MetricField * ); public: SwFormatTablePage( Window* pParent, const SfxItemSet& rSet ); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); virtual void ActivatePage( const SfxItemSet& rSet ); virtual int DeactivatePage( SfxItemSet* pSet = 0 ); }; /*------------------------------------------------------- TabPage Format/Tabelle/Spalten --------------------------------------------------------- */ #define MET_FIELDS 6 //Anzahl der verwendeten MetricFields class SwTableColumnPage : public SfxTabPage { CheckBox aModifyTableCB; CheckBox aProportionalCB; FixedText aSpaceFT; MetricField aSpaceED; ImageButton aUpBtn; FixedText aFT1; PercentField aMF1; FixedText aFT2; PercentField aMF2; FixedText aFT3; PercentField aMF3; FixedText aFT4; PercentField aMF4; FixedText aFT5; PercentField aMF5; FixedText aFT6; PercentField aMF6; ImageButton aDownBtn; FixedLine aColFL; SwTableRep* pTblData; PercentField* pFieldArr[MET_FIELDS]; FixedText* pTextArr[MET_FIELDS]; SwTwips nTableWidth; SwTwips nMinWidth; USHORT nNoOfCols; USHORT nNoOfVisibleCols; //Breite merken, wenn auf autom. Ausrichtung gestellt wird USHORT aValueTbl[MET_FIELDS];//primaere Zuordnung der MetricFields BOOL bModified:1; BOOL bModifyTbl:1; BOOL bPercentMode:1; void Init(BOOL bWeb); DECL_LINK( AutoClickHdl, CheckBox * ); void ModifyHdl( PercentField* pEdit ); DECL_LINK( UpHdl, PercentField * ); DECL_LINK( DownHdl, PercentField * ); DECL_LINK( LoseFocusHdl, PercentField * ); DECL_LINK( ModeHdl, CheckBox * ); void UpdateCols( USHORT nAktPos ); SwTwips GetVisibleWidth(USHORT nPos); void SetVisibleWidth(USHORT nPos, SwTwips nNewWidth); public: SwTableColumnPage( Window* pParent, const SfxItemSet& rSet ); ~SwTableColumnPage(); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); virtual void ActivatePage( const SfxItemSet& rSet ); virtual int DeactivatePage( SfxItemSet* pSet = 0 ); }; /*-----------------12.12.96 11.48------------------- Textflu --------------------------------------------------*/ class SwTextFlowPage : public SfxTabPage { FixedLine aFlowFL; CheckBox aPgBrkCB; RadioButton aPgBrkRB; RadioButton aColBrkRB; RadioButton aPgBrkBeforeRB; RadioButton aPgBrkAfterRB; CheckBox aPageCollCB; ListBox aPageCollLB; FixedText aPageNoFT; NumericField aPageNoNF; CheckBox aSplitCB; TriStateBox aSplitRowCB; CheckBox aKeepCB; CheckBox aHeadLineCB; FixedText aTextDirectionFT; ListBox aTextDirectionLB; FixedLine aVertOrientFL; FixedText aVertOrientFT; ListBox aVertOrientLB; SwWrtShell* pShell; BOOL bPageBreak; BOOL bHtmlMode; DECL_LINK( PageBreakHdl_Impl, CheckBox* ); DECL_LINK( ApplyCollClickHdl_Impl, CheckBox* ); DECL_LINK( PageBreakPosHdl_Impl, RadioButton* ); DECL_LINK( PageBreakTypeHdl_Impl, RadioButton* ); DECL_LINK( SplitHdl_Impl, CheckBox* ); DECL_LINK( SplitRowHdl_Impl, TriStateBox* ); SwTextFlowPage( Window* pParent, const SfxItemSet& rSet ); ~SwTextFlowPage(); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); void SetShell(SwWrtShell* pSh); void DisablePageBreak(); }; #endif <commit_msg>INTEGRATION: CWS gt03 (1.6.18); FILE MERGED 2004/04/23 20:29:58 gt 1.6.18.2: #26167# final strings and redesign 2004/04/08 11:17:45 gt 1.6.18.1: #i26167# repeated rows<commit_after>/************************************************************************* * * $RCSfile: tablepg.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2004-05-03 14:08:37 $ * * 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 _SWTABLEPG_HXX #define _SWTABLEPG_HXX #ifndef _SFXTABDLG_HXX //autogen #include <sfx2/tabdlg.hxx> #endif #ifndef _FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _IMAGEBTN_HXX //autogen #include <vcl/imagebtn.hxx> #endif #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _ACTCTRL_HXX #include <actctrl.hxx> #endif #include "prcntfld.hxx" #include "swtypes.hxx" #include "textcontrolcombo.hxx" class SwTabCols; class SwWrtShell; class SwTableRep; struct TColumn { SwTwips nWidth; BOOL bVisible; }; class SwFormatTablePage : public SfxTabPage { FixedLine aOptionsFL; FixedText aNameFT; TableNameEdit aNameED; FixedText aWidthFT; PercentField aWidthMF; CheckBox aRelWidthCB; FixedLine aPosFL; RadioButton aFullBtn; RadioButton aLeftBtn; RadioButton aFromLeftBtn; RadioButton aRightBtn; RadioButton aCenterBtn; RadioButton aFreeBtn; FixedLine aDistFL; FixedText aLeftFT; PercentField aLeftMF; FixedText aRightFT; PercentField aRightMF; FixedText aTopFT; MetricField aTopMF; FixedText aBottomFT; MetricField aBottomMF; FixedLine aPropertiesFL; FixedText aTextDirectionFT; ListBox aTextDirectionLB; SwTableRep* pTblData; SwTwips nSaveWidth; SwTwips nMinTableWidth; USHORT nOldAlign; BOOL bModified; BOOL bFull:1; BOOL bHtmlMode : 1; void Init(); void ModifyHdl( Edit* pEdit ); DECL_LINK( AutoClickHdl, CheckBox * ); DECL_LINK( RelWidthClickHdl, CheckBox * ); DECL_LINK( RightModifyHdl, MetricField * ); DECL_LINK( UpDownLoseFocusHdl, MetricField * ); public: SwFormatTablePage( Window* pParent, const SfxItemSet& rSet ); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); virtual void ActivatePage( const SfxItemSet& rSet ); virtual int DeactivatePage( SfxItemSet* pSet = 0 ); }; /*------------------------------------------------------- TabPage Format/Tabelle/Spalten --------------------------------------------------------- */ #define MET_FIELDS 6 //Anzahl der verwendeten MetricFields class SwTableColumnPage : public SfxTabPage { CheckBox aModifyTableCB; CheckBox aProportionalCB; FixedText aSpaceFT; MetricField aSpaceED; ImageButton aUpBtn; FixedText aFT1; PercentField aMF1; FixedText aFT2; PercentField aMF2; FixedText aFT3; PercentField aMF3; FixedText aFT4; PercentField aMF4; FixedText aFT5; PercentField aMF5; FixedText aFT6; PercentField aMF6; ImageButton aDownBtn; FixedLine aColFL; SwTableRep* pTblData; PercentField* pFieldArr[MET_FIELDS]; FixedText* pTextArr[MET_FIELDS]; SwTwips nTableWidth; SwTwips nMinWidth; USHORT nNoOfCols; USHORT nNoOfVisibleCols; //Breite merken, wenn auf autom. Ausrichtung gestellt wird USHORT aValueTbl[MET_FIELDS];//primaere Zuordnung der MetricFields BOOL bModified:1; BOOL bModifyTbl:1; BOOL bPercentMode:1; void Init(BOOL bWeb); DECL_LINK( AutoClickHdl, CheckBox * ); void ModifyHdl( PercentField* pEdit ); DECL_LINK( UpHdl, PercentField * ); DECL_LINK( DownHdl, PercentField * ); DECL_LINK( LoseFocusHdl, PercentField * ); DECL_LINK( ModeHdl, CheckBox * ); void UpdateCols( USHORT nAktPos ); SwTwips GetVisibleWidth(USHORT nPos); void SetVisibleWidth(USHORT nPos, SwTwips nNewWidth); public: SwTableColumnPage( Window* pParent, const SfxItemSet& rSet ); ~SwTableColumnPage(); static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); virtual void ActivatePage( const SfxItemSet& rSet ); virtual int DeactivatePage( SfxItemSet* pSet = 0 ); }; /*-----------------12.12.96 11.48------------------- Textflu --------------------------------------------------*/ class SwTextFlowPage : public SfxTabPage { FixedLine aFlowFL; CheckBox aPgBrkCB; RadioButton aPgBrkRB; RadioButton aColBrkRB; RadioButton aPgBrkBeforeRB; RadioButton aPgBrkAfterRB; CheckBox aPageCollCB; ListBox aPageCollLB; FixedText aPageNoFT; NumericField aPageNoNF; CheckBox aSplitCB; TriStateBox aSplitRowCB; CheckBox aKeepCB; CheckBox aHeadLineCB; FixedText aRepeatHeaderFT; // "dummy" to build before and after FT FixedText aRepeatHeaderBeforeFT; NumericField aRepeatHeaderNF; FixedText aRepeatHeaderAfterFT; TextControlCombo aRepeatHeaderCombo; FixedText aTextDirectionFT; ListBox aTextDirectionLB; FixedLine aVertOrientFL; FixedText aVertOrientFT; ListBox aVertOrientLB; SwWrtShell* pShell; BOOL bPageBreak; BOOL bHtmlMode; DECL_LINK( PageBreakHdl_Impl, CheckBox* ); DECL_LINK( ApplyCollClickHdl_Impl, CheckBox* ); DECL_LINK( PageBreakPosHdl_Impl, RadioButton* ); DECL_LINK( PageBreakTypeHdl_Impl, RadioButton* ); DECL_LINK( SplitHdl_Impl, CheckBox* ); DECL_LINK( SplitRowHdl_Impl, TriStateBox* ); DECL_LINK( HeadLineCBClickHdl, void* p = 0 ); SwTextFlowPage( Window* pParent, const SfxItemSet& rSet ); ~SwTextFlowPage(); public: static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet); virtual BOOL FillItemSet( SfxItemSet& rSet ); virtual void Reset( const SfxItemSet& rSet ); void SetShell(SwWrtShell* pSh); void DisablePageBreak(); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wrtundo.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: obo $ $Date: 2006-09-16 23:40:57 $ * * 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_sw.hxx" #define _SVSTDARR_STRINGSDTOR #ifndef _TOOLS_RESID_HXX #include <tools/resid.hxx> #endif #ifndef _SFXAPP_HXX //autogen #include <sfx2/app.hxx> #endif #ifndef _SFXSLSTITM_HXX #include <svtools/slstitm.hxx> #endif #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _SWUNDO_HXX #include <swundo.hxx> // fuer Undo-Ids #endif #ifndef _SWDTFLVR_HXX #include <swdtflvr.hxx> #endif #ifndef _WRTSH_HRC #include <wrtsh.hrc> #endif #include <sfx2/sfx.hrc> // Undo beendet alle Modi. Falls eine Selektion durch das Undo entstanden // ist, muss die fuer die weiteren Aktionen beruecksichtigt werden. void SwWrtShell::Do( DoType eDoType, USHORT nCnt ) { // #105332# save current state of DoesUndo() sal_Bool bSaveDoesUndo = DoesUndo(); StartAllAction(); switch( eDoType ) { case UNDO: DoUndo(sal_False); // #i21739# // Modi zuruecksetzen EnterStdMode(); SwEditShell::Undo(0, nCnt ); break; case REDO: DoUndo(sal_False); // #i21739# // Modi zuruecksetzen EnterStdMode(); SwEditShell::Redo( nCnt ); break; case REPEAT: // #i21739# do not touch undo flag here !!! SwEditShell::Repeat( nCnt ); break; } EndAllAction(); // #105332# restore undo state DoUndo(bSaveDoesUndo); BOOL bCreateXSelection = FALSE; const FASTBOOL bFrmSelected = IsFrmSelected() || IsObjSelected(); if ( IsSelection() ) { if ( bFrmSelected ) UnSelectFrm(); // Funktionspointer fuer das Aufheben der Selektion setzen // bei Cursor setzen fnKillSel = &SwWrtShell::ResetSelect; fnSetCrsr = &SwWrtShell::SetCrsrKillSel; bCreateXSelection = TRUE; } else if ( bFrmSelected ) { EnterSelFrmMode(); bCreateXSelection = TRUE; } else if( (CNT_GRF | CNT_OLE ) & GetCntType() ) { SelectObj( GetCharRect().Pos() ); EnterSelFrmMode(); bCreateXSelection = TRUE; } if( bCreateXSelection ) SwTransferable::CreateSelection( *this ); // Bug 32918: nach loeschen der Numerierung bleibt die Obj. Leiste stehen // Warum wird hier nicht immer ein CallChgLink gerufen? CallChgLnk(); } String SwWrtShell::GetDoString( DoType eDoType ) const { String aStr, aUndoStr; USHORT nResStr; switch( eDoType ) { case UNDO: nResStr = STR_UNDO; aUndoStr = GetUndoIdsStr(); break; case REDO: nResStr = STR_REDO; aUndoStr = GetRedoIdsStr(); break; } aStr.Insert( String(ResId( nResStr, SFX_APP()->GetSfxResManager())), 0 ); aStr += aUndoStr; return aStr; } USHORT SwWrtShell::GetDoStrings( DoType eDoType, SfxStringListItem& rStrs ) const { SwUndoIds aIds; switch( eDoType ) { case UNDO: GetUndoIds( 0, &aIds ); break; case REDO: GetRedoIds( 0, &aIds ); break; } String sList; for( USHORT n = 0, nEnd = aIds.Count(); n < nEnd; ++n ) { const SwUndoIdAndName& rIdNm = *aIds[ n ]; if( rIdNm.GetUndoStr() ) sList += *rIdNm.GetUndoStr(); else { ASSERT( !this, "no Undo/Redo Test set" ); } sList += '\n'; } rStrs.SetString( sList ); return aIds.Count(); } String SwWrtShell::GetRepeatString() const { String aStr; String aUndoStr = GetRepeatIdsStr(); if (aUndoStr.Len() > 0) { aStr.Insert( ResId( STR_REPEAT, SFX_APP()->GetSfxResManager()), 0 ); aStr += aUndoStr; } return aStr; } <commit_msg>INTEGRATION: CWS residcleanup (1.10.240); FILE MERGED 2007/03/04 17:03:13 pl 1.10.240.1: #i73635# ResId cleanup<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wrtundo.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2007-04-26 09:24:54 $ * * 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_sw.hxx" #define _SVSTDARR_STRINGSDTOR #ifndef _TOOLS_RESID_HXX #include <tools/resid.hxx> #endif #ifndef _SFXAPP_HXX //autogen #include <sfx2/app.hxx> #endif #ifndef _SFXSLSTITM_HXX #include <svtools/slstitm.hxx> #endif #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _SWUNDO_HXX #include <swundo.hxx> // fuer Undo-Ids #endif #ifndef _SWDTFLVR_HXX #include <swdtflvr.hxx> #endif #ifndef _WRTSH_HRC #include <wrtsh.hrc> #endif #include <sfx2/sfx.hrc> // Undo beendet alle Modi. Falls eine Selektion durch das Undo entstanden // ist, muss die fuer die weiteren Aktionen beruecksichtigt werden. void SwWrtShell::Do( DoType eDoType, USHORT nCnt ) { // #105332# save current state of DoesUndo() sal_Bool bSaveDoesUndo = DoesUndo(); StartAllAction(); switch( eDoType ) { case UNDO: DoUndo(sal_False); // #i21739# // Modi zuruecksetzen EnterStdMode(); SwEditShell::Undo(0, nCnt ); break; case REDO: DoUndo(sal_False); // #i21739# // Modi zuruecksetzen EnterStdMode(); SwEditShell::Redo( nCnt ); break; case REPEAT: // #i21739# do not touch undo flag here !!! SwEditShell::Repeat( nCnt ); break; } EndAllAction(); // #105332# restore undo state DoUndo(bSaveDoesUndo); BOOL bCreateXSelection = FALSE; const FASTBOOL bFrmSelected = IsFrmSelected() || IsObjSelected(); if ( IsSelection() ) { if ( bFrmSelected ) UnSelectFrm(); // Funktionspointer fuer das Aufheben der Selektion setzen // bei Cursor setzen fnKillSel = &SwWrtShell::ResetSelect; fnSetCrsr = &SwWrtShell::SetCrsrKillSel; bCreateXSelection = TRUE; } else if ( bFrmSelected ) { EnterSelFrmMode(); bCreateXSelection = TRUE; } else if( (CNT_GRF | CNT_OLE ) & GetCntType() ) { SelectObj( GetCharRect().Pos() ); EnterSelFrmMode(); bCreateXSelection = TRUE; } if( bCreateXSelection ) SwTransferable::CreateSelection( *this ); // Bug 32918: nach loeschen der Numerierung bleibt die Obj. Leiste stehen // Warum wird hier nicht immer ein CallChgLink gerufen? CallChgLnk(); } String SwWrtShell::GetDoString( DoType eDoType ) const { String aStr, aUndoStr; USHORT nResStr; switch( eDoType ) { case UNDO: nResStr = STR_UNDO; aUndoStr = GetUndoIdsStr(); break; case REDO: nResStr = STR_REDO; aUndoStr = GetRedoIdsStr(); break; } aStr.Insert( String(ResId( nResStr, *SFX_APP()->GetSfxResManager())), 0 ); aStr += aUndoStr; return aStr; } USHORT SwWrtShell::GetDoStrings( DoType eDoType, SfxStringListItem& rStrs ) const { SwUndoIds aIds; switch( eDoType ) { case UNDO: GetUndoIds( 0, &aIds ); break; case REDO: GetRedoIds( 0, &aIds ); break; } String sList; for( USHORT n = 0, nEnd = aIds.Count(); n < nEnd; ++n ) { const SwUndoIdAndName& rIdNm = *aIds[ n ]; if( rIdNm.GetUndoStr() ) sList += *rIdNm.GetUndoStr(); else { ASSERT( !this, "no Undo/Redo Test set" ); } sList += '\n'; } rStrs.SetString( sList ); return aIds.Count(); } String SwWrtShell::GetRepeatString() const { String aStr; String aUndoStr = GetRepeatIdsStr(); if (aUndoStr.Len() > 0) { aStr.Insert( ResId( STR_REPEAT, *SFX_APP()->GetSfxResManager()), 0 ); aStr += aUndoStr; } return aStr; } <|endoftext|>
<commit_before><commit_msg>SwWrtShell::GetDoStrings: bogus assertion<commit_after><|endoftext|>
<commit_before>//Sample provided by Thiago Massari Guedes //April 2015 //http://www.simplycpp.com/ #include "example_main.h" #include <iostream> #include <algorithm> #include <vector> using namespace std; //Generico. Sem tipos declarados #define FILL(v, i, start, end, step) { \ for(i=start; i < end; i+=step) \ v.push_back(i); \ } //Repare que aqui eu preciso ter operador [] #define DUMP(v) { \ for(int i=0; i < v.size(); i++) \ cout << v[i] << " "; \ cout << endl; \ } #define INCREMENT(v, n) { \ for(int i=0; i < v.size(); i++) \ v[i] += n; \ } #define ACCUM(v, ret) { \ for(int i=0; i < v.size(); i++) \ ret += v[i]; \ } void run_macro() { vector<int> numbers; int i; FILL(numbers, i, 0, 20, 2); DUMP(numbers); INCREMENT(numbers, 1); DUMP(numbers); int total=0; ACCUM(numbers, total); cout << "sum: " << total << endl; } template<typename T, typename U> void fill(T &t, U start, U end, U step) { for(U i=start; i < end; i += step) { t.push_back(i); } } template<typename T> void dump(T &t) { for(const auto &it : t) { cout << it << " "; } cout << endl; } template<typename T, typename U> void increment(T &t, const U &val) { for(auto &item : t) { item += val; } } template<typename RET, typename T> RET accum(T &t) { RET ret{}; for(auto &item : t) { ret += item; } return ret; } void run_templ() { vector<int> numbers; fill(numbers, 0, 20, 2); dump(numbers); increment(numbers, 1); dump(numbers); int total = accum<int>(numbers); cout << "sum: " << total << endl; } template<typename T, typename U> void fill2(T &v, U start, U step) { for(auto &item : v) { item = start; start += step; } //alternative //generate(begin(v), end(v), [&start, &step]() { auto r = start; start += step; return r; }); } template<typename T> void dump2(T &v) { for_each(begin(v), end(v), [](auto &n) { cout << n << " "; }); cout << endl; } template<typename T, typename U> void increment2(T &v, const U &val) { for_each(begin(v), end(v), [&val](U &n) { n += val; }); } template<typename RET, typename T> RET accum2(T &v) { RET ret{}; //auto inside lamba, only in c++14 for_each(begin(v), end(v), [&ret](auto &val) { ret += val; }); return ret; } void run_templ_stl() { vector<int> numbers(10); fill2(numbers, 0, 2); dump2(numbers); increment2(numbers, 1); dump2(numbers); int total = accum2<int>(numbers); cout << "sum: " << total << endl; } EXAMPLE_MAIN(macro_templ) { run_macro(); //C-style run_templ(); //C++-style without stl run_templ_stl(); //C++-style with stl return 0; } <commit_msg>versao final post<commit_after>//Sample provided by Thiago Massari Guedes //April 2015 //http://www.simplycpp.com/ #include "example_main.h" #include <iostream> #include <algorithm> #include <vector> using namespace std; //Generico. Sem tipos declarados #define FILL(v, i, start, end, step) { \ for(i=start; i < end; i+=step) \ v.push_back(i); \ } //Repare que aqui eu preciso ter operador [] #define DUMP(v) { \ for(int i=0; i < v.size(); i++) \ cout << v[i] << " "; \ cout << endl; \ } #define INCREMENT(v, n) { \ for(int i=0; i < v.size(); i++) \ v[i] += n; \ } #define ACCUM(v, ret) { \ for(int i=0; i < v.size(); i++) \ ret += v[i]; \ } void run_macro() { vector<int> numbers; int i; FILL(numbers, i, 0, 20, 2); DUMP(numbers); INCREMENT(numbers, 1); DUMP(numbers); int total=0; ACCUM(numbers, total); cout << "sum: " << total << endl; } template<typename T, typename U> void fill(T &t, U start, U end, U step) { for(U i=start; i < end; i += step) { t.push_back(i); } } template<typename T> void dump(T &t) { for(const auto &it : t) { cout << it << " "; } cout << endl; } template<typename T, typename U> void increment(T &t, const U &val) { for(auto &item : t) { item += val; } } template<typename T> auto accum(T &t) { typename T::value_type ret{}; for(auto &item : t) { ret += item; } return ret; } void run_templ() { vector<int> numbers; fill(numbers, 0, 20, 2); dump(numbers); increment(numbers, 1); dump(numbers); int total = accum(numbers); cout << "sum: " << total << endl; } template<typename T, typename U> void fill2(T &v, U start, U step) { *begin(v) = start; generate(begin(v)+1, end(v), [&start, &step]() { return start += step; }); //alternative - this is not a proper std::fill, but a generate // for(auto &item : v) { // item = start; // start += step; // } } template<typename T> void dump2(T &v) { for_each(begin(v), end(v), [](auto &n) { cout << n << " "; }); cout << endl; } template<typename T, typename U> void increment2(T &v, const U &val) { for_each(begin(v), end(v), [&val](U &n) { n += val; }); } template<typename T> typename T::value_type accum2(T &v) { typename T::value_type ret{}; //auto inside lamba, only in c++14 for_each(begin(v), end(v), [&ret](auto &val) { ret += val; }); return ret; } void run_templ_stl() { vector<int> numbers(10); fill2(numbers, 0, 2); dump2(numbers); increment2(numbers, 1); dump2(numbers); int total = accum2(numbers); cout << "sum: " << total << endl; } EXAMPLE_MAIN(macro_templ) { run_macro(); //C-style run_templ(); //C++-style without stl run_templ_stl(); //C++-style with stl return 0; } <|endoftext|>
<commit_before>/** @file uml_nodeelement.cpp * @brief Класс, представляющий объект на диаграмме * */ #include <QtGui> #include "uml_nodeelement.h" #include "realrepomodel.h" #include "realreporoles.h" #include "editorviewscene.h" using namespace UML; NodeElement::NodeElement() : portsVisible(false) { setAcceptsHoverEvents(true); dragState = None; } NodeElement::~NodeElement() { foreach (EdgeElement *edge, edgeList) edge->removeLink(this); } void NodeElement::mousePressEvent( QGraphicsSceneMouseEvent * event ) { if ( isSelected() ) { if ( QRectF(m_contents.topLeft(),QSizeF(4,4)).contains(event->pos()) ) { dragState = TopLeft; } else if ( QRectF(m_contents.topRight(),QSizeF(-4,4)).contains(event->pos()) ) { dragState = TopRight; } else if ( QRectF(m_contents.bottomRight(),QSizeF(-12,-12)).contains(event->pos()) ) { dragState = BottomRight; } else if ( QRectF(m_contents.bottomLeft(),QSizeF(4,-4)).contains(event->pos()) ) { dragState = BottomLeft; } else Element::mousePressEvent(event); } else Element::mousePressEvent(event); } void NodeElement::mouseMoveEvent ( QGraphicsSceneMouseEvent * event ) { if ( dragState == None ) { Element::mouseMoveEvent(event); } else { QRectF newcontents = m_contents; switch ( dragState ) { case TopLeft: newcontents.setTopLeft(event->pos()); break; case Top: newcontents.setTop(event->pos().y()); break; case TopRight: newcontents.setTopRight(event->pos()); break; case Left: newcontents.setLeft(event->pos().x()); break; case Right: newcontents.setRight(event->pos().x()); break; case BottomLeft: newcontents.setBottomLeft(event->pos()); break; case Bottom: newcontents.setBottom(event->pos().y()); break; case BottomRight: newcontents.setBottomRight(event->pos()); break; case None: break; } if (event->modifiers() & Qt::ShiftModifier) { qreal size = std::max(newcontents.width(), newcontents.height()); newcontents.setWidth(size); newcontents.setHeight(size); } if ( ! ( ( newcontents.width() < 10 ) || ( newcontents.height() < 10 ) ) ) { prepareGeometryChange(); m_contents = newcontents; setPos(pos() + m_contents.topLeft()); m_contents.translate(-m_contents.topLeft()); transform.reset(); transform.scale(m_contents.width(), m_contents.height()); foreach (EdgeElement *edge, edgeList) edge->adjustLink(); } } } void NodeElement::mouseReleaseEvent ( QGraphicsSceneMouseEvent * event ) { m_contents = m_contents.normalized(); moving = 1; RealRepoModel *im = (RealRepoModel *)(dataIndex.model()); im->setData(dataIndex, pos(), Unreal::PositionRole); im->setData(dataIndex, QPolygon(m_contents.toAlignedRect()), Unreal::ConfigurationRole); NodeElement *newParent = getNodeAt(event->scenePos()); moving = 0; if ( dragState != None ) dragState = None; else Element::mouseReleaseEvent(event); EditorViewScene *evscene = dynamic_cast<EditorViewScene *>(scene()); if (newParent) { im->changeParent(dataIndex,newParent->dataIndex, mapToItem(evscene->getElemByModelIndex(newParent->dataIndex),mapFromScene(scenePos()))); } else { im->changeParent(dataIndex,evscene->rootItem(),scenePos()); } } QVariant NodeElement::itemChange(GraphicsItemChange change, const QVariant &value) { switch ( change ) { case ItemPositionHasChanged: foreach (EdgeElement *edge, edgeList) edge->adjustLink(); return value; default: return QGraphicsItem::itemChange(change, value); } } QRectF NodeElement::contentsRect() const { return m_contents; } QRectF NodeElement::boundingRect() const { return m_contents.adjusted(-kvadratik,-kvadratik,kvadratik,kvadratik); } void NodeElement::updateData() { Element::updateData(); if (moving == 0) { setPos(dataIndex.data(Unreal::PositionRole).toPointF()); QRectF newRect = dataIndex.data(Unreal::ConfigurationRole).value<QPolygon>().boundingRect(); if ( ! newRect.isEmpty() ) m_contents = newRect; else if (!m_contents.isEmpty()) // This a temporary hack { QAbstractItemModel *im = const_cast<QAbstractItemModel *>(dataIndex.model()); im->setData(dataIndex, QPolygon(m_contents.toAlignedRect()), Unreal::ConfigurationRole); } transform.reset(); transform.scale(m_contents.width(), m_contents.height()); } } static int portId(qreal id) { int iid = qRound(id); if ( id < ( 1.0 * iid ) ) return iid - 1; else return iid; } const QPointF NodeElement::getPortPos(qreal id) const { int iid = portId(id); if ( id < 0.0 ) return QPointF(0,0); if ( id < pointPorts.size() ) return transform.map(pointPorts[iid]); if ( id < pointPorts.size() + linePorts.size() ) return newTransform(linePorts.at(iid - pointPorts.size())).pointAt(id - 1.0 * iid); else return QPointF(0,0); } QLineF NodeElement::newTransform(const statLine& port) const { float x1,x2,y1,y2; if (port.px1) x1=port.line.x1()*100; else x1=port.line.x1()*contentsRect().width(); if (port.py1) y1=port.line.y1()*100; else y1=port.line.y1()*contentsRect().height(); if (port.px2) x2=port.line.x2()*100; else x2=port.line.x2()*contentsRect().width(); if (port.py2) y2=port.line.y2()*100; else y2=port.line.y2()*contentsRect().height(); return QLineF(x1,y1,x2,y2); } qreal NodeElement::getPortId(const QPointF &location) const { for( int i = 0; i < pointPorts.size(); i++ ) { if ( QRectF(transform.map(pointPorts[i])-QPointF(kvadratik,kvadratik),QSizeF(kvadratik*2,kvadratik*2)).contains( location ) ) return 1.0 * i; } for( int i = 0; i < linePorts.size(); i++ ) { QPainterPathStroker ps; ps.setWidth(kvadratik); QPainterPath path; path.moveTo(newTransform(linePorts[i]).p1()); path.lineTo(newTransform(linePorts[i]).p2()); path = ps.createStroke(path); if ( path.contains(location) ) return ( 1.0 * ( i + pointPorts.size() ) + qMin( 0.9999, QLineF( QLineF(newTransform(linePorts[i])).p1(),location).length() / newTransform(linePorts[i]).length() ) ); } if (pointPorts.size()!=0) { int numMinDistance = 0; qreal minDistance = QLineF( pointPorts[0], transform.inverted().map(location) ).length(); for( int i = 0; i < pointPorts.size(); i++ ) { if (QLineF( pointPorts[i], transform.inverted().map(location) ).length()<minDistance) { numMinDistance = i; minDistance = QLineF( pointPorts[i], transform.inverted().map(location) ).length(); } } return 1.0 * numMinDistance; } else if (linePorts.size()!=0) { int numMinDistance = 0; qreal minDistance = QLineF( QLineF(linePorts[0]).p1(), transform.inverted().map(location) ).length(); for( int i = 0; i < linePorts.size(); i++ ) { if (QLineF( QLineF(linePorts[i]).p1(), transform.inverted().map(location) ).length()<minDistance) { numMinDistance = i; minDistance = QLineF( QLineF(linePorts[i]).p1(), transform.inverted().map(location) ).length(); } } return 1.0 * (numMinDistance + pointPorts.size()); } return -1.0; } void NodeElement::setPortsVisible(bool value) { prepareGeometryChange(); portsVisible = value; } NodeElement *NodeElement::getNodeAt( const QPointF &position ) { foreach( QGraphicsItem *item, scene()->items(position) ) { NodeElement *e = dynamic_cast<NodeElement *>(item); if (( e )&&(item!=this)) return e; } return 0; } void NodeElement::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget*, SdfRenderer* portrenderer) { if (option->levelOfDetail >= 0.5) { if ( option->state & QStyle::State_Selected ) { painter->save(); QBrush b; b.setColor(Qt::blue); b.setStyle(Qt::SolidPattern); painter->setBrush(b); painter->setPen(Qt::blue); painter->drawRect(QRectF(m_contents.topLeft(),QSizeF(4,4))); painter->drawRect(QRectF(m_contents.topRight(),QSizeF(-4,4))); painter->drawRect(QRectF(m_contents.bottomLeft(),QSizeF(4,-4))); painter->translate(m_contents.bottomRight()); painter->drawLine(QLineF(-4,0,0,-4)); painter->drawLine(QLineF(-8,0,0,-8)); painter->drawLine(QLineF(-12,0,0,-12)); painter->restore(); } if ((option->state & QStyle::State_MouseOver) || portsVisible) { painter->save(); painter->setOpacity(0.7); portrenderer->render(painter,m_contents); painter->restore(); } } } <commit_msg>StyleGuide<commit_after>/** @file uml_nodeelement.cpp * @brief Класс, представляющий объект на диаграмме * */ #include <QtGui> #include "uml_nodeelement.h" #include "realrepomodel.h" #include "realreporoles.h" #include "editorviewscene.h" using namespace UML; NodeElement::NodeElement() : portsVisible(false) { setAcceptsHoverEvents(true); dragState = None; } NodeElement::~NodeElement() { foreach (EdgeElement *edge, edgeList) edge->removeLink(this); } void NodeElement::mousePressEvent( QGraphicsSceneMouseEvent * event ) { if ( isSelected() ) { if ( QRectF(m_contents.topLeft(),QSizeF(4,4)).contains(event->pos()) ) { dragState = TopLeft; } else if ( QRectF(m_contents.topRight(),QSizeF(-4,4)).contains(event->pos()) ) { dragState = TopRight; } else if ( QRectF(m_contents.bottomRight(),QSizeF(-12,-12)).contains(event->pos()) ) { dragState = BottomRight; } else if ( QRectF(m_contents.bottomLeft(),QSizeF(4,-4)).contains(event->pos()) ) { dragState = BottomLeft; } else Element::mousePressEvent(event); } else Element::mousePressEvent(event); } void NodeElement::mouseMoveEvent ( QGraphicsSceneMouseEvent * event ) { if ( dragState == None ) { Element::mouseMoveEvent(event); } else { QRectF newcontents = m_contents; switch ( dragState ) { case TopLeft: newcontents.setTopLeft(event->pos()); break; case Top: newcontents.setTop(event->pos().y()); break; case TopRight: newcontents.setTopRight(event->pos()); break; case Left: newcontents.setLeft(event->pos().x()); break; case Right: newcontents.setRight(event->pos().x()); break; case BottomLeft: newcontents.setBottomLeft(event->pos()); break; case Bottom: newcontents.setBottom(event->pos().y()); break; case BottomRight: newcontents.setBottomRight(event->pos()); break; case None: break; } if (event->modifiers() & Qt::ShiftModifier) { qreal size = std::max(newcontents.width(), newcontents.height()); newcontents.setWidth(size); newcontents.setHeight(size); } if ( ! ( ( newcontents.width() < 10 ) || ( newcontents.height() < 10 ) ) ) { prepareGeometryChange(); m_contents = newcontents; setPos(pos() + m_contents.topLeft()); m_contents.translate(-m_contents.topLeft()); transform.reset(); transform.scale(m_contents.width(), m_contents.height()); foreach (EdgeElement *edge, edgeList) edge->adjustLink(); } } } void NodeElement::mouseReleaseEvent ( QGraphicsSceneMouseEvent * event ) { m_contents = m_contents.normalized(); moving = 1; RealRepoModel *im = (RealRepoModel *)(dataIndex.model()); im->setData(dataIndex, pos(), Unreal::PositionRole); im->setData(dataIndex, QPolygon(m_contents.toAlignedRect()), Unreal::ConfigurationRole); NodeElement *newParent = getNodeAt(event->scenePos()); moving = 0; if ( dragState != None ) dragState = None; else Element::mouseReleaseEvent(event); EditorViewScene *evscene = dynamic_cast<EditorViewScene *>(scene()); if (newParent) { im->changeParent(dataIndex,newParent->dataIndex, mapToItem(evscene->getElemByModelIndex(newParent->dataIndex),mapFromScene(scenePos()))); } else { im->changeParent(dataIndex,evscene->rootItem(),scenePos()); } } QVariant NodeElement::itemChange(GraphicsItemChange change, const QVariant &value) { switch ( change ) { case ItemPositionHasChanged: foreach (EdgeElement *edge, edgeList) edge->adjustLink(); return value; default: return QGraphicsItem::itemChange(change, value); } } QRectF NodeElement::contentsRect() const { return m_contents; } QRectF NodeElement::boundingRect() const { return m_contents.adjusted(-kvadratik,-kvadratik,kvadratik,kvadratik); } void NodeElement::updateData() { Element::updateData(); if (moving == 0) { setPos(dataIndex.data(Unreal::PositionRole).toPointF()); QRectF newRect = dataIndex.data(Unreal::ConfigurationRole).value<QPolygon>().boundingRect(); if ( ! newRect.isEmpty() ) m_contents = newRect; else if (!m_contents.isEmpty()) // This a temporary hack { QAbstractItemModel *im = const_cast<QAbstractItemModel *>(dataIndex.model()); im->setData(dataIndex, QPolygon(m_contents.toAlignedRect()), Unreal::ConfigurationRole); } transform.reset(); transform.scale(m_contents.width(), m_contents.height()); } } static int portId(qreal id) { int iid = qRound(id); if ( id < ( 1.0 * iid ) ) return iid - 1; else return iid; } const QPointF NodeElement::getPortPos(qreal id) const { int iid = portId(id); if ( id < 0.0 ) return QPointF(0,0); if ( id < pointPorts.size() ) return transform.map(pointPorts[iid]); if ( id < pointPorts.size() + linePorts.size() ) return newTransform(linePorts.at(iid - pointPorts.size())).pointAt(id - 1.0 * iid); else return QPointF(0,0); } QLineF NodeElement::newTransform(const statLine& port) const { float x1, x2, y1, y2; if (port.px1) x1 = port.line.x1() * 100; else x1 = port.line.x1() * contentsRect().width(); if (port.py1) y1 = port.line.y1() * 100; else y1 = port.line.y1() * contentsRect().height(); if (port.px2) x2 = port.line.x2() * 100; else x2 = port.line.x2() * contentsRect().width(); if (port.py2) y2 = port.line.y2() * 100; else y2 = port.line.y2() * contentsRect().height(); return QLineF(x1, y1, x2, y2); } qreal NodeElement::getPortId(const QPointF &location) const { for( int i = 0; i < pointPorts.size(); i++ ) { if ( QRectF(transform.map(pointPorts[i])-QPointF(kvadratik,kvadratik),QSizeF(kvadratik*2,kvadratik*2)).contains( location ) ) return 1.0 * i; } for( int i = 0; i < linePorts.size(); i++ ) { QPainterPathStroker ps; ps.setWidth(kvadratik); QPainterPath path; path.moveTo(newTransform(linePorts[i]).p1()); path.lineTo(newTransform(linePorts[i]).p2()); path = ps.createStroke(path); if ( path.contains(location) ) return ( 1.0 * ( i + pointPorts.size() ) + qMin( 0.9999, QLineF( QLineF(newTransform(linePorts[i])).p1(),location).length() / newTransform(linePorts[i]).length() ) ); } if (pointPorts.size()!=0) { int numMinDistance = 0; qreal minDistance = QLineF( pointPorts[0], transform.inverted().map(location) ).length(); for( int i = 0; i < pointPorts.size(); i++ ) { if (QLineF( pointPorts[i], transform.inverted().map(location) ).length()<minDistance) { numMinDistance = i; minDistance = QLineF( pointPorts[i], transform.inverted().map(location) ).length(); } } return 1.0 * numMinDistance; } else if (linePorts.size()!=0) { int numMinDistance = 0; qreal minDistance = QLineF( QLineF(linePorts[0]).p1(), transform.inverted().map(location) ).length(); for( int i = 0; i < linePorts.size(); i++ ) { if (QLineF( QLineF(linePorts[i]).p1(), transform.inverted().map(location) ).length()<minDistance) { numMinDistance = i; minDistance = QLineF( QLineF(linePorts[i]).p1(), transform.inverted().map(location) ).length(); } } return 1.0 * (numMinDistance + pointPorts.size()); } return -1.0; } void NodeElement::setPortsVisible(bool value) { prepareGeometryChange(); portsVisible = value; } NodeElement *NodeElement::getNodeAt( const QPointF &position ) { foreach( QGraphicsItem *item, scene()->items(position) ) { NodeElement *e = dynamic_cast<NodeElement *>(item); if (( e )&&(item!=this)) return e; } return 0; } void NodeElement::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget*, SdfRenderer* portrenderer) { if (option->levelOfDetail >= 0.5) { if ( option->state & QStyle::State_Selected ) { painter->save(); QBrush b; b.setColor(Qt::blue); b.setStyle(Qt::SolidPattern); painter->setBrush(b); painter->setPen(Qt::blue); painter->drawRect(QRectF(m_contents.topLeft(),QSizeF(4,4))); painter->drawRect(QRectF(m_contents.topRight(),QSizeF(-4,4))); painter->drawRect(QRectF(m_contents.bottomLeft(),QSizeF(4,-4))); painter->translate(m_contents.bottomRight()); painter->drawLine(QLineF(-4,0,0,-4)); painter->drawLine(QLineF(-8,0,0,-8)); painter->drawLine(QLineF(-12,0,0,-12)); painter->restore(); } if ((option->state & QStyle::State_MouseOver) || portsVisible) { painter->save(); painter->setOpacity(0.7); portrenderer->render(painter,m_contents); painter->restore(); } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: except.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2003-04-15 16:26:28 $ * * 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 <stdio.h> #include <dlfcn.h> #include <cxxabi.h> #include <hash_map> #include <rtl/strbuf.hxx> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <osl/mutex.hxx> #include <bridges/cpp_uno/bridge.hxx> #include <typelib/typedescription.hxx> #include <uno/any2.h> #include "share.hxx" using namespace ::std; using namespace ::osl; using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::__cxxabiv1; namespace CPPU_CURRENT_NAMESPACE { void dummy_can_throw_anything( char const * ) { } //================================================================================================== static OUString toUNOname( char const * p ) SAL_THROW( () ) { #if OSL_DEBUG_LEVEL > 1 char const * start = p; #endif // example: N3com3sun4star4lang24IllegalArgumentExceptionE OUStringBuffer buf( 64 ); OSL_ASSERT( 'N' == *p ); ++p; // skip N while ('E' != *p) { // read chars count long n = (*p++ - '0'); while ('0' <= *p && '9' >= *p) { n *= 10; n += (*p++ - '0'); } buf.appendAscii( p, n ); p += n; if ('E' != *p) buf.append( (sal_Unicode)'.' ); } #if OSL_DEBUG_LEVEL > 1 OUString ret( buf.makeStringAndClear() ); OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> toUNOname(): %s => %s\n", start, c_ret.getStr() ); return ret; #else return buf.makeStringAndClear(); #endif } //================================================================================================== class RTTI { typedef hash_map< OUString, type_info *, OUStringHash > t_rtti_map; Mutex m_mutex; t_rtti_map m_rttis; t_rtti_map m_generatedRttis; void * m_hApp; public: RTTI() SAL_THROW( () ); ~RTTI() SAL_THROW( () ); type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW( () ); }; //__________________________________________________________________________________________________ RTTI::RTTI() SAL_THROW( () ) : m_hApp( dlopen( 0, RTLD_LAZY ) ) { } //__________________________________________________________________________________________________ RTTI::~RTTI() SAL_THROW( () ) { dlclose( m_hApp ); } //__________________________________________________________________________________________________ type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW( () ) { type_info * rtti; OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName; MutexGuard guard( m_mutex ); t_rtti_map::const_iterator iFind( m_rttis.find( unoName ) ); if (iFind == m_rttis.end()) { // RTTI symbol OStringBuffer buf( 64 ); buf.append( RTL_CONSTASCII_STRINGPARAM("_ZTIN") ); sal_Int32 index = 0; do { OUString token( unoName.getToken( 0, '.', index ) ); buf.append( token.getLength() ); OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) ); buf.append( c_token ); } while (index >= 0); buf.append( 'E' ); OString symName( buf.makeStringAndClear() ); rtti = (type_info *)dlsym( m_hApp, symName.getStr() ); if (rtti) { pair< t_rtti_map::iterator, bool > insertion( m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); OSL_ENSURE( insertion.second, "### inserting new rtti failed?!" ); } else { // try to lookup the symbol in the generated rtti map t_rtti_map::const_iterator iFind( m_generatedRttis.find( unoName ) ); if (iFind == m_generatedRttis.end()) { // we must generate it ! // symbol and rtti-name is nearly identical, // the symbol is prefixed with _ZTI char const * rttiName = symName.getStr() +4; #if OSL_DEBUG_LEVEL > 1 fprintf( stderr,"generated rtti for %s\n", rttiName ); #endif if (pTypeDescr->pBaseTypeDescription) { // ensure availability of base type_info * base_rtti = getRTTI( (typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription ); rtti = new __si_class_type_info( strdup( rttiName ), (__class_type_info *)base_rtti ); } else { // this class has no base class rtti = new __class_type_info( strdup( rttiName ) ); } pair< t_rtti_map::iterator, bool > insertion( m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); OSL_ENSURE( insertion.second, "### inserting new generated rtti failed?!" ); } else // taking already generated rtti { rtti = iFind->second; } } } else { rtti = iFind->second; } return rtti; } //-------------------------------------------------------------------------------------------------- static void deleteException( void * pExc ) { __cxa_exception const * header = ((__cxa_exception const *)pExc - 1); typelib_TypeDescription * pTD = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); ::typelib_typedescription_getByName( &pTD, unoName.pData ); OSL_ENSURE( pTD, "### unknown exception type! leaving out destruction => leaking!!!" ); if (pTD) { ::uno_destructData( pExc, pTD, cpp_release ); ::typelib_typedescription_release( pTD ); } } //================================================================================================== void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp ) { void * pCppExc; type_info * rtti; { // construct cpp exception object typelib_TypeDescription * pTypeDescr = 0; TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType ); OSL_ASSERT( pTypeDescr ); if (! pTypeDescr) terminate(); pCppExc = __cxa_allocate_exception( pTypeDescr->nSize ); ::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp ); // destruct uno exception ::uno_any_destruct( pUnoExc, 0 ); // avoiding locked counts static RTTI * s_rtti = 0; if (! s_rtti) { MutexGuard guard( Mutex::getGlobalMutex() ); if (! s_rtti) { #ifdef LEAK_STATIC_DATA s_rtti = new RTTI(); #else static RTTI rtti_data; s_rtti = &rtti_data; #endif } } rtti = (type_info *)s_rtti->getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr ); TYPELIB_DANGER_RELEASE( pTypeDescr ); OSL_ENSURE( rtti, "### no rtti for throwing exception!" ); if (! rtti) terminate(); } __cxa_throw( pCppExc, rtti, deleteException ); } //================================================================================================== void fillUnoException( __cxa_exception * header, uno_Any * pExc, uno_Mapping * pCpp2Uno ) { OSL_ENSURE( header, "### no exception header!!!" ); if (! header) terminate(); typelib_TypeDescription * pExcTypeDescr = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); ::typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData ); OSL_ENSURE( pExcTypeDescr, "### can not get type description for exception!!!" ); if (! pExcTypeDescr) terminate(); // construct uno exception any ::uno_any_constructAndConvert( pExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno ); ::typelib_typedescription_release( pExcTypeDescr ); } } <commit_msg>INTEGRATION: CWS ooo19126 (1.3.194); FILE MERGED 2005/09/05 17:07:20 rt 1.3.194.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: except.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-07 22:24:07 $ * * 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 <stdio.h> #include <dlfcn.h> #include <cxxabi.h> #include <hash_map> #include <rtl/strbuf.hxx> #include <rtl/ustrbuf.hxx> #include <osl/diagnose.h> #include <osl/mutex.hxx> #include <bridges/cpp_uno/bridge.hxx> #include <typelib/typedescription.hxx> #include <uno/any2.h> #include "share.hxx" using namespace ::std; using namespace ::osl; using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::__cxxabiv1; namespace CPPU_CURRENT_NAMESPACE { void dummy_can_throw_anything( char const * ) { } //================================================================================================== static OUString toUNOname( char const * p ) SAL_THROW( () ) { #if OSL_DEBUG_LEVEL > 1 char const * start = p; #endif // example: N3com3sun4star4lang24IllegalArgumentExceptionE OUStringBuffer buf( 64 ); OSL_ASSERT( 'N' == *p ); ++p; // skip N while ('E' != *p) { // read chars count long n = (*p++ - '0'); while ('0' <= *p && '9' >= *p) { n *= 10; n += (*p++ - '0'); } buf.appendAscii( p, n ); p += n; if ('E' != *p) buf.append( (sal_Unicode)'.' ); } #if OSL_DEBUG_LEVEL > 1 OUString ret( buf.makeStringAndClear() ); OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) ); fprintf( stderr, "> toUNOname(): %s => %s\n", start, c_ret.getStr() ); return ret; #else return buf.makeStringAndClear(); #endif } //================================================================================================== class RTTI { typedef hash_map< OUString, type_info *, OUStringHash > t_rtti_map; Mutex m_mutex; t_rtti_map m_rttis; t_rtti_map m_generatedRttis; void * m_hApp; public: RTTI() SAL_THROW( () ); ~RTTI() SAL_THROW( () ); type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW( () ); }; //__________________________________________________________________________________________________ RTTI::RTTI() SAL_THROW( () ) : m_hApp( dlopen( 0, RTLD_LAZY ) ) { } //__________________________________________________________________________________________________ RTTI::~RTTI() SAL_THROW( () ) { dlclose( m_hApp ); } //__________________________________________________________________________________________________ type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW( () ) { type_info * rtti; OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName; MutexGuard guard( m_mutex ); t_rtti_map::const_iterator iFind( m_rttis.find( unoName ) ); if (iFind == m_rttis.end()) { // RTTI symbol OStringBuffer buf( 64 ); buf.append( RTL_CONSTASCII_STRINGPARAM("_ZTIN") ); sal_Int32 index = 0; do { OUString token( unoName.getToken( 0, '.', index ) ); buf.append( token.getLength() ); OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) ); buf.append( c_token ); } while (index >= 0); buf.append( 'E' ); OString symName( buf.makeStringAndClear() ); rtti = (type_info *)dlsym( m_hApp, symName.getStr() ); if (rtti) { pair< t_rtti_map::iterator, bool > insertion( m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); OSL_ENSURE( insertion.second, "### inserting new rtti failed?!" ); } else { // try to lookup the symbol in the generated rtti map t_rtti_map::const_iterator iFind( m_generatedRttis.find( unoName ) ); if (iFind == m_generatedRttis.end()) { // we must generate it ! // symbol and rtti-name is nearly identical, // the symbol is prefixed with _ZTI char const * rttiName = symName.getStr() +4; #if OSL_DEBUG_LEVEL > 1 fprintf( stderr,"generated rtti for %s\n", rttiName ); #endif if (pTypeDescr->pBaseTypeDescription) { // ensure availability of base type_info * base_rtti = getRTTI( (typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription ); rtti = new __si_class_type_info( strdup( rttiName ), (__class_type_info *)base_rtti ); } else { // this class has no base class rtti = new __class_type_info( strdup( rttiName ) ); } pair< t_rtti_map::iterator, bool > insertion( m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) ); OSL_ENSURE( insertion.second, "### inserting new generated rtti failed?!" ); } else // taking already generated rtti { rtti = iFind->second; } } } else { rtti = iFind->second; } return rtti; } //-------------------------------------------------------------------------------------------------- static void deleteException( void * pExc ) { __cxa_exception const * header = ((__cxa_exception const *)pExc - 1); typelib_TypeDescription * pTD = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); ::typelib_typedescription_getByName( &pTD, unoName.pData ); OSL_ENSURE( pTD, "### unknown exception type! leaving out destruction => leaking!!!" ); if (pTD) { ::uno_destructData( pExc, pTD, cpp_release ); ::typelib_typedescription_release( pTD ); } } //================================================================================================== void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp ) { void * pCppExc; type_info * rtti; { // construct cpp exception object typelib_TypeDescription * pTypeDescr = 0; TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType ); OSL_ASSERT( pTypeDescr ); if (! pTypeDescr) terminate(); pCppExc = __cxa_allocate_exception( pTypeDescr->nSize ); ::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp ); // destruct uno exception ::uno_any_destruct( pUnoExc, 0 ); // avoiding locked counts static RTTI * s_rtti = 0; if (! s_rtti) { MutexGuard guard( Mutex::getGlobalMutex() ); if (! s_rtti) { #ifdef LEAK_STATIC_DATA s_rtti = new RTTI(); #else static RTTI rtti_data; s_rtti = &rtti_data; #endif } } rtti = (type_info *)s_rtti->getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr ); TYPELIB_DANGER_RELEASE( pTypeDescr ); OSL_ENSURE( rtti, "### no rtti for throwing exception!" ); if (! rtti) terminate(); } __cxa_throw( pCppExc, rtti, deleteException ); } //================================================================================================== void fillUnoException( __cxa_exception * header, uno_Any * pExc, uno_Mapping * pCpp2Uno ) { OSL_ENSURE( header, "### no exception header!!!" ); if (! header) terminate(); typelib_TypeDescription * pExcTypeDescr = 0; OUString unoName( toUNOname( header->exceptionType->name() ) ); ::typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData ); OSL_ENSURE( pExcTypeDescr, "### can not get type description for exception!!!" ); if (! pExcTypeDescr) terminate(); // construct uno exception any ::uno_any_constructAndConvert( pExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno ); ::typelib_typedescription_release( pExcTypeDescr ); } } <|endoftext|>
<commit_before>#pragma once #include <boost/operators.hpp> #include <iterator> #include "defaults.hpp" #include "tools.hpp" namespace gftools { /** This class describes a point on a grid. It has an index (integer) and a value (pretty much anything) , and it maps between the two. The index is used for fast access, and the value is used for other things like interpolation/physics/math.*/ template <typename ValueType> class point_base : ///dependence on this provides additional comparison operators boost::less_than_comparable<point_base<ValueType> >, ///dependence on this provides additional comparison operators boost::equality_comparable<point_base<ValueType> > { public: //there is a small wrapper for integers down below. Here we exclude grids of ints to avoid confusion in the cast operators. static_assert(!std::is_same<ValueType,int>::value, "Can't create a grid of ints"); typedef ValueType value_type; ///cast operator to value type operator ValueType() const { return val_; } ///cast operator to index type explicit operator size_t() const { return index_; } ///another cast operator to index type explicit operator int() const { return index_; } ///constructor with a pair of values and indices point_base(ValueType val, size_t index):val_(val),index_(index){} bool operator==(const point_base &rhs) const {return index_ == rhs.index_;} bool operator<(const point_base &rhs) const {return this->index_ < rhs.index_;} ValueType value() const { return val_; } size_t index() const { return index_; } protected: ///grid point (in physical units) ValueType val_; ///grid point index size_t index_; }; template<typename T> std::ostream& operator<<(std::ostream& lhs, const point_base<T> &p){ lhs<<"{"<<p.value()<<"<-["<<p.index()<<"]}"; return lhs; } /** A one-dimensional grid, which stores an array of values. Typical examples: grid of real frequencies. Grid of k-points. Grid of Matsubara frequencies. Grid of imaginary times.*/ template <typename ValueType, class Derived> class grid_base : public boost::equality_comparable<grid_base<ValueType, Derived> > { public: typedef point_base<ValueType> point; typedef ValueType value_type; /** constructor a grid out of thin air. */ grid_base(); /** construct a grid given a vector of points. */ grid_base(const std::vector<point> & vals); /** construct a grid from a vector of values (but not associated indices that would be stored in points). */ grid_base(const std::vector<ValueType> & vals); /** Initialize the values from an external function that maps the integer values to the ValueType values. */ grid_base(int min, int max, std::function<ValueType (int)> f); /** Returns a value at given index. */ point operator[](size_t in) const; /** Returns all values. */ const std::vector<point> & points() const; /** Returns values of all points. */ std::vector<ValueType> values() const; /** Checks if a point is present in a grid. */ bool check_point(point in, real_type tolerance = std::numeric_limits<real_type>::epsilon()) const; /** Returns size of grid. */ size_t size() const; /** Returns the closest point to the given value. */ point find_nearest(ValueType in) const; /** Get a value of an object at the given point, which is defined on a grid. */ template <class Obj> auto eval(Obj &&in, point x) const ->decltype(in[0]); /** Shift a point by the given value. */ point shift(point in, ValueType shift_arg) const; ValueType shift(ValueType in, ValueType shift_arg) const; point shift (point in, point shift_arg) const; // CFTP forwards /** Get a value of an object at the given coordinate, which is defined on a grid. */ template <class Obj> auto eval(Obj &in, ValueType x) const ->decltype(in[0]) { return static_cast<const Derived*>(this)->eval(in,x); }; /** Returns a tuple of left closest index, weight, right closest index and weight, which are the closest to input value. */ /** Integrate over grid. */ //template <class Obj> auto integrate(const Obj &in) const ->decltype(in[vals_[0]]) // { return static_cast<const Derived*>(this)->integrate(in); }; /** Integrate over grid with extra arguments provided. */ template <class Obj, typename std::result_of<Obj(point)>::type> auto integrate(Obj &&in) const -> typename std::remove_reference<typename std::result_of<Obj(point)>::type>::type { return static_cast<const Derived*>(this)->integrate(in); }; /// Make the object printable. template <typename ValType, class Derived2> friend std::ostream& operator<<(std::ostream& lhs, const grid_base<ValType,Derived2> &gr); /// Compare 2 grids bool operator==(const grid_base &rhs) const; std::vector<point> vals_; class ex_wrong_index : public std::exception { virtual const char* what() const throw(); }; }; namespace extra { /// A small helper struct to decorate a function object with [] method. template <typename F, typename Grid> struct function_proxy { F f_; const Grid& grid_; function_proxy(F f, Grid const& grid):f_(f),grid_(grid){} typedef typename std::result_of<F(typename Grid::value_type)>::type value_type; value_type operator[](int i) const {return f_((grid_.points()[i]).value()); } }; } // // grid_base implementation // template <typename ValueType, class Derived> grid_base<ValueType,Derived>::grid_base() {}; template <typename ValueType, class Derived> grid_base<ValueType,Derived>::grid_base(const std::vector<point> &vals):vals_(vals) { }; template <typename ValueType, class Derived> grid_base<ValueType,Derived>::grid_base(const std::vector<ValueType> &vals) { vals_.reserve(vals.size()); for (size_t i=0; i<vals.size(); ++i) { vals_.emplace_back(point(vals[i], i)); }; }; template <typename ValueType, class Derived> grid_base<ValueType,Derived>::grid_base(int min, int max, std::function<ValueType (int)> f) { if (max<min) std::swap(min,max); size_t n_points = max-min; vals_.reserve(n_points); for (int i=0; i<n_points; ++i) vals_.emplace_back(f(min+i), i) ; } template <typename ValueType, class Derived> inline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::operator[](size_t index) const { if (index>vals_.size()) throw ex_wrong_index(); return vals_[index]; } template <typename ValueType, class Derived> inline const std::vector<typename grid_base<ValueType,Derived>::point> & grid_base<ValueType,Derived>::points() const { return vals_; } template <typename ValueType, class Derived> inline std::vector<ValueType> grid_base<ValueType,Derived>::values() const { std::vector<ValueType> out; out.reserve(vals_.size()); for (const auto& x : vals_) out.emplace_back(x.value()); return out; } template <typename ValueType, class Derived> inline size_t grid_base<ValueType,Derived>::size() const { return vals_.size(); } template <typename ValueType, class Derived> inline bool grid_base<ValueType,Derived>::check_point(point in, real_type tolerance) const { return (in.index() < vals_.size() && std::abs(in.value() - vals_[in.index()].value()) < tolerance); } template <typename ValueType, class Derived> template <class Obj> inline auto grid_base<ValueType,Derived>::eval(Obj &&in, point x) const ->decltype(in[0]) { if (check_point(x)) return in[x.index()]; else { ERROR ("Point not found"); throw ex_wrong_index(); }; } template <typename ValueType, class Derived> inline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::find_nearest(ValueType in) const { static_assert(std::is_same<bool,decltype(std::declval<ValueType>() < std::declval<ValueType>())>::value, "Default find_nearest is written only for less-comparable types"); auto nearest_iter = std::lower_bound(vals_.begin(), vals_.end(), in, [](ValueType x, ValueType y){return x<y;}); size_t dist = std::distance(vals_.begin(), nearest_iter); if (dist > 0 && std::abs(complex_type(vals_[dist].value()) - complex_type(in)) > std::abs(complex_type(vals_[dist-1].value()) - complex_type(in)) ) dist--; return vals_[dist]; } template <typename ValueType, class Derived> inline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::shift(point in, ValueType shift_arg) const { if (tools::is_float_equal(shift_arg, 0.0)) return in; ValueType out(in.value()); out = static_cast<const Derived*>(this)->shift(ValueType(in),shift_arg); point p1 = static_cast<const Derived*>(this)->find_nearest(out); if (!tools::is_float_equal(p1.value(), out, std::abs(p1.value() - ((p1.index()!=0)?vals_[p1.index() - 1]:vals_[p1.index()+1]).value())/10.)) { #ifndef NDEBUG ERROR("Couldn't shift point" << in << " by " << shift_arg << " got " << out); #endif throw (ex_wrong_index()); } else return p1; } template <typename ValueType, class Derived> inline ValueType grid_base<ValueType,Derived>::shift(ValueType in, ValueType shift_arg) const { return in+shift_arg; } template <typename ValueType, class Derived> inline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::shift(point in, point shift_arg) const { size_t index = (in.index() + shift_arg.index())%vals_.size(); #ifndef NDEBUG ValueType val = static_cast<const Derived*>(this)->shift(in.value(), shift_arg.value()); if (!tools::is_float_equal(val, vals_[index].value())) throw (ex_wrong_index()); #endif return vals_[index]; } template <typename ValueType, class Derived> inline bool grid_base<ValueType,Derived>::operator==(const grid_base &rhs) const { bool out = (this->size() == rhs.size()); for (int i=0; i<vals_.size() && out; i++) { out = out && tools::is_float_equal(vals_[i].value(), rhs.vals_[i].value(), num_io<double>::tolerance()); } return out; } template <typename ValueType, class Derived> std::ostream& operator<<(std::ostream& lhs, const grid_base<ValueType,Derived> &gr) { lhs << "{"; //lhs << gr.vals_; std::ostream_iterator<ValueType> out_it (lhs,", "); std::transform(gr.vals_.begin(),gr.vals_.end(), out_it, [](const typename grid_base<ValueType,Derived>::point &x){return ValueType(x);}); lhs << "}"; return lhs; } template <typename ValueType, class Derived> const char* grid_base<ValueType,Derived>::ex_wrong_index::what() const throw(){ return "Index out of bounds"; }; } // end :: namespace gftools //#include "grid_tools.hpp" <commit_msg>made vals_ in grid_base protected<commit_after>#pragma once #include <boost/operators.hpp> #include <iterator> #include "defaults.hpp" #include "tools.hpp" namespace gftools { /** This class describes a point on a grid. It has an index (integer) and a value (pretty much anything) , and it maps between the two. The index is used for fast access, and the value is used for other things like interpolation/physics/math.*/ template <typename ValueType> class point_base : ///dependence on this provides additional comparison operators boost::less_than_comparable<point_base<ValueType> >, ///dependence on this provides additional comparison operators boost::equality_comparable<point_base<ValueType> > { public: //there is a small wrapper for integers down below. Here we exclude grids of ints to avoid confusion in the cast operators. static_assert(!std::is_same<ValueType,int>::value, "Can't create a grid of ints"); typedef ValueType value_type; ///cast operator to value type operator ValueType() const { return val_; } ///cast operator to index type explicit operator size_t() const { return index_; } ///another cast operator to index type explicit operator int() const { return index_; } ///constructor with a pair of values and indices point_base(ValueType val, size_t index):val_(val),index_(index){} bool operator==(const point_base &rhs) const {return index_ == rhs.index_;} bool operator<(const point_base &rhs) const {return this->index_ < rhs.index_;} ValueType value() const { return val_; } size_t index() const { return index_; } protected: ///grid point (in physical units) ValueType val_; ///grid point index size_t index_; }; template<typename T> std::ostream& operator<<(std::ostream& lhs, const point_base<T> &p){ lhs<<"{"<<p.value()<<"<-["<<p.index()<<"]}"; return lhs; } /** A one-dimensional grid, which stores an array of values. Typical examples: grid of real frequencies. Grid of k-points. Grid of Matsubara frequencies. Grid of imaginary times.*/ template <typename ValueType, class Derived> class grid_base : public boost::equality_comparable<grid_base<ValueType, Derived> > { public: typedef point_base<ValueType> point; typedef ValueType value_type; /** constructor a grid out of thin air. */ grid_base(); /** construct a grid given a vector of points. */ grid_base(const std::vector<point> & vals); /** construct a grid from a vector of values (but not associated indices that would be stored in points). */ grid_base(const std::vector<ValueType> & vals); /** Initialize the values from an external function that maps the integer values to the ValueType values. */ grid_base(int min, int max, std::function<ValueType (int)> f); /** Returns a value at given index. */ point operator[](size_t in) const; /** Returns all values. */ const std::vector<point> & points() const; /** Returns values of all points. (computed on the fly, slow)*/ std::vector<ValueType> values() const; /** Checks if a point is present in a grid. */ bool check_point(point in, real_type tolerance = std::numeric_limits<real_type>::epsilon()) const; /** Returns size of grid. */ size_t size() const; /** Returns the closest point to the given value. */ point find_nearest(ValueType in) const; /** Get a value of an object at the given point, which is defined on a grid. */ template <class Obj> auto eval(Obj &&in, point x) const ->decltype(in[0]); /** Shift a point by the given value. */ point shift(point in, ValueType shift_arg) const; ValueType shift(ValueType in, ValueType shift_arg) const; point shift (point in, point shift_arg) const; // CFTP forwards /** Get a value of an object at the given coordinate, which is defined on a grid. */ template <class Obj> auto eval(Obj &in, ValueType x) const ->decltype(in[0]) { return static_cast<const Derived*>(this)->eval(in,x); }; /** Returns a tuple of left closest index, weight, right closest index and weight, which are the closest to input value. */ /** Integrate over grid. */ //template <class Obj> auto integrate(const Obj &in) const ->decltype(in[vals_[0]]) // { return static_cast<const Derived*>(this)->integrate(in); }; /** Integrate over grid with extra arguments provided. */ template <class Obj, typename std::result_of<Obj(point)>::type> auto integrate(Obj &&in) const -> typename std::remove_reference<typename std::result_of<Obj(point)>::type>::type { return static_cast<const Derived*>(this)->integrate(in); }; /// Make the object printable. template <typename ValType, class Derived2> friend std::ostream& operator<<(std::ostream& lhs, const grid_base<ValType,Derived2> &gr); /// Compare 2 grids bool operator==(const grid_base &rhs) const; class ex_wrong_index : public std::exception { virtual const char* what() const throw(); }; protected: std::vector<point> vals_; }; namespace extra { /// A small helper struct to decorate a function object with [] method. template <typename F, typename Grid> struct function_proxy { F f_; const Grid& grid_; function_proxy(F f, Grid const& grid):f_(f),grid_(grid){} typedef typename std::result_of<F(typename Grid::value_type)>::type value_type; value_type operator[](int i) const {return f_((grid_.points()[i]).value()); } }; } // // grid_base implementation // template <typename ValueType, class Derived> grid_base<ValueType,Derived>::grid_base() {}; template <typename ValueType, class Derived> grid_base<ValueType,Derived>::grid_base(const std::vector<point> &vals):vals_(vals) { }; template <typename ValueType, class Derived> grid_base<ValueType,Derived>::grid_base(const std::vector<ValueType> &vals) { vals_.reserve(vals.size()); for (size_t i=0; i<vals.size(); ++i) { vals_.emplace_back(point(vals[i], i)); }; }; template <typename ValueType, class Derived> grid_base<ValueType,Derived>::grid_base(int min, int max, std::function<ValueType (int)> f) { if (max<min) std::swap(min,max); size_t n_points = max-min; vals_.reserve(n_points); for (int i=0; i<n_points; ++i) vals_.emplace_back(f(min+i), i) ; } template <typename ValueType, class Derived> inline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::operator[](size_t index) const { if (index>vals_.size()) throw ex_wrong_index(); return vals_[index]; } template <typename ValueType, class Derived> inline const std::vector<typename grid_base<ValueType,Derived>::point> & grid_base<ValueType,Derived>::points() const { return vals_; } template <typename ValueType, class Derived> inline std::vector<ValueType> grid_base<ValueType,Derived>::values() const { std::vector<ValueType> out; out.reserve(vals_.size()); for (const auto& x : vals_) out.emplace_back(x.value()); return out; } template <typename ValueType, class Derived> inline size_t grid_base<ValueType,Derived>::size() const { return vals_.size(); } template <typename ValueType, class Derived> inline bool grid_base<ValueType,Derived>::check_point(point in, real_type tolerance) const { return (in.index() < vals_.size() && std::abs(in.value() - vals_[in.index()].value()) < tolerance); } template <typename ValueType, class Derived> template <class Obj> inline auto grid_base<ValueType,Derived>::eval(Obj &&in, point x) const ->decltype(in[0]) { if (check_point(x)) return in[x.index()]; else { ERROR ("Point not found"); throw ex_wrong_index(); }; } template <typename ValueType, class Derived> inline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::find_nearest(ValueType in) const { static_assert(std::is_same<bool,decltype(std::declval<ValueType>() < std::declval<ValueType>())>::value, "Default find_nearest is written only for less-comparable types"); auto nearest_iter = std::lower_bound(vals_.begin(), vals_.end(), in, [](ValueType x, ValueType y){return x<y;}); size_t dist = std::distance(vals_.begin(), nearest_iter); if (dist > 0 && std::abs(complex_type(vals_[dist].value()) - complex_type(in)) > std::abs(complex_type(vals_[dist-1].value()) - complex_type(in)) ) dist--; return vals_[dist]; } template <typename ValueType, class Derived> inline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::shift(point in, ValueType shift_arg) const { if (tools::is_float_equal(shift_arg, 0.0)) return in; ValueType out(in.value()); out = static_cast<const Derived*>(this)->shift(ValueType(in),shift_arg); point p1 = static_cast<const Derived*>(this)->find_nearest(out); if (!tools::is_float_equal(p1.value(), out, std::abs(p1.value() - ((p1.index()!=0)?vals_[p1.index() - 1]:vals_[p1.index()+1]).value())/10.)) { #ifndef NDEBUG ERROR("Couldn't shift point" << in << " by " << shift_arg << " got " << out); #endif throw (ex_wrong_index()); } else return p1; } template <typename ValueType, class Derived> inline ValueType grid_base<ValueType,Derived>::shift(ValueType in, ValueType shift_arg) const { return in+shift_arg; } template <typename ValueType, class Derived> inline typename grid_base<ValueType,Derived>::point grid_base<ValueType,Derived>::shift(point in, point shift_arg) const { size_t index = (in.index() + shift_arg.index())%vals_.size(); #ifndef NDEBUG ValueType val = static_cast<const Derived*>(this)->shift(in.value(), shift_arg.value()); if (!tools::is_float_equal(val, vals_[index].value())) throw (ex_wrong_index()); #endif return vals_[index]; } template <typename ValueType, class Derived> inline bool grid_base<ValueType,Derived>::operator==(const grid_base &rhs) const { bool out = (this->size() == rhs.size()); for (int i=0; i<vals_.size() && out; i++) { out = out && tools::is_float_equal(vals_[i].value(), rhs.vals_[i].value(), num_io<double>::tolerance()); } return out; } template <typename ValueType, class Derived> std::ostream& operator<<(std::ostream& lhs, const grid_base<ValueType,Derived> &gr) { lhs << "{"; //lhs << gr.vals_; std::ostream_iterator<ValueType> out_it (lhs,", "); std::transform(gr.vals_.begin(),gr.vals_.end(), out_it, [](const typename grid_base<ValueType,Derived>::point &x){return ValueType(x);}); lhs << "}"; return lhs; } template <typename ValueType, class Derived> const char* grid_base<ValueType,Derived>::ex_wrong_index::what() const throw(){ return "Index out of bounds"; }; } // end :: namespace gftools //#include "grid_tools.hpp" <|endoftext|>
<commit_before>#include <yttrium/i18n/translation.h> #include <yttrium/ion/document.h> #include <yttrium/ion/node.h> #include <yttrium/ion/object.h> #include <yttrium/ion/value.h> #include <yttrium/memory_manager.h> #include <yttrium/string.h> #include <cstdio> #include <map> using namespace Yttrium; void update_translation(Translation& translation, const IonObject& source); bool update_tr(Translation& translation, const IonObject& tr_object) { if (tr_object.size() != 1) return false; const auto& tr_node = *tr_object.begin(); if (tr_node.name() != S("tr") || tr_node.size() != 1) return false; const auto& tr_value = *tr_node.first(); if (tr_value.type() != IonValue::Type::String) return false; translation.add(tr_value.string()); return true; } void update_translation(Translation& translation, const IonValue& source) { switch (source.type()) { case IonValue::Type::List: for (const auto& value : source.list()) update_translation(translation, value); break; case IonValue::Type::Object: if (!update_tr(translation, *source.object())) update_translation(translation, *source.object()); break; default: break; } } void update_translation(Translation& translation, const IonObject& source) { for (const auto& node : source) for (const auto& value : node) update_translation(translation, value); } int main(int argc, char** argv) { MemoryManager memory_manager; if (argc < 3) { printf("Usage: ytr TRANSLATION SOURCES...\n"); return 1; } Translation translation(argv[1]); for (int i = 2; i < argc; ++i) { IonDocument document; if (!document.load(argv[i])) { printf("ERROR: Failed to load source file \"%s\"\n", argv[i]); return 1; } update_translation(translation, document.root()); } if (!translation.save(argv[1])) { printf("ERROR: Failed to save translation file \"%s\"\n", argv[1]); return 1; } return 0; } <commit_msg>Refactoring.<commit_after>#include <yttrium/i18n/translation.h> #include <yttrium/ion/document.h> #include <yttrium/ion/node.h> #include <yttrium/ion/object.h> #include <yttrium/ion/value.h> #include <yttrium/memory_manager.h> #include <yttrium/string.h> #include <iostream> using namespace Yttrium; void update_translation(Translation& translation, const IonObject& source); bool update_tr(Translation& translation, const IonObject& tr_object) { if (tr_object.size() != 1) return false; const auto& tr_node = *tr_object.begin(); if (tr_node.name() != S("tr") || tr_node.size() != 1) return false; const auto& tr_value = *tr_node.first(); if (tr_value.type() != IonValue::Type::String) return false; translation.add(tr_value.string()); return true; } void update_translation(Translation& translation, const IonValue& source) { switch (source.type()) { case IonValue::Type::List: for (const auto& value : source.list()) update_translation(translation, value); break; case IonValue::Type::Object: if (!update_tr(translation, *source.object())) update_translation(translation, *source.object()); break; default: break; } } void update_translation(Translation& translation, const IonObject& source) { for (const auto& node : source) for (const auto& value : node) update_translation(translation, value); } int main(int argc, char** argv) { MemoryManager memory_manager; if (argc < 3) { std::cerr << "Usage: ytr TRANSLATION SOURCES..." << std::endl; return 1; } Translation translation(argv[1]); for (int i = 2; i < argc; ++i) { IonDocument document; if (!document.load(argv[i])) { std::cerr << "ERROR: Failed to load source file \"" << argv[i] << "\"" << std::endl; return 1; } update_translation(translation, document.root()); } if (!translation.save(argv[1])) { std::cerr << "ERROR: Failed to save translation file \"" << argv[1] << "\"" << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>//===--- tools/extra/clang-tidy/ClangTidyMain.cpp - Clang tidy tool -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file This file implements a clang-tidy tool. /// /// This tool uses the Clang Tooling infrastructure, see /// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html /// for details on setting it up with LLVM source tree. /// //===----------------------------------------------------------------------===// #include "../ClangTidy.h" #include "clang/Tooling/CommonOptionsParser.h" #include "llvm/Support/CommandLine.h" #include <vector> using namespace clang::ast_matchers; using namespace clang::driver; using namespace clang::tooling; using namespace llvm; cl::OptionCategory ClangTidyCategory("clang-tidy options"); static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); static cl::opt<std::string> Checks( "checks", cl::desc("Regular expression matching the names of the checks to be run."), cl::init(".*"), cl::cat(ClangTidyCategory)); static cl::opt<bool> Fix("fix", cl::desc("Fix detected errors if possible."), cl::init(false), cl::cat(ClangTidyCategory)); // FIXME: Add option to list name/description of all checks. int main(int argc, const char **argv) { CommonOptionsParser OptionsParser(argc, argv); SmallVector<clang::tidy::ClangTidyError, 16> Errors; clang::tidy::runClangTidy(Checks, OptionsParser.getCompilations(), OptionsParser.getSourcePathList(), &Errors); clang::tidy::handleErrors(Errors, Fix); return 0; } namespace clang { namespace tidy { // This anchor is used to force the linker to link the LLVMModule. extern volatile int LLVMModuleAnchorSource; static int LLVMModuleAnchorDestination = LLVMModuleAnchorSource; // This anchor is used to force the linker to link the GoogleModule. extern volatile int GoogleModuleAnchorSource; static int GoogleModuleAnchorDestination = GoogleModuleAnchorSource; } // namespace tidy } // namespace clang <commit_msg>Fix the usage of the CommonOptionsParser ctor changed in r197139.<commit_after>//===--- tools/extra/clang-tidy/ClangTidyMain.cpp - Clang tidy tool -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file This file implements a clang-tidy tool. /// /// This tool uses the Clang Tooling infrastructure, see /// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html /// for details on setting it up with LLVM source tree. /// //===----------------------------------------------------------------------===// #include "../ClangTidy.h" #include "clang/Tooling/CommonOptionsParser.h" #include <vector> using namespace clang::ast_matchers; using namespace clang::driver; using namespace clang::tooling; using namespace llvm; cl::OptionCategory ClangTidyCategory("clang-tidy options"); static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); static cl::opt<std::string> Checks( "checks", cl::desc("Regular expression matching the names of the checks to be run."), cl::init(".*"), cl::cat(ClangTidyCategory)); static cl::opt<bool> Fix("fix", cl::desc("Fix detected errors if possible."), cl::init(false), cl::cat(ClangTidyCategory)); // FIXME: Add option to list name/description of all checks. int main(int argc, const char **argv) { CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory); SmallVector<clang::tidy::ClangTidyError, 16> Errors; clang::tidy::runClangTidy(Checks, OptionsParser.getCompilations(), OptionsParser.getSourcePathList(), &Errors); clang::tidy::handleErrors(Errors, Fix); return 0; } namespace clang { namespace tidy { // This anchor is used to force the linker to link the LLVMModule. extern volatile int LLVMModuleAnchorSource; static int LLVMModuleAnchorDestination = LLVMModuleAnchorSource; // This anchor is used to force the linker to link the GoogleModule. extern volatile int GoogleModuleAnchorSource; static int GoogleModuleAnchorDestination = GoogleModuleAnchorSource; } // namespace tidy } // namespace clang <|endoftext|>
<commit_before>/* * Copyright 2010, 2011 Esrille Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "CSSSelector.h" #include <assert.h> #include <org/w3c/dom/Element.h> #include <org/w3c/dom/html/HTMLAnchorElement.h> #include "CSSStyleDeclarationImp.h" #include "ViewCSSImp.h" namespace org { namespace w3c { namespace dom { namespace bootstrap { namespace { inline bool find(const std::u16string& s, const std::u16string& t) { return s.find(t) != std::u16string::npos; } // s is a whitespace-separated list of words inline bool contains(const std::u16string& s, const std::u16string& t) { size_t pos = 0; for (;;) { pos = s.find(t, pos); if (pos == std::u16string::npos) return false; if ((pos == 0 || isSpace(s[pos - 1])) && (pos + t.length() == s.length() || isSpace(s[pos + t.length()]))) return true; ++pos; } } inline bool startsWith(const std::u16string& s, const std::u16string& t) { return !s.compare(0, t.length(), t); } inline bool endsWith(const std::u16string& s, const std::u16string& t) { if (s.length() < t.length()) return false; return !s.compare(s.length() - t.length(), t.length(), t); } } void CSSSelectorsGroup::serialize(std::u16string& result) { for (auto i = selectors.begin(); i != selectors.end(); ++i) { if (i != selectors.begin()) result += u", "; (*i)->serialize(result); if (CSSSerializeControl.serializeSpecificity) { result += u" /* specificity = "; result += CSSSerializeHex((*i)->getSpecificity()); result += u" */ "; } } } void CSSSelector::serialize(std::u16string& result) { for (auto i = simpleSelectors.begin(); i != simpleSelectors.end(); ++i) (*i)->serialize(result); } void CSSPrimarySelector::serialize(std::u16string& result) { if (combinator) { if (combinator != u' ') { result += u' '; result += static_cast<char16_t>(combinator); } result += u' '; } if (name == u"*") result += name; else result += CSSSerializeIdentifier(name); for (auto i = chain.begin(); i != chain.end(); ++i) (*i)->serialize(result); } void CSSAttributeSelector::serialize(std::u16string& result) { result += u'['; result += CSSSerializeIdentifier(name); if (op) { result += static_cast<char16_t>(op); if (op != u'=') result += u'='; result += CSSSerializeString(value); } result += u']'; } void CSSNthPseudoClassSelector::serialize(std::u16string& text) { text += u':' + CSSSerializeIdentifier(name) + u'('; if (!a) text += CSSSerializeInteger(b); else { if (a == -1) // TODO: Ask Anne about this. text += '-'; else if (a != 1 && a != -1) text += CSSSerializeInteger(a); text += u'n'; if (b) { if (0 < b) text += u'+'; text += CSSSerializeInteger(b); } } text += u')'; } CSSSpecificity CSSPrimarySelector::getSpecificity() { CSSSpecificity specificity; if (name != u"*") specificity += CSSSpecificity(0, 0, 0, 1); for (auto i = chain.begin(); i != chain.end(); ++i) specificity += (*i)->getSpecificity(); return specificity; } CSSSpecificity CSSSelector::getSpecificity() { CSSSpecificity specificity; for (auto i = simpleSelectors.begin(); i != simpleSelectors.end(); ++i) specificity += (*i)->getSpecificity(); return specificity; } bool CSSPrimarySelector::match(Element e, ViewCSSImp* view) { if (name != u"*") { if (e.getLocalName() != name) return false; if (namespacePrefix != u"*") { if (!e.getNamespaceURI().hasValue() || e.getNamespaceURI().value() != namespacePrefix) return false; } } for (auto i = chain.begin(); i != chain.end(); ++i) { if (!(*i)->match(e, view)) return false; } return true; } bool CSSIDSelector::match(Element e, ViewCSSImp* view) { Nullable<std::u16string> id = e.getAttribute(u"id"); if (!id.hasValue()) return false; return id.value() == name; // TODO: ignore case } bool CSSClassSelector::match(Element e, ViewCSSImp* view) { Nullable<std::u16string> classes = e.getAttribute(u"class"); if (!classes.hasValue()) return false; return contains(classes.value(), name); // TODO: ignore case } bool CSSAttributeSelector::match(Element e, ViewCSSImp* view) { Nullable<std::u16string> attr = e.getAttribute(name); if (!attr.hasValue()) return false; switch (op) { case None: return true; case Equals: return attr.value() == value; case Includes: if (attr.value().length() == 0 || contains(attr.value(), u" ")) return false; return contains(attr.value(), value); case DashMatch: if (!startsWith(attr.value(), value)) return false; return attr.value().length() == value.length() || attr.value()[value.length()] == u'-'; case PrefixMatch: if (attr.value().length() == 0) return false; return startsWith(attr.value(), value); case SuffixMatch: if (attr.value().length() == 0) return false; return endsWith(attr.value(), value); case SubstringMatch: if (attr.value().length() == 0) return false; return find(attr.value(), value); default: return false; } } bool CSSSelector::match(Element e, ViewCSSImp* view) { if (!e || simpleSelectors.size() == 0) return false; auto i = simpleSelectors.rbegin(); if (!(*i)->match(e, view)) return false; int combinator = (*i)->getCombinator(); ++i; while (i != simpleSelectors.rend()) { switch (combinator) { case CSSPrimarySelector::Descendant: while (e = e.getParentElement()) { // TODO: do we need to retry from here upon failure? if ((*i)->match(e, view)) break; } if (!e) return false; break; case CSSPrimarySelector::Child: e = e.getParentElement(); if (!(*i)->match(e, view)) return false; break; case CSSPrimarySelector::AdjacentSibling: e = e.getPreviousElementSibling(); if (!(*i)->match(e, view)) return false; break; case CSSPrimarySelector::GeneralSibling: while (e = e.getPreviousElementSibling()) { if ((*i)->match(e, view)) break; } if (!e) return false; default: return false; } combinator = (*i)->getCombinator(); ++i; } if (combinator != CSSPrimarySelector::None) return false; return true; } CSSSelector* CSSSelectorsGroup::match(Element e, ViewCSSImp* view) { specificity = CSSSpecificity(); for (auto i = selectors.begin(); i != selectors.end(); ++i) { if ((*i)->match(e, view)) { specificity = (*i)->getSpecificity(); return *i; } } return 0; } bool CSSPseudoClassSelector::match(Element element, ViewCSSImp* view) { switch (id) { case Link: case Visited: if (html::HTMLAnchorElement::hasInstance(element)) return true; break; case Hover: if (view->isHovered(element)) return true; break; default: break; } return false; } CSSPseudoElementSelector* CSSPrimarySelector::getPseudoElement() const { if (chain.empty()) return 0; if (CSSPseudoElementSelector* pseudo = dynamic_cast<CSSPseudoElementSelector*>(chain.back())) return pseudo; return 0; } CSSPseudoElementSelector* CSSSelector::getPseudoElement() const { if (simpleSelectors.empty()) return 0; return simpleSelectors.back()->getPseudoElement(); } CSSPseudoClassSelector::CSSPseudoClassSelector(const std::u16string& ident, int id) : CSSPseudoSelector(getPseudoClassName(id)), id(id) { } CSSPseudoClassSelector::CSSPseudoClassSelector(const CSSParserTerm& function) : CSSPseudoSelector(function), id(-1) { } CSSPseudoElementSelector::CSSPseudoElementSelector(int id) : CSSPseudoSelector(getPseudoElementName(id)), id(id) { } CSSPseudoSelector* CSSPseudoSelector::createPseudoSelector(int type, const std::u16string& ident) { if (type == PseudoClass) { /* Exceptions: :first-line, :first-letter, :before and :after. */ if (ident == u"first-line" || ident == u"first-letter" || ident == u"before" || ident == u"after") type = PseudoElement; } int id = -1; switch (type) { case PseudoClass: id = getPseudoClassID(ident); if (0 <= id) return new(std::nothrow) CSSPseudoClassSelector(ident, id); break; case PseudoElement: id = getPseudoElementID(ident); if (0 <= id) return new(std::nothrow) CSSPseudoElementSelector(id); break; default: break; } return 0; } CSSPseudoSelector* CSSPseudoSelector::createPseudoSelector(int type, const CSSParserTerm& function) { switch (type) { case PseudoClass: return new(std::nothrow) CSSPseudoClassSelector(function); break; case PseudoElement: // No functional pseudo element is defined in CSS 2.1 break; default: break; } return 0; } namespace { const char16_t* pseudoElementNames[] = { u"", u"first-line", u"first-letter", u"before", u"after" }; const char16_t* pseudoClassNames[] = { // CSS 2.1 u"link", u"visited", u"hover", u"active", u"focus", u"lang", u"first-child", // CSS 3 u"last-child", u"target", u"enabled", u"disabled", u"checked", u"indeterminate", u"root", u"empty", u"first-of-type", u"last-of-type", u"only-child", u"only-of-type", }; const char16_t* pseudoFunctionalClassNames[] = { // CSS 3 u"nth-child", u"nth-last-child", u"nth-of-type", u"nth-last-of-type", }; } int CSSPseudoSelector::getPseudoElementID(const std::u16string& name) { for (unsigned id = 0; id < CSSPseudoElementSelector::MaxPseudoElements; ++id) { if (name == pseudoElementNames[id]) return id; } return -1; } int CSSPseudoSelector::getPseudoClassID(const std::u16string& name) { for (unsigned id = 0; id < CSSPseudoClassSelector::MaxPseudoClasses; ++id) { if (name == pseudoClassNames[id]) return id; } return -1; } const char16_t* CSSPseudoSelector::getPseudoElementName(int id) { if (0 <= id && id < CSSPseudoElementSelector::MaxPseudoElements) return pseudoElementNames[id]; return 0; } const char16_t* CSSPseudoSelector::getPseudoClassName(int id) { if (0 <= id && id < CSSPseudoClassSelector::MaxPseudoClasses) return pseudoClassNames[id]; return 0; } }}}} // org::w3c::dom::bootstrap<commit_msg>(CSSPseudoClassSelector::match) : Ignore :visited for now.<commit_after>/* * Copyright 2010, 2011 Esrille Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "CSSSelector.h" #include <assert.h> #include <org/w3c/dom/Element.h> #include <org/w3c/dom/html/HTMLAnchorElement.h> #include "CSSStyleDeclarationImp.h" #include "ViewCSSImp.h" namespace org { namespace w3c { namespace dom { namespace bootstrap { namespace { inline bool find(const std::u16string& s, const std::u16string& t) { return s.find(t) != std::u16string::npos; } // s is a whitespace-separated list of words inline bool contains(const std::u16string& s, const std::u16string& t) { size_t pos = 0; for (;;) { pos = s.find(t, pos); if (pos == std::u16string::npos) return false; if ((pos == 0 || isSpace(s[pos - 1])) && (pos + t.length() == s.length() || isSpace(s[pos + t.length()]))) return true; ++pos; } } inline bool startsWith(const std::u16string& s, const std::u16string& t) { return !s.compare(0, t.length(), t); } inline bool endsWith(const std::u16string& s, const std::u16string& t) { if (s.length() < t.length()) return false; return !s.compare(s.length() - t.length(), t.length(), t); } } void CSSSelectorsGroup::serialize(std::u16string& result) { for (auto i = selectors.begin(); i != selectors.end(); ++i) { if (i != selectors.begin()) result += u", "; (*i)->serialize(result); if (CSSSerializeControl.serializeSpecificity) { result += u" /* specificity = "; result += CSSSerializeHex((*i)->getSpecificity()); result += u" */ "; } } } void CSSSelector::serialize(std::u16string& result) { for (auto i = simpleSelectors.begin(); i != simpleSelectors.end(); ++i) (*i)->serialize(result); } void CSSPrimarySelector::serialize(std::u16string& result) { if (combinator) { if (combinator != u' ') { result += u' '; result += static_cast<char16_t>(combinator); } result += u' '; } if (name == u"*") result += name; else result += CSSSerializeIdentifier(name); for (auto i = chain.begin(); i != chain.end(); ++i) (*i)->serialize(result); } void CSSAttributeSelector::serialize(std::u16string& result) { result += u'['; result += CSSSerializeIdentifier(name); if (op) { result += static_cast<char16_t>(op); if (op != u'=') result += u'='; result += CSSSerializeString(value); } result += u']'; } void CSSNthPseudoClassSelector::serialize(std::u16string& text) { text += u':' + CSSSerializeIdentifier(name) + u'('; if (!a) text += CSSSerializeInteger(b); else { if (a == -1) // TODO: Ask Anne about this. text += '-'; else if (a != 1 && a != -1) text += CSSSerializeInteger(a); text += u'n'; if (b) { if (0 < b) text += u'+'; text += CSSSerializeInteger(b); } } text += u')'; } CSSSpecificity CSSPrimarySelector::getSpecificity() { CSSSpecificity specificity; if (name != u"*") specificity += CSSSpecificity(0, 0, 0, 1); for (auto i = chain.begin(); i != chain.end(); ++i) specificity += (*i)->getSpecificity(); return specificity; } CSSSpecificity CSSSelector::getSpecificity() { CSSSpecificity specificity; for (auto i = simpleSelectors.begin(); i != simpleSelectors.end(); ++i) specificity += (*i)->getSpecificity(); return specificity; } bool CSSPrimarySelector::match(Element e, ViewCSSImp* view) { if (name != u"*") { if (e.getLocalName() != name) return false; if (namespacePrefix != u"*") { if (!e.getNamespaceURI().hasValue() || e.getNamespaceURI().value() != namespacePrefix) return false; } } for (auto i = chain.begin(); i != chain.end(); ++i) { if (!(*i)->match(e, view)) return false; } return true; } bool CSSIDSelector::match(Element e, ViewCSSImp* view) { Nullable<std::u16string> id = e.getAttribute(u"id"); if (!id.hasValue()) return false; return id.value() == name; // TODO: ignore case } bool CSSClassSelector::match(Element e, ViewCSSImp* view) { Nullable<std::u16string> classes = e.getAttribute(u"class"); if (!classes.hasValue()) return false; return contains(classes.value(), name); // TODO: ignore case } bool CSSAttributeSelector::match(Element e, ViewCSSImp* view) { Nullable<std::u16string> attr = e.getAttribute(name); if (!attr.hasValue()) return false; switch (op) { case None: return true; case Equals: return attr.value() == value; case Includes: if (attr.value().length() == 0 || contains(attr.value(), u" ")) return false; return contains(attr.value(), value); case DashMatch: if (!startsWith(attr.value(), value)) return false; return attr.value().length() == value.length() || attr.value()[value.length()] == u'-'; case PrefixMatch: if (attr.value().length() == 0) return false; return startsWith(attr.value(), value); case SuffixMatch: if (attr.value().length() == 0) return false; return endsWith(attr.value(), value); case SubstringMatch: if (attr.value().length() == 0) return false; return find(attr.value(), value); default: return false; } } bool CSSSelector::match(Element e, ViewCSSImp* view) { if (!e || simpleSelectors.size() == 0) return false; auto i = simpleSelectors.rbegin(); if (!(*i)->match(e, view)) return false; int combinator = (*i)->getCombinator(); ++i; while (i != simpleSelectors.rend()) { switch (combinator) { case CSSPrimarySelector::Descendant: while (e = e.getParentElement()) { // TODO: do we need to retry from here upon failure? if ((*i)->match(e, view)) break; } if (!e) return false; break; case CSSPrimarySelector::Child: e = e.getParentElement(); if (!(*i)->match(e, view)) return false; break; case CSSPrimarySelector::AdjacentSibling: e = e.getPreviousElementSibling(); if (!(*i)->match(e, view)) return false; break; case CSSPrimarySelector::GeneralSibling: while (e = e.getPreviousElementSibling()) { if ((*i)->match(e, view)) break; } if (!e) return false; default: return false; } combinator = (*i)->getCombinator(); ++i; } if (combinator != CSSPrimarySelector::None) return false; return true; } CSSSelector* CSSSelectorsGroup::match(Element e, ViewCSSImp* view) { specificity = CSSSpecificity(); for (auto i = selectors.begin(); i != selectors.end(); ++i) { if ((*i)->match(e, view)) { specificity = (*i)->getSpecificity(); return *i; } } return 0; } bool CSSPseudoClassSelector::match(Element element, ViewCSSImp* view) { switch (id) { case Link: if (html::HTMLAnchorElement::hasInstance(element)) return true; break; case Hover: if (view->isHovered(element)) return true; break; default: break; } return false; } CSSPseudoElementSelector* CSSPrimarySelector::getPseudoElement() const { if (chain.empty()) return 0; if (CSSPseudoElementSelector* pseudo = dynamic_cast<CSSPseudoElementSelector*>(chain.back())) return pseudo; return 0; } CSSPseudoElementSelector* CSSSelector::getPseudoElement() const { if (simpleSelectors.empty()) return 0; return simpleSelectors.back()->getPseudoElement(); } CSSPseudoClassSelector::CSSPseudoClassSelector(const std::u16string& ident, int id) : CSSPseudoSelector(getPseudoClassName(id)), id(id) { } CSSPseudoClassSelector::CSSPseudoClassSelector(const CSSParserTerm& function) : CSSPseudoSelector(function), id(-1) { } CSSPseudoElementSelector::CSSPseudoElementSelector(int id) : CSSPseudoSelector(getPseudoElementName(id)), id(id) { } CSSPseudoSelector* CSSPseudoSelector::createPseudoSelector(int type, const std::u16string& ident) { if (type == PseudoClass) { /* Exceptions: :first-line, :first-letter, :before and :after. */ if (ident == u"first-line" || ident == u"first-letter" || ident == u"before" || ident == u"after") type = PseudoElement; } int id = -1; switch (type) { case PseudoClass: id = getPseudoClassID(ident); if (0 <= id) return new(std::nothrow) CSSPseudoClassSelector(ident, id); break; case PseudoElement: id = getPseudoElementID(ident); if (0 <= id) return new(std::nothrow) CSSPseudoElementSelector(id); break; default: break; } return 0; } CSSPseudoSelector* CSSPseudoSelector::createPseudoSelector(int type, const CSSParserTerm& function) { switch (type) { case PseudoClass: return new(std::nothrow) CSSPseudoClassSelector(function); break; case PseudoElement: // No functional pseudo element is defined in CSS 2.1 break; default: break; } return 0; } namespace { const char16_t* pseudoElementNames[] = { u"", u"first-line", u"first-letter", u"before", u"after" }; const char16_t* pseudoClassNames[] = { // CSS 2.1 u"link", u"visited", u"hover", u"active", u"focus", u"lang", u"first-child", // CSS 3 u"last-child", u"target", u"enabled", u"disabled", u"checked", u"indeterminate", u"root", u"empty", u"first-of-type", u"last-of-type", u"only-child", u"only-of-type", }; const char16_t* pseudoFunctionalClassNames[] = { // CSS 3 u"nth-child", u"nth-last-child", u"nth-of-type", u"nth-last-of-type", }; } int CSSPseudoSelector::getPseudoElementID(const std::u16string& name) { for (unsigned id = 0; id < CSSPseudoElementSelector::MaxPseudoElements; ++id) { if (name == pseudoElementNames[id]) return id; } return -1; } int CSSPseudoSelector::getPseudoClassID(const std::u16string& name) { for (unsigned id = 0; id < CSSPseudoClassSelector::MaxPseudoClasses; ++id) { if (name == pseudoClassNames[id]) return id; } return -1; } const char16_t* CSSPseudoSelector::getPseudoElementName(int id) { if (0 <= id && id < CSSPseudoElementSelector::MaxPseudoElements) return pseudoElementNames[id]; return 0; } const char16_t* CSSPseudoSelector::getPseudoClassName(int id) { if (0 <= id && id < CSSPseudoClassSelector::MaxPseudoClasses) return pseudoClassNames[id]; return 0; } }}}} // org::w3c::dom::bootstrap<|endoftext|>
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #if (defined(GOOGLE_CUDA) && GOOGLE_CUDA) || \ (defined(TENSORFLOW_USE_ROCM) && TENSORFLOW_USE_ROCM) #define EIGEN_USE_GPU #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/kernels/fill_functor.h" #include "tensorflow/core/platform/types.h" namespace Eigen { namespace internal { template <typename T> struct scalar_const_op { typedef typename packet_traits<T>::type Packet; const T* val; EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE scalar_const_op(const scalar_const_op& x) : val(x.val) {} EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE scalar_const_op(const T* v) : val(v) {} EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const T operator()() const { return *val; } template <typename PacketType = Packet> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const PacketType packetOp() const { return internal::pset1<PacketType>(*val); } }; template <typename T> struct functor_traits<scalar_const_op<T> > { enum { Cost = 1, PacketAccess = packet_traits<T>::Vectorizable, IsRepeatable = true }; }; } // end namespace internal } // end namespace Eigen namespace tensorflow { namespace functor { typedef Eigen::GpuDevice GPUDevice; // Partial specialization FillFunctor<Device=GPUDevice, T> template <typename T> struct FillFunctor<GPUDevice, T> { void operator()(const GPUDevice& d, typename TTypes<T>::Flat out, typename TTypes<T>::ConstScalar in) { Eigen::internal::scalar_const_op<T> f(in.data()); MaybeWith32BitIndexing<GPUDevice>( [&](auto out32) { out32.device(d) = out32.nullaryExpr(f); }, out); } }; #define DEFINE_FILL_GPU(T) template struct FillFunctor<GPUDevice, T>; TF_CALL_REAL_NUMBER_TYPES(DEFINE_FILL_GPU); TF_CALL_bool(DEFINE_FILL_GPU); #undef DEFINE_FILL_GPU // Partial specialization of FillFunctor<Device=GPUDevice, T>. template <typename T> struct SetZeroFunctor<GPUDevice, T> { void operator()(const GPUDevice& d, typename TTypes<T>::Flat out) { MaybeWith32BitIndexing<GPUDevice>( [&](auto out32) { out32.device(d) = out32.constant(T(0)); }, out); } }; #define DEFINE_SETZERO_GPU(T) template struct SetZeroFunctor<GPUDevice, T>; // The SetZeroFunctor is called from several other ops, so even though on GPU we // are using a MLIR generated ZerosLike kernel, we still need to define this // functor for the other ops. TF_CALL_bool(DEFINE_SETZERO_GPU); TF_CALL_int64(DEFINE_SETZERO_GPU); TF_CALL_FLOAT_TYPES(DEFINE_SETZERO_GPU); TF_CALL_int32(DEFINE_SETZERO_GPU); TF_CALL_COMPLEX_TYPES(DEFINE_SETZERO_GPU); #undef DEFINE_SETZERO_GPU // Partial specialization of FillFunctor<Device=GPUDevice, T>. template <typename T> struct SetOneFunctor<GPUDevice, T> { void operator()(const GPUDevice& d, typename TTypes<T>::Flat out) { MaybeWith32BitIndexing<GPUDevice>( [&](auto out32) { out32.device(d) = out32.constant(T(1)); }, out); } }; #define DEFINE_SETONE_GPU(T) template struct SetOneFunctor<GPUDevice, T>; #if !defined(MLIR_GENERATED_GPU_KERNELS_ENABLED) || \ !defined(MLIR_GENERATED_EXPERIMENTAL_KERNELS_ENABLED) TF_CALL_bool(DEFINE_SETONE_GPU); TF_CALL_int64(DEFINE_SETONE_GPU); TF_CALL_FLOAT_TYPES(DEFINE_SETONE_GPU); #else TF_CALL_bfloat16(DEFINE_SETONE_GPU); #endif TF_CALL_int32(DEFINE_SETONE_GPU); TF_CALL_COMPLEX_TYPES(DEFINE_SETONE_GPU); #undef DEFINE_SETONE_GPU } // end namespace functor } // end namespace tensorflow #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM <commit_msg>Delete constant_op_gpu.cu.cc which contains duplicate functors.<commit_after><|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/trajectory/CTrajectoryTask.cpp,v $ $Revision: 1.40 $ $Name: $ $Author: ssahle $ $Date: 2004/10/08 09:19:10 $ End CVS Header */ /** * CTrajectoryTask class. * * This class implements a trajectory task which is comprised of a * of a problem and a method. Additionally calls to the reporting * methods are done when initialized. * * Created for Copasi by Stefan Hoops 2002 */ #include <string> #include "copasi.h" #include "CTrajectoryTask.h" #include "CTrajectoryProblem.h" #include "CTrajectoryMethod.h" #include "model/CModel.h" #include "model/CState.h" #include "utilities/CGlobals.h" #include "report/CKeyFactory.h" #include "report/CReport.h" #include "utilities/COutputHandler.h" #define XXXX_Reporting CTrajectoryTask::CTrajectoryTask(const CCopasiContainer * pParent): CCopasiTask(CCopasiTask::timeCourse, pParent), mpState(NULL), mTimeSeriesRequested(true) { mpProblem = new CTrajectoryProblem(this); mpMethod = CTrajectoryMethod::createTrajectoryMethod(CCopasiMethod::deterministic, (CTrajectoryProblem *) mpProblem); mpMethod->setObjectParent(this); } /*CTrajectoryTask::CTrajectoryTask(const CTrajectoryTask & src, const CCopasiContainer * pParent): CCopasiTask(src, pParent), mpState(src.mpState), mTimeSeriesRequested(src.mTimeSeriesRequested) {fatalError();}*/ /*CTrajectoryTask::CTrajectoryTask(CTrajectoryProblem * pProblem, CTrajectoryMethod::SubType subType, const CCopasiContainer * pParent): CCopasiTask(CCopasiTask::timeCourse, pParent), mpState(NULL), mTimeSeriesRequested(true) { mpProblem = pProblem; mpProblem->setObjectParent(this); mpMethod = CTrajectoryMethod::createTrajectoryMethod(subType, (CTrajectoryProblem *) mpProblem); mpMethod->setObjectParent(this); }*/ /*CTrajectoryTask::CTrajectoryTask(CModel * pModel, C_FLOAT64 starttime, C_FLOAT64 endtime, unsigned C_INT32 stepnumber, CTrajectoryMethod::SubType subType, const CCopasiContainer * pParent): CCopasiTask(CCopasiTask::timeCourse, pParent), mpState(NULL), mTimeSeriesRequested(true) { mpProblem = new CTrajectoryProblem(this); ((CTrajectoryProblem *) mpProblem)->setModel(pModel); ((CTrajectoryProblem *) mpProblem)->setStartTime(starttime); ((CTrajectoryProblem *) mpProblem)->setEndTime(endtime); ((CTrajectoryProblem *) mpProblem)->setStepNumber(stepnumber); mpMethod = CTrajectoryMethod::createTrajectoryMethod(subType, (CTrajectoryProblem *) mpProblem); mpMethod->setObjectParent(this); }*/ CTrajectoryTask::~CTrajectoryTask() { cleanup(); } void CTrajectoryTask::cleanup() { pdelete(mpState); } void CTrajectoryTask::load(CReadConfig & configBuffer) { configBuffer.getVariable("Dynamics", "bool", &mScheduled, CReadConfig::LOOP); pdelete(mpProblem); mpProblem = new CTrajectoryProblem(this); ((CTrajectoryProblem *) mpProblem)->load(configBuffer); pdelete(mpMethod); mpMethod = CTrajectoryMethod::createTrajectoryMethod(); mpMethod->setObjectParent(this); ((CTrajectoryMethod *)mpMethod)->setProblem((CTrajectoryProblem *) mpProblem); } bool CTrajectoryTask::initialize(std::ostream * pOstream) { assert(mpProblem && mpMethod); CTrajectoryProblem* pProblem = dynamic_cast<CTrajectoryProblem *>(mpProblem); assert(pProblem); bool success = true; if (!mReport.open(pOstream)) success = false; if (!mReport.compile()) success = false; if (!pProblem->getModel()->compileIfNecessary()) success = false; // if (!pProblem-> // setInitialState(pProblem->getModel()->getInitialState())) // success = false; pProblem->setInitialState(pProblem->getModel()->getInitialState()); return success; } bool CTrajectoryTask::process() { assert(mpProblem && mpMethod); CTrajectoryProblem * pProblem = (CTrajectoryProblem *) mpProblem; CTrajectoryMethod * pMethod = (CTrajectoryMethod *) mpMethod; mTimeSeriesRequested = pProblem->timeSeriesRequested(); pdelete(mpState); mpState = new CState(pProblem->getInitialState()); pMethod->setCurrentState(mpState); pMethod->setProblem(pProblem); bool flagStopped = false; C_FLOAT64 handlerFactor = 1000 / (pProblem->getEndTime() - pProblem->getStartTime()); if (mpProgressHandler) mpProgressHandler->init(1000, "performing simulation...", true); pProblem->getModel()->setState(mpState); pProblem->getModel()->updateRates(); mReport.printHeader(); mReport.printBody(); if (mpOutputHandler) mpOutputHandler->init(); if (mTimeSeriesRequested) mTimeSeries.init(pProblem->getStepNumber(), mpState); if (mpOutputHandler) mpOutputHandler->doOutput(); if (mTimeSeriesRequested) mTimeSeries.add(); C_FLOAT64 StepSize = pProblem->getStepSize(); C_FLOAT64 ActualStepSize; const C_FLOAT64 & Time = mpState->getTime(); C_FLOAT64 EndTime = pProblem->getEndTime() - StepSize; ActualStepSize = pMethod->step(StepSize, mpState); if (mpProgressHandler) flagStopped = mpProgressHandler->progress((Time - pProblem->getStartTime()) * handlerFactor); pProblem->getModel()->setState(mpState); pProblem->getModel()->updateRates(); mReport.printBody(); if (mpOutputHandler) mpOutputHandler->doOutput(); if (mTimeSeriesRequested) mTimeSeries.add(); #ifdef XXXX_Event if (ActualStepSize != StepSize) { /* Here we will do conditional event processing */ } #endif // XXXX_Event while ((Time < EndTime) && (!flagStopped)) { ActualStepSize = pMethod->step(StepSize); if (mpProgressHandler) flagStopped = mpProgressHandler->progress((Time - pProblem->getStartTime()) * handlerFactor); pProblem->getModel()->setState(mpState); pProblem->getModel()->updateRates(); mReport.printBody(); if (mpOutputHandler) mpOutputHandler->doOutput(); if (mTimeSeriesRequested) mTimeSeries.add(); #ifdef XXXX_Event if (ActualStepSize != StepSize) { /* Here we will do conditional event processing */ } #endif // XXXX_Event } while ((Time < pProblem->getEndTime()) && (!flagStopped)) { ActualStepSize = pMethod->step(pProblem->getEndTime() - Time); if (mpProgressHandler) flagStopped = mpProgressHandler->progress((Time - pProblem->getStartTime()) * handlerFactor); pProblem->getModel()->setState(mpState); pProblem->getModel()->updateRates(); mReport.printBody(); if (mpOutputHandler) mpOutputHandler->doOutput(); if (mTimeSeriesRequested) mTimeSeries.add(); #ifdef XXXX_Event if (ActualStepSize != (pProblem->getEndTime() - Time)) { /* Here we will do conditional event processing */ } #endif // XXXX_Event } //pProblem->setEndState(new CState(*mpState)); if (mpProgressHandler) mpProgressHandler->finish(); pProblem->getModel()->setState(mpState); pProblem->getModel()->updateRates(); mReport.printFooter(); if (mpOutputHandler) mpOutputHandler->finish(); if (mTimeSeriesRequested) mTimeSeries.finish(); return true; } bool CTrajectoryTask::processSimple(bool singleStep) //without output { assert(mpProblem && mpMethod); CTrajectoryProblem * pProblem = (CTrajectoryProblem *) mpProblem; CTrajectoryMethod * pMethod = (CTrajectoryMethod *) mpMethod; //give the method a state to work on pdelete(mpState); mpState = new CState(pProblem->getInitialState()); pMethod->setCurrentState(mpState); pMethod->setProblem(pProblem); bool flagStopped = false; C_FLOAT64 handlerFactor = 1000 / (pProblem->getEndTime() - pProblem->getStartTime()); if (mpProgressHandler) mpProgressHandler->init(1000, "performing simulation...", true); //first step C_FLOAT64 StepSize = pProblem->getEndTime() - pProblem->getInitialState().getTime(); pMethod->step(StepSize, &pProblem->getInitialState()); if (mpProgressHandler) flagStopped = mpProgressHandler->progress((mpState->getTime() - pProblem->getStartTime()) * handlerFactor); if (mpState->getTime() == pProblem->getEndTime()) return true; //end reached in one step if (singleStep) return false; //end not reached but only one step requested //more Steps if necessary while ((mpState->getTime() < pProblem->getEndTime()) && (!flagStopped)) { StepSize = pProblem->getEndTime() - mpState->getTime(); pMethod->step(StepSize); if (mpProgressHandler) flagStopped = mpProgressHandler->progress((mpState->getTime() - pProblem->getStartTime()) * handlerFactor); } //pProblem->setEndState(new CState(*mpState)); //if (mpProgressHandler) mpProgressHandler->finish(); return true; } bool CTrajectoryTask::setMethodType(const int & type) { CCopasiMethod::SubType Type = (CCopasiMethod::SubType) type; if (!CTrajectoryMethod::isValidSubType(Type)) return false; if (mpMethod->getSubType() == Type) return true; pdelete (mpMethod); mpMethod = CTrajectoryMethod::createTrajectoryMethod(Type, (CTrajectoryProblem *) mpProblem); mpMethod->setObjectParent(this); return true; } CState * CTrajectoryTask::getState() {return mpState;} const CTimeSeries & CTrajectoryTask::getTimeSeries() const {return mTimeSeries;} <commit_msg>the task should not set the initial state in the problem<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/trajectory/CTrajectoryTask.cpp,v $ $Revision: 1.41 $ $Name: $ $Author: ssahle $ $Date: 2004/10/14 21:20:59 $ End CVS Header */ /** * CTrajectoryTask class. * * This class implements a trajectory task which is comprised of a * of a problem and a method. Additionally calls to the reporting * methods are done when initialized. * * Created for Copasi by Stefan Hoops 2002 */ #include <string> #include "copasi.h" #include "CTrajectoryTask.h" #include "CTrajectoryProblem.h" #include "CTrajectoryMethod.h" #include "model/CModel.h" #include "model/CState.h" #include "utilities/CGlobals.h" #include "report/CKeyFactory.h" #include "report/CReport.h" #include "utilities/COutputHandler.h" #define XXXX_Reporting CTrajectoryTask::CTrajectoryTask(const CCopasiContainer * pParent): CCopasiTask(CCopasiTask::timeCourse, pParent), mpState(NULL), mTimeSeriesRequested(true) { mpProblem = new CTrajectoryProblem(this); mpMethod = CTrajectoryMethod::createTrajectoryMethod(CCopasiMethod::deterministic, (CTrajectoryProblem *) mpProblem); mpMethod->setObjectParent(this); } /*CTrajectoryTask::CTrajectoryTask(const CTrajectoryTask & src, const CCopasiContainer * pParent): CCopasiTask(src, pParent), mpState(src.mpState), mTimeSeriesRequested(src.mTimeSeriesRequested) {fatalError();}*/ /*CTrajectoryTask::CTrajectoryTask(CTrajectoryProblem * pProblem, CTrajectoryMethod::SubType subType, const CCopasiContainer * pParent): CCopasiTask(CCopasiTask::timeCourse, pParent), mpState(NULL), mTimeSeriesRequested(true) { mpProblem = pProblem; mpProblem->setObjectParent(this); mpMethod = CTrajectoryMethod::createTrajectoryMethod(subType, (CTrajectoryProblem *) mpProblem); mpMethod->setObjectParent(this); }*/ /*CTrajectoryTask::CTrajectoryTask(CModel * pModel, C_FLOAT64 starttime, C_FLOAT64 endtime, unsigned C_INT32 stepnumber, CTrajectoryMethod::SubType subType, const CCopasiContainer * pParent): CCopasiTask(CCopasiTask::timeCourse, pParent), mpState(NULL), mTimeSeriesRequested(true) { mpProblem = new CTrajectoryProblem(this); ((CTrajectoryProblem *) mpProblem)->setModel(pModel); ((CTrajectoryProblem *) mpProblem)->setStartTime(starttime); ((CTrajectoryProblem *) mpProblem)->setEndTime(endtime); ((CTrajectoryProblem *) mpProblem)->setStepNumber(stepnumber); mpMethod = CTrajectoryMethod::createTrajectoryMethod(subType, (CTrajectoryProblem *) mpProblem); mpMethod->setObjectParent(this); }*/ CTrajectoryTask::~CTrajectoryTask() { cleanup(); } void CTrajectoryTask::cleanup() { pdelete(mpState); } void CTrajectoryTask::load(CReadConfig & configBuffer) { configBuffer.getVariable("Dynamics", "bool", &mScheduled, CReadConfig::LOOP); pdelete(mpProblem); mpProblem = new CTrajectoryProblem(this); ((CTrajectoryProblem *) mpProblem)->load(configBuffer); pdelete(mpMethod); mpMethod = CTrajectoryMethod::createTrajectoryMethod(); mpMethod->setObjectParent(this); ((CTrajectoryMethod *)mpMethod)->setProblem((CTrajectoryProblem *) mpProblem); } bool CTrajectoryTask::initialize(std::ostream * pOstream) { assert(mpProblem && mpMethod); CTrajectoryProblem* pProblem = dynamic_cast<CTrajectoryProblem *>(mpProblem); assert(pProblem); bool success = true; if (!mReport.open(pOstream)) success = false; if (!mReport.compile()) success = false; if (!pProblem->getModel()->compileIfNecessary()) success = false; // if (!pProblem-> // setInitialState(pProblem->getModel()->getInitialState())) // success = false; //pProblem->setInitialState(pProblem->getModel()->getInitialState()); return success; } bool CTrajectoryTask::process() { assert(mpProblem && mpMethod); CTrajectoryProblem * pProblem = (CTrajectoryProblem *) mpProblem; CTrajectoryMethod * pMethod = (CTrajectoryMethod *) mpMethod; mTimeSeriesRequested = pProblem->timeSeriesRequested(); pdelete(mpState); mpState = new CState(pProblem->getInitialState()); pMethod->setCurrentState(mpState); pMethod->setProblem(pProblem); bool flagStopped = false; C_FLOAT64 handlerFactor = 1000 / (pProblem->getEndTime() - pProblem->getStartTime()); if (mpProgressHandler) mpProgressHandler->init(1000, "performing simulation...", true); pProblem->getModel()->setState(mpState); pProblem->getModel()->updateRates(); mReport.printHeader(); mReport.printBody(); if (mpOutputHandler) mpOutputHandler->init(); if (mTimeSeriesRequested) mTimeSeries.init(pProblem->getStepNumber(), mpState); if (mpOutputHandler) mpOutputHandler->doOutput(); if (mTimeSeriesRequested) mTimeSeries.add(); C_FLOAT64 StepSize = pProblem->getStepSize(); C_FLOAT64 ActualStepSize; const C_FLOAT64 & Time = mpState->getTime(); C_FLOAT64 EndTime = pProblem->getEndTime() - StepSize; ActualStepSize = pMethod->step(StepSize, mpState); if (mpProgressHandler) flagStopped = mpProgressHandler->progress((Time - pProblem->getStartTime()) * handlerFactor); pProblem->getModel()->setState(mpState); pProblem->getModel()->updateRates(); mReport.printBody(); if (mpOutputHandler) mpOutputHandler->doOutput(); if (mTimeSeriesRequested) mTimeSeries.add(); #ifdef XXXX_Event if (ActualStepSize != StepSize) { /* Here we will do conditional event processing */ } #endif // XXXX_Event while ((Time < EndTime) && (!flagStopped)) { ActualStepSize = pMethod->step(StepSize); if (mpProgressHandler) flagStopped = mpProgressHandler->progress((Time - pProblem->getStartTime()) * handlerFactor); pProblem->getModel()->setState(mpState); pProblem->getModel()->updateRates(); mReport.printBody(); if (mpOutputHandler) mpOutputHandler->doOutput(); if (mTimeSeriesRequested) mTimeSeries.add(); #ifdef XXXX_Event if (ActualStepSize != StepSize) { /* Here we will do conditional event processing */ } #endif // XXXX_Event } while ((Time < pProblem->getEndTime()) && (!flagStopped)) { ActualStepSize = pMethod->step(pProblem->getEndTime() - Time); if (mpProgressHandler) flagStopped = mpProgressHandler->progress((Time - pProblem->getStartTime()) * handlerFactor); pProblem->getModel()->setState(mpState); pProblem->getModel()->updateRates(); mReport.printBody(); if (mpOutputHandler) mpOutputHandler->doOutput(); if (mTimeSeriesRequested) mTimeSeries.add(); #ifdef XXXX_Event if (ActualStepSize != (pProblem->getEndTime() - Time)) { /* Here we will do conditional event processing */ } #endif // XXXX_Event } //pProblem->setEndState(new CState(*mpState)); if (mpProgressHandler) mpProgressHandler->finish(); pProblem->getModel()->setState(mpState); pProblem->getModel()->updateRates(); mReport.printFooter(); if (mpOutputHandler) mpOutputHandler->finish(); if (mTimeSeriesRequested) mTimeSeries.finish(); return true; } bool CTrajectoryTask::processSimple(bool singleStep) //without output { assert(mpProblem && mpMethod); CTrajectoryProblem * pProblem = (CTrajectoryProblem *) mpProblem; CTrajectoryMethod * pMethod = (CTrajectoryMethod *) mpMethod; //give the method a state to work on pdelete(mpState); mpState = new CState(pProblem->getInitialState()); pMethod->setCurrentState(mpState); pMethod->setProblem(pProblem); bool flagStopped = false; C_FLOAT64 handlerFactor = 1000 / (pProblem->getEndTime() - pProblem->getStartTime()); if (mpProgressHandler) mpProgressHandler->init(1000, "performing simulation...", true); //first step C_FLOAT64 StepSize = pProblem->getEndTime() - pProblem->getInitialState().getTime(); pMethod->step(StepSize, &pProblem->getInitialState()); if (mpProgressHandler) flagStopped = mpProgressHandler->progress((mpState->getTime() - pProblem->getStartTime()) * handlerFactor); if (mpState->getTime() == pProblem->getEndTime()) return true; //end reached in one step if (singleStep) return false; //end not reached but only one step requested //more Steps if necessary while ((mpState->getTime() < pProblem->getEndTime()) && (!flagStopped)) { StepSize = pProblem->getEndTime() - mpState->getTime(); pMethod->step(StepSize); if (mpProgressHandler) flagStopped = mpProgressHandler->progress((mpState->getTime() - pProblem->getStartTime()) * handlerFactor); } //pProblem->setEndState(new CState(*mpState)); //if (mpProgressHandler) mpProgressHandler->finish(); return true; } bool CTrajectoryTask::setMethodType(const int & type) { CCopasiMethod::SubType Type = (CCopasiMethod::SubType) type; if (!CTrajectoryMethod::isValidSubType(Type)) return false; if (mpMethod->getSubType() == Type) return true; pdelete (mpMethod); mpMethod = CTrajectoryMethod::createTrajectoryMethod(Type, (CTrajectoryProblem *) mpProblem); mpMethod->setObjectParent(this); return true; } CState * CTrajectoryTask::getState() {return mpState;} const CTimeSeries & CTrajectoryTask::getTimeSeries() const {return mTimeSeries;} <|endoftext|>
<commit_before>// Copyright (c) 2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bench.h" #include "key.h" #include "stacktraces.h" #include "validation.h" #include "util.h" #include "bls/bls.h" void InitBLSTests(); void CleanupBLSTests(); void CleanupBLSDkgTests(); int main(int argc, char** argv) { RegisterPrettySignalHandlers(); RegisterPrettyTerminateHander(); ECC_Start(); ECCVerifyHandle verifyHandle; BLSInit(); InitBLSTests(); SetupEnvironment(); fPrintToDebugLog = false; // don't want to write to debug.log file benchmark::BenchRunner::RunAll(); // need to be called before global destructors kick in (PoolAllocator is needed due to many BLSSecretKeys) CleanupBLSDkgTests(); CleanupBLSTests(); ECC_Stop(); } <commit_msg>#10821 continued<commit_after>// Copyright (c) 2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bench.h" #include "crypto/sha256.h" #include "key.h" #include "stacktraces.h" #include "validation.h" #include "util.h" #include "bls/bls.h" void InitBLSTests(); void CleanupBLSTests(); void CleanupBLSDkgTests(); int main(int argc, char** argv) { SHA256AutoDetect(); RegisterPrettySignalHandlers(); RegisterPrettyTerminateHander(); ECC_Start(); ECCVerifyHandle verifyHandle; BLSInit(); InitBLSTests(); SetupEnvironment(); fPrintToDebugLog = false; // don't want to write to debug.log file benchmark::BenchRunner::RunAll(); // need to be called before global destructors kick in (PoolAllocator is needed due to many BLSSecretKeys) CleanupBLSDkgTests(); CleanupBLSTests(); ECC_Stop(); } <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/CAnnotatedMatrix.cpp,v $ $Revision: 1.5 $ $Name: $ $Author: ssahle $ $Date: 2005/11/09 16:23:12 $ End CVS Header */ #include "CAnnotatedMatrix.h" #include "report/CKeyFactory.h" CCopasiArray::CCopasiArray() : mDim(0) {} CCopasiArray::CCopasiArray(const index_type & sizes) { resize(sizes); } void CCopasiArray::resize(const index_type & sizes) { mDim = sizes.size(); mSizes = sizes; mFactors.resize(mDim); unsigned int tmpDataSize = 1; index_type::const_reverse_iterator it, itEnd = sizes.rend(); index_type::reverse_iterator itFaktor; for (it = sizes.rbegin(), itFaktor = mFactors.rbegin(); it != itEnd; ++it, ++itFaktor) { *itFaktor = tmpDataSize; tmpDataSize *= *it; } mData.resize(tmpDataSize); } CCopasiArray::data_type & CCopasiArray::operator[] (const index_type & index) { #ifdef COPASI_DEBUG assert(index.size() == mDim); #endif unsigned int tmpindex = 0; index_type::const_iterator itIndex, it, itEnd = mFactors.end(); for (itIndex = index.begin(), it = mFactors.begin(); it != itEnd; ++it, ++itIndex) tmpindex += *itIndex * *it; return mData[tmpindex]; } const CCopasiArray::data_type & CCopasiArray::operator[] (const index_type & index) const { #ifdef COPASI_DEBUG assert(index.size() == mDim); #endif unsigned int tmpindex = 0; index_type::const_iterator itIndex, it, itEnd = mFactors.end(); for (itIndex = index.begin(), it = mFactors.begin(); it != itEnd; ++it, ++itIndex) tmpindex += *itIndex * *it; return mData[tmpindex]; } // //******************************************************* CCopasiMatrixInterface::CCopasiMatrixInterface(CMatrix<C_FLOAT64> * matrix) : mMatrix(matrix) { assert(mMatrix); mSizes.resize(2); mSizes[0] = mMatrix->numRows(); mSizes[1] = mMatrix->numCols(); } void CCopasiMatrixInterface::resize(const index_type & sizes) { assert(sizes.size() == 2); mSizes = sizes; mMatrix->resize(mSizes[0], mSizes[1]); } CCopasiArray::data_type & CCopasiMatrixInterface::operator[] (const index_type & index) { #ifdef COPASI_DEBUG assert(index.size() == 2); #endif return (*mMatrix)(index[0], index[1]); } const CCopasiArray::data_type & CCopasiMatrixInterface::operator[] (const index_type & index) const { #ifdef COPASI_DEBUG assert(index.size() == 2); #endif return (*mMatrix)(index[0], index[1]); } // //******************************************************* CArrayAnnotation::CArrayAnnotation(const std::string & name, const CCopasiContainer * pParent, CCopasiAbstractArray * array) : CCopasiContainer(name, pParent, "Array" /*, flags */), //TODO: flags mArray(array) { assert(mArray); resizeAnnotations(); } unsigned int CArrayAnnotation::dimensionality() const { if (mOnTheFly) return mArray->dimensionality(); else return mAnnotations.size(); } const std::vector<CRegisteredObjectName> & CArrayAnnotation::getAnnotations(unsigned int d) { if (mOnTheFly) updateAnnotations(); return mAnnotations[d]; } void CArrayAnnotation::setAnnotation(unsigned int d, unsigned int i, const std::string cn) { assert(d < mAnnotations.size()); assert(i < mAnnotations[d].size()); mAnnotations[d][i] = s; } const std::string & CArrayAnnotation::getDimensionDescription(unsigned int d) { if (mOnTheFly) mDimensionDescriptions.resize(mArray->dimensionality()); return mDimensionDescriptions[d]; } void CArrayAnnotation::setDimensionDescription(unsigned int d, const std::string & s) { assert(d < mDimensionDescriptions.size()); mDimensionDescriptions[d] = s; } const std::string & CArrayAnnotation::getDescription() const {return mDescription;} void CArrayAnnotation::setDescription(const std::string & s) {mDescription = s;} //private bool CArrayAnnotation::updateAnnotations() { bool success = true; resizeAnnotations(); unsigned int i; for (i = 0; i < mArray->dimensionality(); ++i) { if (mCopasiVectors[i]) if (!createAnnotationsFromCopasiVector(i, mCopasiVectors[i])) success = false; else success = false; } return success; } bool CArrayAnnotation::createAnnotationsFromCopasiVector(unsigned int d, const CCopasiContainer* v) { if (!v) return false; if (! (v->isVector() || v->isNameVector())) return false; if (d >= mArray->dimensionality()) return false; //now we know we have a vector. A CCopasiVector[N/S], hopefully, so that the following cast is valid: const std::vector<const CCopasiObject*>* pVector = reinterpret_cast<const std::vector<const CCopasiObject*>* >(v); if (pVector->size() != mAnnotations[d].size()) return false; unsigned int i; for (i = 0; i < pVector->size(); ++i) { if (!(*pVector)[i]) return false; else mAnnotations[d][i] = (*pVector)[i]->getCN(); } return true; } //private void CArrayAnnotation::resizeAnnotations() { mAnnotations.resize(mArray->dimensionality()); unsigned int i; for (i = 0; i < mArray->dimensionality(); ++i) mAnnotations[i].resize(mArray->size()[i]); mDimensionDescriptions.resize(mArray->dimensionality()); mCopasiVectors.resize(mArray->dimensionality()); } void CArrayAnnotation::resize(const CCopasiAbstractArray::index_type & sizes) { assert(mArray); mArray->resize(sizes); resizeAnnotations(); } void CArrayAnnotation::printDebug(std::ostream & out) const { out << mDescription << std::endl; out << " Dimensionality: " << dimensionality() << std::endl; unsigned int i, j; for (i = 0; i < dimensionality(); ++i) { out << " " << i << ": " << mDimensionDescriptions[i] << std::endl; for (j = 0; j < mAnnotations[i].size(); ++j) out << " " << mAnnotations[i][j] << std::endl; out << std::endl; } } // //******************************************************* CAnnotatedMatrixOld::CAnnotatedMatrixOld(const std::string & name, const CCopasiContainer * pParent): CMatrix<C_FLOAT64>(), CCopasiContainer(name, pParent, "AnnotatedMatrix", CCopasiObject::Container | CCopasiObject::NonUniqueName), mKey(GlobalKeys.add("AnnotatedMatrix", this)) { //initObjects(); CONSTRUCTOR_TRACE; } CAnnotatedMatrixOld::CAnnotatedMatrixOld(const CAnnotatedMatrixOld & src, const CCopasiContainer * pParent): CMatrix<C_FLOAT64>(), CCopasiContainer(src, pParent), mKey(GlobalKeys.add("AnnotatedMatrix", this)) { //initObjects(); CONSTRUCTOR_TRACE; } CAnnotatedMatrixOld::~CAnnotatedMatrixOld() {} <commit_msg>fixed typo<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/CAnnotatedMatrix.cpp,v $ $Revision: 1.6 $ $Name: $ $Author: ssahle $ $Date: 2005/11/09 16:27:43 $ End CVS Header */ #include "CAnnotatedMatrix.h" #include "report/CKeyFactory.h" CCopasiArray::CCopasiArray() : mDim(0) {} CCopasiArray::CCopasiArray(const index_type & sizes) { resize(sizes); } void CCopasiArray::resize(const index_type & sizes) { mDim = sizes.size(); mSizes = sizes; mFactors.resize(mDim); unsigned int tmpDataSize = 1; index_type::const_reverse_iterator it, itEnd = sizes.rend(); index_type::reverse_iterator itFaktor; for (it = sizes.rbegin(), itFaktor = mFactors.rbegin(); it != itEnd; ++it, ++itFaktor) { *itFaktor = tmpDataSize; tmpDataSize *= *it; } mData.resize(tmpDataSize); } CCopasiArray::data_type & CCopasiArray::operator[] (const index_type & index) { #ifdef COPASI_DEBUG assert(index.size() == mDim); #endif unsigned int tmpindex = 0; index_type::const_iterator itIndex, it, itEnd = mFactors.end(); for (itIndex = index.begin(), it = mFactors.begin(); it != itEnd; ++it, ++itIndex) tmpindex += *itIndex * *it; return mData[tmpindex]; } const CCopasiArray::data_type & CCopasiArray::operator[] (const index_type & index) const { #ifdef COPASI_DEBUG assert(index.size() == mDim); #endif unsigned int tmpindex = 0; index_type::const_iterator itIndex, it, itEnd = mFactors.end(); for (itIndex = index.begin(), it = mFactors.begin(); it != itEnd; ++it, ++itIndex) tmpindex += *itIndex * *it; return mData[tmpindex]; } // //******************************************************* CCopasiMatrixInterface::CCopasiMatrixInterface(CMatrix<C_FLOAT64> * matrix) : mMatrix(matrix) { assert(mMatrix); mSizes.resize(2); mSizes[0] = mMatrix->numRows(); mSizes[1] = mMatrix->numCols(); } void CCopasiMatrixInterface::resize(const index_type & sizes) { assert(sizes.size() == 2); mSizes = sizes; mMatrix->resize(mSizes[0], mSizes[1]); } CCopasiArray::data_type & CCopasiMatrixInterface::operator[] (const index_type & index) { #ifdef COPASI_DEBUG assert(index.size() == 2); #endif return (*mMatrix)(index[0], index[1]); } const CCopasiArray::data_type & CCopasiMatrixInterface::operator[] (const index_type & index) const { #ifdef COPASI_DEBUG assert(index.size() == 2); #endif return (*mMatrix)(index[0], index[1]); } // //******************************************************* CArrayAnnotation::CArrayAnnotation(const std::string & name, const CCopasiContainer * pParent, CCopasiAbstractArray * array) : CCopasiContainer(name, pParent, "Array" /*, flags */), //TODO: flags mArray(array) { assert(mArray); resizeAnnotations(); } unsigned int CArrayAnnotation::dimensionality() const { if (mOnTheFly) return mArray->dimensionality(); else return mAnnotations.size(); } const std::vector<CRegisteredObjectName> & CArrayAnnotation::getAnnotations(unsigned int d) { if (mOnTheFly) updateAnnotations(); return mAnnotations[d]; } void CArrayAnnotation::setAnnotation(unsigned int d, unsigned int i, const std::string cn) { assert(d < mAnnotations.size()); assert(i < mAnnotations[d].size()); mAnnotations[d][i] = cn; } const std::string & CArrayAnnotation::getDimensionDescription(unsigned int d) { if (mOnTheFly) mDimensionDescriptions.resize(mArray->dimensionality()); return mDimensionDescriptions[d]; } void CArrayAnnotation::setDimensionDescription(unsigned int d, const std::string & s) { assert(d < mDimensionDescriptions.size()); mDimensionDescriptions[d] = s; } const std::string & CArrayAnnotation::getDescription() const {return mDescription;} void CArrayAnnotation::setDescription(const std::string & s) {mDescription = s;} //private bool CArrayAnnotation::updateAnnotations() { bool success = true; resizeAnnotations(); unsigned int i; for (i = 0; i < mArray->dimensionality(); ++i) { if (mCopasiVectors[i]) if (!createAnnotationsFromCopasiVector(i, mCopasiVectors[i])) success = false; else success = false; } return success; } bool CArrayAnnotation::createAnnotationsFromCopasiVector(unsigned int d, const CCopasiContainer* v) { if (!v) return false; if (! (v->isVector() || v->isNameVector())) return false; if (d >= mArray->dimensionality()) return false; //now we know we have a vector. A CCopasiVector[N/S], hopefully, so that the following cast is valid: const std::vector<const CCopasiObject*>* pVector = reinterpret_cast<const std::vector<const CCopasiObject*>* >(v); if (pVector->size() != mAnnotations[d].size()) return false; unsigned int i; for (i = 0; i < pVector->size(); ++i) { if (!(*pVector)[i]) return false; else mAnnotations[d][i] = (*pVector)[i]->getCN(); } return true; } //private void CArrayAnnotation::resizeAnnotations() { mAnnotations.resize(mArray->dimensionality()); unsigned int i; for (i = 0; i < mArray->dimensionality(); ++i) mAnnotations[i].resize(mArray->size()[i]); mDimensionDescriptions.resize(mArray->dimensionality()); mCopasiVectors.resize(mArray->dimensionality()); } void CArrayAnnotation::resize(const CCopasiAbstractArray::index_type & sizes) { assert(mArray); mArray->resize(sizes); resizeAnnotations(); } void CArrayAnnotation::printDebug(std::ostream & out) const { out << mDescription << std::endl; out << " Dimensionality: " << dimensionality() << std::endl; unsigned int i, j; for (i = 0; i < dimensionality(); ++i) { out << " " << i << ": " << mDimensionDescriptions[i] << std::endl; for (j = 0; j < mAnnotations[i].size(); ++j) out << " " << mAnnotations[i][j] << std::endl; out << std::endl; } } // //******************************************************* CAnnotatedMatrixOld::CAnnotatedMatrixOld(const std::string & name, const CCopasiContainer * pParent): CMatrix<C_FLOAT64>(), CCopasiContainer(name, pParent, "AnnotatedMatrix", CCopasiObject::Container | CCopasiObject::NonUniqueName), mKey(GlobalKeys.add("AnnotatedMatrix", this)) { //initObjects(); CONSTRUCTOR_TRACE; } CAnnotatedMatrixOld::CAnnotatedMatrixOld(const CAnnotatedMatrixOld & src, const CCopasiContainer * pParent): CMatrix<C_FLOAT64>(), CCopasiContainer(src, pParent), mKey(GlobalKeys.add("AnnotatedMatrix", this)) { //initObjects(); CONSTRUCTOR_TRACE; } CAnnotatedMatrixOld::~CAnnotatedMatrixOld() {} <|endoftext|>
<commit_before>// Copyright (c) 2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bench.h" #include "util.h" #include "validation/validation.h" #include "checkqueue.h" #include "prevector.h" #include "random.h" #include <vector> #include <boost/thread/thread.hpp> // This Benchmark tests the CheckQueue with the lightest // weight Checks, so it should make any lock contention // particularly visible static const int MIN_CORES = 2; static const size_t BATCHES = 101; static const size_t BATCH_SIZE = 30; static const int PREVECTOR_SIZE = 28; static const int QUEUE_BATCH_SIZE = 128; static void CCheckQueueSpeed(benchmark::State& state) { struct FakeJobNoWork { bool operator()() { return true; } void swap(FakeJobNoWork& x){}; }; CCheckQueue<FakeJobNoWork> queue {QUEUE_BATCH_SIZE}; boost::thread_group tg; for (auto x = 0; x < std::max(MIN_CORES, GetNumCores()); ++x) { tg.create_thread([&]{queue.Thread();}); } while (state.KeepRunning()) { CCheckQueueControl<FakeJobNoWork> control(&queue); // We call Add a number of times to simulate the behavior of adding // a block of transactions at once. std::vector<std::vector<FakeJobNoWork>> vBatches(BATCHES); for (auto& vChecks : vBatches) { vChecks.resize(BATCH_SIZE); } for (auto& vChecks : vBatches) { // We can't make vChecks in the inner loop because we want to measure // the cost of getting the memory to each thread and we might get the same // memory control.Add(vChecks); } // control waits for completion by RAII, but // it is done explicitly here for clarity control.Wait(); } tg.interrupt_all(); tg.join_all(); } // This Benchmark tests the CheckQueue with a slightly realistic workload, // where checks all contain a prevector that is indirect 50% of the time // and there is a little bit of work done between calls to Add. static void CCheckQueueSpeedPrevectorJob(benchmark::State& state) { struct PrevectorJob { prevector<PREVECTOR_SIZE, uint8_t> p; PrevectorJob(){ } PrevectorJob(FastRandomContext& insecure_rand){ p.resize(insecure_rand.rand32() % (PREVECTOR_SIZE*2)); } bool operator()() { return true; } void swap(PrevectorJob& x){p.swap(x.p);}; }; CCheckQueue<PrevectorJob> queue {QUEUE_BATCH_SIZE}; boost::thread_group tg; for (auto x = 0; x < std::max(MIN_CORES, GetNumCores()); ++x) { tg.create_thread([&]{queue.Thread();}); } while (state.KeepRunning()) { // Make insecure_rand here so that each iteration is identical. FastRandomContext insecure_rand(true); CCheckQueueControl<PrevectorJob> control(&queue); std::vector<std::vector<PrevectorJob>> vBatches(BATCHES); for (auto& vChecks : vBatches) { vChecks.reserve(BATCH_SIZE); for (size_t x = 0; x < BATCH_SIZE; ++x) vChecks.emplace_back(insecure_rand); control.Add(vChecks); } // control waits for completion by RAII, but // it is done explicitly here for clarity control.Wait(); } tg.interrupt_all(); tg.join_all(); } BENCHMARK(CCheckQueueSpeed); BENCHMARK(CCheckQueueSpeedPrevectorJob); <commit_msg>Use FastRandomContext::randrange in src/bench/checkqueue.cpp<commit_after>// Copyright (c) 2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bench.h" #include "util.h" #include "validation/validation.h" #include "checkqueue.h" #include "prevector.h" #include "random.h" #include <vector> #include <boost/thread/thread.hpp> // This Benchmark tests the CheckQueue with the lightest // weight Checks, so it should make any lock contention // particularly visible static const int MIN_CORES = 2; static const size_t BATCHES = 101; static const size_t BATCH_SIZE = 30; static const int PREVECTOR_SIZE = 28; static const int QUEUE_BATCH_SIZE = 128; static void CCheckQueueSpeed(benchmark::State& state) { struct FakeJobNoWork { bool operator()() { return true; } void swap(FakeJobNoWork& x){}; }; CCheckQueue<FakeJobNoWork> queue {QUEUE_BATCH_SIZE}; boost::thread_group tg; for (auto x = 0; x < std::max(MIN_CORES, GetNumCores()); ++x) { tg.create_thread([&]{queue.Thread();}); } while (state.KeepRunning()) { CCheckQueueControl<FakeJobNoWork> control(&queue); // We call Add a number of times to simulate the behavior of adding // a block of transactions at once. std::vector<std::vector<FakeJobNoWork>> vBatches(BATCHES); for (auto& vChecks : vBatches) { vChecks.resize(BATCH_SIZE); } for (auto& vChecks : vBatches) { // We can't make vChecks in the inner loop because we want to measure // the cost of getting the memory to each thread and we might get the same // memory control.Add(vChecks); } // control waits for completion by RAII, but // it is done explicitly here for clarity control.Wait(); } tg.interrupt_all(); tg.join_all(); } // This Benchmark tests the CheckQueue with a slightly realistic workload, // where checks all contain a prevector that is indirect 50% of the time // and there is a little bit of work done between calls to Add. static void CCheckQueueSpeedPrevectorJob(benchmark::State& state) { struct PrevectorJob { prevector<PREVECTOR_SIZE, uint8_t> p; PrevectorJob(){ } PrevectorJob(FastRandomContext& insecure_rand){ p.resize(insecure_rand.randrange(PREVECTOR_SIZE*2)); } bool operator()() { return true; } void swap(PrevectorJob& x){p.swap(x.p);}; }; CCheckQueue<PrevectorJob> queue {QUEUE_BATCH_SIZE}; boost::thread_group tg; for (auto x = 0; x < std::max(MIN_CORES, GetNumCores()); ++x) { tg.create_thread([&]{queue.Thread();}); } while (state.KeepRunning()) { // Make insecure_rand here so that each iteration is identical. FastRandomContext insecure_rand(true); CCheckQueueControl<PrevectorJob> control(&queue); std::vector<std::vector<PrevectorJob>> vBatches(BATCHES); for (auto& vChecks : vBatches) { vChecks.reserve(BATCH_SIZE); for (size_t x = 0; x < BATCH_SIZE; ++x) vChecks.emplace_back(insecure_rand); control.Add(vChecks); } // control waits for completion by RAII, but // it is done explicitly here for clarity control.Wait(); } tg.interrupt_all(); tg.join_all(); } BENCHMARK(CCheckQueueSpeed); BENCHMARK(CCheckQueueSpeedPrevectorJob); <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/CCopasiParameter.cpp,v $ $Revision: 1.6 $ $Name: $ $Author: shoops $ $Date: 2003/11/07 18:15:36 $ End CVS Header */ /** * CCopasiParameter class. * This class is used to describe method paramters. This class is intended * to be used with integration or optimization methods. * * Created for Copasi by Stefan Hoops 2002 */ #include <string> #include "copasi.h" #include "CCopasiParameter.h" #include "CCopasiParameterGroup.h" #include "CCopasiMessage.h" #include "report/CKeyFactory.h" const std::string CCopasiParameter::TypeName[] = { "float", "unsigned float", "integer", "unsigned integer", "bool", "group", "string", "" }; const char* CCopasiParameter::XMLType[] = { "float", "unsignedFloat", "integer", "unsignedInteger", "bool", "group", "string", NULL }; CCopasiParameter::CCopasiParameter(): CCopasiContainer("NoName", NULL, "Parameter"), mType(INVALID) {} CCopasiParameter::CCopasiParameter(const CCopasiParameter & src, const CCopasiContainer * pParent): CCopasiContainer(src, pParent), mKey(CKeyFactory::add(src.getObjectType(), this)), mType(src.mType), mSize(0), mpValue(createValue(src.mpValue)) {} CCopasiParameter::CCopasiParameter(const std::string & name, const CCopasiParameter::Type & type, const void * pValue, const CCopasiContainer * pParent, const std::string & objectType): CCopasiContainer(name, pParent, objectType, CCopasiObject::Container | (type == DOUBLE || type == UDOUBLE) ? CCopasiObject::ValueDbl : (type == INT || type == UINT) ? CCopasiObject::ValueInt : (type == BOOL) ? CCopasiObject::ValueBool : 0), mKey(CKeyFactory::add(objectType, this)), mType(type), mSize(0), mpValue(createValue(pValue)) {} CCopasiParameter::~CCopasiParameter() { CKeyFactory::remove(mKey); deleteValue(); } std::string CCopasiParameter::getKey() const {return mKey;} bool CCopasiParameter::setName(const std::string & name) {return setObjectName(name);} const std::string & CCopasiParameter::getName() const {return getObjectName();} const void * CCopasiParameter::getValue() const {return mpValue;} void * CCopasiParameter::getValue() {return mpValue;} const CCopasiParameter::Type & CCopasiParameter::getType() const {return mType;} bool CCopasiParameter::isValidValue(const C_FLOAT64 & value) const { if ((mType != CCopasiParameter::DOUBLE && mType != CCopasiParameter::UDOUBLE) || (mType == CCopasiParameter::UDOUBLE && value < 0.0)) return false; return true; } bool CCopasiParameter::isValidValue(const C_INT32 & C_UNUSED(value)) const { if (mType != CCopasiParameter::INT) return false; return true; } bool CCopasiParameter::isValidValue(const unsigned C_INT32 & C_UNUSED(value)) const { if (mType != CCopasiParameter::UINT) return false; return true; } bool CCopasiParameter::isValidValue(const bool & C_UNUSED(value)) const { if (mType != CCopasiParameter::BOOL) return false; return true; } bool CCopasiParameter::isValidValue(const std::string & C_UNUSED(value)) const { if (mType != CCopasiParameter::STRING) return false; return true; } bool CCopasiParameter::isValidValue(const CCopasiParameterGroup::parameterGroup & C_UNUSED(value)) const { if (mType != CCopasiParameter::GROUP) return false; return true; } void * CCopasiParameter::createValue(const void * pValue) { switch (mType) { case CCopasiParameter::DOUBLE: case CCopasiParameter::UDOUBLE: mpValue = new C_FLOAT64; if (pValue) * (C_FLOAT64 *) mpValue = * (C_FLOAT64 *) pValue; mSize = sizeof(C_FLOAT64); break; case CCopasiParameter::INT: mpValue = new C_INT32; if (pValue) * (C_INT32 *) mpValue = * (C_INT32 *) pValue; mSize = sizeof(C_INT32); break; case CCopasiParameter::UINT: mpValue = new unsigned C_INT32; if (pValue) * (unsigned C_INT32 *) mpValue = * (unsigned C_INT32 *) pValue; mSize = sizeof(unsigned C_INT32); break; case CCopasiParameter::BOOL: mpValue = new bool; if (pValue) * (bool *) mpValue = * (bool *) pValue; mSize = sizeof(bool); break; case CCopasiParameter::STRING: if (pValue) mpValue = new std::string(* (std::string *) pValue); else mpValue = new std::string; mSize = sizeof(std::string); break; case CCopasiParameter::GROUP: case CCopasiParameter::INVALID: mpValue = NULL; mSize = 0; break; } return mpValue; } void CCopasiParameter::deleteValue() { if (!mpValue) return; switch (mType) { case CCopasiParameter::DOUBLE: case CCopasiParameter::UDOUBLE: delete (C_FLOAT64 *) mpValue; break; case CCopasiParameter::INT: delete (C_INT32 *) mpValue; break; case CCopasiParameter::UINT: delete (unsigned C_INT32 *) mpValue; break; case CCopasiParameter::BOOL: delete (bool *) mpValue; break; case CCopasiParameter::STRING: delete (std::string *) mpValue; break; default: fatalError(); break; } mpValue = NULL; return; } <commit_msg>Beautified.<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/utilities/CCopasiParameter.cpp,v $ $Revision: 1.7 $ $Name: $ $Author: shoops $ $Date: 2003/11/12 16:44:26 $ End CVS Header */ /** * CCopasiParameter class. * This class is used to describe method paramters. This class is intended * to be used with integration or optimization methods. * * Created for Copasi by Stefan Hoops 2002 */ #include <string> #include "copasi.h" #include "CCopasiParameter.h" #include "CCopasiParameterGroup.h" #include "CCopasiMessage.h" #include "report/CKeyFactory.h" const std::string CCopasiParameter::TypeName[] = { "float", "unsigned float", "integer", "unsigned integer", "bool", "group", "string", "" }; const char* CCopasiParameter::XMLType[] = { "float", "unsignedFloat", "integer", "unsignedInteger", "bool", "group", "string", NULL }; CCopasiParameter::CCopasiParameter(): CCopasiContainer("NoName", NULL, "Parameter"), mType(INVALID) {} CCopasiParameter::CCopasiParameter(const CCopasiParameter & src, const CCopasiContainer * pParent): CCopasiContainer(src, pParent), mKey(CKeyFactory::add(src.getObjectType(), this)), mType(src.mType), mSize(0), mpValue(createValue(src.mpValue)) {} CCopasiParameter::CCopasiParameter(const std::string & name, const CCopasiParameter::Type & type, const void * pValue, const CCopasiContainer * pParent, const std::string & objectType): CCopasiContainer(name, pParent, objectType, CCopasiObject::Container | ((type == DOUBLE || type == UDOUBLE) ? CCopasiObject::ValueDbl : ((type == INT || type == UINT) ? CCopasiObject::ValueInt : (type == BOOL) ? CCopasiObject::ValueBool : 0))), mKey(CKeyFactory::add(objectType, this)), mType(type), mSize(0), mpValue(createValue(pValue)) {} CCopasiParameter::~CCopasiParameter() { CKeyFactory::remove(mKey); deleteValue(); } std::string CCopasiParameter::getKey() const {return mKey;} bool CCopasiParameter::setName(const std::string & name) {return setObjectName(name);} const std::string & CCopasiParameter::getName() const {return getObjectName();} const void * CCopasiParameter::getValue() const {return mpValue;} void * CCopasiParameter::getValue() {return mpValue;} const CCopasiParameter::Type & CCopasiParameter::getType() const {return mType;} bool CCopasiParameter::isValidValue(const C_FLOAT64 & value) const { if ((mType != CCopasiParameter::DOUBLE && mType != CCopasiParameter::UDOUBLE) || (mType == CCopasiParameter::UDOUBLE && value < 0.0)) return false; return true; } bool CCopasiParameter::isValidValue(const C_INT32 & C_UNUSED(value)) const { if (mType != CCopasiParameter::INT) return false; return true; } bool CCopasiParameter::isValidValue(const unsigned C_INT32 & C_UNUSED(value)) const { if (mType != CCopasiParameter::UINT) return false; return true; } bool CCopasiParameter::isValidValue(const bool & C_UNUSED(value)) const { if (mType != CCopasiParameter::BOOL) return false; return true; } bool CCopasiParameter::isValidValue(const std::string & C_UNUSED(value)) const { if (mType != CCopasiParameter::STRING) return false; return true; } bool CCopasiParameter::isValidValue(const CCopasiParameterGroup::parameterGroup & C_UNUSED(value)) const { if (mType != CCopasiParameter::GROUP) return false; return true; } void * CCopasiParameter::createValue(const void * pValue) { switch (mType) { case CCopasiParameter::DOUBLE: case CCopasiParameter::UDOUBLE: mpValue = new C_FLOAT64; if (pValue) * (C_FLOAT64 *) mpValue = * (C_FLOAT64 *) pValue; mSize = sizeof(C_FLOAT64); break; case CCopasiParameter::INT: mpValue = new C_INT32; if (pValue) * (C_INT32 *) mpValue = * (C_INT32 *) pValue; mSize = sizeof(C_INT32); break; case CCopasiParameter::UINT: mpValue = new unsigned C_INT32; if (pValue) * (unsigned C_INT32 *) mpValue = * (unsigned C_INT32 *) pValue; mSize = sizeof(unsigned C_INT32); break; case CCopasiParameter::BOOL: mpValue = new bool; if (pValue) * (bool *) mpValue = * (bool *) pValue; mSize = sizeof(bool); break; case CCopasiParameter::STRING: if (pValue) mpValue = new std::string(* (std::string *) pValue); else mpValue = new std::string; mSize = sizeof(std::string); break; case CCopasiParameter::GROUP: case CCopasiParameter::INVALID: mpValue = NULL; mSize = 0; break; } return mpValue; } void CCopasiParameter::deleteValue() { if (!mpValue) return; switch (mType) { case CCopasiParameter::DOUBLE: case CCopasiParameter::UDOUBLE: delete (C_FLOAT64 *) mpValue; break; case CCopasiParameter::INT: delete (C_INT32 *) mpValue; break; case CCopasiParameter::UINT: delete (unsigned C_INT32 *) mpValue; break; case CCopasiParameter::BOOL: delete (bool *) mpValue; break; case CCopasiParameter::STRING: delete (std::string *) mpValue; break; default: fatalError(); break; } mpValue = NULL; return; } <|endoftext|>
<commit_before>// Copyright (c) 2018-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bench/bench.h> #include <blockfilter.h> static const GCSFilter::ElementSet GenerateGCSTestElements() { GCSFilter::ElementSet elements; for (int i = 0; i < 10000; ++i) { GCSFilter::Element element(32); element[0] = static_cast<unsigned char>(i); element[1] = static_cast<unsigned char>(i >> 8); elements.insert(std::move(element)); } return elements; } static void GCSBlockFilterGetHash(benchmark::Bench& bench) { auto elements = GenerateGCSTestElements(); GCSFilter filter({0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, elements); BlockFilter block_filter(BlockFilterType::BASIC, {}, filter.GetEncoded(), /*skip_decode_check=*/false); bench.run([&] { block_filter.GetHash(); }); } static void GCSFilterConstruct(benchmark::Bench& bench) { auto elements = GenerateGCSTestElements(); uint64_t siphash_k0 = 0; bench.batch(elements.size()).unit("elem").run([&] { GCSFilter filter({siphash_k0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, elements); siphash_k0++; }); } static void GCSFilterDecode(benchmark::Bench& bench) { auto elements = GenerateGCSTestElements(); GCSFilter filter({0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, elements); auto encoded = filter.GetEncoded(); bench.run([&] { GCSFilter filter({0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, encoded, /*skip_decode_check=*/false); }); } static void GCSFilterDecodeSkipCheck(benchmark::Bench& bench) { auto elements = GenerateGCSTestElements(); GCSFilter filter({0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, elements); auto encoded = filter.GetEncoded(); bench.run([&] { GCSFilter filter({0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, encoded, /*skip_decode_check=*/true); }); } static void GCSFilterMatch(benchmark::Bench& bench) { auto elements = GenerateGCSTestElements(); GCSFilter filter({0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, elements); bench.run([&] { filter.Match(GCSFilter::Element()); }); } BENCHMARK(GCSBlockFilterGetHash); BENCHMARK(GCSFilterConstruct); BENCHMARK(GCSFilterDecode); BENCHMARK(GCSFilterDecodeSkipCheck); BENCHMARK(GCSFilterMatch); <commit_msg>Update GCSFilter benchmarks<commit_after>// Copyright (c) 2018-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bench/bench.h> #include <blockfilter.h> static const GCSFilter::ElementSet GenerateGCSTestElements() { GCSFilter::ElementSet elements; // Testing the benchmarks with different number of elements show that a filter // with at least 100,000 elements results in benchmarks that have the same // ns/op. This makes it easy to reason about how long (in nanoseconds) a single // filter element takes to process. for (int i = 0; i < 100000; ++i) { GCSFilter::Element element(32); element[0] = static_cast<unsigned char>(i); element[1] = static_cast<unsigned char>(i >> 8); elements.insert(std::move(element)); } return elements; } static void GCSBlockFilterGetHash(benchmark::Bench& bench) { auto elements = GenerateGCSTestElements(); GCSFilter filter({0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, elements); BlockFilter block_filter(BlockFilterType::BASIC, {}, filter.GetEncoded(), /*skip_decode_check=*/false); bench.run([&] { block_filter.GetHash(); }); } static void GCSFilterConstruct(benchmark::Bench& bench) { auto elements = GenerateGCSTestElements(); uint64_t siphash_k0 = 0; bench.run([&]{ GCSFilter filter({siphash_k0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, elements); siphash_k0++; }); } static void GCSFilterDecode(benchmark::Bench& bench) { auto elements = GenerateGCSTestElements(); GCSFilter filter({0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, elements); auto encoded = filter.GetEncoded(); bench.run([&] { GCSFilter filter({0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, encoded, /*skip_decode_check=*/false); }); } static void GCSFilterDecodeSkipCheck(benchmark::Bench& bench) { auto elements = GenerateGCSTestElements(); GCSFilter filter({0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, elements); auto encoded = filter.GetEncoded(); bench.run([&] { GCSFilter filter({0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, encoded, /*skip_decode_check=*/true); }); } static void GCSFilterMatch(benchmark::Bench& bench) { auto elements = GenerateGCSTestElements(); GCSFilter filter({0, 0, BASIC_FILTER_P, BASIC_FILTER_M}, elements); bench.run([&] { filter.Match(GCSFilter::Element()); }); } BENCHMARK(GCSBlockFilterGetHash); BENCHMARK(GCSFilterConstruct); BENCHMARK(GCSFilterDecode); BENCHMARK(GCSFilterDecodeSkipCheck); BENCHMARK(GCSFilterMatch); <|endoftext|>
<commit_before>/* * 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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include <geode/geode_globals.hpp> #include <geode/DistributedSystem.hpp> #include "statistics/StatisticsManager.hpp" #include <geode/SystemProperties.hpp> #include <CppCacheLibrary.hpp> #include <Utils.hpp> #include "util/Log.hpp" #include <geode/CacheFactory.hpp> #include <ace/OS.h> #include <ace/Guard_T.h> #include <ace/Recursive_Thread_Mutex.h> #include "ExpiryTaskManager.hpp" #include "CacheImpl.hpp" #include "geode/DataOutput.hpp" #include "TcrMessage.hpp" #include "DistributedSystemImpl.hpp" #include "RegionStats.hpp" #include "PoolStatistics.hpp" #include "CacheRegionHelper.hpp" #include "DiffieHellman.hpp" #include "version.h" using namespace apache::geode::client; using namespace apache::geode::statistics; ACE_Recursive_Thread_Mutex* g_disconnectLock = new ACE_Recursive_Thread_Mutex(); namespace {} // namespace namespace apache { namespace geode { namespace client { void setLFH() { #ifdef _WIN32 static HINSTANCE kernelMod = nullptr; if (kernelMod == nullptr) { kernelMod = GetModuleHandle("kernel32"); if (kernelMod != nullptr) { typedef BOOL(WINAPI * PHSI)( HANDLE HeapHandle, HEAP_INFORMATION_CLASS HeapInformationClass, PVOID HeapInformation, SIZE_T HeapInformationLength); typedef HANDLE(WINAPI * PGPH)(); PHSI pHSI = nullptr; PGPH pGPH = nullptr; if ((pHSI = (PHSI)GetProcAddress(kernelMod, "HeapSetInformation")) != nullptr) { // The LFH API is available /* Only set LFH for process heap; causes problems in C++ framework if set for all heaps HANDLE hProcessHeapHandles[1024]; DWORD dwRet; ULONG heapFragValue = 2; dwRet= GetProcessHeaps( 1024, hProcessHeapHandles ); for (DWORD i = 0; i < dwRet; i++) { HeapSetInformation( hProcessHeapHandles[i], HeapCompatibilityInformation, &heapFragValue, sizeof(heapFragValue) ); } */ HANDLE hProcessHeapHandle; ULONG heapFragValue = 2; if ((pGPH = (PGPH)GetProcAddress(kernelMod, "GetProcessHeap")) != nullptr) { hProcessHeapHandle = pGPH(); LOGCONFIG( "Setting Microsoft Windows' low-fragmentation heap for use as " "the main process heap."); pHSI(hProcessHeapHandle, HeapCompatibilityInformation, &heapFragValue, sizeof(heapFragValue)); } } } } #endif } } // namespace client } // namespace geode } // namespace apache DistributedSystem::DistributedSystem( const std::string& name, std::unique_ptr<SystemProperties> sysProps) : m_name(name), m_statisticsManager(nullptr), m_sysProps(std::move(sysProps)), m_connected(false) { LOGDEBUG("DistributedSystem::DistributedSystem"); if (!m_sysProps->securityClientDhAlgo().empty()) { DiffieHellman::initOpenSSLFuncPtrs(); } } DistributedSystem::~DistributedSystem() {} void DistributedSystem::logSystemInformation() const { std::string gfcpp = CppCacheLibrary::getProductDir(); LOGCONFIG("Using Geode Native Client Product Directory: %s", gfcpp.c_str()); // Add version information, source revision, current directory etc. LOGCONFIG("Product version: %s", PRODUCT_VENDOR " " PRODUCT_NAME " " PRODUCT_VERSION " (" PRODUCT_BITS ") " PRODUCT_BUILDDATE); LOGCONFIG("Source revision: %s", PRODUCT_SOURCE_REVISION); LOGCONFIG("Source repository: %s", PRODUCT_SOURCE_REPOSITORY); ACE_utsname u; ACE_OS::uname(&u); LOGCONFIG( "Running on: SystemName=%s Machine=%s Host=%s Release=%s Version=%s", u.sysname, u.machine, u.nodename, u.release, u.version); #ifdef _WIN32 const uint32_t pathMax = _MAX_PATH; #else const uint32_t pathMax = PATH_MAX; #endif ACE_TCHAR cwd[pathMax + 1]; (void)ACE_OS::getcwd(cwd, pathMax); LOGCONFIG("Current directory: %s", cwd); LOGCONFIG("Current value of PATH: %s", ACE_OS::getenv("PATH")); #ifndef _WIN32 const char* ld_libpath = ACE_OS::getenv("LD_LIBRARY_PATH"); LOGCONFIG("Current library path: %s", ld_libpath == nullptr ? "nullptr" : ld_libpath); #endif // Log the Geode system properties m_sysProps->logSettings(); } std::unique_ptr<DistributedSystem> DistributedSystem::create( const std::string& _name, const std::shared_ptr<Properties>& configPtr) { // TODO global - Refactory out the static initialization // Trigger other library initialization. CppCacheLibrary::initLib(); auto sysProps = std::unique_ptr<SystemProperties>(new SystemProperties(configPtr)); auto name = _name; if (name.empty()) { name = "NativeDS"; } // Set client name via native client API auto&& propName = sysProps->name(); if (!propName.empty()) { name = propName; } // TODO global - keep global but setup once. auto&& logFilename = sysProps->logFilename(); if (!logFilename.empty()) { try { Log::close(); Log::init(sysProps->logLevel(), logFilename.c_str(), sysProps->logFileSizeLimit(), sysProps->logDiskSpaceLimit()); } catch (const GeodeIOException&) { Log::close(); sysProps = nullptr; throw; } } else { Log::setLogLevel(sysProps->logLevel()); } try { std::string gfcpp = CppCacheLibrary::getProductDir(); } catch (const Exception&) { LOGERROR( "Unable to determine Product Directory. Please set the " "GFCPP environment variable."); throw; } auto distributedSystem = std::unique_ptr<DistributedSystem>( new DistributedSystem(name, std::move(sysProps))); if (!distributedSystem) { throw NullPointerException("DistributedSystem::connect: new failed"); } distributedSystem->m_impl = new DistributedSystemImpl(name.c_str(), distributedSystem.get()); distributedSystem->logSystemInformation(); LOGCONFIG("Starting the Geode Native Client"); return distributedSystem; } void DistributedSystem::connect(Cache* cache) { ACE_Guard<ACE_Recursive_Thread_Mutex> disconnectGuard(*g_disconnectLock); if (m_connected == true) { throw AlreadyConnectedException( "DistributedSystem::connect: already connected, call getInstance to " "get it"); } try { m_impl->connect(); } catch (const apache::geode::client::Exception& e) { LOGERROR("Exception caught during client initialization: %s", e.what()); std::string msg = "DistributedSystem::connect: caught exception: "; msg.append(e.what()); throw NotConnectedException(msg.c_str()); } catch (const std::exception& e) { LOGERROR("Exception caught during client initialization: %s", e.what()); std::string msg = "DistributedSystem::connect: caught exception: "; msg.append(e.what()); throw NotConnectedException(msg.c_str()); } catch (...) { LOGERROR("Unknown exception caught during client initialization"); throw NotConnectedException( "DistributedSystem::connect: caught unknown exception"); } auto cacheImpl = CacheRegionHelper::getCacheImpl(cache); try { m_statisticsManager = std::unique_ptr<StatisticsManager>(new StatisticsManager( m_sysProps->statisticsArchiveFile().c_str(), m_sysProps->statisticsSampleInterval(), m_sysProps->statisticsEnabled(), cacheImpl, m_sysProps->durableClientId().c_str(), m_sysProps->durableTimeout(), m_sysProps->statsFileSizeLimit(), m_sysProps->statsDiskSpaceLimit())); cacheImpl->m_cacheStats = new CachePerfStats(getStatisticsManager()->getStatisticsFactory()); } catch (const NullPointerException&) { Log::close(); throw; } m_connected = true; } void DistributedSystem::disconnect() { ACE_Guard<ACE_Recursive_Thread_Mutex> disconnectGuard(*g_disconnectLock); if (!m_connected) { throw NotConnectedException( "DistributedSystem::disconnect: connect " "not called"); } if (m_impl) { m_impl->disconnect(); delete m_impl; m_impl = nullptr; } LOGFINEST("Deleted DistributedSystemImpl"); LOGCONFIG("Stopped the Geode Native Client"); // TODO global - log stays global so lets move this Log::close(); m_connected = false; } SystemProperties& DistributedSystem::getSystemProperties() const { return *m_sysProps; } const std::string& DistributedSystem::getName() const { return m_name; } <commit_msg>GEODE-3058: Remove low fragmentation heap feature enablement<commit_after>/* * 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 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include <geode/geode_globals.hpp> #include <geode/DistributedSystem.hpp> #include "statistics/StatisticsManager.hpp" #include <geode/SystemProperties.hpp> #include <CppCacheLibrary.hpp> #include <Utils.hpp> #include "util/Log.hpp" #include <geode/CacheFactory.hpp> #include <ace/OS.h> #include <ace/Guard_T.h> #include <ace/Recursive_Thread_Mutex.h> #include "ExpiryTaskManager.hpp" #include "CacheImpl.hpp" #include "geode/DataOutput.hpp" #include "TcrMessage.hpp" #include "DistributedSystemImpl.hpp" #include "RegionStats.hpp" #include "PoolStatistics.hpp" #include "CacheRegionHelper.hpp" #include "DiffieHellman.hpp" #include "version.h" using namespace apache::geode::client; using namespace apache::geode::statistics; ACE_Recursive_Thread_Mutex* g_disconnectLock = new ACE_Recursive_Thread_Mutex(); DistributedSystem::DistributedSystem( const std::string& name, std::unique_ptr<SystemProperties> sysProps) : m_name(name), m_statisticsManager(nullptr), m_sysProps(std::move(sysProps)), m_connected(false) { LOGDEBUG("DistributedSystem::DistributedSystem"); if (!m_sysProps->securityClientDhAlgo().empty()) { DiffieHellman::initOpenSSLFuncPtrs(); } } DistributedSystem::~DistributedSystem() {} void DistributedSystem::logSystemInformation() const { std::string gfcpp = CppCacheLibrary::getProductDir(); LOGCONFIG("Using Geode Native Client Product Directory: %s", gfcpp.c_str()); // Add version information, source revision, current directory etc. LOGCONFIG("Product version: %s", PRODUCT_VENDOR " " PRODUCT_NAME " " PRODUCT_VERSION " (" PRODUCT_BITS ") " PRODUCT_BUILDDATE); LOGCONFIG("Source revision: %s", PRODUCT_SOURCE_REVISION); LOGCONFIG("Source repository: %s", PRODUCT_SOURCE_REPOSITORY); ACE_utsname u; ACE_OS::uname(&u); LOGCONFIG( "Running on: SystemName=%s Machine=%s Host=%s Release=%s Version=%s", u.sysname, u.machine, u.nodename, u.release, u.version); #ifdef _WIN32 const uint32_t pathMax = _MAX_PATH; #else const uint32_t pathMax = PATH_MAX; #endif ACE_TCHAR cwd[pathMax + 1]; (void)ACE_OS::getcwd(cwd, pathMax); LOGCONFIG("Current directory: %s", cwd); LOGCONFIG("Current value of PATH: %s", ACE_OS::getenv("PATH")); #ifndef _WIN32 const char* ld_libpath = ACE_OS::getenv("LD_LIBRARY_PATH"); LOGCONFIG("Current library path: %s", ld_libpath == nullptr ? "nullptr" : ld_libpath); #endif // Log the Geode system properties m_sysProps->logSettings(); } std::unique_ptr<DistributedSystem> DistributedSystem::create( const std::string& _name, const std::shared_ptr<Properties>& configPtr) { // TODO global - Refactory out the static initialization // Trigger other library initialization. CppCacheLibrary::initLib(); auto sysProps = std::unique_ptr<SystemProperties>(new SystemProperties(configPtr)); auto name = _name; if (name.empty()) { name = "NativeDS"; } // Set client name via native client API auto&& propName = sysProps->name(); if (!propName.empty()) { name = propName; } // TODO global - keep global but setup once. auto&& logFilename = sysProps->logFilename(); if (!logFilename.empty()) { try { Log::close(); Log::init(sysProps->logLevel(), logFilename.c_str(), sysProps->logFileSizeLimit(), sysProps->logDiskSpaceLimit()); } catch (const GeodeIOException&) { Log::close(); sysProps = nullptr; throw; } } else { Log::setLogLevel(sysProps->logLevel()); } try { std::string gfcpp = CppCacheLibrary::getProductDir(); } catch (const Exception&) { LOGERROR( "Unable to determine Product Directory. Please set the " "GFCPP environment variable."); throw; } auto distributedSystem = std::unique_ptr<DistributedSystem>( new DistributedSystem(name, std::move(sysProps))); if (!distributedSystem) { throw NullPointerException("DistributedSystem::connect: new failed"); } distributedSystem->m_impl = new DistributedSystemImpl(name.c_str(), distributedSystem.get()); distributedSystem->logSystemInformation(); LOGCONFIG("Starting the Geode Native Client"); return distributedSystem; } void DistributedSystem::connect(Cache* cache) { ACE_Guard<ACE_Recursive_Thread_Mutex> disconnectGuard(*g_disconnectLock); if (m_connected == true) { throw AlreadyConnectedException( "DistributedSystem::connect: already connected, call getInstance to " "get it"); } try { m_impl->connect(); } catch (const apache::geode::client::Exception& e) { LOGERROR("Exception caught during client initialization: %s", e.what()); std::string msg = "DistributedSystem::connect: caught exception: "; msg.append(e.what()); throw NotConnectedException(msg.c_str()); } catch (const std::exception& e) { LOGERROR("Exception caught during client initialization: %s", e.what()); std::string msg = "DistributedSystem::connect: caught exception: "; msg.append(e.what()); throw NotConnectedException(msg.c_str()); } catch (...) { LOGERROR("Unknown exception caught during client initialization"); throw NotConnectedException( "DistributedSystem::connect: caught unknown exception"); } auto cacheImpl = CacheRegionHelper::getCacheImpl(cache); try { m_statisticsManager = std::unique_ptr<StatisticsManager>(new StatisticsManager( m_sysProps->statisticsArchiveFile().c_str(), m_sysProps->statisticsSampleInterval(), m_sysProps->statisticsEnabled(), cacheImpl, m_sysProps->durableClientId().c_str(), m_sysProps->durableTimeout(), m_sysProps->statsFileSizeLimit(), m_sysProps->statsDiskSpaceLimit())); cacheImpl->m_cacheStats = new CachePerfStats(getStatisticsManager()->getStatisticsFactory()); } catch (const NullPointerException&) { Log::close(); throw; } m_connected = true; } void DistributedSystem::disconnect() { ACE_Guard<ACE_Recursive_Thread_Mutex> disconnectGuard(*g_disconnectLock); if (!m_connected) { throw NotConnectedException( "DistributedSystem::disconnect: connect " "not called"); } if (m_impl) { m_impl->disconnect(); delete m_impl; m_impl = nullptr; } LOGFINEST("Deleted DistributedSystemImpl"); LOGCONFIG("Stopped the Geode Native Client"); // TODO global - log stays global so lets move this Log::close(); m_connected = false; } SystemProperties& DistributedSystem::getSystemProperties() const { return *m_sysProps; } const std::string& DistributedSystem::getName() const { return m_name; } <|endoftext|>
<commit_before>/* * CodeQuery * Copyright (C) 2013 ruben2020 https://github.com/ruben2020/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <string> #include "optlist.h" #include "csdbparser.h" #include "cs2sq.h" #include "ctagread.h" #include "small_lib.h" #include "swver.h" #if 0 // test code for csdbparser - not needed int test_csdbparser (void) { csdbparser csdbp; std::string s; long int num = 0; csdbparser::enResult res; //csdbp.setDebug(true); int k = csdbparser::file_sanity_check("./cscope.out"); printf("%d\n",k); csdbp.open_file("./cscope.out"); //csdbp.setup_srcfil_read(); do { csdbp.get_next_srcfil(&s); if (s.length() == 0) break; num++; //printf("\"%s\"\n",s.data()); } while (s.length() > 0); printf("Total num of files = %ld\nBase path = %s\n\n", num, csdbp.getBasePath()); num = 0; res = csdbp.setup_symbol_read(); if (res != csdbparser::resOK) printf("Error in setup_symbol_read: %d\n", res); symdata_pack sp; sp.valid = true; while(sp.valid) { res = csdbp.get_next_symbol(&sp); if (res != csdbparser::resOK) { printf("Error in get_next_symbol: %d\n", res); break; } if (sp.valid) { printf("[[ %s, linenum=%ld, symbols=%d, \"%s\" ]]\n", sp.filename.c_str(), sp.line_num, sp.symbols.size(), sp.line_text.c_str()); if (sp.symbols.size() > 0) { for (int i=0; i < sp.symbols.size(); i++) { printf("{%s, %s", sp.symbols[i].symbname.c_str(), sp.symbols[i].getTypeDesc()); if (sp.symbols[i].sym_type == sym_data::symFuncCall) printf(", func[%s], macro[%s]", sp.symbols[i].calling_func.c_str(), sp.symbols[i].calling_macro.c_str()); printf("} "); } printf("\n"); } num += sp.symbols.size(); } } printf("Total number of symbols found = %ld\n",num); } #endif int process_cscope(const char* cscopefn, const char* sqfn, bool debug) { cs2sq::enResult res; cs2sq dbmaker; dbmaker.setDebug(debug); int k = csdbparser::file_sanity_check(cscopefn); printf("cscope.out sanity check %s\n",(k==0 ? "OK" : "Error")); if (k != 0) return 1; dbmaker.open_csdb(cscopefn); k = dbmaker.test_csdb(); printf("cscope.out detailed check %s\n",(k==0 ? "OK" : "Error")); if (k != 0) { printf("Please note that assembly code embedded in C/C++ files is unsupported.\n" "This might be the cause for this error.\n" "Please use the -d (for debug) argument to get more info.\n"); return 1; } remove(sqfn); res = dbmaker.open_db(sqfn); if (res != cs2sq::resOK) {printf("Error1! %d\n",res); return 1;} res = dbmaker.setup_tables(); if (res != cs2sq::resOK) {printf("Error2! %d\n",res); return 1;} printf("Adding symbols ...\n"); res = dbmaker.add_symbols(); if (res != cs2sq::resOK) {printf("Error3! %d\n",res); return 1;} printf("Finalizing ...\n"); res = dbmaker.finalize(); if (res != cs2sq::resOK) {printf("Error4! %d\n",res); return 1;} return 0; } int process_ctags(const char* ctagsfn, const char* sqfn, bool debug) { ctagread tagreader; ctagread::enResult restag; tagreader.setDebug(debug); restag = tagreader.open_files(sqfn, ctagsfn); if (restag != ctagread::resOK) {printf("Error!!!\n"); return 1;} printf("Processing ctags file ...\n"); restag = tagreader.process_ctags(); if (restag != ctagread::resOK) {printf("Error!!!\n"); return 1;} printf("Finalizing ...\n"); restag = tagreader.finalize(); if (restag != ctagread::resOK) {printf("Error!!!\n"); return 1;} return 0; } void printhelp(const char* str) { printf("Usage: %s [-s <sqdbfile> [-c <cscope.out>] [-t <ctags>]] [-p] [-d] [-v] [-h]\n\n", str); printf("options:\n"); printf(" -s : CodeQuery sqlite3 db file path\n"); printf(" -c : cscope.out file path\n"); printf(" -t : ctags tags file path\n"); printf(" -p : \"vacuum\", compact database (may take more time)\n"); printf(" -d : debug\n"); printf(" -v : version\n"); printf(" -h : help\n\n"); printf("The combinations possible are -s -c, -s -t, -s -c -t\n"); printf("The additional optional arguments are -p and -d\n"); printf("if -c is present then sqdbfile need not exist. It will be created.\n"); printf("if -t is present but not -c, then sqdbfile has to exist. Ctags info will be added to it.\n\n"); } void printlicense(void) { printf(CODEQUERY_SW_VERSION); printf("\n"); printf(CODEQUERY_SW_LICENSE); } bool fileexists(const char* fn) { bool retval; FILE *fp; fp = fopen(fn, "r"); retval = (fp != NULL); if (retval) fclose(fp); return retval; } void process_argwithopt(option_t* thisOpt, bool& err, std::string& fnstr, bool filemustexist) { if (thisOpt->argument != NULL) { fnstr = thisOpt->argument; if (filemustexist && (fileexists(fnstr.c_str()) == false)) { printf("Error: File %s doesn't exist.\n", fnstr.c_str()); err = true; } } else { printf("Error: -%c used without file option.\n", thisOpt->option); err = true; } } int main(int argc, char *argv[]) { option_t *optList=NULL, *thisOpt=NULL; bool bHelp, bSqlite, bCscope, bCtags, bDebug, bError, bVacuum, bVersion; bHelp = (argc <= 1); bVersion = false; bSqlite = false; bCscope = false; bCtags = false; bDebug = false; bError = false; bVacuum = false; std::string sqfn, csfn, ctfn; /* get list of command line options and their arguments */ optList = GetOptList(argc, argv, (char*)"s:c:t:pdvh"); /* display results of parsing */ while (optList != NULL) { thisOpt = optList; optList = optList->next; switch(thisOpt->option) { case 'v': bVersion = true; break; case 'h': bHelp = true; break; case 's': bSqlite = true; process_argwithopt(thisOpt, bError, sqfn, false); break; case 'c': bCscope = true; process_argwithopt(thisOpt, bError, csfn, true); break; case 't': bCtags = true; process_argwithopt(thisOpt, bError, ctfn, true); break; case 'd': bDebug = true; break; case 'p': bVacuum = true; break; default: break; } free(thisOpt); /* done with this item, free it */ } if (bVersion) { printlicense(); return 0; } if (bHelp || bError) { printhelp(extract_filename(argv[0])); return (bError ? 1 : 0); } if (!bSqlite) { printf("Error: -s is required.\n"); bError = true; } if ((bCscope == false)&&(bCtags == false)) { printf("Error: Either -c or -t or both must be present. Both are missing.\n"); bError = true; } if ((!bCscope) && (fileexists(sqfn.c_str()) == false)) { printf("Error: File %s doesn't exist.\n", sqfn.c_str()); printf("Error: Without -c, sqdbfile must exist.\n"); bError = true; } if (bError) { printhelp(extract_filename(argv[0])); return 1; } if (bCscope) { if (process_cscope(csfn.c_str(), sqfn.c_str(), bDebug) == 1) return 1; } if (bCtags) { if (process_ctags(ctfn.c_str(), sqfn.c_str(), bDebug) == 1) return 1; } if (bVacuum) { printf("Compacting database ...\n"); if (sqlbase::vacuum(sqfn.c_str(), bDebug) != 0) return 1; } else { if (sqlbase::analyze(sqfn.c_str(), bDebug) != 0) return 1; } return 0; } <commit_msg>Added a better error message for not using -c with cscope<commit_after>/* * CodeQuery * Copyright (C) 2013 ruben2020 https://github.com/ruben2020/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <string> #include "optlist.h" #include "csdbparser.h" #include "cs2sq.h" #include "ctagread.h" #include "small_lib.h" #include "swver.h" #if 0 // test code for csdbparser - not needed int test_csdbparser (void) { csdbparser csdbp; std::string s; long int num = 0; csdbparser::enResult res; //csdbp.setDebug(true); int k = csdbparser::file_sanity_check("./cscope.out"); printf("%d\n",k); csdbp.open_file("./cscope.out"); //csdbp.setup_srcfil_read(); do { csdbp.get_next_srcfil(&s); if (s.length() == 0) break; num++; //printf("\"%s\"\n",s.data()); } while (s.length() > 0); printf("Total num of files = %ld\nBase path = %s\n\n", num, csdbp.getBasePath()); num = 0; res = csdbp.setup_symbol_read(); if (res != csdbparser::resOK) printf("Error in setup_symbol_read: %d\n", res); symdata_pack sp; sp.valid = true; while(sp.valid) { res = csdbp.get_next_symbol(&sp); if (res != csdbparser::resOK) { printf("Error in get_next_symbol: %d\n", res); break; } if (sp.valid) { printf("[[ %s, linenum=%ld, symbols=%d, \"%s\" ]]\n", sp.filename.c_str(), sp.line_num, sp.symbols.size(), sp.line_text.c_str()); if (sp.symbols.size() > 0) { for (int i=0; i < sp.symbols.size(); i++) { printf("{%s, %s", sp.symbols[i].symbname.c_str(), sp.symbols[i].getTypeDesc()); if (sp.symbols[i].sym_type == sym_data::symFuncCall) printf(", func[%s], macro[%s]", sp.symbols[i].calling_func.c_str(), sp.symbols[i].calling_macro.c_str()); printf("} "); } printf("\n"); } num += sp.symbols.size(); } } printf("Total number of symbols found = %ld\n",num); } #endif int process_cscope(const char* cscopefn, const char* sqfn, bool debug) { cs2sq::enResult res; cs2sq dbmaker; dbmaker.setDebug(debug); int k = csdbparser::file_sanity_check(cscopefn); printf("cscope.out sanity check %s\n",(k==csdbparser::resOK ? "OK" : "Error")); if (k == csdbparser::resUNSUPPORTED_PARAM) printf("Unsupported cscope parameters: -c is required. -q, -b and -R are optional. The rest should not be used.\n"); if (k != csdbparser::resOK) return 1; dbmaker.open_csdb(cscopefn); k = dbmaker.test_csdb(); printf("cscope.out detailed check %s\n",(k==0 ? "OK" : "Error")); if (k != 0) { printf("Please note that assembly code embedded in C/C++ files is unsupported.\n" "This might be the cause for this error.\n" "Please use the -d (for debug) argument to get more info.\n"); return 1; } remove(sqfn); res = dbmaker.open_db(sqfn); if (res != cs2sq::resOK) {printf("Error1! %d\n",res); return 1;} res = dbmaker.setup_tables(); if (res != cs2sq::resOK) {printf("Error2! %d\n",res); return 1;} printf("Adding symbols ...\n"); res = dbmaker.add_symbols(); if (res != cs2sq::resOK) {printf("Error3! %d\n",res); return 1;} printf("Finalizing ...\n"); res = dbmaker.finalize(); if (res != cs2sq::resOK) {printf("Error4! %d\n",res); return 1;} return 0; } int process_ctags(const char* ctagsfn, const char* sqfn, bool debug) { ctagread tagreader; ctagread::enResult restag; tagreader.setDebug(debug); restag = tagreader.open_files(sqfn, ctagsfn); if (restag != ctagread::resOK) {printf("Error!!!\n"); return 1;} printf("Processing ctags file ...\n"); restag = tagreader.process_ctags(); if (restag != ctagread::resOK) {printf("Error!!!\n"); return 1;} printf("Finalizing ...\n"); restag = tagreader.finalize(); if (restag != ctagread::resOK) {printf("Error!!!\n"); return 1;} return 0; } void printhelp(const char* str) { printf("Usage: %s [-s <sqdbfile> [-c <cscope.out>] [-t <ctags>]] [-p] [-d] [-v] [-h]\n\n", str); printf("options:\n"); printf(" -s : CodeQuery sqlite3 db file path\n"); printf(" -c : cscope.out file path\n"); printf(" -t : ctags tags file path\n"); printf(" -p : \"vacuum\", compact database (may take more time)\n"); printf(" -d : debug\n"); printf(" -v : version\n"); printf(" -h : help\n\n"); printf("The combinations possible are -s -c, -s -t, -s -c -t\n"); printf("The additional optional arguments are -p and -d\n"); printf("if -c is present then sqdbfile need not exist. It will be created.\n"); printf("if -t is present but not -c, then sqdbfile has to exist. Ctags info will be added to it.\n\n"); } void printlicense(void) { printf(CODEQUERY_SW_VERSION); printf("\n"); printf(CODEQUERY_SW_LICENSE); } bool fileexists(const char* fn) { bool retval; FILE *fp; fp = fopen(fn, "r"); retval = (fp != NULL); if (retval) fclose(fp); return retval; } void process_argwithopt(option_t* thisOpt, bool& err, std::string& fnstr, bool filemustexist) { if (thisOpt->argument != NULL) { fnstr = thisOpt->argument; if (filemustexist && (fileexists(fnstr.c_str()) == false)) { printf("Error: File %s doesn't exist.\n", fnstr.c_str()); err = true; } } else { printf("Error: -%c used without file option.\n", thisOpt->option); err = true; } } int main(int argc, char *argv[]) { option_t *optList=NULL, *thisOpt=NULL; bool bHelp, bSqlite, bCscope, bCtags, bDebug, bError, bVacuum, bVersion; bHelp = (argc <= 1); bVersion = false; bSqlite = false; bCscope = false; bCtags = false; bDebug = false; bError = false; bVacuum = false; std::string sqfn, csfn, ctfn; /* get list of command line options and their arguments */ optList = GetOptList(argc, argv, (char*)"s:c:t:pdvh"); /* display results of parsing */ while (optList != NULL) { thisOpt = optList; optList = optList->next; switch(thisOpt->option) { case 'v': bVersion = true; break; case 'h': bHelp = true; break; case 's': bSqlite = true; process_argwithopt(thisOpt, bError, sqfn, false); break; case 'c': bCscope = true; process_argwithopt(thisOpt, bError, csfn, true); break; case 't': bCtags = true; process_argwithopt(thisOpt, bError, ctfn, true); break; case 'd': bDebug = true; break; case 'p': bVacuum = true; break; default: break; } free(thisOpt); /* done with this item, free it */ } if (bVersion) { printlicense(); return 0; } if (bHelp || bError) { printhelp(extract_filename(argv[0])); return (bError ? 1 : 0); } if (!bSqlite) { printf("Error: -s is required.\n"); bError = true; } if ((bCscope == false)&&(bCtags == false)) { printf("Error: Either -c or -t or both must be present. Both are missing.\n"); bError = true; } if ((!bCscope) && (fileexists(sqfn.c_str()) == false)) { printf("Error: File %s doesn't exist.\n", sqfn.c_str()); printf("Error: Without -c, sqdbfile must exist.\n"); bError = true; } if (bError) { printhelp(extract_filename(argv[0])); return 1; } if (bCscope) { if (process_cscope(csfn.c_str(), sqfn.c_str(), bDebug) == 1) return 1; } if (bCtags) { if (process_ctags(ctfn.c_str(), sqfn.c_str(), bDebug) == 1) return 1; } if (bVacuum) { printf("Compacting database ...\n"); if (sqlbase::vacuum(sqfn.c_str(), bDebug) != 0) return 1; } else { if (sqlbase::analyze(sqfn.c_str(), bDebug) != 0) return 1; } return 0; } <|endoftext|>
<commit_before>/** \brief Utility for creating Debian/Ubunto AMD64 packages. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * \documentation See https://ubuntuforums.org/showthread.php?t=910717 * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <vector> #include "ExecUtil.h" #include "FileUtil.h" #include "StringUtil.h" #include "util.h" namespace { struct Library { std::string full_name_; std::string name_; std::string version_; public: Library() = default; Library(const Library &other) = default; Library(const std::string &full_name, const std::string &name, const std::string &version) : full_name_(full_name), name_(name), version_(version) { } inline std::string toString() const { return name_ + " (>= " + version_ + ")"; } }; void ExtractLibrary(const std::string &line, std::string * const full_name, std::string * const simplified_name) { const auto first_space_pos(line.find(' ')); if (first_space_pos == std::string::npos) LOG_ERROR("no space found in \"" + line + "\"!"); *full_name = line.substr(0, first_space_pos); const auto first_dot_pos(full_name->find('.')); *simplified_name = (first_dot_pos == std::string::npos) ? *full_name : full_name->substr(0, first_dot_pos); } std::string GetVersionHelper(const std::string &library_name) { std::string dpkg_output; if (not ExecUtil::ExecSubcommandAndCaptureStdout("dpkg -s " + library_name, &dpkg_output)) LOG_ERROR("failed to execute dpkg!"); std::vector<std::string> lines; StringUtil::SplitThenTrimWhite(dpkg_output, '\n', &lines); for (const auto &line : lines) { if (StringUtil::StartsWith(line, "Version: ")) { const auto version(line.substr(__builtin_strlen("Version: "))); const auto first_plus_pos(version.find('+')); return (first_plus_pos == std::string::npos) ? version : version.substr(0, first_plus_pos); } } return ""; } inline std::set<std::string> FilterPackages(const std::set<std::string> &unfiltered_set, const std::set<std::string> &filter) { std::set<std::string> filtered_set; for (const auto &element : unfiltered_set) { if (filter.find(element) == filter.cend()) filtered_set.emplace(element); } return filtered_set; } std::string GetVersion(const std::string &full_library_name, const std::set<std::string> &blacklist) { std::string dpkg_output; if (not ExecUtil::ExecSubcommandAndCaptureStdout("dpkg -S " + full_library_name, &dpkg_output)) LOG_ERROR("failed to execute dpkg!"); std::vector<std::string> lines; StringUtil::SplitThenTrimWhite(dpkg_output, '\n', &lines); std::set<std::string> packages; for (const auto &line : lines) { const auto first_colon_pos(line.find(':')); if (first_colon_pos == std::string::npos or first_colon_pos == 0) LOG_ERROR("weird output line of \"dpkg -S\": \"" + line + "\"!"); const auto package(line.substr(0, first_colon_pos)); if (not StringUtil::EndsWith(package, "-dev")) packages.emplace(package); } if (packages.empty()) LOG_ERROR("no packages found for library \"" + full_library_name + "\"!"); static const std::set<std::string> BASE_PACKAGES{ "libc6", "libc6-i386", "lib32stdc++6", "libstdc++6", "lib32gcc1", "libgcc1" }; packages = FilterPackages(packages, BASE_PACKAGES); if (packages.size() > 1) { packages = FilterPackages(packages, blacklist); if (packages.size() > 1) LOG_ERROR("multiple packages for \"" + full_library_name + "\": " + StringUtil::Join(packages, ", ")); } if (packages.empty()) return ""; std::string version = GetVersionHelper(*(packages.cbegin())); if (version.empty()) LOG_ERROR("library \"" + full_library_name + "\" not found!"); return version; } void GetLibraries(const std::string &binary_path, const std::set<std::string> &blacklist, std::vector<Library> * const libraries) { std::string ldd_output; if (not ExecUtil::ExecSubcommandAndCaptureStdout("ldd " + binary_path, &ldd_output)) LOG_ERROR("failed to execute ldd!"); std::vector<std::string> lines; StringUtil::SplitThenTrimWhite(ldd_output, '\n', &lines); for (auto line(lines.cbegin() + 1); line != lines.cend(); ++line) { std::string full_name, simplified_name; ExtractLibrary(*line, &full_name, &simplified_name); const auto version(GetVersion(full_name, blacklist)); if (not version.empty()) libraries->emplace_back(full_name, simplified_name, version); } } void GenerateControl(File * const output, const std::string &package, const std::string &version, const std::string &description, const std::vector<Library> &libraries) { (*output) << "Package: " << StringUtil::Map(package, '_', '-') << '\n'; (*output) << "Version: " << version << '\n'; (*output) << "Section: ub_tools\n"; (*output) << "Priority: optional\n"; (*output) << "Architecture: amd64\n"; (*output) << "Depends: "; bool first(true); for (const auto library : libraries) { if (first) first = false; else (*output) << ", "; (*output) << library.toString(); } (*output) << '\n'; (*output) << "Maintainer: johannes.ruscheinski@uni-tuebingen.de\n"; (*output) << "Description:"; std::vector<std::string> description_lines; StringUtil::SplitThenTrimWhite(description, "\\n", &description_lines); for (const auto &line : description_lines) (*output) << ' ' << line << '\n'; } void BuildPackage(const std::string &binary_path, const std::string &package_version, const std::string &description, const std::vector<Library> &libraries) { const std::string package_name(FileUtil::GetBasename(binary_path)); const std::string target_directory(package_name + "_" + package_version + "/usr/local/bin"); FileUtil::MakeDirectoryOrDie(target_directory, /* recursive = */true); const std::string target_binary(target_directory + "/" + package_name); FileUtil::CopyOrDie(binary_path, target_binary); ExecUtil::ExecOrDie(ExecUtil::Which("strip"), { target_binary }); FileUtil::MakeDirectoryOrDie(package_name + "_" + package_version + "/DEBIAN"); const auto control(FileUtil::OpenOutputFileOrDie(package_name + "_" + package_version + "/DEBIAN/control")); GenerateControl(control.get(), FileUtil::GetBasename(binary_path), package_version, description, libraries); control->close(); ExecUtil::ExecOrDie(ExecUtil::Which("dpkg-deb"), { "--build", package_name + "_" + package_version }); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 3) ::Usage("path_to_binary description deb_output blacklist"); const std::string binary_path(argv[1]); if (not FileUtil::Exists(binary_path)) LOG_ERROR("file not found: " + binary_path); const std::string description(argv[2]); std::set<std::string> blacklist; for (int arg_no(3); arg_no < argc; ++arg_no) blacklist.emplace(argv[arg_no]); std::vector<Library> libraries; GetLibraries(binary_path, blacklist, &libraries); const auto package_version(TimeUtil::GetCurrentDateAndTime("%Y.%m.%d")); BuildPackage(binary_path, package_version, description, libraries); return EXIT_SUCCESS; } <commit_msg>Added cleanup of working directory.<commit_after>/** \brief Utility for creating Debian/Ubunto AMD64 packages. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * \documentation See https://ubuntuforums.org/showthread.php?t=910717 * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <vector> #include "ExecUtil.h" #include "FileUtil.h" #include "StringUtil.h" #include "util.h" namespace { struct Library { std::string full_name_; std::string name_; std::string version_; public: Library() = default; Library(const Library &other) = default; Library(const std::string &full_name, const std::string &name, const std::string &version) : full_name_(full_name), name_(name), version_(version) { } inline std::string toString() const { return name_ + " (>= " + version_ + ")"; } }; void ExtractLibrary(const std::string &line, std::string * const full_name, std::string * const simplified_name) { const auto first_space_pos(line.find(' ')); if (first_space_pos == std::string::npos) LOG_ERROR("no space found in \"" + line + "\"!"); *full_name = line.substr(0, first_space_pos); const auto first_dot_pos(full_name->find('.')); *simplified_name = (first_dot_pos == std::string::npos) ? *full_name : full_name->substr(0, first_dot_pos); } std::string GetVersionHelper(const std::string &library_name) { std::string dpkg_output; if (not ExecUtil::ExecSubcommandAndCaptureStdout("dpkg -s " + library_name, &dpkg_output)) LOG_ERROR("failed to execute dpkg!"); std::vector<std::string> lines; StringUtil::SplitThenTrimWhite(dpkg_output, '\n', &lines); for (const auto &line : lines) { if (StringUtil::StartsWith(line, "Version: ")) { const auto version(line.substr(__builtin_strlen("Version: "))); const auto first_plus_pos(version.find('+')); return (first_plus_pos == std::string::npos) ? version : version.substr(0, first_plus_pos); } } return ""; } inline std::set<std::string> FilterPackages(const std::set<std::string> &unfiltered_set, const std::set<std::string> &filter) { std::set<std::string> filtered_set; for (const auto &element : unfiltered_set) { if (filter.find(element) == filter.cend()) filtered_set.emplace(element); } return filtered_set; } std::string GetVersion(const std::string &full_library_name, const std::set<std::string> &blacklist) { std::string dpkg_output; if (not ExecUtil::ExecSubcommandAndCaptureStdout("dpkg -S " + full_library_name, &dpkg_output)) LOG_ERROR("failed to execute dpkg!"); std::vector<std::string> lines; StringUtil::SplitThenTrimWhite(dpkg_output, '\n', &lines); std::set<std::string> packages; for (const auto &line : lines) { const auto first_colon_pos(line.find(':')); if (first_colon_pos == std::string::npos or first_colon_pos == 0) LOG_ERROR("weird output line of \"dpkg -S\": \"" + line + "\"!"); const auto package(line.substr(0, first_colon_pos)); if (not StringUtil::EndsWith(package, "-dev")) packages.emplace(package); } if (packages.empty()) LOG_ERROR("no packages found for library \"" + full_library_name + "\"!"); static const std::set<std::string> BASE_PACKAGES{ "libc6", "libc6-i386", "lib32stdc++6", "libstdc++6", "lib32gcc1", "libgcc1" }; packages = FilterPackages(packages, BASE_PACKAGES); if (packages.size() > 1) { packages = FilterPackages(packages, blacklist); if (packages.size() > 1) LOG_ERROR("multiple packages for \"" + full_library_name + "\": " + StringUtil::Join(packages, ", ")); } if (packages.empty()) return ""; std::string version = GetVersionHelper(*(packages.cbegin())); if (version.empty()) LOG_ERROR("library \"" + full_library_name + "\" not found!"); return version; } void GetLibraries(const std::string &binary_path, const std::set<std::string> &blacklist, std::vector<Library> * const libraries) { std::string ldd_output; if (not ExecUtil::ExecSubcommandAndCaptureStdout("ldd " + binary_path, &ldd_output)) LOG_ERROR("failed to execute ldd!"); std::vector<std::string> lines; StringUtil::SplitThenTrimWhite(ldd_output, '\n', &lines); for (auto line(lines.cbegin() + 1); line != lines.cend(); ++line) { std::string full_name, simplified_name; ExtractLibrary(*line, &full_name, &simplified_name); const auto version(GetVersion(full_name, blacklist)); if (not version.empty()) libraries->emplace_back(full_name, simplified_name, version); } } void GenerateControl(File * const output, const std::string &package, const std::string &version, const std::string &description, const std::vector<Library> &libraries) { (*output) << "Package: " << StringUtil::Map(package, '_', '-') << '\n'; (*output) << "Version: " << version << '\n'; (*output) << "Section: ub_tools\n"; (*output) << "Priority: optional\n"; (*output) << "Architecture: amd64\n"; (*output) << "Depends: "; bool first(true); for (const auto library : libraries) { if (first) first = false; else (*output) << ", "; (*output) << library.toString(); } (*output) << '\n'; (*output) << "Maintainer: johannes.ruscheinski@uni-tuebingen.de\n"; (*output) << "Description:"; std::vector<std::string> description_lines; StringUtil::SplitThenTrimWhite(description, "\\n", &description_lines); for (const auto &line : description_lines) (*output) << ' ' << line << '\n'; } void BuildPackage(const std::string &binary_path, const std::string &package_version, const std::string &description, const std::vector<Library> &libraries) { const std::string PACKAGE_NAME(FileUtil::GetBasename(binary_path)); const std::string WORKING_DIR(PACKAGE_NAME + "_" + package_version); const std::string TARGET_DIRECTORY(WORKING_DIR + "/usr/local/bin"); FileUtil::MakeDirectoryOrDie(TARGET_DIRECTORY, /* recursive = */true); const std::string target_binary(TARGET_DIRECTORY + "/" + PACKAGE_NAME); FileUtil::CopyOrDie(binary_path, target_binary); ExecUtil::ExecOrDie(ExecUtil::Which("strip"), { target_binary }); FileUtil::MakeDirectoryOrDie(WORKING_DIR + "/DEBIAN"); const auto control(FileUtil::OpenOutputFileOrDie(WORKING_DIR + "/DEBIAN/control")); GenerateControl(control.get(), FileUtil::GetBasename(binary_path), package_version, description, libraries); control->close(); ExecUtil::ExecOrDie(ExecUtil::Which("dpkg-deb"), { "--build", PACKAGE_NAME + "_" + package_version }); if (not FileUtil::RemoveDirectory(WORKING_DIR)) LOG_ERROR("failed to recursively delete \"" + WORKING_DIR + "\"!"); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 3) ::Usage("path_to_binary description deb_output blacklist"); const std::string binary_path(argv[1]); if (not FileUtil::Exists(binary_path)) LOG_ERROR("file not found: " + binary_path); const std::string description(argv[2]); std::set<std::string> blacklist; for (int arg_no(3); arg_no < argc; ++arg_no) blacklist.emplace(argv[arg_no]); std::vector<Library> libraries; GetLibraries(binary_path, blacklist, &libraries); const auto package_version(TimeUtil::GetCurrentDateAndTime("%Y.%m.%d")); BuildPackage(binary_path, package_version, description, libraries); return EXIT_SUCCESS; } <|endoftext|>
<commit_before> #include "btree/modify_oper.hpp" #include "utils.hpp" #include <boost/shared_ptr.hpp> #include "buffer_cache/buf_lock.hpp" #include "buffer_cache/co_functions.hpp" #include "btree/internal_node.hpp" #include "btree/leaf_node.hpp" #include "btree/operations.hpp" #include "btree/slice.hpp" // TODO: consider B#/B* trees to improve space efficiency // TODO: perhaps allow memory reclamation due to oversplitting? We can // be smart and only use a limited amount of ram for incomplete nodes // (doing this efficiently very tricky for high insert // workloads). Also, if the serializer is log-structured, we can write // only a small part of each node. // TODO: change rwi_write to rwi_intent followed by rwi_upgrade where // relevant. void insert_root(block_id_t root_id, buf_lock_t& sb_buf) { rassert(sb_buf.is_acquired()); // TODO: WTF is up with this const cast? This makes NO SENSE. gtfo. sb_buf->set_data(const_cast<block_id_t *>(&reinterpret_cast<const btree_superblock_t *>(sb_buf->get_data_read())->root_block), &root_id, sizeof(root_id)); sb_buf.release(); } // Split the node if necessary. If the node is a leaf_node, provide the new // value that will be inserted; if it's an internal node, provide NULL (we // split internal nodes proactively). void check_and_handle_split(value_sizer_t *sizer, transaction_t *txn, buf_lock_t& buf, buf_lock_t& last_buf, buf_lock_t& sb_buf, const btree_key_t *key, value_type_t *new_value, block_size_t block_size) { txn->assert_thread(); const node_t *node = reinterpret_cast<const node_t *>(buf->get_data_read()); // If the node isn't full, we don't need to split, so we're done. if (node::is_leaf(node)) { // This should only be called when update_needed. rassert(new_value); if (!leaf::is_full(sizer, reinterpret_cast<const leaf_node_t *>(node), key, new_value)) { return; } } else { rassert(!new_value); if (!internal_node::is_full(reinterpret_cast<const internal_node_t *>(node))) { return; } } // Allocate a new node to split into, and some temporary memory to keep // track of the median key in the split; then actually split. buf_lock_t rbuf; rbuf.allocate(txn); btree_key_buffer_t median_buffer; btree_key_t *median = median_buffer.key(); node::split(block_size, *buf.buf(), *rbuf.buf(), median); // Insert the key that sets the two nodes apart into the parent. if (!last_buf.is_acquired()) { // We're splitting what was previously the root, so create a new root to use as the parent. last_buf.allocate(txn); internal_node::init(block_size, *last_buf.buf()); insert_root(last_buf->get_block_id(), sb_buf); } bool success __attribute__((unused)) = internal_node::insert(block_size, *last_buf.buf(), median, buf->get_block_id(), rbuf->get_block_id()); rassert(success, "could not insert internal btree node"); // We've split the node; now figure out where the key goes and release the other buf (since we're done with it). if (0 >= sized_strcmp(key->contents, key->size, median->contents, median->size)) { // The key goes in the old buf (the left one). // Do nothing. } else { // The key goes in the new buf (the right one). buf.swap(rbuf); } } // Merge or level the node if necessary. void check_and_handle_underfull(transaction_t *txn, buf_lock_t& buf, buf_lock_t& last_buf, buf_lock_t& sb_buf, const btree_key_t *key, block_size_t block_size) { const node_t *node = reinterpret_cast<const node_t *>(buf->get_data_read()); if (last_buf.is_acquired() && node::is_underfull(block_size, node)) { // The root node is never underfull. const internal_node_t *parent_node = reinterpret_cast<const internal_node_t *>(last_buf->get_data_read()); // Acquire a sibling to merge or level with. block_id_t sib_node_id; int nodecmp_node_with_sib = internal_node::sibling(parent_node, key, &sib_node_id); // Now decide whether to merge or level. buf_lock_t sib_buf(txn, sib_node_id, rwi_write); const node_t *sib_node = reinterpret_cast<const node_t *>(sib_buf->get_data_read()); #ifndef NDEBUG node::validate(block_size, sib_node); #endif if (node::is_mergable(block_size, node, sib_node, parent_node)) { // Merge. // This is the key that we remove. btree_key_buffer_t key_to_remove_buffer; btree_key_t *key_to_remove = key_to_remove_buffer.key(); if (nodecmp_node_with_sib < 0) { // Nodes must be passed to merge in ascending order. node::merge(block_size, node, *sib_buf.buf(), key_to_remove, parent_node); buf->mark_deleted(); buf.swap(sib_buf); } else { node::merge(block_size, sib_node, *buf.buf(), key_to_remove, parent_node); sib_buf->mark_deleted(); } sib_buf.release(); if (!internal_node::is_singleton(parent_node)) { internal_node::remove(block_size, *last_buf.buf(), key_to_remove); } else { // The parent has only 1 key after the merge (which means that // it's the root and our node is its only child). Insert our // node as the new root. last_buf->mark_deleted(); insert_root(buf->get_block_id(), sb_buf); } } else { // Level btree_key_buffer_t key_to_replace_buffer, replacement_key_buffer; btree_key_t *key_to_replace = key_to_replace_buffer.key(); btree_key_t *replacement_key = replacement_key_buffer.key(); bool leveled = node::level(block_size, *buf.buf(), *sib_buf.buf(), key_to_replace, replacement_key, parent_node); if (leveled) { internal_node::update_key(*last_buf.buf(), key_to_replace, replacement_key); } } } } // Get a root block given a superblock, or make a new root if there isn't one. void get_root(value_sizer_t *sizer, transaction_t *txn, buf_lock_t& sb_buf, buf_lock_t *buf_out, repli_timestamp timestamp) { rassert(!buf_out->is_acquired()); block_id_t node_id = reinterpret_cast<const btree_superblock_t*>(sb_buf->get_data_read())->root_block; if (node_id != NULL_BLOCK_ID) { buf_lock_t tmp(txn, node_id, rwi_write); buf_out->swap(tmp); } else { buf_out->allocate(txn); leaf::init(sizer, *buf_out->buf(), timestamp); insert_root(buf_out->buf()->get_block_id(), sb_buf); } } // Runs a btree_modify_oper_t. void run_btree_modify_oper(value_sizer_t *sizer, btree_modify_oper_t *oper, btree_slice_t *slice, const store_key_t &store_key, castime_t castime, order_token_t token) { btree_key_buffer_t kbuffer(store_key); btree_key_t *key = kbuffer.key(); block_size_t block_size = slice->cache()->get_block_size(); { slice->assert_thread(); slice->pre_begin_transaction_sink_.check_out(token); order_token_t begin_transaction_token = slice->pre_begin_transaction_write_mode_source_.check_in(token.tag() + "+begin_transaction_token"); transaction_t txn(slice->cache(), rwi_write, oper->compute_expected_change_count(block_size), castime.timestamp); txn.set_token(slice->post_begin_transaction_checkpoint_.check_through(begin_transaction_token)); buf_lock_t sb_buf(&txn, SUPERBLOCK_ID, rwi_write); // TODO: do_superblock_sidequest is blocking. It doesn't have // to be, but when you fix this, make sure the superblock // sidequest is done using the superblock before the // superblock gets released. oper->do_superblock_sidequest(&txn, sb_buf, castime.timestamp, &store_key); keyvalue_location_t kv_location; find_keyvalue_location_for_write(sizer, &txn, sb_buf, key, castime.timestamp, &kv_location); bool key_found = kv_location.value; scoped_malloc<value_type_t> the_value; the_value.swap(kv_location.value); bool expired = key_found && the_value.as<btree_value_t>()->expired(); // If the value's expired, delete it. if (expired) { blob_t b(the_value.as<btree_value_t>()->value_ref(), blob::btree_maxreflen); b.unappend_region(&txn, b.valuesize()); the_value.reset(); } bool update_needed = oper->operate(&txn, the_value); update_needed = update_needed || expired; // Actually update the leaf, if needed. if (update_needed) { if (the_value) { // We have a value to insert. // Split the node if necessary, to make sure that we have room // for the value; This isn't necessary when we're deleting, // because the node isn't going to grow. check_and_handle_split(sizer, &txn, kv_location.buf, kv_location.last_buf, sb_buf, key, the_value.get(), block_size); // Add a CAS to the value if necessary (this won't change its size). if (the_value.as<btree_value_t>()->has_cas()) { rassert(castime.proposed_cas != BTREE_MODIFY_OPER_DUMMY_PROPOSED_CAS); the_value.as<btree_value_t>()->set_cas(block_size, castime.proposed_cas); } repli_timestamp new_value_timestamp = castime.timestamp; bool success = leaf::insert(sizer, *kv_location.buf.buf(), key, the_value.get(), new_value_timestamp); guarantee(success, "could not insert leaf btree node"); } else { // Delete the value if it's there. if (key_found) { leaf::remove(sizer, *kv_location.buf.buf(), key); } } // TODO: Previously this was checked whether or not update_needed, // but I'm pretty sure a leaf node can only be underfull // immediately following a split or an update. Double check this. // Check to see if the leaf is underfull (following a change in // size or a deletion), and merge/level if it is. check_and_handle_underfull(&txn, kv_location.buf, kv_location.last_buf, sb_buf, key, block_size); } // Release bufs as necessary. sb_buf.release_if_acquired(); rassert(kv_location.buf.is_acquired()); kv_location.buf.release(); kv_location.last_buf.release_if_acquired(); // Committing the transaction and moving back to the home thread are // handled automatically with RAII. } } <commit_msg>Replaced the_value with kv_location.value.<commit_after> #include "btree/modify_oper.hpp" #include "utils.hpp" #include <boost/shared_ptr.hpp> #include "buffer_cache/buf_lock.hpp" #include "buffer_cache/co_functions.hpp" #include "btree/internal_node.hpp" #include "btree/leaf_node.hpp" #include "btree/operations.hpp" #include "btree/slice.hpp" // TODO: consider B#/B* trees to improve space efficiency // TODO: perhaps allow memory reclamation due to oversplitting? We can // be smart and only use a limited amount of ram for incomplete nodes // (doing this efficiently very tricky for high insert // workloads). Also, if the serializer is log-structured, we can write // only a small part of each node. // TODO: change rwi_write to rwi_intent followed by rwi_upgrade where // relevant. void insert_root(block_id_t root_id, buf_lock_t& sb_buf) { rassert(sb_buf.is_acquired()); // TODO: WTF is up with this const cast? This makes NO SENSE. gtfo. sb_buf->set_data(const_cast<block_id_t *>(&reinterpret_cast<const btree_superblock_t *>(sb_buf->get_data_read())->root_block), &root_id, sizeof(root_id)); sb_buf.release(); } // Split the node if necessary. If the node is a leaf_node, provide the new // value that will be inserted; if it's an internal node, provide NULL (we // split internal nodes proactively). void check_and_handle_split(value_sizer_t *sizer, transaction_t *txn, buf_lock_t& buf, buf_lock_t& last_buf, buf_lock_t& sb_buf, const btree_key_t *key, value_type_t *new_value, block_size_t block_size) { txn->assert_thread(); const node_t *node = reinterpret_cast<const node_t *>(buf->get_data_read()); // If the node isn't full, we don't need to split, so we're done. if (node::is_leaf(node)) { // This should only be called when update_needed. rassert(new_value); if (!leaf::is_full(sizer, reinterpret_cast<const leaf_node_t *>(node), key, new_value)) { return; } } else { rassert(!new_value); if (!internal_node::is_full(reinterpret_cast<const internal_node_t *>(node))) { return; } } // Allocate a new node to split into, and some temporary memory to keep // track of the median key in the split; then actually split. buf_lock_t rbuf; rbuf.allocate(txn); btree_key_buffer_t median_buffer; btree_key_t *median = median_buffer.key(); node::split(block_size, *buf.buf(), *rbuf.buf(), median); // Insert the key that sets the two nodes apart into the parent. if (!last_buf.is_acquired()) { // We're splitting what was previously the root, so create a new root to use as the parent. last_buf.allocate(txn); internal_node::init(block_size, *last_buf.buf()); insert_root(last_buf->get_block_id(), sb_buf); } bool success __attribute__((unused)) = internal_node::insert(block_size, *last_buf.buf(), median, buf->get_block_id(), rbuf->get_block_id()); rassert(success, "could not insert internal btree node"); // We've split the node; now figure out where the key goes and release the other buf (since we're done with it). if (0 >= sized_strcmp(key->contents, key->size, median->contents, median->size)) { // The key goes in the old buf (the left one). // Do nothing. } else { // The key goes in the new buf (the right one). buf.swap(rbuf); } } // Merge or level the node if necessary. void check_and_handle_underfull(transaction_t *txn, buf_lock_t& buf, buf_lock_t& last_buf, buf_lock_t& sb_buf, const btree_key_t *key, block_size_t block_size) { const node_t *node = reinterpret_cast<const node_t *>(buf->get_data_read()); if (last_buf.is_acquired() && node::is_underfull(block_size, node)) { // The root node is never underfull. const internal_node_t *parent_node = reinterpret_cast<const internal_node_t *>(last_buf->get_data_read()); // Acquire a sibling to merge or level with. block_id_t sib_node_id; int nodecmp_node_with_sib = internal_node::sibling(parent_node, key, &sib_node_id); // Now decide whether to merge or level. buf_lock_t sib_buf(txn, sib_node_id, rwi_write); const node_t *sib_node = reinterpret_cast<const node_t *>(sib_buf->get_data_read()); #ifndef NDEBUG node::validate(block_size, sib_node); #endif if (node::is_mergable(block_size, node, sib_node, parent_node)) { // Merge. // This is the key that we remove. btree_key_buffer_t key_to_remove_buffer; btree_key_t *key_to_remove = key_to_remove_buffer.key(); if (nodecmp_node_with_sib < 0) { // Nodes must be passed to merge in ascending order. node::merge(block_size, node, *sib_buf.buf(), key_to_remove, parent_node); buf->mark_deleted(); buf.swap(sib_buf); } else { node::merge(block_size, sib_node, *buf.buf(), key_to_remove, parent_node); sib_buf->mark_deleted(); } sib_buf.release(); if (!internal_node::is_singleton(parent_node)) { internal_node::remove(block_size, *last_buf.buf(), key_to_remove); } else { // The parent has only 1 key after the merge (which means that // it's the root and our node is its only child). Insert our // node as the new root. last_buf->mark_deleted(); insert_root(buf->get_block_id(), sb_buf); } } else { // Level btree_key_buffer_t key_to_replace_buffer, replacement_key_buffer; btree_key_t *key_to_replace = key_to_replace_buffer.key(); btree_key_t *replacement_key = replacement_key_buffer.key(); bool leveled = node::level(block_size, *buf.buf(), *sib_buf.buf(), key_to_replace, replacement_key, parent_node); if (leveled) { internal_node::update_key(*last_buf.buf(), key_to_replace, replacement_key); } } } } // Get a root block given a superblock, or make a new root if there isn't one. void get_root(value_sizer_t *sizer, transaction_t *txn, buf_lock_t& sb_buf, buf_lock_t *buf_out, repli_timestamp timestamp) { rassert(!buf_out->is_acquired()); block_id_t node_id = reinterpret_cast<const btree_superblock_t*>(sb_buf->get_data_read())->root_block; if (node_id != NULL_BLOCK_ID) { buf_lock_t tmp(txn, node_id, rwi_write); buf_out->swap(tmp); } else { buf_out->allocate(txn); leaf::init(sizer, *buf_out->buf(), timestamp); insert_root(buf_out->buf()->get_block_id(), sb_buf); } } // Runs a btree_modify_oper_t. void run_btree_modify_oper(value_sizer_t *sizer, btree_modify_oper_t *oper, btree_slice_t *slice, const store_key_t &store_key, castime_t castime, order_token_t token) { btree_key_buffer_t kbuffer(store_key); btree_key_t *key = kbuffer.key(); block_size_t block_size = slice->cache()->get_block_size(); { slice->assert_thread(); slice->pre_begin_transaction_sink_.check_out(token); order_token_t begin_transaction_token = slice->pre_begin_transaction_write_mode_source_.check_in(token.tag() + "+begin_transaction_token"); transaction_t txn(slice->cache(), rwi_write, oper->compute_expected_change_count(block_size), castime.timestamp); txn.set_token(slice->post_begin_transaction_checkpoint_.check_through(begin_transaction_token)); buf_lock_t sb_buf(&txn, SUPERBLOCK_ID, rwi_write); // TODO: do_superblock_sidequest is blocking. It doesn't have // to be, but when you fix this, make sure the superblock // sidequest is done using the superblock before the // superblock gets released. oper->do_superblock_sidequest(&txn, sb_buf, castime.timestamp, &store_key); keyvalue_location_t kv_location; find_keyvalue_location_for_write(sizer, &txn, sb_buf, key, castime.timestamp, &kv_location); bool key_found = kv_location.value; bool expired = key_found && kv_location.value.as<btree_value_t>()->expired(); // If the value's expired, delete it. if (expired) { blob_t b(kv_location.value.as<btree_value_t>()->value_ref(), blob::btree_maxreflen); b.unappend_region(&txn, b.valuesize()); kv_location.value.reset(); } bool update_needed = oper->operate(&txn, kv_location.value); update_needed = update_needed || expired; // Add a CAS to the value if necessary if (kv_location.value) { if (kv_location.value.as<btree_value_t>()->has_cas()) { rassert(castime.proposed_cas != BTREE_MODIFY_OPER_DUMMY_PROPOSED_CAS); kv_location.value.as<btree_value_t>()->set_cas(block_size, castime.proposed_cas); } } // Actually update the leaf, if needed. if (update_needed) { if (kv_location.value) { // We have a value to insert. // Split the node if necessary, to make sure that we have room // for the value; This isn't necessary when we're deleting, // because the node isn't going to grow. check_and_handle_split(sizer, &txn, kv_location.buf, kv_location.last_buf, sb_buf, key, kv_location.value.get(), block_size); repli_timestamp new_value_timestamp = castime.timestamp; bool success = leaf::insert(sizer, *kv_location.buf.buf(), key, kv_location.value.get(), new_value_timestamp); guarantee(success, "could not insert leaf btree node"); } else { // Delete the value if it's there. if (key_found) { leaf::remove(sizer, *kv_location.buf.buf(), key); } } // TODO: Previously this was checked whether or not update_needed, // but I'm pretty sure a leaf node can only be underfull // immediately following a split or an update. Double check this. // Check to see if the leaf is underfull (following a change in // size or a deletion), and merge/level if it is. check_and_handle_underfull(&txn, kv_location.buf, kv_location.last_buf, sb_buf, key, block_size); } // Release bufs as necessary. sb_buf.release_if_acquired(); rassert(kv_location.buf.is_acquired()); kv_location.buf.release(); kv_location.last_buf.release_if_acquired(); // Committing the transaction and moving back to the home thread are // handled automatically with RAII. } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** If you have questions regarding the use of this file, please ** contact Nokia at http://www.qtsoftware.com/contact. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsysteminfo.h" #include "qsysteminfo_p.h" #include <qt_windows.h> #include <QStringList> #include <QSize> #include <QFile> #include <QTextStream> #include <QLocale> #include <QLibraryInfo> #include <QApplication> #include <QDesktopWidget> #include <QDebug> #include <QSettings> #include <QSysInfo> #include <locale.h> //#include <windows.h> #include <Wlanapi.h> #include <Ntddvdeo.h> #define _WCHAR_T_DEFINED #define _TIME64_T_DEFINED QSystemInfoPrivate::QSystemInfoPrivate(QObject *parent) { Q_UNUSED(parent); availableLanguages(); } // 2 letter ISO 639-1 QString QSystemInfoPrivate::currentLanguage() const { return QString(setlocale(LC_ALL,NULL)).left(2); } QStringList QSystemInfoPrivate::availableLanguages() const { QStringList lgList; QString rSubKey = "SOFTWARE\\Classes\\MIME\\Database\\Rfc1766"; QSettings languageSetting("HKEY_LOCAL_MACHINE\\" + rSubKey, QSettings::NativeFormat); QStringList grp = languageSetting.childKeys(); for (int i = 0; i < grp.count(); i++) { QString lg = languageSetting.value(grp.at(i)).toString().left(2); if(!lgList.contains(lg)) { lgList << lg; qWarning() << lg; } } return lgList; } QString QSystemInfoPrivate::qtVersion() const { return qVersion(); } QString QSystemInfoPrivate::browserVersion() const { return QString(); } QString QSystemInfoPrivate::firmwareVersion() const { return QString(); } QString QSystemInfoPrivate::platformVersion() const { // QString wVer; DWORD qt_cever = 0; OSVERSIONINFOW osver; osver.dwOSVersionInfoSize = sizeof(osver); GetVersionEx(&osver); qt_cever = osver.dwMajorVersion * 100; qt_cever += osver.dwMinorVersion * 10; QString wVer = QString("%1.%2.%3") .arg(osver.dwMajorVersion) .arg(osver.dwMinorVersion) .arg(osver.dwBuildNumber); wVer += " " + QString::fromWCharArray(osver.szCSDVersion); return wVer; } //2 letter ISO 3166-1 QString QSystemInfoPrivate::countryCode() const { return QString(setlocale(LC_ALL,"")).mid(3,2); } qint32 QSystemInfoPrivate::networkSignalStrength() { return -1; } qint32 QSystemInfoPrivate::cellId() { return -1; } qint32 QSystemInfoPrivate::lac() { return -1; } // Mobile Country Code qint32 QSystemInfoPrivate::currentMCC() { return -1; } // Mobile Network Code qint32 QSystemInfoPrivate::currentMNC() { return -1; } qint32 QSystemInfoPrivate::homeMCC() { return -1; } qint32 QSystemInfoPrivate::homeMNC() { return -1; } bool QSystemInfoPrivate::isLocationEnabled() const { return false; } bool QSystemInfoPrivate::isWLANAccessible() const { HANDLE phClientHandle = NULL; DWORD result; DWORD pdwNegotiatedVersion = 0; PWLAN_INTERFACE_INFO_LIST pIntfList = NULL; result = WlanOpenHandle(WLAN_API_VERSION, NULL, &pdwNegotiatedVersion, &phClientHandle); if( result != ERROR_SUCCESS ) { qWarning() << "Error opening Wlanapi" << result ; return false; } result = WlanEnumInterfaces(phClientHandle, NULL, &pIntfList); if( result != ERROR_SUCCESS ) { qWarning() << "Error in WlanEnumInterfaces" << result; return false; } return true; } //returns OR'd feature qint32 QSystemInfoPrivate::supportedFeatures() { return -1; } // display qint32 QSystemInfoPrivate::displayBrightness() { qint32 brightness; HANDLE display = CreateFile(L"\\\\.\\LCD", FILE_ANY_ACCESS, 0, NULL, OPEN_EXISTING, 0, NULL); if( display != INVALID_HANDLE_VALUE ) { DISPLAY_BRIGHTNESS bright; DWORD bytesReturned; if( DeviceIoControl(display, IOCTL_VIDEO_QUERY_DISPLAY_BRIGHTNESS, NULL, 0, &bright, sizeof(bright), &bytesReturned, NULL) ) { if( bytesReturned > 0 ) { brightness = bright.ucACBrightness; qWarning() << bright.ucACBrightness; } } CloseHandle(display); } return brightness; } qint32 QSystemInfoPrivate::screenSaverTimeout() { return -1; } qint32 QSystemInfoPrivate::screenBlankingTimeout() { return -1; } QSize QSystemInfoPrivate::screenSize() { QSize sz = QApplication::desktop()->availableGeometry().size(); if (sz.isValid()) return sz; else return QSize(); } qint32 QSystemInfoPrivate::colorDepth() { return QPixmap::defaultDepth(); } qint64 QSystemInfoPrivate::memory() const { return -1; } qint64 QSystemInfoPrivate::diskSpace(const QString &drive) { Q_UNUSED(drive); return -1; } QStringList QSystemInfoPrivate::listOfVolumes() { return QStringList(); } // device QString QSystemInfoPrivate::imei() const { return QString(); } QString QSystemInfoPrivate::imsi() const { return QString(); } QString QSystemInfoPrivate::manufacturer() const { return QString(); } QString QSystemInfoPrivate::model() const { return QString(); } // //qint32 QSystemInfoPrivate::batteryLevel() const //{ // return -1; //} bool QSystemInfoPrivate::isSimAvailable() { return false; } bool QSystemInfoPrivate::isDiskSpaceCritical(const QString &drive) { Q_UNUSED(drive); return false; } bool QSystemInfoPrivate::isBatteryCharging() { return false; } bool QSystemInfoPrivate::isCriticalMemory() const { return false; } <commit_msg>update<commit_after>/**************************************************************************** ** ** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** If you have questions regarding the use of this file, please ** contact Nokia at http://www.qtsoftware.com/contact. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsysteminfo.h" #include "qsysteminfo_p.h" #include <qt_windows.h> #include <QStringList> #include <QSize> #include <QFile> #include <QTextStream> #include <QLocale> #include <QLibraryInfo> #include <QApplication> #include <QDesktopWidget> #include <QDebug> #include <QSettings> #include <QSysInfo> #include <locale.h> //#include <windows.h> #include <Wlanapi.h> #include <Ntddvdeo.h> #define _WCHAR_T_DEFINED #define _TIME64_T_DEFINED QSystemInfoPrivate::QSystemInfoPrivate(QObject *parent) : QObject(parent) { } QSystemInfoPrivate::~QSystemInfoPrivate() { } // 2 letter ISO 639-1 QString QSystemInfoPrivate::currentLanguage() const { return QString(setlocale(LC_ALL,NULL)).left(2); } // 2 letter ISO 639-1 QStringList QSystemInfoPrivate::availableLanguages() const { QStringList lgList; QString rSubKey = "SOFTWARE\\Classes\\MIME\\Database\\Rfc1766"; QSettings languageSetting("HKEY_LOCAL_MACHINE\\" + rSubKey, QSettings::NativeFormat); QStringList grp = languageSetting.childKeys(); for (int i = 0; i < grp.count(); i++) { QString lg = languageSetting.value(grp.at(i)).toString().left(2); if(!lgList.contains(lg)) { lgList << lg; qWarning() << lg; } } return lgList; return QStringList() << currentLanguage(); } // "major.minor.build" format. /*QPair< int, double >*/ QString QSystemInfoPrivate::getVersion(QSystemInfo::Version type, const QString &parameter) { Q_UNUSED(parameter); QString errorStr = "Not Available"; bool useDate = false; if(parameter == "versionDate") { useDate = true; } switch(type) { case QSystemInfo::Os : { } break; case QSystemInfo::QtCore : return qVersion(); break; case QSystemInfo::WrtCore : { } break; case QSystemInfo::Webkit : { } break; case QSystemInfo::ServiceFramework : { } break; case QSystemInfo::WrtExtensions : { } break; case QSystemInfo::ServiceProvider : { } break; case QSystemInfo::NetscapePlugin : { } break; case QSystemInfo::WebApp : { } break; case QSystemInfo::Firmware : { } break; }; return errorStr; } //2 letter ISO 3166-1 QString QSystemInfoPrivate::currentCountryCode() const { return QString(setlocale(LC_ALL,"")).mid(3,2); } bool QSystemInfoPrivate::hasFeatureSupported(QSystemInfo::Feature feature) { bool featureSupported = false; switch (feature) { case QSystemInfo::BluetoothFeature : { } break; case QSystemInfo::CameraFeature : { } break; case QSystemInfo::FmradioFeature : { } break; case QSystemInfo::IrFeature : { } break; case QSystemInfo::LedFeature : { } break; case QSystemInfo::MemcardFeature : { } break; case QSystemInfo::UsbFeature : { } break; case QSystemInfo::VibFeature : break; case QSystemInfo::WlanFeature : { } break; case QSystemInfo::SimFeature : break; case QSystemInfo::LocationFeature : break; case QSystemInfo::VideoOutFeature : { } break; case QSystemInfo::HapticsFeature: break; case QSystemInfo::UnknownFeature : default: featureSupported = true; break; }; return featureSupported; } QString QSystemInfoPrivate::getDetailOfFeature(QSystemInfo::Feature feature) { Q_UNUSED(feature); return "No other features"; } //////// QSystemNetworkInfo QSystemNetworkInfoPrivate::QSystemNetworkInfoPrivate(QObject *parent) : QObject(parent) { } QSystemNetworkInfoPrivate::~QSystemNetworkInfoPrivate() { } QSystemNetworkInfo::CellNetworkStatus QSystemNetworkInfoPrivate::getCellNetworkStatus() { return QSystemNetworkInfo::NoNetworkAvailable; } int QSystemNetworkInfoPrivate::networkSignalStrength(QSystemNetworkInfo::NetworkMode mode) { return -1; } int QSystemNetworkInfoPrivate::cellId() { return -1; } int QSystemNetworkInfoPrivate::locationAreaCode() { return -1; } // Mobile Country Code QString QSystemNetworkInfoPrivate::currentMobileCountryCode() { return "No Network"; } // Mobile Network Code QString QSystemNetworkInfoPrivate::currentMobileNetworkCode() { return "No Network"; } QString QSystemNetworkInfoPrivate::homeMobileCountryCode() { return "No Network"; } QString QSystemNetworkInfoPrivate::homeMobileNetworkCode() { return "No Network"; } bool QSystemNetworkInfoPrivate::isLocationEnabled() const { return false; } bool QSystemNetworkInfoPrivate::isWLANAccessible() const { HANDLE phClientHandle = NULL; DWORD result; DWORD pdwNegotiatedVersion = 0; PWLAN_INTERFACE_INFO_LIST pIntfList = NULL; result = WlanOpenHandle(WLAN_API_VERSION, NULL, &pdwNegotiatedVersion, &phClientHandle); if( result != ERROR_SUCCESS ) { qWarning() << "Error opening Wlanapi" << result ; return false; } result = WlanEnumInterfaces(phClientHandle, NULL, &pIntfList); if( result != ERROR_SUCCESS ) { qWarning() << "Error in WlanEnumInterfaces" << result; return false; } return false; } QString QSystemNetworkInfoPrivate::operatorName() { return "No Operator"; } //////// QSystemDisplayInfo QSystemDisplayInfoPrivate::QSystemDisplayInfoPrivate(QObject *parent) : QObject(parent) { } QSystemDisplayInfoPrivate::~QSystemDisplayInfoPrivate() { } int QSystemDisplayInfoPrivate::displayBrightness(int screen) { qint32 brightness; HANDLE display = CreateFile(L"\\\\.\\LCD", FILE_ANY_ACCESS, 0, NULL, OPEN_EXISTING, 0, NULL); if( display != INVALID_HANDLE_VALUE ) { DISPLAY_BRIGHTNESS bright; DWORD bytesReturned; if( DeviceIoControl(display, IOCTL_VIDEO_QUERY_DISPLAY_BRIGHTNESS, NULL, 0, &bright, sizeof(bright), &bytesReturned, NULL) ) { if( bytesReturned > 0 ) { brightness = bright.ucACBrightness; qWarning() << bright.ucACBrightness; } } CloseHandle(display); } return brightness; } int QSystemDisplayInfoPrivate::colorDepth(int screen) { Q_UNUSED(screen); } bool QSystemDisplayInfoPrivate::isScreenLockOn() { return false; } //////// QSystemMemoryInfo QSystemMemoryInfoPrivate::QSystemMemoryInfoPrivate(QObject *parent) : QObject(parent) { } QSystemMemoryInfoPrivate::~QSystemMemoryInfoPrivate() { } bool QSystemMemoryInfoPrivate::hasRamMemoryLevel() { return true; } qint64 QSystemMemoryInfoPrivate::freeMemoryLevel() const { } qint64 QSystemMemoryInfoPrivate::availableDiskSpace(const QString &driveVolume) { } qint64 QSystemMemoryInfoPrivate::totalDiskSpace(const QString &driveVolume) { } QSystemMemoryInfo::VolumeType QSystemMemoryInfoPrivate::getVolumeType(const QString &driveVolume) { return QSystemMemoryInfo::Internal; } QStringList QSystemMemoryInfoPrivate::listOfVolumes() { } void QSystemMemoryInfoPrivate::getMountEntries() { } bool QSystemMemoryInfoPrivate::isCriticalMemory() const { return false; } //bool QSystemMemoryInfoPrivate::isDiskSpaceCritical(const QString &driveVolume) // { // Q_UNUSED(driveVolume); // return false; // } //////// QSystemDeviceInfo QSystemDeviceInfoPrivate::QSystemDeviceInfoPrivate(QObject *parent) : QObject(parent) { halIsAvailable = halAvailable(); } QSystemDeviceInfoPrivate::~QSystemDeviceInfoPrivate() { } QSystemDeviceInfo::Profile QSystemDeviceInfoPrivate::getCurrentProfile() { return QSystemDeviceInfo::UnknownProfile; } QSystemDeviceInfo::InputMethods QSystemDeviceInfoPrivate::getInputMethodType() { return methods; } QString QSystemDeviceInfoPrivate::imei() { // if(this->getSimStatus() == QSystemDeviceInfo::SimNotAvailable) return "Sim Not Available"; } QString QSystemDeviceInfoPrivate::imsi() { // if(getSimStatus() == QSystemDeviceInfo::SimNotAvailable) return "Sim Not Available"; } QString QSystemDeviceInfoPrivate::manufacturer() { return QString(); } QString QSystemDeviceInfoPrivate::model() { return QString(); } QString QSystemDeviceInfoPrivate::productName() { return QString(); } bool QSystemDeviceInfoPrivate::isBatteryCharging() { return isCharging; } QSystemDeviceInfo::BatteryLevel QSystemDeviceInfoPrivate::batteryLevel() const { return QSystemDeviceInfo::NoBatteryLevel; } QSystemDeviceInfo::SimStatus QSystemDeviceInfoPrivate::getSimStatus() { return QSystemDeviceInfo::SimNotAvailable; } bool QSystemDeviceInfoPrivate::isDeviceLocked() { return false; } ////////////// /////// QSystemScreenSaverPrivate::QSystemScreenSaverPrivate(QObject *parent) : QSystemScreenSaver(parent) { } bool QSystemScreenSaverPrivate::setScreenSaverEnabled(QSystemScreenSaver::ScreenSaverState state) { Q_UNUSED(state); return false; } bool QSystemScreenSaverPrivate::setScreenBlankingEnabled(QSystemScreenSaver::ScreenSaverState state) { Q_UNUSED(state); return false; } QSystemScreenSaver::ScreenSaverState QSystemScreenSaverPrivate::screenSaverEnabled() { return QSystemScreenSaver::UnknownScreenSaverState; } QSystemScreenSaver::ScreenSaverState QSystemScreenSaverPrivate::screenBlankingEnabled() { return QSystemScreenSaver::UnknownScreenSaverState; } QT_END_NAMESPACE <|endoftext|>
<commit_before>#include <boost/python.hpp> #include "ModelInterface.h" #include "pyToCppModelInterface.h" #include <boost/python/stl_iterator.hpp> #include <iostream> #include <stdexcept> //#include <boost/python.hpp> namespace threeML { template< typename T > inline std::vector< T > to_std_vector( const boost::python::object& iterable ) { return std::vector< T >( boost::python::stl_input_iterator< T >( iterable ), boost::python::stl_input_iterator< T >( ) ); } pyToCppModelInterface::pyToCppModelInterface(PyObject *pyModelUninterpreted) : m_nPtSources(0), m_nExtSources(0), n_calls(0) { try { boost::python::object o(boost::python::handle<>(boost::python::borrowed(pyModelUninterpreted))); m_pyModel = o; } catch (...) { throw std::runtime_error("ModelInterface: Could not interpret the LikelihoodModel class"); } //TODO: add a verification of the interface for the pyObject try { m_nPtSources = boost::python::extract<int>(m_pyModel.attr("getNumberOfPointSources")()); } catch (...) { throw std::runtime_error( "ModelInterface: Could not use getNumberOfPointSources from python Object"); } try { m_nExtSources = boost::python::extract<int>(m_pyModel.attr("getNumberOfExtendedSources")()); } catch (...) { throw std::runtime_error( "ModelInterface: Could not use getNumberOfExtendedSources from python Object"); } } bool pyToCppModelInterface::isInsideAnyExtendedSource(double j2000_ra, double j2000_dec) const { return true; } int pyToCppModelInterface::getNumberOfPointSources() const { return m_nPtSources; } void pyToCppModelInterface::getPointSourcePosition(int srcid, double *j2000_ra, double *j2000_dec) const { boost::python::object coords; try { coords = m_pyModel.attr("getPointSourcePosition")(srcid); } catch (...) { throw std::runtime_error( "ModelInterface: Could not call getPointSourcePosition on the python side"); } try { (*j2000_ra) = boost::python::extract<double>(coords[0]); (*j2000_dec) = boost::python::extract<double>(coords[1]); } catch (...) { throw std::runtime_error( "ModelInterface: Could not convert the coordinates I got from the python side"); } } void pyToCppModelInterface::update() { //std::cerr << "Emptying cache" << std::endl; //Empty the cache m_cache.clear(); } std::vector<double> pyToCppModelInterface::getPointSourceFluxes(int srcid, std::vector<double> energies) const { if ( m_cache.count( srcid )==1 ) { //std::cerr << "Cached" << std::endl; //Return cached version return m_cache[srcid]; } else { n_calls += 1; //std::cerr << "Filling cache for " << srcid << " (" << n_calls << ")" << std::endl; } //Construct a generic object (instead of for example a list) so that //the pyModel can return any iterable (list, numpy.array, etc) boost::python::object fluxes; //try { //Transform MeV to keV for(unsigned int i=0; i < energies.size(); ++i) { energies[i] = energies[i] * 1000.0; } //expects and returns MeV-related-units fluxes = m_pyModel.attr("getPointSourceFluxes")(srcid,energies); //} catch (...) { // throw std::runtime_error( // "ModelInterface: Could not get the fluxes from the python side"); //} std::vector<double> fluxes_v; try { fluxes_v = to_std_vector<double>(fluxes); //Transform in ph/cm2/s/MeV from ph/cm2/s/keV for(unsigned int i=0; i < fluxes_v.size(); ++i) { fluxes_v[i] = fluxes_v[i] * 1000.0; } } catch (...) { throw std::runtime_error( "ModelInterface: Could not convert the fluxes I got from the python side"); } //Cache result m_cache[srcid] = fluxes_v; return fluxes_v; } int pyToCppModelInterface::getNumberOfExtendedSources() const { return m_nExtSources; } std::vector<double> pyToCppModelInterface::getExtendedSourceFluxes(int srcid, double j2000_ra, double j2000_dec, std::vector<double> energies) const { /* if ( m_cache.count( srcid * 1000 )==1 ) { //std::cerr << "Cached" << std::endl; //Return cached version return m_cache[srcid * 1000]; } else { */ n_calls += 1; //std::cerr << "Filling cache for " << srcid << " (" << n_calls << ")" << std::endl; // } //Construct a generic object (instead of for example a list) so that //the pyModel can return any iterable (list, numpy.array, etc) boost::python::object fluxes; //try { //Transform MeV to keV for(unsigned int i=0; i < energies.size(); ++i) { energies[i] = energies[i] * 1000.0; } //expects and returns MeV-related-units fluxes = m_pyModel.attr("getExtendedSourceFluxes")(srcid, j2000_ra, j2000_dec, energies); //} catch (...) { // throw std::runtime_error( // "ModelInterface: Could not get the fluxes from the python side"); //} std::vector<double> fluxes_v; try { fluxes_v = to_std_vector<double>(fluxes); //Transform in ph/cm2/s/MeV from ph/cm2/s/keV for(unsigned int i=0; i < fluxes_v.size(); ++i) { fluxes_v[i] = fluxes_v[i] * 1000.0; } } catch (...) { throw std::runtime_error( "ModelInterface: Could not convert the fluxes I got from the python side"); } //Cache result // m_cache[srcid * 1000] = fluxes_v; return fluxes_v; } std::string pyToCppModelInterface::getPointSourceName(int srcid) const { std::string name; try { name = boost::python::extract<std::string>( m_pyModel.attr("getPointSourceName")(srcid) ); } catch (...) { throw std::runtime_error( "ModelInterface: Could not get the point source name from the python side"); } return name; } std::string pyToCppModelInterface::getExtendedSourceName(int srcid) const { std::string name; try { name = boost::python::extract<std::string>( m_pyModel.attr("getExtendedSourceName")(srcid) ); } catch (...) { throw std::runtime_error( "ModelInterface: Could not get the extended source name from the python side"); } return name; } void pyToCppModelInterface::getExtendedSourceBoundaries(int srcid, double *j2000_ra_min, double *j2000_ra_max, double *j2000_dec_min, double *j2000_dec_max) const { boost::python::object boundaries; boundaries = m_pyModel.attr("getExtendedSourceBoundaries")( srcid ); std::vector<double> boundaries_v = to_std_vector<double>(boundaries); *j2000_ra_min = boundaries_v[0]; *j2000_ra_max = boundaries_v[1]; *j2000_dec_min = boundaries_v[2]; *j2000_dec_max = boundaries_v[3]; } } using namespace threeML; using namespace boost::python; //This is needed to wrap the interface (i.e., all methods are virtual) //contained in ModelInterface.h struct ModelInterfaceWrap : ModelInterface, wrapper<ModelInterface> { int getNumberOfPointSources() const { return this->get_override("getNumberOfPointSources")(); } void getPointSourcePosition(int srcid, double *j2000_ra, double *j2000_dec) const { this->get_override("getPointSourcePosition")(); } std::vector<double> getPointSourceFluxes(int srcid, std::vector<double> energies) const { return this->get_override("getPointSourceFluxes")(); } std::string getPointSourceName(int srcid) const { return this->get_override("getPointSourceName")(); } int getNumberOfExtendedSources() const { return this->get_override("getNumberOfExtendedSources")(); } std::vector<double> getExtendedSourceFluxes(int srcid, double j2000_ra, double j2000_dec, std::vector<double> energies) const { return this->get_override("getExtendedSourceFluxes")(); } std::string getExtendedSourceName(int srcid) const { return this->get_override("getExtendedSourceName")(); } bool isInsideAnyExtendedSource(double j2000_ra, double j2000_dec) const { return this->get_override("isInsideAnyExtendedSource")(); } void getExtendedSourceBoundaries(int srcid, double *j2000_ra_min, double *j2000_ra_max, double *j2000_dec_min, double *j2000_dec_max) const { this->get_override("getExtendedSourceBoundaries")(); } }; template<class T> struct VecToList { static PyObject* convert(const std::vector<T>& vec) { boost::python::list* l = new boost::python::list(); for(size_t i = 0; i < vec.size(); i++) (*l).append(vec[i]); return l->ptr(); } }; BOOST_PYTHON_MODULE(pyModelInterface) { //hello to_python_converter<std::vector<double,std::allocator<double> >, VecToList<double> >(); class_<ModelInterfaceWrap, boost::noncopyable>("ModelInterface") .def("getNumberOfPointSources", pure_virtual(&ModelInterface::getNumberOfPointSources)) .def("getPointSourcePosition", pure_virtual(&ModelInterface::getPointSourcePosition)) .def("getPointSourceFluxes", pure_virtual(&ModelInterface::getPointSourceFluxes)) .def("getPointSourceName", pure_virtual(&ModelInterface::getPointSourceName)) .def("getNumberOfExtendedSources", pure_virtual(&ModelInterface::getNumberOfExtendedSources)) .def("getExtendedSourceFluxes", pure_virtual(&ModelInterface::getExtendedSourceFluxes)) .def("getExtendedSourceName", pure_virtual(&ModelInterface::getExtendedSourceName)) .def("isInsideAnyExtendedSource", pure_virtual(&ModelInterface::isInsideAnyExtendedSource)) .def("getExtendedSourceBoundaries", pure_virtual(&ModelInterface::getExtendedSourceBoundaries)) ; class_<pyToCppModelInterface, bases<ModelInterface> >("pyToCppModelInterface",init<PyObject *>()) .def("getNumberOfPointSources", &pyToCppModelInterface::getNumberOfPointSources) .def("getPointSourceFluxes", &pyToCppModelInterface::getPointSourceFluxes) .def("update", &pyToCppModelInterface::update) ; } <commit_msg>Changed to the new syntax for the python methods, from camelCase to camel_case<commit_after>#include <boost/python.hpp> #include "ModelInterface.h" #include "pyToCppModelInterface.h" #include <boost/python/stl_iterator.hpp> #include <iostream> #include <stdexcept> //#include <boost/python.hpp> namespace threeML { template< typename T > inline std::vector< T > to_std_vector( const boost::python::object& iterable ) { return std::vector< T >( boost::python::stl_input_iterator< T >( iterable ), boost::python::stl_input_iterator< T >( ) ); } pyToCppModelInterface::pyToCppModelInterface(PyObject *pyModelUninterpreted) : m_nPtSources(0), m_nExtSources(0), n_calls(0) { try { boost::python::object o(boost::python::handle<>(boost::python::borrowed(pyModelUninterpreted))); m_pyModel = o; } catch (...) { throw std::runtime_error("ModelInterface: Could not interpret the LikelihoodModel class"); } //TODO: add a verification of the interface for the pyObject try { m_nPtSources = boost::python::extract<int>(m_pyModel.attr("get_number_of_point_sources")()); } catch (...) { throw std::runtime_error( "ModelInterface: Could not use get_number_of_point_sources from python Object"); } try { m_nExtSources = boost::python::extract<int>(m_pyModel.attr("get_number_of_extended_sources")()); } catch (...) { throw std::runtime_error( "ModelInterface: Could not use get_number_of_extended_sources from python Object"); } } bool pyToCppModelInterface::isInsideAnyExtendedSource(double j2000_ra, double j2000_dec) const { return true; } int pyToCppModelInterface::getNumberOfPointSources() const { return m_nPtSources; } void pyToCppModelInterface::getPointSourcePosition(int srcid, double *j2000_ra, double *j2000_dec) const { boost::python::object coords; try { coords = m_pyModel.attr("get_point_source_position")(srcid); } catch (...) { throw std::runtime_error( "ModelInterface: Could not call get_point_source_position on the python side"); } try { (*j2000_ra) = boost::python::extract<double>(coords[0]); (*j2000_dec) = boost::python::extract<double>(coords[1]); } catch (...) { throw std::runtime_error( "ModelInterface: Could not convert the coordinates I got from the python side"); } } void pyToCppModelInterface::update() { //std::cerr << "Emptying cache" << std::endl; //Empty the cache m_cache.clear(); } std::vector<double> pyToCppModelInterface::getPointSourceFluxes(int srcid, std::vector<double> energies) const { if ( m_cache.count( srcid )==1 ) { //std::cerr << "Cached" << std::endl; //Return cached version return m_cache[srcid]; } else { n_calls += 1; //std::cerr << "Filling cache for " << srcid << " (" << n_calls << ")" << std::endl; } //Construct a generic object (instead of for example a list) so that //the pyModel can return any iterable (list, numpy.array, etc) boost::python::object fluxes; //try { //Transform MeV to keV for(unsigned int i=0; i < energies.size(); ++i) { energies[i] = energies[i] * 1000.0; } //expects and returns MeV-related-units fluxes = m_pyModel.attr("get_point_source_fluxes")(srcid,energies); //} catch (...) { // throw std::runtime_error( // "ModelInterface: Could not get the fluxes from the python side"); //} std::vector<double> fluxes_v; try { fluxes_v = to_std_vector<double>(fluxes); //Transform in ph/cm2/s/MeV from ph/cm2/s/keV for(unsigned int i=0; i < fluxes_v.size(); ++i) { fluxes_v[i] = fluxes_v[i] * 1000.0; } } catch (...) { throw std::runtime_error( "ModelInterface: Could not convert the fluxes I got from the python side"); } //Cache result m_cache[srcid] = fluxes_v; return fluxes_v; } int pyToCppModelInterface::getNumberOfExtendedSources() const { return m_nExtSources; } std::vector<double> pyToCppModelInterface::getExtendedSourceFluxes(int srcid, double j2000_ra, double j2000_dec, std::vector<double> energies) const { /* if ( m_cache.count( srcid * 1000 )==1 ) { //std::cerr << "Cached" << std::endl; //Return cached version return m_cache[srcid * 1000]; } else { */ n_calls += 1; //std::cerr << "Filling cache for " << srcid << " (" << n_calls << ")" << std::endl; // } //Construct a generic object (instead of for example a list) so that //the pyModel can return any iterable (list, numpy.array, etc) boost::python::object fluxes; //try { //Transform MeV to keV for(unsigned int i=0; i < energies.size(); ++i) { energies[i] = energies[i] * 1000.0; } //expects and returns MeV-related-units fluxes = m_pyModel.attr("get_extended_source_fluxes")(srcid, j2000_ra, j2000_dec, energies); //} catch (...) { // throw std::runtime_error( // "ModelInterface: Could not get the fluxes from the python side"); //} std::vector<double> fluxes_v; try { fluxes_v = to_std_vector<double>(fluxes); //Transform in ph/cm2/s/MeV from ph/cm2/s/keV for(unsigned int i=0; i < fluxes_v.size(); ++i) { fluxes_v[i] = fluxes_v[i] * 1000.0; } } catch (...) { throw std::runtime_error( "ModelInterface: Could not convert the fluxes I got from the python side"); } //Cache result // m_cache[srcid * 1000] = fluxes_v; return fluxes_v; } std::string pyToCppModelInterface::getPointSourceName(int srcid) const { std::string name; try { name = boost::python::extract<std::string>( m_pyModel.attr("get_point_source_name")(srcid) ); } catch (...) { throw std::runtime_error( "ModelInterface: Could not get the point source name from the python side"); } return name; } std::string pyToCppModelInterface::getExtendedSourceName(int srcid) const { std::string name; try { name = boost::python::extract<std::string>( m_pyModel.attr("get_extended_source_name")(srcid) ); } catch (...) { throw std::runtime_error( "ModelInterface: Could not get the extended source name from the python side"); } return name; } void pyToCppModelInterface::getExtendedSourceBoundaries(int srcid, double *j2000_ra_min, double *j2000_ra_max, double *j2000_dec_min, double *j2000_dec_max) const { boost::python::object boundaries; boundaries = m_pyModel.attr("get_extended_source_boundaries")( srcid ); std::vector<double> boundaries_v = to_std_vector<double>(boundaries); *j2000_ra_min = boundaries_v[0]; *j2000_ra_max = boundaries_v[1]; *j2000_dec_min = boundaries_v[2]; *j2000_dec_max = boundaries_v[3]; } } using namespace threeML; using namespace boost::python; //This is needed to wrap the interface (i.e., all methods are virtual) //contained in ModelInterface.h struct ModelInterfaceWrap : ModelInterface, wrapper<ModelInterface> { int getNumberOfPointSources() const { return this->get_override("getNumberOfPointSources")(); } void getPointSourcePosition(int srcid, double *j2000_ra, double *j2000_dec) const { this->get_override("getPointSourcePosition")(); } std::vector<double> getPointSourceFluxes(int srcid, std::vector<double> energies) const { return this->get_override("getPointSourceFluxes")(); } std::string getPointSourceName(int srcid) const { return this->get_override("getPointSourceName")(); } int getNumberOfExtendedSources() const { return this->get_override("getNumberOfExtendedSources")(); } std::vector<double> getExtendedSourceFluxes(int srcid, double j2000_ra, double j2000_dec, std::vector<double> energies) const { return this->get_override("getExtendedSourceFluxes")(); } std::string getExtendedSourceName(int srcid) const { return this->get_override("getExtendedSourceName")(); } bool isInsideAnyExtendedSource(double j2000_ra, double j2000_dec) const { return this->get_override("isInsideAnyExtendedSource")(); } void getExtendedSourceBoundaries(int srcid, double *j2000_ra_min, double *j2000_ra_max, double *j2000_dec_min, double *j2000_dec_max) const { this->get_override("getExtendedSourceBoundaries")(); } }; template<class T> struct VecToList { static PyObject* convert(const std::vector<T>& vec) { boost::python::list* l = new boost::python::list(); for(size_t i = 0; i < vec.size(); i++) (*l).append(vec[i]); return l->ptr(); } }; BOOST_PYTHON_MODULE(pyModelInterface) { //hello to_python_converter<std::vector<double,std::allocator<double> >, VecToList<double> >(); class_<ModelInterfaceWrap, boost::noncopyable>("ModelInterface") .def("getNumberOfPointSources", pure_virtual(&ModelInterface::getNumberOfPointSources)) .def("getPointSourcePosition", pure_virtual(&ModelInterface::getPointSourcePosition)) .def("getPointSourceFluxes", pure_virtual(&ModelInterface::getPointSourceFluxes)) .def("getPointSourceName", pure_virtual(&ModelInterface::getPointSourceName)) .def("getNumberOfExtendedSources", pure_virtual(&ModelInterface::getNumberOfExtendedSources)) .def("getExtendedSourceFluxes", pure_virtual(&ModelInterface::getExtendedSourceFluxes)) .def("getExtendedSourceName", pure_virtual(&ModelInterface::getExtendedSourceName)) .def("isInsideAnyExtendedSource", pure_virtual(&ModelInterface::isInsideAnyExtendedSource)) .def("getExtendedSourceBoundaries", pure_virtual(&ModelInterface::getExtendedSourceBoundaries)) ; class_<pyToCppModelInterface, bases<ModelInterface> >("pyToCppModelInterface",init<PyObject *>()) .def("getNumberOfPointSources", &pyToCppModelInterface::getNumberOfPointSources) .def("getPointSourceFluxes", &pyToCppModelInterface::getPointSourceFluxes) .def("update", &pyToCppModelInterface::update) ; } <|endoftext|>
<commit_before>/*************************************************************************** copyright : (C) 2002 - 2008 by Scott Wheeler email : wheeler@kde.org ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License 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., 51 Franklin Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include "tfilestream.h" #include "tstring.h" #include "tdebug.h" #ifdef _WIN32 # include <windows.h> #else # include <stdio.h> # include <unistd.h> #endif using namespace TagLib; namespace { #ifdef _WIN32 // Uses Win32 native API instead of POSIX API to reduce the resource consumption. typedef FileName FileNameHandle; typedef HANDLE FileHandle; const FileHandle InvalidFileHandle = INVALID_HANDLE_VALUE; FileHandle openFile(const FileName &path, bool readOnly) { const DWORD access = readOnly ? GENERIC_READ : (GENERIC_READ | GENERIC_WRITE); #if defined (PLATFORM_WINRT) return CreateFile2(path.wstr().c_str(), access, FILE_SHARE_READ, OPEN_EXISTING, NULL); #else return CreateFileW(path.wstr().c_str(), access, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); #endif } FileHandle openFile(const int fileDescriptor, bool readOnly) { return InvalidFileHandle; } void closeFile(FileHandle file) { CloseHandle(file); } size_t readFile(FileHandle file, ByteVector &buffer) { DWORD length; if(ReadFile(file, buffer.data(), static_cast<DWORD>(buffer.size()), &length, NULL)) return static_cast<size_t>(length); else return 0; } size_t writeFile(FileHandle file, const ByteVector &buffer) { DWORD length; if(WriteFile(file, buffer.data(), static_cast<DWORD>(buffer.size()), &length, NULL)) return static_cast<size_t>(length); else return 0; } #else // _WIN32 struct FileNameHandle : public std::string { FileNameHandle(FileName name) : std::string(name) {} operator FileName () const { return c_str(); } }; typedef FILE* FileHandle; const FileHandle InvalidFileHandle = 0; FileHandle openFile(const FileName &path, bool readOnly) { return fopen(path, readOnly ? "rb" : "rb+"); } FileHandle openFile(const int fileDescriptor, bool readOnly) { return fdopen(fileDescriptor, readOnly ? "rb" : "rb+"); } void closeFile(FileHandle file) { fclose(file); } size_t readFile(FileHandle file, ByteVector &buffer) { return fread(buffer.data(), sizeof(char), buffer.size(), file); } size_t writeFile(FileHandle file, const ByteVector &buffer) { return fwrite(buffer.data(), sizeof(char), buffer.size(), file); } #endif // _WIN32 } class FileStream::FileStreamPrivate { public: FileStreamPrivate(const FileName &fileName) : file(InvalidFileHandle) , name(fileName) , readOnly(true) { } FileHandle file; FileNameHandle name; bool readOnly; }; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// FileStream::FileStream(FileName fileName, bool openReadOnly) : d(new FileStreamPrivate(fileName)) { // First try with read / write mode, if that fails, fall back to read only. if(!openReadOnly) d->file = openFile(fileName, false); if(d->file != InvalidFileHandle) d->readOnly = false; else d->file = openFile(fileName, true); if(d->file == InvalidFileHandle) { # ifdef _WIN32 debug("Could not open file " + fileName.toString()); # else debug("Could not open file " + String(static_cast<const char *>(d->name))); # endif } } FileStream::FileStream(int fileDescriptor, bool openReadOnly) : d(new FileStreamPrivate("")) { // First try with read / write mode, if that fails, fall back to read only. if(!openReadOnly) d->file = openFile(fileDescriptor, false); if(d->file != InvalidFileHandle) d->readOnly = false; else d->file = openFile(fileDescriptor, true); if(d->file == InvalidFileHandle) { debug("Could not open file using file descriptor"); } } FileStream::~FileStream() { if(isOpen()) closeFile(d->file); delete d; } FileName FileStream::name() const { return d->name; } ByteVector FileStream::readBlock(unsigned long length) { if(!isOpen()) { debug("FileStream::readBlock() -- invalid file."); return ByteVector(); } if(length == 0) return ByteVector(); const unsigned long streamLength = static_cast<unsigned long>(FileStream::length()); if(length > bufferSize() && length > streamLength) length = streamLength; ByteVector buffer(static_cast<unsigned int>(length)); const size_t count = readFile(d->file, buffer); buffer.resize(static_cast<unsigned int>(count)); return buffer; } void FileStream::writeBlock(const ByteVector &data) { if(!isOpen()) { debug("FileStream::writeBlock() -- invalid file."); return; } if(readOnly()) { debug("FileStream::writeBlock() -- read only file."); return; } writeFile(d->file, data); } void FileStream::insert(const ByteVector &data, unsigned long start, unsigned long replace) { if(!isOpen()) { debug("FileStream::insert() -- invalid file."); return; } if(readOnly()) { debug("FileStream::insert() -- read only file."); return; } if(data.size() == replace) { seek(start); writeBlock(data); return; } else if(data.size() < replace) { seek(start); writeBlock(data); removeBlock(start + data.size(), replace - data.size()); return; } // Woohoo! Faster (about 20%) than id3lib at last. I had to get hardcore // and avoid TagLib's high level API for rendering just copying parts of // the file that don't contain tag data. // // Now I'll explain the steps in this ugliness: // First, make sure that we're working with a buffer that is longer than // the *differnce* in the tag sizes. We want to avoid overwriting parts // that aren't yet in memory, so this is necessary. unsigned long bufferLength = bufferSize(); while(data.size() - replace > bufferLength) bufferLength += bufferSize(); // Set where to start the reading and writing. long readPosition = start + replace; long writePosition = start; ByteVector buffer = data; ByteVector aboutToOverwrite(static_cast<unsigned int>(bufferLength)); while(true) { // Seek to the current read position and read the data that we're about // to overwrite. Appropriately increment the readPosition. seek(readPosition); const unsigned int bytesRead = static_cast<unsigned int>(readFile(d->file, aboutToOverwrite)); aboutToOverwrite.resize(bytesRead); readPosition += bufferLength; // Check to see if we just read the last block. We need to call clear() // if we did so that the last write succeeds. if(bytesRead < bufferLength) clear(); // Seek to the write position and write our buffer. Increment the // writePosition. seek(writePosition); writeBlock(buffer); // We hit the end of the file. if(bytesRead == 0) break; writePosition += buffer.size(); // Make the current buffer the data that we read in the beginning. buffer = aboutToOverwrite; } } void FileStream::removeBlock(unsigned long start, unsigned long length) { if(!isOpen()) { debug("FileStream::removeBlock() -- invalid file."); return; } unsigned long bufferLength = bufferSize(); long readPosition = start + length; long writePosition = start; ByteVector buffer(static_cast<unsigned int>(bufferLength)); for(unsigned int bytesRead = -1; bytesRead != 0;) { seek(readPosition); bytesRead = static_cast<unsigned int>(readFile(d->file, buffer)); readPosition += bytesRead; // Check to see if we just read the last block. We need to call clear() // if we did so that the last write succeeds. if(bytesRead < buffer.size()) { clear(); buffer.resize(bytesRead); } seek(writePosition); writeFile(d->file, buffer); writePosition += bytesRead; } truncate(writePosition); } bool FileStream::readOnly() const { return d->readOnly; } bool FileStream::isOpen() const { return (d->file != InvalidFileHandle); } void FileStream::seek(long offset, Position p) { if(!isOpen()) { debug("FileStream::seek() -- invalid file."); return; } #ifdef _WIN32 if(p != Beginning && p != Current && p != End) { debug("FileStream::seek() -- Invalid Position value."); return; } LARGE_INTEGER liOffset; liOffset.QuadPart = offset; if(!SetFilePointerEx(d->file, liOffset, NULL, static_cast<DWORD>(p))) { debug("FileStream::seek() -- Failed to set the file pointer."); } #else int whence; switch(p) { case Beginning: whence = SEEK_SET; break; case Current: whence = SEEK_CUR; break; case End: whence = SEEK_END; break; default: debug("FileStream::seek() -- Invalid Position value."); return; } fseek(d->file, offset, whence); #endif } void FileStream::clear() { #ifdef _WIN32 // NOP #else clearerr(d->file); #endif } long FileStream::tell() const { #ifdef _WIN32 const LARGE_INTEGER zero = {}; LARGE_INTEGER position; if(SetFilePointerEx(d->file, zero, &position, FILE_CURRENT) && position.QuadPart <= LONG_MAX) { return static_cast<long>(position.QuadPart); } else { debug("FileStream::tell() -- Failed to get the file pointer."); return 0; } #else return ftell(d->file); #endif } long FileStream::length() { if(!isOpen()) { debug("FileStream::length() -- invalid file."); return 0; } #ifdef _WIN32 LARGE_INTEGER fileSize; if(GetFileSizeEx(d->file, &fileSize) && fileSize.QuadPart <= LONG_MAX) { return static_cast<long>(fileSize.QuadPart); } else { debug("FileStream::length() -- Failed to get the file size."); return 0; } #else const long curpos = tell(); seek(0, End); const long endpos = tell(); seek(curpos, Beginning); return endpos; #endif } //////////////////////////////////////////////////////////////////////////////// // protected members //////////////////////////////////////////////////////////////////////////////// void FileStream::truncate(long length) { #ifdef _WIN32 const long currentPos = tell(); seek(length); if(!SetEndOfFile(d->file)) { debug("FileStream::truncate() -- Failed to truncate the file."); } seek(currentPos); #else const int error = ftruncate(fileno(d->file), length); if(error != 0) { debug("FileStream::truncate() -- Coundn't truncate the file."); } #endif } unsigned int FileStream::bufferSize() { return 1024; } <commit_msg>Follow TagLib's brace style<commit_after>/*************************************************************************** copyright : (C) 2002 - 2008 by Scott Wheeler email : wheeler@kde.org ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License 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., 51 Franklin Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include "tfilestream.h" #include "tstring.h" #include "tdebug.h" #ifdef _WIN32 # include <windows.h> #else # include <stdio.h> # include <unistd.h> #endif using namespace TagLib; namespace { #ifdef _WIN32 // Uses Win32 native API instead of POSIX API to reduce the resource consumption. typedef FileName FileNameHandle; typedef HANDLE FileHandle; const FileHandle InvalidFileHandle = INVALID_HANDLE_VALUE; FileHandle openFile(const FileName &path, bool readOnly) { const DWORD access = readOnly ? GENERIC_READ : (GENERIC_READ | GENERIC_WRITE); #if defined (PLATFORM_WINRT) return CreateFile2(path.wstr().c_str(), access, FILE_SHARE_READ, OPEN_EXISTING, NULL); #else return CreateFileW(path.wstr().c_str(), access, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); #endif } FileHandle openFile(const int fileDescriptor, bool readOnly) { return InvalidFileHandle; } void closeFile(FileHandle file) { CloseHandle(file); } size_t readFile(FileHandle file, ByteVector &buffer) { DWORD length; if(ReadFile(file, buffer.data(), static_cast<DWORD>(buffer.size()), &length, NULL)) return static_cast<size_t>(length); else return 0; } size_t writeFile(FileHandle file, const ByteVector &buffer) { DWORD length; if(WriteFile(file, buffer.data(), static_cast<DWORD>(buffer.size()), &length, NULL)) return static_cast<size_t>(length); else return 0; } #else // _WIN32 struct FileNameHandle : public std::string { FileNameHandle(FileName name) : std::string(name) {} operator FileName () const { return c_str(); } }; typedef FILE* FileHandle; const FileHandle InvalidFileHandle = 0; FileHandle openFile(const FileName &path, bool readOnly) { return fopen(path, readOnly ? "rb" : "rb+"); } FileHandle openFile(const int fileDescriptor, bool readOnly) { return fdopen(fileDescriptor, readOnly ? "rb" : "rb+"); } void closeFile(FileHandle file) { fclose(file); } size_t readFile(FileHandle file, ByteVector &buffer) { return fread(buffer.data(), sizeof(char), buffer.size(), file); } size_t writeFile(FileHandle file, const ByteVector &buffer) { return fwrite(buffer.data(), sizeof(char), buffer.size(), file); } #endif // _WIN32 } class FileStream::FileStreamPrivate { public: FileStreamPrivate(const FileName &fileName) : file(InvalidFileHandle) , name(fileName) , readOnly(true) { } FileHandle file; FileNameHandle name; bool readOnly; }; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// FileStream::FileStream(FileName fileName, bool openReadOnly) : d(new FileStreamPrivate(fileName)) { // First try with read / write mode, if that fails, fall back to read only. if(!openReadOnly) d->file = openFile(fileName, false); if(d->file != InvalidFileHandle) d->readOnly = false; else d->file = openFile(fileName, true); if(d->file == InvalidFileHandle) # ifdef _WIN32 debug("Could not open file " + fileName.toString()); # else debug("Could not open file " + String(static_cast<const char *>(d->name))); # endif } FileStream::FileStream(int fileDescriptor, bool openReadOnly) : d(new FileStreamPrivate("")) { // First try with read / write mode, if that fails, fall back to read only. if(!openReadOnly) d->file = openFile(fileDescriptor, false); if(d->file != InvalidFileHandle) d->readOnly = false; else d->file = openFile(fileDescriptor, true); if(d->file == InvalidFileHandle) debug("Could not open file using file descriptor"); } FileStream::~FileStream() { if(isOpen()) closeFile(d->file); delete d; } FileName FileStream::name() const { return d->name; } ByteVector FileStream::readBlock(unsigned long length) { if(!isOpen()) { debug("FileStream::readBlock() -- invalid file."); return ByteVector(); } if(length == 0) return ByteVector(); const unsigned long streamLength = static_cast<unsigned long>(FileStream::length()); if(length > bufferSize() && length > streamLength) length = streamLength; ByteVector buffer(static_cast<unsigned int>(length)); const size_t count = readFile(d->file, buffer); buffer.resize(static_cast<unsigned int>(count)); return buffer; } void FileStream::writeBlock(const ByteVector &data) { if(!isOpen()) { debug("FileStream::writeBlock() -- invalid file."); return; } if(readOnly()) { debug("FileStream::writeBlock() -- read only file."); return; } writeFile(d->file, data); } void FileStream::insert(const ByteVector &data, unsigned long start, unsigned long replace) { if(!isOpen()) { debug("FileStream::insert() -- invalid file."); return; } if(readOnly()) { debug("FileStream::insert() -- read only file."); return; } if(data.size() == replace) { seek(start); writeBlock(data); return; } else if(data.size() < replace) { seek(start); writeBlock(data); removeBlock(start + data.size(), replace - data.size()); return; } // Woohoo! Faster (about 20%) than id3lib at last. I had to get hardcore // and avoid TagLib's high level API for rendering just copying parts of // the file that don't contain tag data. // // Now I'll explain the steps in this ugliness: // First, make sure that we're working with a buffer that is longer than // the *differnce* in the tag sizes. We want to avoid overwriting parts // that aren't yet in memory, so this is necessary. unsigned long bufferLength = bufferSize(); while(data.size() - replace > bufferLength) bufferLength += bufferSize(); // Set where to start the reading and writing. long readPosition = start + replace; long writePosition = start; ByteVector buffer = data; ByteVector aboutToOverwrite(static_cast<unsigned int>(bufferLength)); while(true) { // Seek to the current read position and read the data that we're about // to overwrite. Appropriately increment the readPosition. seek(readPosition); const unsigned int bytesRead = static_cast<unsigned int>(readFile(d->file, aboutToOverwrite)); aboutToOverwrite.resize(bytesRead); readPosition += bufferLength; // Check to see if we just read the last block. We need to call clear() // if we did so that the last write succeeds. if(bytesRead < bufferLength) clear(); // Seek to the write position and write our buffer. Increment the // writePosition. seek(writePosition); writeBlock(buffer); // We hit the end of the file. if(bytesRead == 0) break; writePosition += buffer.size(); // Make the current buffer the data that we read in the beginning. buffer = aboutToOverwrite; } } void FileStream::removeBlock(unsigned long start, unsigned long length) { if(!isOpen()) { debug("FileStream::removeBlock() -- invalid file."); return; } unsigned long bufferLength = bufferSize(); long readPosition = start + length; long writePosition = start; ByteVector buffer(static_cast<unsigned int>(bufferLength)); for(unsigned int bytesRead = -1; bytesRead != 0;) { seek(readPosition); bytesRead = static_cast<unsigned int>(readFile(d->file, buffer)); readPosition += bytesRead; // Check to see if we just read the last block. We need to call clear() // if we did so that the last write succeeds. if(bytesRead < buffer.size()) { clear(); buffer.resize(bytesRead); } seek(writePosition); writeFile(d->file, buffer); writePosition += bytesRead; } truncate(writePosition); } bool FileStream::readOnly() const { return d->readOnly; } bool FileStream::isOpen() const { return (d->file != InvalidFileHandle); } void FileStream::seek(long offset, Position p) { if(!isOpen()) { debug("FileStream::seek() -- invalid file."); return; } #ifdef _WIN32 if(p != Beginning && p != Current && p != End) { debug("FileStream::seek() -- Invalid Position value."); return; } LARGE_INTEGER liOffset; liOffset.QuadPart = offset; if(!SetFilePointerEx(d->file, liOffset, NULL, static_cast<DWORD>(p))) { debug("FileStream::seek() -- Failed to set the file pointer."); } #else int whence; switch(p) { case Beginning: whence = SEEK_SET; break; case Current: whence = SEEK_CUR; break; case End: whence = SEEK_END; break; default: debug("FileStream::seek() -- Invalid Position value."); return; } fseek(d->file, offset, whence); #endif } void FileStream::clear() { #ifdef _WIN32 // NOP #else clearerr(d->file); #endif } long FileStream::tell() const { #ifdef _WIN32 const LARGE_INTEGER zero = {}; LARGE_INTEGER position; if(SetFilePointerEx(d->file, zero, &position, FILE_CURRENT) && position.QuadPart <= LONG_MAX) { return static_cast<long>(position.QuadPart); } else { debug("FileStream::tell() -- Failed to get the file pointer."); return 0; } #else return ftell(d->file); #endif } long FileStream::length() { if(!isOpen()) { debug("FileStream::length() -- invalid file."); return 0; } #ifdef _WIN32 LARGE_INTEGER fileSize; if(GetFileSizeEx(d->file, &fileSize) && fileSize.QuadPart <= LONG_MAX) { return static_cast<long>(fileSize.QuadPart); } else { debug("FileStream::length() -- Failed to get the file size."); return 0; } #else const long curpos = tell(); seek(0, End); const long endpos = tell(); seek(curpos, Beginning); return endpos; #endif } //////////////////////////////////////////////////////////////////////////////// // protected members //////////////////////////////////////////////////////////////////////////////// void FileStream::truncate(long length) { #ifdef _WIN32 const long currentPos = tell(); seek(length); if(!SetEndOfFile(d->file)) { debug("FileStream::truncate() -- Failed to truncate the file."); } seek(currentPos); #else const int error = ftruncate(fileno(d->file), length); if(error != 0) debug("FileStream::truncate() -- Coundn't truncate the file."); #endif } unsigned int FileStream::bufferSize() { return 1024; } <|endoftext|>