text
stringlengths
54
60.6k
<commit_before>#include "sphere.h" #include "utils.h" namespace batoid { Sphere::Sphere(double R) : _R(R), _Rsq(R*R), _Rinv(1./R), _Rinvsq(1./R/R) {} double Sphere::sag(double x, double y) const { if (_R != 0) return _R*(1-std::sqrt(1-(x*x + y*y)*_Rinvsq)); return 0.0; } Vector3d Sphere::normal(double x, double y) const { if (_R == 0.0) return Vector3d(0,0,1); double r = std::sqrt(x*x + y*y); if (r == 0) return Vector3d(0,0,1); double dzdr1 = dzdr(r); return Vector3d(-dzdr1*x/r, -dzdr1*y/r, 1).normalized(); } bool Sphere::timeToIntersect(const Ray& r, double& t) const { double vr2 = r.v[0]*r.v[0] + r.v[1]*r.v[1]; double vz2 = r.v[2]*r.v[2]; double vrr0 = r.v[0]*r.r[0] + r.v[1]*r.r[1]; double r02 = r.r[0]*r.r[0] + r.r[1]*r.r[1]; double z0term = (r.r[2]-_R); // Quadratic equation coefficients double a = vz2 + vr2; double b = 2*r.v[2]*z0term + 2*vrr0; double c = z0term*z0term - _Rsq + r02; double r1, r2; int n = solveQuadratic(a, b, c, r1, r2); // Should probably check the solutions here since we obtained the quadratic // formula above by squaring both sides of an equation. if (n == 0) { return false; } else if (n == 1) { if (r1 < 0) return false; t = r1; } else { if (r1 < 0) { if (r2 < 0) return false; else t = r2; } else t = std::min(r1, r2); } t += r.t; return true; } double Sphere::dzdr(double r) const { double rat = r*_Rinv; return rat/std::sqrt(1-rat*rat); } } <commit_msg>Choose correct time for Sphere intersect<commit_after>#include "sphere.h" #include "utils.h" namespace batoid { Sphere::Sphere(double R) : _R(R), _Rsq(R*R), _Rinv(1./R), _Rinvsq(1./R/R) {} double Sphere::sag(double x, double y) const { if (_R != 0) return _R*(1-std::sqrt(1-(x*x + y*y)*_Rinvsq)); return 0.0; } Vector3d Sphere::normal(double x, double y) const { if (_R == 0.0) return Vector3d(0,0,1); double r = std::sqrt(x*x + y*y); if (r == 0) return Vector3d(0,0,1); double dzdr1 = dzdr(r); return Vector3d(-dzdr1*x/r, -dzdr1*y/r, 1).normalized(); } bool Sphere::timeToIntersect(const Ray& r, double& t) const { double vr2 = r.v[0]*r.v[0] + r.v[1]*r.v[1]; double vz2 = r.v[2]*r.v[2]; double vrr0 = r.v[0]*r.r[0] + r.v[1]*r.r[1]; double r02 = r.r[0]*r.r[0] + r.r[1]*r.r[1]; double z0term = (r.r[2]-_R); // Quadratic equation coefficients double a = vz2 + vr2; double b = 2*r.v[2]*z0term + 2*vrr0; double c = z0term*z0term - _Rsq + r02; double t1, t2; int n = solveQuadratic(a, b, c, t1, t2); // Should probably check the solutions here since we obtained the quadratic // formula above by squaring both sides of an equation. if (n == 0) { return false; } else if (n == 1) { if (t1 < 0) return false; t = t1; } else { if (t1 < 0) { if (t2 < 0) return false; else t = t2; } else { // We need to pick whichever time is most consistent with the sag. Ray r1 = r.propagatedToTime(r.t + t1); Ray r2 = r.propagatedToTime(r.t + t2); double d1 = std::abs(sag(r1.r[0], r1.r[1]) - r1.r[2]); double d2 = std::abs(sag(r2.r[0], r2.r[1]) - r2.r[2]); t = (d1 < d2) ? t1 : t2; } } t += r.t; return true; } double Sphere::dzdr(double r) const { double rat = r*_Rinv; return rat/std::sqrt(1-rat*rat); } } <|endoftext|>
<commit_before>/*! * FrameReceiverRxThreadUnitTest.cpp * * Created on: Feb 5, 2015 * Author: Tim Nicholls, STFC Application Engineering Group */ #include <boost/test/unit_test.hpp> #include "FrameReceiverUDPRxThread.h" #include "IpcMessage.h" #include "SharedBufferManager.h" #include <log4cxx/logger.h> #include <log4cxx/consoleappender.h> #include <log4cxx/basicconfigurator.h> #include <log4cxx/simplelayout.h> #include "../include/DummyUDPFrameDecoder.h" namespace FrameReceiver { class FrameReceiverRxThreadTestProxy { public: FrameReceiverRxThreadTestProxy(FrameReceiver::FrameReceiverConfig& config) : config_(config) { // Override default RX buffer size on OS X as Linux default // is too large for test to pass #ifdef __MACH__ config_.rx_recv_buffer_size_ = 1048576; #endif } std::string& get_rx_channel_endpoint(void) { return config_.rx_channel_endpoint_; } private: FrameReceiver::FrameReceiverConfig& config_; }; } class FrameReceiverRxThreadTestFixture { public: FrameReceiverRxThreadTestFixture() : rx_channel(ZMQ_PAIR), logger(log4cxx::Logger::getLogger("FrameReceiverRxThreadUnitTest")), proxy(config), frame_decoder(new FrameReceiver::DummyUDPFrameDecoder()), buffer_manager(new OdinData::SharedBufferManager("TestSharedBuffer", 10000, 1000)) { BOOST_TEST_MESSAGE("Setup test fixture"); // Create a log4cxx console appender so that thread messages can be printed, suppress debug messages log4cxx::ConsoleAppender* consoleAppender = new log4cxx::ConsoleAppender(log4cxx::LayoutPtr(new log4cxx::SimpleLayout())); log4cxx::helpers::Pool p; consoleAppender->activateOptions(p); log4cxx::BasicConfigurator::configure(log4cxx::AppenderPtr(consoleAppender)); log4cxx::Logger::getRootLogger()->setLevel(log4cxx::Level::getInfo()); frame_decoder->init(logger); // Bind the endpoint of the channel to communicate with the RX thread rx_channel.bind(proxy.get_rx_channel_endpoint()); } ~FrameReceiverRxThreadTestFixture() { BOOST_TEST_MESSAGE("Tear down test fixture"); } OdinData::IpcChannel rx_channel; FrameReceiver::FrameReceiverConfig config; log4cxx::LoggerPtr logger; FrameReceiver::FrameReceiverRxThreadTestProxy proxy; FrameReceiver::FrameDecoderPtr frame_decoder; OdinData::SharedBufferManagerPtr buffer_manager; }; BOOST_FIXTURE_TEST_SUITE(FrameReceiverRxThreadUnitTest, FrameReceiverRxThreadTestFixture); BOOST_AUTO_TEST_CASE( CreateAndPingRxThread ) { bool initOK = true; try { FrameReceiver::FrameReceiverUDPRxThread rxThread(config, buffer_manager, frame_decoder, 1); rxThread.start(); OdinData::IpcMessage::MsgType msg_type = OdinData::IpcMessage::MsgTypeCmd; OdinData::IpcMessage::MsgVal msg_val = OdinData::IpcMessage::MsgValCmdStatus; int loopCount = 500; int replyCount = 0; int timeoutCount = 0; bool msgMatch = true; for (int loop = 0; loop < loopCount; loop++) { OdinData::IpcMessage message(msg_type, msg_val); message.set_param<int>("count", loop); rx_channel.send(message.encode()); } while ((replyCount < loopCount) && (timeoutCount < 10)) { if (rx_channel.poll(100)) { std::string reply = rx_channel.recv(); OdinData::IpcMessage response(reply.c_str()); msgMatch &= (response.get_msg_type() == OdinData::IpcMessage::MsgTypeAck); msgMatch &= (response.get_msg_val() == OdinData::IpcMessage::MsgValCmdStatus); msgMatch &= (response.get_param<int>("count", -1) == replyCount); replyCount++; timeoutCount = 0; } else { timeoutCount++; } } rxThread.stop(); BOOST_CHECK_EQUAL(msgMatch, true); BOOST_CHECK_EQUAL(loopCount, replyCount); BOOST_CHECK_EQUAL(timeoutCount, 0); } catch (OdinData::OdinDataException& e) { initOK = false; BOOST_TEST_MESSAGE("Creation of FrameReceiverRxThread failed: " << e.what()); } BOOST_REQUIRE_EQUAL(initOK, true); } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>Make RX thread unit test understand buffer precharge request.<commit_after>/*! * FrameReceiverRxThreadUnitTest.cpp * * Created on: Feb 5, 2015 * Author: Tim Nicholls, STFC Application Engineering Group */ #include <boost/test/unit_test.hpp> #include "FrameReceiverUDPRxThread.h" #include "IpcMessage.h" #include "SharedBufferManager.h" #include <log4cxx/logger.h> #include <log4cxx/consoleappender.h> #include <log4cxx/basicconfigurator.h> #include <log4cxx/simplelayout.h> #include "../include/DummyUDPFrameDecoder.h" namespace FrameReceiver { class FrameReceiverRxThreadTestProxy { public: FrameReceiverRxThreadTestProxy(FrameReceiver::FrameReceiverConfig& config) : config_(config) { // Override default RX buffer size on OS X as Linux default // is too large for test to pass #ifdef __MACH__ config_.rx_recv_buffer_size_ = 1048576; #endif } std::string& get_rx_channel_endpoint(void) { return config_.rx_channel_endpoint_; } private: FrameReceiver::FrameReceiverConfig& config_; }; } class FrameReceiverRxThreadTestFixture { public: FrameReceiverRxThreadTestFixture() : rx_channel(ZMQ_PAIR), logger(log4cxx::Logger::getLogger("FrameReceiverRxThreadUnitTest")), proxy(config), frame_decoder(new FrameReceiver::DummyUDPFrameDecoder()), buffer_manager(new OdinData::SharedBufferManager("TestSharedBuffer", 10000, 1000)) { BOOST_TEST_MESSAGE("Setup test fixture"); // Create a log4cxx console appender so that thread messages can be printed, suppress debug messages log4cxx::ConsoleAppender* consoleAppender = new log4cxx::ConsoleAppender(log4cxx::LayoutPtr(new log4cxx::SimpleLayout())); log4cxx::helpers::Pool p; consoleAppender->activateOptions(p); log4cxx::BasicConfigurator::configure(log4cxx::AppenderPtr(consoleAppender)); log4cxx::Logger::getRootLogger()->setLevel(log4cxx::Level::getInfo()); frame_decoder->init(logger); // Bind the endpoint of the channel to communicate with the RX thread rx_channel.bind(proxy.get_rx_channel_endpoint()); } ~FrameReceiverRxThreadTestFixture() { BOOST_TEST_MESSAGE("Tear down test fixture"); } OdinData::IpcChannel rx_channel; FrameReceiver::FrameReceiverConfig config; log4cxx::LoggerPtr logger; FrameReceiver::FrameReceiverRxThreadTestProxy proxy; FrameReceiver::FrameDecoderPtr frame_decoder; OdinData::SharedBufferManagerPtr buffer_manager; }; BOOST_FIXTURE_TEST_SUITE(FrameReceiverRxThreadUnitTest, FrameReceiverRxThreadTestFixture); BOOST_AUTO_TEST_CASE( CreateAndPingRxThread ) { bool initOK = true; try { FrameReceiver::FrameReceiverUDPRxThread rxThread(config, buffer_manager, frame_decoder, 1); rxThread.start(); // The RX thread will, immediately on startup, send a buffer precharge request, so check // this is received with the correct parameters std::string precharge_request = rx_channel.recv(); OdinData::IpcMessage precharge_msg(precharge_request.c_str()); BOOST_CHECK_EQUAL(precharge_msg.get_msg_type(), OdinData::IpcMessage::MsgTypeCmd); BOOST_CHECK_EQUAL(precharge_msg.get_msg_val(), OdinData::IpcMessage::MsgValCmdBufferPrechargeRequest); OdinData::IpcMessage::MsgType msg_type = OdinData::IpcMessage::MsgTypeCmd; OdinData::IpcMessage::MsgVal msg_val = OdinData::IpcMessage::MsgValCmdStatus; int loopCount = 1; int replyCount = 0; int timeoutCount = 0; bool msgMatch = true; for (int loop = 0; loop < loopCount; loop++) { OdinData::IpcMessage message(msg_type, msg_val); message.set_param<int>("count", loop); rx_channel.send(message.encode()); } while ((replyCount < loopCount) && (timeoutCount < 10)) { if (rx_channel.poll(100)) { std::string reply = rx_channel.recv(); OdinData::IpcMessage response(reply.c_str()); msgMatch &= (response.get_msg_type() == OdinData::IpcMessage::MsgTypeAck); msgMatch &= (response.get_msg_val() == OdinData::IpcMessage::MsgValCmdStatus); msgMatch &= (response.get_param<int>("count", -1) == replyCount); replyCount++; timeoutCount = 0; } else { timeoutCount++; } } rxThread.stop(); BOOST_CHECK_EQUAL(msgMatch, true); BOOST_CHECK_EQUAL(loopCount, replyCount); BOOST_CHECK_EQUAL(timeoutCount, 0); } catch (OdinData::OdinDataException& e) { initOK = false; BOOST_TEST_MESSAGE("Creation of FrameReceiverRxThread failed: " << e.what()); } BOOST_REQUIRE_EQUAL(initOK, true); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ /// \file string.cpp //------------------------------------------------------------------------------ /// \brief Implementation of general purpose functions for string processing //------------------------------------------------------------------------------ // Copyright (c) 2010 Serge Aleynikov <saleyn@gmail.com> // Created: 2010-05-06 //------------------------------------------------------------------------------ /* ***** BEGIN LICENSE BLOCK ***** This file is part of the utxx open-source project. Copyright (C) 2010 Serge Aleynikov <saleyn@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.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***** END LICENSE BLOCK ***** */ #include <utxx/string.hpp> #include <utxx/print_opts.hpp> namespace utxx { std::string to_bin_string(const char* a_buf, size_t a_sz, bool a_hex, bool a_readable, bool a_eol) { std::stringstream out; const char* begin = a_buf, *end = a_buf + a_sz; print_opts opts = a_hex ? (a_readable ? print_opts::printable_or_hex : print_opts::hex) : (a_readable ? print_opts::printable_or_dec : print_opts::dec); output(out, begin, end, opts, ",", "", "\"", "<<", ">>"); if (a_eol) out << std::endl; return out.str(); } bool wildcard_match(const char* a_input, const char* a_pattern) { // Pattern match a_input against a_pattern, and exit // at the end of the input string for(const char* ip = nullptr, *pp = nullptr; *a_input;) if (*a_pattern == '*') { if (!*++a_pattern) return true; // Reached '*' at the end of pattern pp = a_pattern; // Store matching state right after '*' ip = a_input; } else if ((*a_pattern == *a_input) || (*a_pattern == '?')) { a_pattern++; // Continue successful input match a_input++; } else if (pp) { a_pattern = pp; // Match failed - restore state of pattern after '*' a_input = ++ip; // Advance the input on every match failure } else return false; // Match failed before the first '*' is found // Skip trailing '*' in the pattern, since they don't affect the outcome: while (*a_pattern == '*') a_pattern++; // This point is reached only when the a_input string was fully // exhaused. If at this point the a_pattern is exhaused too ('\0'), // there's a match, otherwise pattern match is incomplete. return !*a_pattern; } } // namespace utxx <commit_msg>Update string.cpp<commit_after>//------------------------------------------------------------------------------ /// \file string.cpp //------------------------------------------------------------------------------ /// \brief Implementation of general purpose functions for string processing //------------------------------------------------------------------------------ // Copyright (c) 2010 Serge Aleynikov <saleyn@gmail.com> // Created: 2010-05-06 //------------------------------------------------------------------------------ /* ***** BEGIN LICENSE BLOCK ***** This file is part of the utxx open-source project. Copyright (C) 2010 Serge Aleynikov <saleyn@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.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***** END LICENSE BLOCK ***** */ #include <utxx/string.hpp> #include <utxx/print_opts.hpp> namespace utxx { std::string to_bin_string(const char* a_buf, size_t a_sz, bool a_hex, bool a_readable, bool a_eol) { std::stringstream out; const char* begin = a_buf, *end = a_buf + a_sz; print_opts opts = a_hex ? (a_readable ? print_opts::printable_or_hex : print_opts::hex) : (a_readable ? print_opts::printable_or_dec : print_opts::dec); output(out, begin, end, opts, ",", "", "\"", "<<", ">>"); if (a_eol) out << std::endl; return out.str(); } bool wildcard_match(const char* a_input, const char* a_pattern) { // Pattern match a_input against a_pattern, and exit // at the end of the input string for (const char* ip = nullptr, *pp = nullptr; *a_input;) if (*a_pattern == '*') { if (!*++a_pattern) return true; // Reached '*' at the end of pattern pp = a_pattern; // Store matching state right after '*' ip = a_input; } else if ((*a_pattern == *a_input) || (*a_pattern == '?')) { a_pattern++; // Continue successful input match a_input++; } else if (pp) { a_pattern = pp; // Match failed - restore state of pattern after '*' a_input = ++ip; // Advance the input on every match failure } else return false; // Match failed before the first '*' is found // Skip trailing '*' in the pattern, since they don't affect the outcome: while (*a_pattern == '*') a_pattern++; // This point is reached only when the a_input string was fully // exhaused. If at this point the a_pattern is exhaused too ('\0'), // there's a match, otherwise pattern match is incomplete. return !*a_pattern; } } // namespace utxx <|endoftext|>
<commit_before>#include <vector> #include <string> #include <sstream> #include "error_handling.h" #include "game.h" #include "coordinate.h" #include "fight.h" #include "io.h" #include "item.h" #include "level.h" #include "misc.h" #include "monster.h" #include "options.h" #include "os.h" #include "player.h" #include "rogue.h" #include "weapons.h" using namespace std; static Weapon::Type random_weapon_type() { int value = os_rand_range(100); int end = static_cast<int>(Weapon::Type::NWEAPONS); for (int i = 0; i < end; ++i) { Weapon::Type type = static_cast<Weapon::Type>(i); int probability = Weapon::probability(type); if (value < probability) { return type; } else { value -= probability; } } error("Error! Sum of probabilities is not 100%"); } class Weapon* Weapon::clone() const { return new Weapon(*this); } bool Weapon::is_magic() const { return get_hit_plus() != 0 || get_damage_plus() != 0; } Weapon::~Weapon() {} Weapon::Weapon(bool random_stats) : Weapon(random_weapon_type(), random_stats) {} Weapon::Weapon(Weapon::Type subtype_, bool random_stats) : Item(), subtype(subtype_), identified(false) { o_type = IO::Weapon; o_which = subtype; o_count = 1; switch (subtype) { case MACE: { set_attack_damage({2,4}); set_throw_damage({1,3}); o_launch = NO_WEAPON; } break; case SWORD: { set_attack_damage({3,4}); set_throw_damage({1,2}); o_launch = NO_WEAPON; } break; case BOW: { set_attack_damage({1,1}); set_throw_damage({2,3}); o_launch = NO_WEAPON; } break; case ARROW: { set_attack_damage({0,0}); set_throw_damage({1,1}); o_launch = BOW; o_count = os_rand_range(8) + 8; o_flags = ISMANY|ISMISL; o_type = IO::Ammo; } break; case DAGGER: { set_attack_damage({1,6}); set_throw_damage({1,4}); o_launch = NO_WEAPON; o_count = os_rand_range(4) + 2; o_flags = ISMISL; } break; case TWOSWORD: { set_attack_damage({4,4}); set_throw_damage({1,3}); o_launch = NO_WEAPON; } break; case DART: { set_attack_damage({0,0}); set_throw_damage({1,3}); o_launch = NO_WEAPON; o_count = os_rand_range(8) + 8; o_flags = ISMANY|ISMISL; o_type = IO::Ammo; } break; case SHIRAKEN: { set_attack_damage({0,0}); set_throw_damage({2,4}); o_launch = NO_WEAPON; o_count = os_rand_range(8) + 8; o_flags = ISMANY|ISMISL; o_type = IO::Ammo; } break; case SPEAR: { set_attack_damage({2,3}); set_throw_damage({1,6}); set_armor(2); o_launch = NO_WEAPON; o_flags = ISMISL; } break; case NWEAPONS: error("Unknown type NWEAPONS"); case NO_WEAPON: error("Unknown type NO_WEAPON"); } if (random_stats) { int rand = os_rand_range(100); if (rand < 10) { set_cursed(); modify_hit_plus(-os_rand_range(3) + 1); } else if (rand < 15) { modify_hit_plus(os_rand_range(3) + 1); } } } void Weapon::set_identified() { identified = true; } void Weapon::set_not_identified() { identified = false; } bool Weapon::is_identified() const { return identified; } string Weapon::name(Weapon::Type type) { switch (type) { case MACE: return "mace"; case SWORD: return "long sword"; case BOW: return "short bow"; case ARROW: return "arrow"; case DAGGER: return "dagger"; case TWOSWORD: return "two handed sword"; case DART: return "dart"; case SHIRAKEN: return "shuriken"; case SPEAR: return "spear"; case NWEAPONS: error("Unknown type NWEAPONS"); case NO_WEAPON: error("Unknown type NO_WEAPON"); } } int Weapon::probability(Weapon::Type type) { switch (type) { case MACE: return 11; case SWORD: return 11; case BOW: return 12; case ARROW: return 12; case DAGGER: return 8; case TWOSWORD: return 10; case DART: return 12; case SHIRAKEN: return 12; case SPEAR: return 12; case NWEAPONS: error("Unknown type NWEAPONS"); case NO_WEAPON: error("Unknown type NO_WEAPON"); } } int Weapon::worth(Weapon::Type type) { switch (type) { case MACE: return 8; case SWORD: return 15; case BOW: return 15; case ARROW: return 1; case DAGGER: return 3; case TWOSWORD: return 75; case DART: return 2; case SHIRAKEN: return 5; case SPEAR: return 5; case NWEAPONS: error("Unknown type NWEAPONS"); case NO_WEAPON: error("Unknown type NO_WEAPON"); } } string Weapon::get_description() const { stringstream buffer; string const& obj_name = Weapon::name(static_cast<Weapon::Type>(o_which)); if (o_count == 1) { buffer << "a" << vowelstr(obj_name) << " " << obj_name; } else { buffer << o_count << " " << obj_name << "s"; } int dices; int sides; if (o_type == IO::Ammo || o_which == Weapon::BOW) { dices = get_throw_damage().dices; sides = get_throw_damage().sides; } else if (o_type == IO::Weapon) { dices = get_attack_damage().dices; sides = get_attack_damage().sides; } else { error("Bad item type"); } buffer << " (" << sides << "d" << dices << ")"; if (identified) { buffer << " ("; int p_hit = get_hit_plus(); if (p_hit >= 0) { buffer << "+"; } buffer << p_hit << ","; int p_dmg = get_damage_plus(); if (p_dmg >= 0) { buffer << "+"; } buffer << p_dmg << ")"; } if (get_armor() != 0) { buffer << " ["; int p_armor = get_armor(); if (p_armor >= 0) { buffer << "+"; } buffer << p_armor << "]"; } if (!get_nickname().empty()) { buffer << " called " << get_nickname(); } return buffer.str(); } void weapon_missile_fall(Item* obj, bool pr) { Coordinate fpos; if (fallpos(&obj->get_position(), &fpos)) { obj->set_position(fpos); // See if we can stack it with something on the ground for (Item* ground_item : Game::level->items) { if (ground_item->get_position() == obj->get_position() && ground_item->o_type == obj->o_type && ground_item->o_which == obj->o_which && ground_item->get_hit_plus() == obj->get_hit_plus() && ground_item->get_damage_plus() == obj->get_damage_plus()) { ground_item->o_count++; delete obj; obj = nullptr; break; } } if (obj != nullptr) { Game::level->items.push_back(obj); } return; } if (pr) { stringstream os; os << "the " << Weapon::name(static_cast<Weapon::Type>(obj->o_which)) << " vanishes as it hits the ground"; Game::io->message(os.str()); } delete obj; } <commit_msg>Arrows should never display damage, only +1 and stuff<commit_after>#include <vector> #include <string> #include <sstream> #include "error_handling.h" #include "game.h" #include "coordinate.h" #include "fight.h" #include "io.h" #include "item.h" #include "level.h" #include "misc.h" #include "monster.h" #include "options.h" #include "os.h" #include "player.h" #include "rogue.h" #include "weapons.h" using namespace std; static Weapon::Type random_weapon_type() { int value = os_rand_range(100); int end = static_cast<int>(Weapon::Type::NWEAPONS); for (int i = 0; i < end; ++i) { Weapon::Type type = static_cast<Weapon::Type>(i); int probability = Weapon::probability(type); if (value < probability) { return type; } else { value -= probability; } } error("Error! Sum of probabilities is not 100%"); } class Weapon* Weapon::clone() const { return new Weapon(*this); } bool Weapon::is_magic() const { return get_hit_plus() != 0 || get_damage_plus() != 0; } Weapon::~Weapon() {} Weapon::Weapon(bool random_stats) : Weapon(random_weapon_type(), random_stats) {} Weapon::Weapon(Weapon::Type subtype_, bool random_stats) : Item(), subtype(subtype_), identified(false) { o_type = IO::Weapon; o_which = subtype; o_count = 1; switch (subtype) { case MACE: { set_attack_damage({2,4}); set_throw_damage({1,3}); o_launch = NO_WEAPON; } break; case SWORD: { set_attack_damage({3,4}); set_throw_damage({1,2}); o_launch = NO_WEAPON; } break; case BOW: { set_attack_damage({1,1}); set_throw_damage({2,3}); o_launch = NO_WEAPON; } break; case ARROW: { set_attack_damage({0,0}); set_throw_damage({1,1}); o_launch = BOW; o_count = os_rand_range(8) + 8; o_flags = ISMANY|ISMISL; o_type = IO::Ammo; } break; case DAGGER: { set_attack_damage({1,6}); set_throw_damage({1,4}); o_launch = NO_WEAPON; o_count = os_rand_range(4) + 2; o_flags = ISMISL; } break; case TWOSWORD: { set_attack_damage({4,4}); set_throw_damage({1,3}); o_launch = NO_WEAPON; } break; case DART: { set_attack_damage({0,0}); set_throw_damage({1,3}); o_launch = NO_WEAPON; o_count = os_rand_range(8) + 8; o_flags = ISMANY|ISMISL; o_type = IO::Ammo; } break; case SHIRAKEN: { set_attack_damage({0,0}); set_throw_damage({2,4}); o_launch = NO_WEAPON; o_count = os_rand_range(8) + 8; o_flags = ISMANY|ISMISL; o_type = IO::Ammo; } break; case SPEAR: { set_attack_damage({2,3}); set_throw_damage({1,6}); set_armor(2); o_launch = NO_WEAPON; o_flags = ISMISL; } break; case NWEAPONS: error("Unknown type NWEAPONS"); case NO_WEAPON: error("Unknown type NO_WEAPON"); } if (random_stats) { int rand = os_rand_range(100); if (rand < 10) { set_cursed(); modify_hit_plus(-os_rand_range(3) + 1); } else if (rand < 15) { modify_hit_plus(os_rand_range(3) + 1); } } } void Weapon::set_identified() { identified = true; } void Weapon::set_not_identified() { identified = false; } bool Weapon::is_identified() const { return identified; } string Weapon::name(Weapon::Type type) { switch (type) { case MACE: return "mace"; case SWORD: return "long sword"; case BOW: return "short bow"; case ARROW: return "arrow"; case DAGGER: return "dagger"; case TWOSWORD: return "two handed sword"; case DART: return "dart"; case SHIRAKEN: return "shuriken"; case SPEAR: return "spear"; case NWEAPONS: error("Unknown type NWEAPONS"); case NO_WEAPON: error("Unknown type NO_WEAPON"); } } int Weapon::probability(Weapon::Type type) { switch (type) { case MACE: return 11; case SWORD: return 11; case BOW: return 12; case ARROW: return 12; case DAGGER: return 8; case TWOSWORD: return 10; case DART: return 12; case SHIRAKEN: return 12; case SPEAR: return 12; case NWEAPONS: error("Unknown type NWEAPONS"); case NO_WEAPON: error("Unknown type NO_WEAPON"); } } int Weapon::worth(Weapon::Type type) { switch (type) { case MACE: return 8; case SWORD: return 15; case BOW: return 15; case ARROW: return 1; case DAGGER: return 3; case TWOSWORD: return 75; case DART: return 2; case SHIRAKEN: return 5; case SPEAR: return 5; case NWEAPONS: error("Unknown type NWEAPONS"); case NO_WEAPON: error("Unknown type NO_WEAPON"); } } string Weapon::get_description() const { stringstream buffer; string const& obj_name = Weapon::name(static_cast<Weapon::Type>(o_which)); if (o_count == 1) { buffer << "a" << vowelstr(obj_name) << " " << obj_name; } else { buffer << o_count << " " << obj_name << "s"; } if (o_which == Weapon::BOW) { buffer << " (" << get_throw_damage().sides << "d" << get_throw_damage().dices << ")"; } else if (o_type == IO::Weapon) { buffer << " (" << get_attack_damage().sides << "d" << get_attack_damage().dices << ")"; } if (identified) { buffer << " ("; int p_hit = get_hit_plus(); if (p_hit >= 0) { buffer << "+"; } buffer << p_hit << ","; int p_dmg = get_damage_plus(); if (p_dmg >= 0) { buffer << "+"; } buffer << p_dmg << ")"; } if (get_armor() != 0) { buffer << " ["; int p_armor = get_armor(); if (p_armor >= 0) { buffer << "+"; } buffer << p_armor << "]"; } if (!get_nickname().empty()) { buffer << " called " << get_nickname(); } return buffer.str(); } void weapon_missile_fall(Item* obj, bool pr) { Coordinate fpos; if (fallpos(&obj->get_position(), &fpos)) { obj->set_position(fpos); // See if we can stack it with something on the ground for (Item* ground_item : Game::level->items) { if (ground_item->get_position() == obj->get_position() && ground_item->o_type == obj->o_type && ground_item->o_which == obj->o_which && ground_item->get_hit_plus() == obj->get_hit_plus() && ground_item->get_damage_plus() == obj->get_damage_plus()) { ground_item->o_count++; delete obj; obj = nullptr; break; } } if (obj != nullptr) { Game::level->items.push_back(obj); } return; } if (pr) { stringstream os; os << "the " << Weapon::name(static_cast<Weapon::Type>(obj->o_which)) << " vanishes as it hits the ground"; Game::io->message(os.str()); } delete obj; } <|endoftext|>
<commit_before>#include "window.h" #include "game_engine_interface.h" #include <iostream> void Window::initialise (GameEngineInterface* a_engine, void* args, void* retval) { m_engine = a_engine; m_args = args; m_retval = retval; setDimensions (2, 2, 2, 2); } void Window::setDimensions (int x, int y, int width, int height) { m_xOffset = x; m_yOffset = y; m_width = width; m_height = height; getEngine()->getGraphics()->calculateWindowOffsetsFromCentre (height, width, y, x); if (m_xOffset == 0) { m_xOffset = x; } if (m_yOffset == 0) { m_yOffset = y; } } unsigned int Window::drawString (int y, int x, const char* text, Color fg, Color bg) { return getEngine()->getGraphics()->drawString (m_yOffset+y, m_xOffset+x, text, fg, bg); } void Window::drawTile (int y, int x, unsigned int tile, Color fg, Color bg) { getEngine()->getGraphics()->drawTile (m_yOffset+y, m_xOffset+x, tile, fg, bg); } void Window::drawBorder (int y, int x, int height, int width) { getEngine()->getGraphics()->drawBorder (m_yOffset+y, m_xOffset+x, height, width); } void Window::clearArea (int y, int x, int height, int width) { getEngine()->getGraphics()->clearArea (m_yOffset+y, m_xOffset+x, height, width); } void Window::beforeRedraw() { getEngine()->getGraphics()->clearArea (m_yOffset, m_xOffset, m_height, m_width); getEngine()->getGraphics()->drawBorder (m_yOffset, m_xOffset, m_height-2, m_width-2); int x, y; getEngine()->getGraphics()->calculateWindowOffsetsFromCentre (0, m_title.size(), y, x); getEngine()->getGraphics()->clearArea (m_yOffset, x, 1, m_title.size()); drawString (0, x-m_xOffset, m_title.c_str()); } void Window::afterRedraw() { } void Window::destroy (void) { } void Window::resize (int width, int height) { } void Window::mouseDown (int x, int y, int button) { if (button < MAX_BUTTONS) { m_buttons[button] = true; } } void Window::mouseUp (int x, int y, int button) { if (button < MAX_BUTTONS) { m_buttons[button] = false; } } bool Window::getMouseButton (int button) { if (button < MAX_BUTTONS) { return m_buttons[button]; } return false; } void Window::drawProgress (unsigned int x, unsigned int y, unsigned int value, unsigned int max) { float l_value = (float) value; float l_max = (float) max; Color l_color ((1.0f-(l_value/l_max)), l_value/l_max, 0); for (unsigned int xx = 0; xx < value; xx++) { drawTile (y, x+xx, 178, l_color, Color(BLACK)); } } unsigned int Window::wrapText (const std::string& text, std::vector<std::string>& lines, unsigned int maxWidth, unsigned int maxRows) { size_t wordStart = 0; size_t wordEnd = 0; unsigned int lineNum = 0; lines.resize (maxRows); while (wordEnd != std::string::npos) { wordEnd = text.find (' ', wordStart); std::string word (text.substr (wordStart, wordEnd-wordStart)); std::cout << "Word: " << word << std::endl; if (lines[lineNum].length() + word.length() + 1 > maxWidth) { if (lineNum + 1 >= maxRows) { lines[lineNum].append ("..."); return lineNum; } // Start the next line lineNum++; } lines[lineNum].append (word); lines[lineNum].append (" "); wordStart = wordEnd+1; std::cout << "Line: " << lines[lineNum] << std::endl; } return lineNum; } <commit_msg>Now end of line calculation include the ...<commit_after>#include "window.h" #include "game_engine_interface.h" #include <iostream> void Window::initialise (GameEngineInterface* a_engine, void* args, void* retval) { m_engine = a_engine; m_args = args; m_retval = retval; setDimensions (2, 2, 2, 2); } void Window::setDimensions (int x, int y, int width, int height) { m_xOffset = x; m_yOffset = y; m_width = width; m_height = height; getEngine()->getGraphics()->calculateWindowOffsetsFromCentre (height, width, y, x); if (m_xOffset == 0) { m_xOffset = x; } if (m_yOffset == 0) { m_yOffset = y; } } unsigned int Window::drawString (int y, int x, const char* text, Color fg, Color bg) { return getEngine()->getGraphics()->drawString (m_yOffset+y, m_xOffset+x, text, fg, bg); } void Window::drawTile (int y, int x, unsigned int tile, Color fg, Color bg) { getEngine()->getGraphics()->drawTile (m_yOffset+y, m_xOffset+x, tile, fg, bg); } void Window::drawBorder (int y, int x, int height, int width) { getEngine()->getGraphics()->drawBorder (m_yOffset+y, m_xOffset+x, height, width); } void Window::clearArea (int y, int x, int height, int width) { getEngine()->getGraphics()->clearArea (m_yOffset+y, m_xOffset+x, height, width); } void Window::beforeRedraw() { getEngine()->getGraphics()->clearArea (m_yOffset, m_xOffset, m_height, m_width); getEngine()->getGraphics()->drawBorder (m_yOffset, m_xOffset, m_height-2, m_width-2); int x, y; getEngine()->getGraphics()->calculateWindowOffsetsFromCentre (0, m_title.size(), y, x); getEngine()->getGraphics()->clearArea (m_yOffset, x, 1, m_title.size()); drawString (0, x-m_xOffset, m_title.c_str()); } void Window::afterRedraw() { } void Window::destroy (void) { } void Window::resize (int width, int height) { } void Window::mouseDown (int x, int y, int button) { if (button < MAX_BUTTONS) { m_buttons[button] = true; } } void Window::mouseUp (int x, int y, int button) { if (button < MAX_BUTTONS) { m_buttons[button] = false; } } bool Window::getMouseButton (int button) { if (button < MAX_BUTTONS) { return m_buttons[button]; } return false; } void Window::drawProgress (unsigned int x, unsigned int y, unsigned int value, unsigned int max) { float l_value = (float) value; float l_max = (float) max; Color l_color ((1.0f-(l_value/l_max)), l_value/l_max, 0); for (unsigned int xx = 0; xx < value; xx++) { drawTile (y, x+xx, 178, l_color, Color(BLACK)); } } unsigned int Window::wrapText (const std::string& text, std::vector<std::string>& lines, unsigned int maxWidth, unsigned int maxRows) { size_t wordStart = 0; size_t wordEnd = 0; unsigned int lineNum = 0; lines.resize (maxRows); while (wordEnd != std::string::npos) { wordEnd = text.find (' ', wordStart); std::string word (text.substr (wordStart, wordEnd-wordStart)); if (lines[lineNum].length() + word.length() + 3 /*...*/ + 2 /*spaces*/ > maxWidth && lineNum + 1 >= maxRows) { lines[lineNum].append ("..."); return lineNum; } if (lines[lineNum].length() + word.length() + 1 > maxWidth) { if (lineNum + 1 >= maxRows) { lines[lineNum].append ("..."); return lineNum; } // Start the next line lineNum++; } lines[lineNum].append (word); lines[lineNum].append (" "); wordStart = wordEnd+1; } return lineNum; } <|endoftext|>
<commit_before>#include <array> #include "core/image.h" #include "core/image_draw.h" #include "core/io.h" #include "core/identicon.h" #include "core/hashgen_retro.h" #include "core/hashgen_sprator.h" #include "core/argparse.h" #include "core/random.h" #include "core/str.h" #include "core/collage.h" #include "core/palette.h" using namespace euphoria::core; enum class HashType { Identicon, Retro, Sprator }; struct CommonArguments { int image_size = 512; int number_of_images = 10; bool use_random = true; HashType type = HashType::Identicon; explicit CommonArguments(argparse::ParserBase* base) { base->Add("--size", &image_size).Help("image size"); base->Add("--count", &number_of_images).Help("The number of images to generate"); base->SetFalse("--const", &use_random).Help("Use a constant value"); base->Add("-t", &type).Help("Set the type to use"); } }; const auto PALETTE = Palette { "", Color::Red, Color::White, Color::Blue, Color::LightGreen, Color::Yellow, Color::LightBlue, Color::Pink, Color::Orange, Color::Tan, Color::Brown, Color::Green, Color::Purple, Color::CornflowerBlue, Color::Cyan }; void RunMain ( int image_size, int number_of_images, bool use_random, HashType type, bool collage ) { if(use_random==false && number_of_images > 1) { std::cout << "Since random isn't requested: setting the number of images to 1...\n"; number_of_images = 1; } Random random; auto images = std::vector<Image>{}; Image image; image.SetupWithAlphaSupport(image_size, image_size); for(int i = 0; i < number_of_images; i += 1) { int code = -2044886870; if(use_random) { code = random.NextInteger(); } switch(type) { case HashType::Identicon: RenderIdenticon(&image, code); break; case HashType::Retro: RenderRetro(&image, code); break; case HashType::Sprator: RenderSprator(&image, code, PALETTE.GetSafeIndex(i)); break; default: DIE("Unhandled type"); break; } std::string file_name = "identicon.png"; if(collage) { images.emplace_back(image); std::cout << "Generated collage image\n"; } else { if(number_of_images > 1) { file_name = Str() << "identicon_" << (i + 1) << ".png"; std::cout << "Writing " << file_name << "\n"; } io::ChunkToFile(image.Write(ImageWriteFormat::PNG), file_name); } } if(collage) { std::cout << "writing collage...\n"; int padding = 20; auto collage_image = GridLayout(images, padding, Color::Gray, true); std::string file_name = "identicon.png"; io::ChunkToFile(collage_image.Write(ImageWriteFormat::PNG), file_name); } } void RunSpratorCollage ( int image_size, int number_of_images, int frames ) { Random random; auto sprites = std::vector<std::vector<Image>>{}; for(int image_index = 0; image_index < number_of_images; image_index += 1) { auto image_frames = std::vector<Image>{}; for(int frame_index = 0; frame_index < frames; frame_index +=1) { Image image; image.SetupWithAlphaSupport(image_size, image_size); image_frames.emplace_back(image); } const int code = random.NextInteger(); RenderSprator(&image_frames, code, PALETTE.GetSafeIndex(image_index)); sprites.emplace_back(image_frames); std::cout << "Generated collage image\n"; } const auto c = Max(frames-2, 0); const auto write_frames = c + c*2 + 1; for(int image_index = 0; image_index < write_frames; image_index +=1) { const auto frame_index = (image_index % 2 == 0) ? 0 : (image_index+1) / 2; auto images = std::vector<Image>{}; for(int image_index = 0; image_index < number_of_images; image_index += 1) { images.emplace_back(sprites[image_index][frame_index]); } std::cout << "writing collage...\n"; int padding = 20; auto collage_image = GridLayout(images, padding, Color::Gray, true); std::string file_name = "identicon.png"; if(frames > 1) { file_name = Str() << "identicon_" << image_index << ".png"; } io::ChunkToFile(collage_image.Write(ImageWriteFormat::PNG), file_name); } } int main(int argc, char* argv[]) { auto parser = argparse::Parser {"identicon test"}; auto subs = parser.AddSubParsers(); subs->Add ( "singles", "write many images", [](argparse::SubParser* sub) { auto arguments = CommonArguments{sub}; return sub->OnComplete ( [&] { RunMain ( arguments.image_size, arguments.number_of_images, arguments.use_random, arguments.type, false ); return argparse::ParseResult::Ok; } ); } ); subs->Add ( "collage", "write collage", [](argparse::SubParser* sub) { auto arguments = CommonArguments{sub}; return sub->OnComplete ( [&] { RunMain ( arguments.image_size, arguments.number_of_images, arguments.use_random, arguments.type, true ); return argparse::ParseResult::Ok; } ); } ); subs->Add ( "sprator", "write sprator collage", [](argparse::SubParser* sub) { int image_size = 100; int number_of_images = 9; int frames = 3; sub->Add("--size", &image_size).Help("Image size"); sub->Add("--images", &number_of_images).Help("the number of sprators"); sub->Add("--frames", &frames).Help("the number of anim frames"); return sub->OnComplete ( [&] { RunSpratorCollage ( image_size, number_of_images, frames ); return argparse::ParseResult::Ok; } ); } ); return argparse::ParseFromMain(&parser, argc, argv); } <commit_msg>better name that doesn't cause warning<commit_after>#include <array> #include "core/image.h" #include "core/image_draw.h" #include "core/io.h" #include "core/identicon.h" #include "core/hashgen_retro.h" #include "core/hashgen_sprator.h" #include "core/argparse.h" #include "core/random.h" #include "core/str.h" #include "core/collage.h" #include "core/palette.h" using namespace euphoria::core; enum class HashType { Identicon, Retro, Sprator }; struct CommonArguments { int image_size = 512; int number_of_images = 10; bool use_random = true; HashType type = HashType::Identicon; explicit CommonArguments(argparse::ParserBase* base) { base->Add("--size", &image_size).Help("image size"); base->Add("--count", &number_of_images).Help("The number of images to generate"); base->SetFalse("--const", &use_random).Help("Use a constant value"); base->Add("-t", &type).Help("Set the type to use"); } }; const auto PALETTE = Palette { "", Color::Red, Color::White, Color::Blue, Color::LightGreen, Color::Yellow, Color::LightBlue, Color::Pink, Color::Orange, Color::Tan, Color::Brown, Color::Green, Color::Purple, Color::CornflowerBlue, Color::Cyan }; void RunMain ( int image_size, int number_of_images, bool use_random, HashType type, bool collage ) { if(use_random==false && number_of_images > 1) { std::cout << "Since random isn't requested: setting the number of images to 1...\n"; number_of_images = 1; } Random random; auto images = std::vector<Image>{}; Image image; image.SetupWithAlphaSupport(image_size, image_size); for(int i = 0; i < number_of_images; i += 1) { int code = -2044886870; if(use_random) { code = random.NextInteger(); } switch(type) { case HashType::Identicon: RenderIdenticon(&image, code); break; case HashType::Retro: RenderRetro(&image, code); break; case HashType::Sprator: RenderSprator(&image, code, PALETTE.GetSafeIndex(i)); break; default: DIE("Unhandled type"); break; } std::string file_name = "identicon.png"; if(collage) { images.emplace_back(image); std::cout << "Generated collage image\n"; } else { if(number_of_images > 1) { file_name = Str() << "identicon_" << (i + 1) << ".png"; std::cout << "Writing " << file_name << "\n"; } io::ChunkToFile(image.Write(ImageWriteFormat::PNG), file_name); } } if(collage) { std::cout << "writing collage...\n"; int padding = 20; auto collage_image = GridLayout(images, padding, Color::Gray, true); std::string file_name = "identicon.png"; io::ChunkToFile(collage_image.Write(ImageWriteFormat::PNG), file_name); } } void RunSpratorCollage ( int image_size, int number_of_images, int frames ) { Random random; auto sprites = std::vector<std::vector<Image>>{}; for(int image_index = 0; image_index < number_of_images; image_index += 1) { auto image_frames = std::vector<Image>{}; for(int frame_index = 0; frame_index < frames; frame_index +=1) { Image image; image.SetupWithAlphaSupport(image_size, image_size); image_frames.emplace_back(image); } const int code = random.NextInteger(); RenderSprator(&image_frames, code, PALETTE.GetSafeIndex(image_index)); sprites.emplace_back(image_frames); std::cout << "Generated collage image\n"; } const auto c = Max(frames-2, 0); const auto write_frames = c + c*2 + 1; for(int anim_index = 0; anim_index < write_frames; anim_index +=1) { const auto frame_index = (anim_index % 2 == 0) ? 0 : (anim_index+1) / 2; auto images = std::vector<Image>{}; for(int image_index = 0; image_index < number_of_images; image_index += 1) { images.emplace_back(sprites[image_index][frame_index]); } std::cout << "writing collage...\n"; int padding = 20; auto collage_image = GridLayout(images, padding, Color::Gray, true); std::string file_name = "identicon.png"; if(frames > 1) { file_name = Str() << "identicon_" << anim_index << ".png"; } io::ChunkToFile(collage_image.Write(ImageWriteFormat::PNG), file_name); } } int main(int argc, char* argv[]) { auto parser = argparse::Parser {"identicon test"}; auto subs = parser.AddSubParsers(); subs->Add ( "singles", "write many images", [](argparse::SubParser* sub) { auto arguments = CommonArguments{sub}; return sub->OnComplete ( [&] { RunMain ( arguments.image_size, arguments.number_of_images, arguments.use_random, arguments.type, false ); return argparse::ParseResult::Ok; } ); } ); subs->Add ( "collage", "write collage", [](argparse::SubParser* sub) { auto arguments = CommonArguments{sub}; return sub->OnComplete ( [&] { RunMain ( arguments.image_size, arguments.number_of_images, arguments.use_random, arguments.type, true ); return argparse::ParseResult::Ok; } ); } ); subs->Add ( "sprator", "write sprator collage", [](argparse::SubParser* sub) { int image_size = 100; int number_of_images = 9; int frames = 3; sub->Add("--size", &image_size).Help("Image size"); sub->Add("--images", &number_of_images).Help("the number of sprators"); sub->Add("--frames", &frames).Help("the number of anim frames"); return sub->OnComplete ( [&] { RunSpratorCollage ( image_size, number_of_images, frames ); return argparse::ParseResult::Ok; } ); } ); return argparse::ParseFromMain(&parser, argc, argv); } <|endoftext|>
<commit_before>/****************************************************************************** * ____ ______ ____ __ __ * * /\ _`\ /\ _ \ /\ _`\ /\ \/\ \ * * \ \,\L\_\\ \ \L\ \\ \,\L\_\\ \ \_\ \ * * \/_\__ \ \ \ __ \\/_\__ \ \ \ _ \ * * /\ \L\ \\ \ \/\ \ /\ \L\ \\ \ \ \ \ * * \ `\____\\ \_\ \_\\ `\____\\ \_\ \_\ * * \/_____/ \/_/\/_/ \/_____/ \/_/\/_/ * * * * * * Copyright (c) 2014 * * Matthias Vallentin <vallentin (at) icir.org> * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the 3-clause BSD License. * * See accompanying file LICENSE. * \******************************************************************************/ #ifndef SASH_VARIABLES_ENGINE_HPP #define SASH_VARIABLES_ENGINE_HPP #include <map> #include <string> #include <iterator> #include <algorithm> namespace sash { /// An example implementation for a variables engine that is /// convertible to a std::function object. template<typename Container = std::map<std::string, std::string>> class variables_engine { public: /// The type of a std::function wrapper. using functor = std::function<void (std::string&, const std::string&, std::string&)>; /// Parses an input line and replaces all variables in the output. void parse(std::string& err, const std::string& in, std::string& out, bool sub_parse = false) { auto valid_varname_char = [](char c) { return std::isalnum(c) || c == '_'; }; using iter = typename std::string::const_iterator; char c = '\0'; // current character char lastc = ' '; // the last character, needed to distinct "$" from "\$" iter pos = in.begin(); // our current position in the stream iter last = in.end(); enum { // traversing input, copying characters as we go traverse, // just read a $ indicating the start of a variable name after_dollar_sign, // read a variable name in the form of $name read_variable, // read a variable name in the form of ${name} read_braced_variable } state = traverse; auto i = in.begin(); raii_error_string scoped_err{err}; auto set_error = [&]() -> std::ostream& { return scoped_err.oss << "syntax error at position " << std::to_string(std::distance(in.begin(), i)) << ": "; }; auto flush = [&]() -> bool { switch (state) { case traverse: if (pos != last) out.insert(out.end(), pos, i); return true; case after_dollar_sign: if (i == last) { set_error() << "$ at end of line"; } else if (*i == '$') { set_error() << "$$ is not a valid expression"; } else { set_error() << "unexpected character '" << *i << "' after $"; } out.clear(); return false; // pos is always set to the first character of the variable name, // i is always set to the first character that's not part of it case read_braced_variable: if (! valid_varname_char(c) && c != '}') { set_error() << "'" << c << "' is an invalid character inside ${...}"; return false; } // else:: fall through case read_variable: std::string varname(pos, i); auto j = variables_.find(varname); out += j == variables_.end() ? "" : j->second; state = traverse; if (state == read_braced_variable) pos = i + 1; else pos = i; return true; } return false; // should be unreachable }; while (i != last) { c = *i; switch (c) { case '=': // assignment lines are parsed as '([a-zA-Z0-9_]+)=(.+)' => check if (! sub_parse && i != pos && pos == in.begin() && std::all_of(pos, i, valid_varname_char)) { std::string key(pos, i); std::string val_input(i + 1, in.end()); std::string value; // assignments don't produce an output out.clear(); // our value can in turn have variables parse(err, val_input, value, true); if (err.empty()) variables_.emplace(std::move(key), std::move(value)); return; } break; case '$': if (lastc == '\\') break; // write previous input if (! flush()) return; state = after_dollar_sign; pos = i + 1; break; case '{': if (state == after_dollar_sign) { pos = i + 1; // '{' is not part of the variable name state = read_braced_variable; } break; case '}': if (state == read_braced_variable) { if (! flush()) return; pos = i + 1; // '}' won't be part of the output break; } // else: fall through default: if (! valid_varname_char(c) && state != traverse) { if (! flush()) return; } else if (state == after_dollar_sign) { pos = i; state = read_variable; } break; } lastc = c; ++i; } if (state == read_braced_variable) { err = "syntax error: missing '}' at end of line"; } flush(); } /// Factory function to create a std::function using this implementation. /// @param predef A set of predefined variables to initialize the engine. static functor create(Container predef = Container{}) { auto ptr = std::make_shared<variables_engine>(); ptr->variables_ = std::move(predef); return [ptr](std::string& err, const std::string& in, std::string& out) { ptr->parse(err, in, out); }; } private: struct raii_error_string { raii_error_string(std::string& ref) : err(ref) { // nop } ~raii_error_string() { // leave err untouched if no error occured auto str = oss.str(); if (! str.empty()) err = std::move(str); } std::ostringstream oss; std::string& err; }; Container variables_; }; } // namespace sash #endif // SASH_VARIABLES_ENGINE_HPP <commit_msg>Allow setting/unsetting of variables directly<commit_after>/****************************************************************************** * ____ ______ ____ __ __ * * /\ _`\ /\ _ \ /\ _`\ /\ \/\ \ * * \ \,\L\_\\ \ \L\ \\ \,\L\_\\ \ \_\ \ * * \/_\__ \ \ \ __ \\/_\__ \ \ \ _ \ * * /\ \L\ \\ \ \/\ \ /\ \L\ \\ \ \ \ \ * * \ `\____\\ \_\ \_\\ `\____\\ \_\ \_\ * * \/_____/ \/_/\/_/ \/_____/ \/_/\/_/ * * * * * * Copyright (c) 2014 * * Matthias Vallentin <vallentin (at) icir.org> * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the 3-clause BSD License. * * See accompanying file LICENSE. * \******************************************************************************/ #ifndef SASH_VARIABLES_ENGINE_HPP #define SASH_VARIABLES_ENGINE_HPP #include <map> #include <string> #include <iterator> #include <algorithm> namespace sash { /// An example implementation for a variables engine that is /// convertible to a std::function object. template<typename Container = std::map<std::string, std::string>> class variables_engine { public: /// The type of a std::function wrapper. using functor = std::function<void (std::string&, const std::string&, std::string&)>; /// Parses an input line and replaces all variables in the output. void parse(std::string& err, const std::string& in, std::string& out, bool sub_parse = false) { auto valid_varname_char = [](char c) { return std::isalnum(c) || c == '_'; }; using iter = typename std::string::const_iterator; char c = '\0'; // current character char lastc = ' '; // the last character, needed to distinct "$" from "\$" iter pos = in.begin(); // our current position in the stream iter last = in.end(); enum { // traversing input, copying characters as we go traverse, // just read a $ indicating the start of a variable name after_dollar_sign, // read a variable name in the form of $name read_variable, // read a variable name in the form of ${name} read_braced_variable } state = traverse; auto i = in.begin(); raii_error_string scoped_err{err}; auto set_error = [&]() -> std::ostream& { return scoped_err.oss << "syntax error at position " << std::to_string(std::distance(in.begin(), i)) << ": "; }; auto flush = [&]() -> bool { switch (state) { case traverse: if (pos != last) out.insert(out.end(), pos, i); return true; case after_dollar_sign: if (i == last) { set_error() << "$ at end of line"; } else if (*i == '$') { set_error() << "$$ is not a valid expression"; } else { set_error() << "unexpected character '" << *i << "' after $"; } out.clear(); return false; // pos is always set to the first character of the variable name, // i is always set to the first character that's not part of it case read_braced_variable: if (! valid_varname_char(c) && c != '}') { set_error() << "'" << c << "' is an invalid character inside ${...}"; return false; } // else:: fall through case read_variable: std::string varname(pos, i); auto j = variables_.find(varname); out += j == variables_.end() ? "" : j->second; state = traverse; if (state == read_braced_variable) pos = i + 1; else pos = i; return true; } return false; // should be unreachable }; while (i != last) { c = *i; switch (c) { case '=': // assignment lines are parsed as '([a-zA-Z0-9_]+)=(.+)' => check if (! sub_parse && i != pos && pos == in.begin() && std::all_of(pos, i, valid_varname_char)) { std::string key(pos, i); std::string val_input(i + 1, in.end()); std::string value; // assignments don't produce an output out.clear(); // our value can in turn have variables parse(err, val_input, value, true); if (err.empty()) variables_.emplace(std::move(key), std::move(value)); return; } break; case '$': if (lastc == '\\') break; // write previous input if (! flush()) return; state = after_dollar_sign; pos = i + 1; break; case '{': if (state == after_dollar_sign) { pos = i + 1; // '{' is not part of the variable name state = read_braced_variable; } break; case '}': if (state == read_braced_variable) { if (! flush()) return; pos = i + 1; // '}' won't be part of the output break; } // else: fall through default: if (! valid_varname_char(c) && state != traverse) { if (! flush()) return; } else if (state == after_dollar_sign) { pos = i; state = read_variable; } break; } lastc = c; ++i; } if (state == read_braced_variable) { err = "syntax error: missing '}' at end of line"; } flush(); } /// Sets a variable to given value. void set(const std::string& identifier, std::string value) { variables_[identifier] = std::move(value); } /// Unsets a variable. void unset(const std::string& identifier) { variables_.erase(identifier); } /// Factory function to create a std::function using this implementation. /// @param predef A set of predefined variables to initialize the engine. static functor create(Container predef = Container{}) { auto ptr = std::make_shared<variables_engine>(); ptr->variables_ = std::move(predef); return [ptr](std::string& err, const std::string& in, std::string& out) { ptr->parse(err, in, out); }; } private: struct raii_error_string { raii_error_string(std::string& ref) : err(ref) { // nop } ~raii_error_string() { // leave err untouched if no error occured auto str = oss.str(); if (! str.empty()) err = std::move(str); } std::ostringstream oss; std::string& err; }; Container variables_; }; } // namespace sash #endif // SASH_VARIABLES_ENGINE_HPP <|endoftext|>
<commit_before>/* * Copyright (C) 2015 deipi.com LLC and contributors. 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 "xapiand.h" #include "utils.h" #include "manager.h" #include <stdlib.h> XapiandManager *manager_ptr = NULL; static void sig_shutdown_handler(int sig) { if (manager_ptr) { manager_ptr->sig_shutdown_handler(sig); } } void setup_signal_handlers(void) { signal(SIGHUP, SIG_IGN); signal(SIGPIPE, SIG_IGN); struct sigaction act; /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used. * Otherwise, sa_handler is used. */ sigemptyset(&act.sa_mask); act.sa_flags = 0; act.sa_handler = sig_shutdown_handler; sigaction(SIGTERM, &act, NULL); sigaction(SIGINT, &act, NULL); } void run(int num_servers, const char *cluster_name_, const char *discovery_group, int discovery_port, int http_port, int binary_port) { ev::default_loop default_loop; setup_signal_handlers(); XapiandManager manager(&default_loop, cluster_name_, discovery_group, discovery_port, http_port, binary_port); manager_ptr = &manager; manager.run(num_servers); manager_ptr = NULL; } int main(int argc, char **argv) { int num_servers = 8; int discovery_port = 0; int http_port = 0; int binary_port = 0; const char *discovery_group = NULL; const char *cluster_name = "xapiand"; const char *p; INFO((void *)NULL, "\n\n" " __ __ _ _\n" " \\ \\/ /__ _ _ __ (_) __ _ _ __ __| |\n" " \\ // _` | '_ \\| |/ _` | '_ \\ / _` |\n" " / \\ (_| | |_) | | (_| | | | | (_| |\n" " /_/\\_\\__,_| .__/|_|\\__,_|_| |_|\\__,_|\n" " |_| v%s\n" " [%s]\n" " Using Xapian v%s\n\n", PACKAGE_VERSION, PACKAGE_BUGREPORT, XAPIAN_VERSION); INFO((void *)NULL, "Joined cluster: %s\n", cluster_name); // Prefer glass database if (setenv("XAPIAN_PREFER_GLASS", "1", false) == 0) { INFO((void *)NULL, "Enabled glass database.\n"); } // Enable changesets if (setenv("XAPIAN_MAX_CHANGESETS", "10", false) == 0) { INFO((void *)NULL, "Database changesets set to 10.\n"); } // Flush threshold increased int flush_threshold = 10000; // Default is 10000 (if no set) p = getenv("XAPIAN_FLUSH_THRESHOLD"); if (p) flush_threshold = atoi(p); if (flush_threshold < 100000 && setenv("XAPIAN_FLUSH_THRESHOLD", "100000", false) == 0) { INFO((void *)NULL, "Increased flush threshold to 100000 (it was originally set to %d).\n", flush_threshold); } time(&init_time); struct tm *timeinfo = localtime(&init_time); timeinfo->tm_hour = 0; timeinfo->tm_min = 0; timeinfo->tm_sec = 0; int diff_t = (int)(init_time - mktime(timeinfo)); b_time.minute = diff_t / SLOT_TIME_SECOND; b_time.second = diff_t % SLOT_TIME_SECOND; if (argc > 2) { http_port = atoi(argv[1]); binary_port = atoi(argv[2]); } run(num_servers, cluster_name, discovery_group, discovery_port, http_port, binary_port); INFO((void *)NULL, "Done with all work!\n"); return 0; } <commit_msg>Added BRASS support with XAPIAN_PREFER_BRASS<commit_after>/* * Copyright (C) 2015 deipi.com LLC and contributors. 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 "xapiand.h" #include "utils.h" #include "manager.h" #include <stdlib.h> XapiandManager *manager_ptr = NULL; static void sig_shutdown_handler(int sig) { if (manager_ptr) { manager_ptr->sig_shutdown_handler(sig); } } void setup_signal_handlers(void) { signal(SIGHUP, SIG_IGN); signal(SIGPIPE, SIG_IGN); struct sigaction act; /* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used. * Otherwise, sa_handler is used. */ sigemptyset(&act.sa_mask); act.sa_flags = 0; act.sa_handler = sig_shutdown_handler; sigaction(SIGTERM, &act, NULL); sigaction(SIGINT, &act, NULL); } void run(int num_servers, const char *cluster_name_, const char *discovery_group, int discovery_port, int http_port, int binary_port) { ev::default_loop default_loop; setup_signal_handlers(); XapiandManager manager(&default_loop, cluster_name_, discovery_group, discovery_port, http_port, binary_port); manager_ptr = &manager; manager.run(num_servers); manager_ptr = NULL; } int main(int argc, char **argv) { int num_servers = 8; int discovery_port = 0; int http_port = 0; int binary_port = 0; const char *discovery_group = NULL; const char *cluster_name = "xapiand"; const char *p; INFO((void *)NULL, "\n\n" " __ __ _ _\n" " \\ \\/ /__ _ _ __ (_) __ _ _ __ __| |\n" " \\ // _` | '_ \\| |/ _` | '_ \\ / _` |\n" " / \\ (_| | |_) | | (_| | | | | (_| |\n" " /_/\\_\\__,_| .__/|_|\\__,_|_| |_|\\__,_|\n" " |_| v%s\n" " [%s]\n" " Using Xapian v%s\n\n", PACKAGE_VERSION, PACKAGE_BUGREPORT, XAPIAN_VERSION); INFO((void *)NULL, "Joined cluster: %s\n", cluster_name); #ifdef XAPIAN_HAS_GLASS_BACKEND // Prefer glass database if (setenv("XAPIAN_PREFER_GLASS", "1", false) == 0) { INFO((void *)NULL, "Enabled glass database.\n"); } #elif XAPIAN_HAS_BRASS_BACKEND // Prefer brass database if (setenv("XAPIAN_PREFER_BRASS", "1", false) == 0) { INFO((void *)NULL, "Enabled brass database.\n"); } #endif // Enable changesets if (setenv("XAPIAN_MAX_CHANGESETS", "10", false) == 0) { INFO((void *)NULL, "Database changesets set to 10.\n"); } // Flush threshold increased int flush_threshold = 10000; // Default is 10000 (if no set) p = getenv("XAPIAN_FLUSH_THRESHOLD"); if (p) flush_threshold = atoi(p); if (flush_threshold < 100000 && setenv("XAPIAN_FLUSH_THRESHOLD", "100000", false) == 0) { INFO((void *)NULL, "Increased flush threshold to 100000 (it was originally set to %d).\n", flush_threshold); } time(&init_time); struct tm *timeinfo = localtime(&init_time); timeinfo->tm_hour = 0; timeinfo->tm_min = 0; timeinfo->tm_sec = 0; int diff_t = (int)(init_time - mktime(timeinfo)); b_time.minute = diff_t / SLOT_TIME_SECOND; b_time.second = diff_t % SLOT_TIME_SECOND; if (argc > 2) { http_port = atoi(argv[1]); binary_port = atoi(argv[2]); } run(num_servers, cluster_name, discovery_group, discovery_port, http_port, binary_port); INFO((void *)NULL, "Done with all work!\n"); return 0; } <|endoftext|>
<commit_before> #include <iostream> #include <fstream> #include <iterator> #include <steve/Language.hpp> #include <steve/Lexer.hpp> #include <steve/Parser.hpp> #include <steve/Elaborator.hpp> using namespace steve; int main() { Language lang; // Read the input text into a file. using Iter = std::istreambuf_iterator<char>; std::string text(Iter(std::cin), Iter()); Lexer lex; Tokens toks = lex(text); for (const Token& k : toks) std::cout << debug(k) << ' '; std::cout << '\n'; return 0; Parser parse; Tree* pt = parse(toks); if (not parse.diags.empty()) { std::cerr << "got errors\n" << parse.diags; return -1; } Elaborator elab; Expr* ast = elab(pt); if (not elab.diags.empty()) { std::cerr << "got typing errors\n" << elab.diags; return -1; } std::cout << debug(ast) << '\n'; } <commit_msg>Comment out token printing.<commit_after> #include <iostream> #include <fstream> #include <iterator> #include <steve/Language.hpp> #include <steve/Lexer.hpp> #include <steve/Parser.hpp> #include <steve/Elaborator.hpp> using namespace steve; int main() { Language lang; // Read the input text into a file. using Iter = std::istreambuf_iterator<char>; std::string text(Iter(std::cin), Iter()); Lexer lex; Tokens toks = lex(text); // for (const Token& k : toks) // std::cout << debug(k) << ' '; // std::cout << '\n'; // return 0; Parser parse; Tree* pt = parse(toks); if (not parse.diags.empty()) { std::cerr << "got errors\n" << parse.diags; return -1; } Elaborator elab; Expr* ast = elab(pt); if (not elab.diags.empty()) { std::cerr << "got typing errors\n" << elab.diags; return -1; } std::cout << debug(ast) << '\n'; } <|endoftext|>
<commit_before>/* * article.cpp * * Copyright (c) 2001, 2002, 2003, 2004 Frerich Raabe <raabe@kde.org> * * 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. For licensing and distribution details, check the * accompanying file 'COPYING'. */ #include "article.h" #include "tools_p.h" #include <kdebug.h> #include <krfcdate.h> #include <kurl.h> #include <kurllabel.h> #include <kmdcodec.h> #include <qdatetime.h> #include <qdom.h> using namespace RSS; namespace RSS { KMD5 md5Machine; } struct Article::Private : public Shared { QString title; KURL link; QString description; QDateTime pubDate; QString guid; bool guidIsPermaLink; MetaInfoMap meta; KURL commentsLink; int numComments; }; Article::Article() : d(new Private) { } Article::Article(const Article &other) : d(0) { *this = other; } Article::Article(const QDomNode &node, Format format) : d(new Private) { QString elemText; d->numComments=0; if (!(elemText = extractNode(node, QString::fromLatin1("title"))).isNull()) d->title = elemText; if (format==AtomFeed) { QDomNode n; for (n = node.firstChild(); !n.isNull(); n = n.nextSibling()) { const QDomElement e = n.toElement(); if ( (e.tagName()==QString::fromLatin1("link")) && (e.attribute(QString::fromLatin1("rel"))==QString::fromLatin1("alternate"))) { d->link=n.toElement().attribute(QString::fromLatin1("href")); break; } } } else { if (!(elemText = extractNode(node, QString::fromLatin1("link"))).isNull()) d->link = elemText; } // prefer content/content:encoded over summary/description for feeds that provide it QString tagName=(format==AtomFeed)? QString::fromLatin1("content"): QString::fromLatin1("content:encoded"); if (!(elemText = extractNode(node, tagName, false)).isNull()) d->description = elemText; if (d->description.isEmpty()) { if (!(elemText = extractNode(node, QString::fromLatin1("body"), false)).isNull()) d->description = elemText; if (d->description.isEmpty()) // 3rd try: see http://www.intertwingly.net/blog/1299.html { if (!(elemText = extractNode(node, QString::fromLatin1((format==AtomFeed)? "summary" : "description"), false)).isNull()) d->description = elemText; } } if (!(elemText = extractNode(node, QString::fromLatin1((format==AtomFeed)? "created": "pubDate"))).isNull()) { time_t _time; if (format==AtomFeed) _time = parseISO8601Date(elemText); else _time = KRFCDate::parseDate(elemText); // 0 means invalid, not epoch (it returns epoch+1 when it parsed epoch, see the KRFCDate::parseDate() docs) if (_time != 0) d->pubDate.setTime_t(_time); } if (!(elemText = extractNode(node, QString::fromLatin1("dc:date"))).isNull()) { time_t _time = parseISO8601Date(elemText); // 0 means invalid, not epoch (it returns epoch+1 when it parsed epoch, see the KRFCDate::parseDate() docs) if (_time != 0) d->pubDate.setTime_t(_time); } if (!(elemText = extractNode(node, QString::fromLatin1("wfw:comment"))).isNull()) { d->commentsLink = elemText; } if (!(elemText = extractNode(node, QString::fromLatin1("slash:comments"))).isNull()) { d->numComments = elemText.toInt(); } QDomElement element = QDomNode(node).toElement(); // in RSS 1.0, we use <item about> attribute as ID // FIXME: pass format version instead of checking for attribute if (!element.isNull() && element.hasAttribute(QString::fromLatin1("rdf:about"))) { d->guid = element.attribute(QString::fromLatin1("rdf:about")); // HACK: using ns properly did not work d->guidIsPermaLink = false; } else { tagName=(format==AtomFeed)? QString::fromLatin1("id"): QString::fromLatin1("guid"); QDomNode n = node.namedItem(tagName); if (!n.isNull()) { d->guidIsPermaLink = (format==AtomFeed)? false : true; if (n.toElement().attribute(QString::fromLatin1("isPermaLink"), "true") == "false") d->guidIsPermaLink = false; if (!(elemText = extractNode(node, tagName)).isNull()) d->guid = elemText; } } if(d->guid.isEmpty()) { d->guidIsPermaLink = false; md5Machine.reset(); QDomNode n(node); md5Machine.update(d->title.utf8()); md5Machine.update(d->description.utf8()); d->guid = QString(md5Machine.hexDigest().data()); d->meta[QString::fromLatin1("guidIsHash")] = QString::fromLatin1("true"); } for (QDomNode i = node.firstChild(); !i.isNull(); i = i.nextSibling()) { if (i.isElement() && i.toElement().tagName() == QString::fromLatin1("metaInfo:meta")) { QString type = i.toElement().attribute(QString::fromLatin1("type")); d->meta[type] = i.toElement().text(); } } } Article::~Article() { if (d->deref()) delete d; } QString Article::title() const { return d->title; } const KURL &Article::link() const { return d->link; } QString Article::description() const { return d->description; } QString Article::guid() const { return d->guid; } bool Article::guidIsPermaLink() const { return d->guidIsPermaLink; } const QDateTime &Article::pubDate() const { return d->pubDate; } const KURL &Article::commentsLink() const { return d->commentsLink; } int Article::comments() const { return d->numComments; } QString Article::meta(const QString &key) const { return d->meta[key]; } KURLLabel *Article::widget(QWidget *parent, const char *name) const { KURLLabel *label = new KURLLabel(d->link.url(), d->title, parent, name); label->setUseTips(true); if (!d->description.isNull()) label->setTipText(d->description); return label; } Article &Article::operator=(const Article &other) { if (this != &other) { other.d->ref(); if (d && d->deref()) delete d; d = other.d; } return *this; } bool Article::operator==(const Article &other) const { return d->guid == other.guid(); } // vim:noet:ts=4 <commit_msg>backport: Atom: use <issued> instead of <created> for pubdates CCBUG: 97874<commit_after>/* * article.cpp * * Copyright (c) 2001, 2002, 2003, 2004 Frerich Raabe <raabe@kde.org> * * 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. For licensing and distribution details, check the * accompanying file 'COPYING'. */ #include "article.h" #include "tools_p.h" #include <kdebug.h> #include <krfcdate.h> #include <kurl.h> #include <kurllabel.h> #include <kmdcodec.h> #include <qdatetime.h> #include <qdom.h> using namespace RSS; namespace RSS { KMD5 md5Machine; } struct Article::Private : public Shared { QString title; KURL link; QString description; QDateTime pubDate; QString guid; bool guidIsPermaLink; MetaInfoMap meta; KURL commentsLink; int numComments; }; Article::Article() : d(new Private) { } Article::Article(const Article &other) : d(0) { *this = other; } Article::Article(const QDomNode &node, Format format) : d(new Private) { QString elemText; d->numComments=0; if (!(elemText = extractNode(node, QString::fromLatin1("title"))).isNull()) d->title = elemText; if (format==AtomFeed) { QDomNode n; for (n = node.firstChild(); !n.isNull(); n = n.nextSibling()) { const QDomElement e = n.toElement(); if ( (e.tagName()==QString::fromLatin1("link")) && (e.attribute(QString::fromLatin1("rel"))==QString::fromLatin1("alternate"))) { d->link=n.toElement().attribute(QString::fromLatin1("href")); break; } } } else { if (!(elemText = extractNode(node, QString::fromLatin1("link"))).isNull()) d->link = elemText; } // prefer content/content:encoded over summary/description for feeds that provide it QString tagName=(format==AtomFeed)? QString::fromLatin1("content"): QString::fromLatin1("content:encoded"); if (!(elemText = extractNode(node, tagName, false)).isNull()) d->description = elemText; if (d->description.isEmpty()) { if (!(elemText = extractNode(node, QString::fromLatin1("body"), false)).isNull()) d->description = elemText; if (d->description.isEmpty()) // 3rd try: see http://www.intertwingly.net/blog/1299.html { if (!(elemText = extractNode(node, QString::fromLatin1((format==AtomFeed)? "summary" : "description"), false)).isNull()) d->description = elemText; } } time_t time = 0; if (format == AtomFeed) { elemText = extractNode(node, QString::fromLatin1("issued")); if (!elemText.isNull()) time = parseISO8601Date(elemText); } else { elemText = extractNode(node, QString::fromLatin1("pubDate")); if (!elemText.isNull()) time = KRFCDate::parseDate(elemText); } if (!(elemText = extractNode(node, QString::fromLatin1("dc:date"))).isNull()) { time = parseISO8601Date(elemText); } // 0 means invalid, not epoch (parsers return epoch+1 when parsing epoch, see the KRFCDate::parseDate() docs) if (time != 0) d->pubDate.setTime_t(time); if (!(elemText = extractNode(node, QString::fromLatin1("wfw:comment"))).isNull()) { d->commentsLink = elemText; } if (!(elemText = extractNode(node, QString::fromLatin1("slash:comments"))).isNull()) { d->numComments = elemText.toInt(); } QDomElement element = QDomNode(node).toElement(); // in RSS 1.0, we use <item about> attribute as ID // FIXME: pass format version instead of checking for attribute if (!element.isNull() && element.hasAttribute(QString::fromLatin1("rdf:about"))) { d->guid = element.attribute(QString::fromLatin1("rdf:about")); // HACK: using ns properly did not work d->guidIsPermaLink = false; } else { tagName=(format==AtomFeed)? QString::fromLatin1("id"): QString::fromLatin1("guid"); QDomNode n = node.namedItem(tagName); if (!n.isNull()) { d->guidIsPermaLink = (format==AtomFeed)? false : true; if (n.toElement().attribute(QString::fromLatin1("isPermaLink"), "true") == "false") d->guidIsPermaLink = false; if (!(elemText = extractNode(node, tagName)).isNull()) d->guid = elemText; } } if(d->guid.isEmpty()) { d->guidIsPermaLink = false; md5Machine.reset(); QDomNode n(node); md5Machine.update(d->title.utf8()); md5Machine.update(d->description.utf8()); d->guid = QString(md5Machine.hexDigest().data()); d->meta[QString::fromLatin1("guidIsHash")] = QString::fromLatin1("true"); } for (QDomNode i = node.firstChild(); !i.isNull(); i = i.nextSibling()) { if (i.isElement() && i.toElement().tagName() == QString::fromLatin1("metaInfo:meta")) { QString type = i.toElement().attribute(QString::fromLatin1("type")); d->meta[type] = i.toElement().text(); } } } Article::~Article() { if (d->deref()) delete d; } QString Article::title() const { return d->title; } const KURL &Article::link() const { return d->link; } QString Article::description() const { return d->description; } QString Article::guid() const { return d->guid; } bool Article::guidIsPermaLink() const { return d->guidIsPermaLink; } const QDateTime &Article::pubDate() const { return d->pubDate; } const KURL &Article::commentsLink() const { return d->commentsLink; } int Article::comments() const { return d->numComments; } QString Article::meta(const QString &key) const { return d->meta[key]; } KURLLabel *Article::widget(QWidget *parent, const char *name) const { KURLLabel *label = new KURLLabel(d->link.url(), d->title, parent, name); label->setUseTips(true); if (!d->description.isNull()) label->setTipText(d->description); return label; } Article &Article::operator=(const Article &other) { if (this != &other) { other.d->ref(); if (d && d->deref()) delete d; d = other.d; } return *this; } bool Article::operator==(const Article &other) const { return d->guid == other.guid(); } // vim:noet:ts=4 <|endoftext|>
<commit_before>#ifndef AMGCL_PRECONDITIONER_CPR_HPP #define AMGCL_PRECONDITIONER_CPR_HPP /* The MIT License Copyright (c) 2012-2016 Denis Demidov <dennis.demidov@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file amgcl/preconditioner/cpr.hpp * \author Denis Demidov <dennis.demidov@gmail.com> * \brief Two stage preconditioner of the Constrained Pressure Residual type. */ #include <vector> #include <boost/shared_ptr.hpp> #include <amgcl/backend/builtin.hpp> #include <amgcl/util.hpp> namespace amgcl { namespace preconditioner { template <class PPrecond, class SPrecond> class cpr_drs { BOOST_STATIC_ASSERT_MSG( ( boost::is_same< typename PPrecond::backend_type, typename SPrecond::backend_type >::value ), "Backends for pressure and flow preconditioners should coinside!" ); public: typedef typename PPrecond::backend_type backend_type; typedef typename backend_type::value_type value_type; typedef typename backend_type::matrix matrix; typedef typename backend_type::vector vector; typedef typename backend_type::params backend_params; typedef typename backend::builtin<value_type>::matrix build_matrix; struct params { typedef typename PPrecond::params pprecond_params; typedef typename SPrecond::params sprecond_params; pprecond_params pprecond; sprecond_params sprecond; int block_size; size_t active_rows; double eps_dd; double eps_ps; params() : block_size(2), active_rows(0), eps_dd(0.2), eps_ps(0.02) {} params(const boost::property_tree::ptree &p) : AMGCL_PARAMS_IMPORT_CHILD(p, pprecond), AMGCL_PARAMS_IMPORT_CHILD(p, sprecond), AMGCL_PARAMS_IMPORT_VALUE(p, block_size), AMGCL_PARAMS_IMPORT_VALUE(p, active_rows), AMGCL_PARAMS_IMPORT_VALUE(p, eps_dd), AMGCL_PARAMS_IMPORT_VALUE(p, eps_ps) { } void get(boost::property_tree::ptree &p, const std::string &path = "") const { AMGCL_PARAMS_EXPORT_CHILD(p, path, pprecond); AMGCL_PARAMS_EXPORT_CHILD(p, path, sprecond); AMGCL_PARAMS_EXPORT_VALUE(p, path, block_size); AMGCL_PARAMS_EXPORT_VALUE(p, path, active_rows); AMGCL_PARAMS_EXPORT_VALUE(p, path, eps_dd); AMGCL_PARAMS_EXPORT_VALUE(p, path, eps_ps); } } prm; template <class Matrix> cpr_drs( const Matrix &K, const params &prm = params(), const backend_params &bprm = backend_params() ) : prm(prm), n(backend::rows(K)) { init(boost::make_shared<build_matrix>(K), bprm); } cpr_drs( boost::shared_ptr<build_matrix> K, const params &prm = params(), const backend_params bprm = backend_params() ) : prm(prm), n(backend::rows(*K)) { init(K, bprm); } template <class Vec1, class Vec2> void apply( const Vec1 &rhs, #ifdef BOOST_NO_CXX11_RVALUE_REFERENCES Vec2 &x #else Vec2 &&x #endif ) const { S->apply(rhs, x); backend::residual(rhs, S->system_matrix(), x, *rs); backend::spmv(1, *Fpp, *rs, 0, *rp); P->apply(*rp, *xp); backend::spmv(1, *Scatter, *xp, 1, x); } const matrix& system_matrix() const { return S->system_matrix(); } private: size_t n, np; boost::shared_ptr<PPrecond> P; boost::shared_ptr<SPrecond> S; boost::shared_ptr<matrix> Fpp, Scatter; boost::shared_ptr<vector> rp, xp, rs; void init(boost::shared_ptr<build_matrix> K, const backend_params bprm) { typedef typename backend::row_iterator<build_matrix>::type row_iterator; const int B = prm.block_size; const ptrdiff_t N = (prm.active_rows ? prm.active_rows : n); np = N / B; boost::shared_ptr<build_matrix> fpp = boost::make_shared<build_matrix>(); fpp->nrows = np; fpp->ncols = n; fpp->col.resize(n); fpp->val.resize(n, 1); fpp->ptr.resize(np+1); fpp->ptr[0] = 0; boost::shared_ptr<build_matrix> App = boost::make_shared<build_matrix>(); App->nrows = App->ncols = np; App->ptr.resize(np+1, 0); #pragma omp parallel { std::vector<value_type> a_dia(B), a_off(B), a_top(B); std::vector<row_iterator> k; k.reserve(B); #pragma omp for for(ptrdiff_t ip = 0; ip < static_cast<ptrdiff_t>(np); ++ip) { ptrdiff_t ik = ip * B; bool done = true; ptrdiff_t cur_col; boost::fill(a_dia, 0); boost::fill(a_off, 0); boost::fill(a_top, 0); k.clear(); for(int i = 0; i < B; ++i) { k.push_back(backend::row_begin(*K, ik + i)); if (k.back() && k.back().col() < N) { ptrdiff_t col = k.back().col() / B; if (done) { cur_col = col; done = false; } else { cur_col = std::min(cur_col, col); } } } while (!done) { ++App->ptr[ip+1]; ptrdiff_t end = (cur_col + 1) * B; for(int i = 0; i < B; ++i) { for(; k[i] && k[i].col() < end; ++k[i]) { ptrdiff_t c = k[i].col() % B; value_type v = k[i].value(); if (i == 0) { a_top[c] += std::abs(v); } if (c == 0) { if (cur_col == ip) { a_dia[i] = v; } else { a_off[i] += std::abs(v); } } } } // Get next column number. done = true; for(int i = 0; i < B; ++i) { if (k[i] && k[i].col() < N) { ptrdiff_t col = k[i].col() / B; if (done) { cur_col = col; done = false; } else { cur_col = std::min(cur_col, col); } } } } for(int i = 0; i < B; ++i) { fpp->col[ik+i] = ik+i; if (a_dia[i] < prm.eps_dd * a_off[i]) fpp->val[ik+i] = 0; if (a_top[i] < prm.eps_ps * std::abs(a_dia[0])) fpp->val[ik+i] = 0; } fpp->val[ik] = 1; // Keep delta[0] = 1 fpp->ptr[ip+1] = ik + B; } } boost::partial_sum(App->ptr, App->ptr.begin()); App->col.resize(App->ptr.back()); App->val.resize(App->ptr.back()); boost::shared_ptr<build_matrix> scatter = boost::make_shared<build_matrix>(); scatter->nrows = n; scatter->ncols = np; scatter->ptr.resize(n+1); scatter->ptr[0] = 0; scatter->col.resize(np); scatter->val.resize(np, 1); #pragma omp parallel { std::vector<row_iterator> k; k.reserve(B); #pragma omp for for(ptrdiff_t ip = 0; ip < static_cast<ptrdiff_t>(np); ++ip) { ptrdiff_t ik = ip * B; ptrdiff_t head = App->ptr[ip]; bool done = true; ptrdiff_t cur_col; value_type *d = &fpp->val[ik]; k.clear(); for(int i = 0; i < B; ++i) { k.push_back(backend::row_begin(*K, ik + i)); if (k.back() && k.back().col() < N) { ptrdiff_t col = k.back().col() / B; if (done) { cur_col = col; done = false; } else { cur_col = std::min(cur_col, col); } } } while (!done) { ptrdiff_t end = (cur_col + 1) * B; value_type app = 0; for(int i = 0; i < B; ++i) { for(; k[i] && k[i].col() < end; ++k[i]) { if (k[i].col() % B == 0) { app += d[i] * k[i].value(); } } } App->col[head] = cur_col; App->val[head] = app; ++head; // Get next column number. done = true; for(int i = 0; i < B; ++i) { if (k[i] && k[i].col() < N) { ptrdiff_t col = k[i].col() / B; if (done) { cur_col = col; done = false; } else { cur_col = std::min(cur_col, col); } } } } scatter->col[ip] = ip; ptrdiff_t nnz = ip; for(int i = 0; i < B; ++i) { if (i == 0) ++nnz; scatter->ptr[ik + i + 1] = nnz; } } } for(size_t i = N; i < n; ++i) scatter->ptr[i+1] = scatter->ptr[i]; P = boost::make_shared<PPrecond>(App, prm.pprecond, bprm); S = boost::make_shared<SPrecond>(K, prm.sprecond, bprm); Fpp = backend_type::copy_matrix(fpp, bprm); Scatter = backend_type::copy_matrix(scatter, bprm); rp = backend_type::create_vector(np, bprm); xp = backend_type::create_vector(np, bprm); rs = backend_type::create_vector(n, bprm); } }; } // namespace preconditioner } // namespace amgcl #endif <commit_msg>Fix header guard in cpr_drs<commit_after>#ifndef AMGCL_PRECONDITIONER_CPR_DRS_HPP #define AMGCL_PRECONDITIONER_CPR_DRS_HPP /* The MIT License Copyright (c) 2012-2016 Denis Demidov <dennis.demidov@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * \file amgcl/preconditioner/cpr_drs.hpp * \author Denis Demidov <dennis.demidov@gmail.com> * \brief CPR preconditioner with Dynamic Row Sum modification. */ #include <vector> #include <boost/shared_ptr.hpp> #include <amgcl/backend/builtin.hpp> #include <amgcl/util.hpp> namespace amgcl { namespace preconditioner { template <class PPrecond, class SPrecond> class cpr_drs { BOOST_STATIC_ASSERT_MSG( ( boost::is_same< typename PPrecond::backend_type, typename SPrecond::backend_type >::value ), "Backends for pressure and flow preconditioners should coinside!" ); public: typedef typename PPrecond::backend_type backend_type; typedef typename backend_type::value_type value_type; typedef typename backend_type::matrix matrix; typedef typename backend_type::vector vector; typedef typename backend_type::params backend_params; typedef typename backend::builtin<value_type>::matrix build_matrix; struct params { typedef typename PPrecond::params pprecond_params; typedef typename SPrecond::params sprecond_params; pprecond_params pprecond; sprecond_params sprecond; int block_size; size_t active_rows; double eps_dd; double eps_ps; params() : block_size(2), active_rows(0), eps_dd(0.2), eps_ps(0.02) {} params(const boost::property_tree::ptree &p) : AMGCL_PARAMS_IMPORT_CHILD(p, pprecond), AMGCL_PARAMS_IMPORT_CHILD(p, sprecond), AMGCL_PARAMS_IMPORT_VALUE(p, block_size), AMGCL_PARAMS_IMPORT_VALUE(p, active_rows), AMGCL_PARAMS_IMPORT_VALUE(p, eps_dd), AMGCL_PARAMS_IMPORT_VALUE(p, eps_ps) { } void get(boost::property_tree::ptree &p, const std::string &path = "") const { AMGCL_PARAMS_EXPORT_CHILD(p, path, pprecond); AMGCL_PARAMS_EXPORT_CHILD(p, path, sprecond); AMGCL_PARAMS_EXPORT_VALUE(p, path, block_size); AMGCL_PARAMS_EXPORT_VALUE(p, path, active_rows); AMGCL_PARAMS_EXPORT_VALUE(p, path, eps_dd); AMGCL_PARAMS_EXPORT_VALUE(p, path, eps_ps); } } prm; template <class Matrix> cpr_drs( const Matrix &K, const params &prm = params(), const backend_params &bprm = backend_params() ) : prm(prm), n(backend::rows(K)) { init(boost::make_shared<build_matrix>(K), bprm); } cpr_drs( boost::shared_ptr<build_matrix> K, const params &prm = params(), const backend_params bprm = backend_params() ) : prm(prm), n(backend::rows(*K)) { init(K, bprm); } template <class Vec1, class Vec2> void apply( const Vec1 &rhs, #ifdef BOOST_NO_CXX11_RVALUE_REFERENCES Vec2 &x #else Vec2 &&x #endif ) const { S->apply(rhs, x); backend::residual(rhs, S->system_matrix(), x, *rs); backend::spmv(1, *Fpp, *rs, 0, *rp); P->apply(*rp, *xp); backend::spmv(1, *Scatter, *xp, 1, x); } const matrix& system_matrix() const { return S->system_matrix(); } private: size_t n, np; boost::shared_ptr<PPrecond> P; boost::shared_ptr<SPrecond> S; boost::shared_ptr<matrix> Fpp, Scatter; boost::shared_ptr<vector> rp, xp, rs; void init(boost::shared_ptr<build_matrix> K, const backend_params bprm) { typedef typename backend::row_iterator<build_matrix>::type row_iterator; const int B = prm.block_size; const ptrdiff_t N = (prm.active_rows ? prm.active_rows : n); np = N / B; boost::shared_ptr<build_matrix> fpp = boost::make_shared<build_matrix>(); fpp->nrows = np; fpp->ncols = n; fpp->col.resize(n); fpp->val.resize(n, 1); fpp->ptr.resize(np+1); fpp->ptr[0] = 0; boost::shared_ptr<build_matrix> App = boost::make_shared<build_matrix>(); App->nrows = App->ncols = np; App->ptr.resize(np+1, 0); #pragma omp parallel { std::vector<value_type> a_dia(B), a_off(B), a_top(B); std::vector<row_iterator> k; k.reserve(B); #pragma omp for for(ptrdiff_t ip = 0; ip < static_cast<ptrdiff_t>(np); ++ip) { ptrdiff_t ik = ip * B; bool done = true; ptrdiff_t cur_col; boost::fill(a_dia, 0); boost::fill(a_off, 0); boost::fill(a_top, 0); k.clear(); for(int i = 0; i < B; ++i) { k.push_back(backend::row_begin(*K, ik + i)); if (k.back() && k.back().col() < N) { ptrdiff_t col = k.back().col() / B; if (done) { cur_col = col; done = false; } else { cur_col = std::min(cur_col, col); } } } while (!done) { ++App->ptr[ip+1]; ptrdiff_t end = (cur_col + 1) * B; for(int i = 0; i < B; ++i) { for(; k[i] && k[i].col() < end; ++k[i]) { ptrdiff_t c = k[i].col() % B; value_type v = k[i].value(); if (i == 0) { a_top[c] += std::abs(v); } if (c == 0) { if (cur_col == ip) { a_dia[i] = v; } else { a_off[i] += std::abs(v); } } } } // Get next column number. done = true; for(int i = 0; i < B; ++i) { if (k[i] && k[i].col() < N) { ptrdiff_t col = k[i].col() / B; if (done) { cur_col = col; done = false; } else { cur_col = std::min(cur_col, col); } } } } for(int i = 0; i < B; ++i) { fpp->col[ik+i] = ik+i; if (a_dia[i] < prm.eps_dd * a_off[i]) fpp->val[ik+i] = 0; if (a_top[i] < prm.eps_ps * std::abs(a_dia[0])) fpp->val[ik+i] = 0; } fpp->val[ik] = 1; // Keep delta[0] = 1 fpp->ptr[ip+1] = ik + B; } } boost::partial_sum(App->ptr, App->ptr.begin()); App->col.resize(App->ptr.back()); App->val.resize(App->ptr.back()); boost::shared_ptr<build_matrix> scatter = boost::make_shared<build_matrix>(); scatter->nrows = n; scatter->ncols = np; scatter->ptr.resize(n+1); scatter->ptr[0] = 0; scatter->col.resize(np); scatter->val.resize(np, 1); #pragma omp parallel { std::vector<row_iterator> k; k.reserve(B); #pragma omp for for(ptrdiff_t ip = 0; ip < static_cast<ptrdiff_t>(np); ++ip) { ptrdiff_t ik = ip * B; ptrdiff_t head = App->ptr[ip]; bool done = true; ptrdiff_t cur_col; value_type *d = &fpp->val[ik]; k.clear(); for(int i = 0; i < B; ++i) { k.push_back(backend::row_begin(*K, ik + i)); if (k.back() && k.back().col() < N) { ptrdiff_t col = k.back().col() / B; if (done) { cur_col = col; done = false; } else { cur_col = std::min(cur_col, col); } } } while (!done) { ptrdiff_t end = (cur_col + 1) * B; value_type app = 0; for(int i = 0; i < B; ++i) { for(; k[i] && k[i].col() < end; ++k[i]) { if (k[i].col() % B == 0) { app += d[i] * k[i].value(); } } } App->col[head] = cur_col; App->val[head] = app; ++head; // Get next column number. done = true; for(int i = 0; i < B; ++i) { if (k[i] && k[i].col() < N) { ptrdiff_t col = k[i].col() / B; if (done) { cur_col = col; done = false; } else { cur_col = std::min(cur_col, col); } } } } scatter->col[ip] = ip; ptrdiff_t nnz = ip; for(int i = 0; i < B; ++i) { if (i == 0) ++nnz; scatter->ptr[ik + i + 1] = nnz; } } } for(size_t i = N; i < n; ++i) scatter->ptr[i+1] = scatter->ptr[i]; P = boost::make_shared<PPrecond>(App, prm.pprecond, bprm); S = boost::make_shared<SPrecond>(K, prm.sprecond, bprm); Fpp = backend_type::copy_matrix(fpp, bprm); Scatter = backend_type::copy_matrix(scatter, bprm); rp = backend_type::create_vector(np, bprm); xp = backend_type::create_vector(np, bprm); rs = backend_type::create_vector(n, bprm); } }; } // namespace preconditioner } // namespace amgcl #endif <|endoftext|>
<commit_before><commit_msg>fix string conversion in 1da3af5f1eb6a32fd0ab10da7cf2f8ddb298a3a1<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: pickerhistory.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2005-04-13 10:25:01 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SVTOOLS_PICKERHISTORY_HXX #define SVTOOLS_PICKERHISTORY_HXX #ifndef INCLUDED_SVLDLLAPI_H #include "svtools/svldllapi.h" #endif #ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_ #include <com/sun/star/uno/XInterface.hpp> #endif //......................................................................... namespace svt { //......................................................................... // -------------------------------------------------------------------- SVL_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > GetTopMostFolderPicker( ); SVL_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > GetTopMostFilePicker( ); //......................................................................... } // namespace svt //......................................................................... #endif // SVTOOLS_PICKERHISTORY_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.3.140); FILE MERGED 2005/09/05 14:50:57 rt 1.3.140.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pickerhistory.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 10:04: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 * ************************************************************************/ #ifndef SVTOOLS_PICKERHISTORY_HXX #define SVTOOLS_PICKERHISTORY_HXX #ifndef INCLUDED_SVLDLLAPI_H #include "svtools/svldllapi.h" #endif #ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_ #include <com/sun/star/uno/XInterface.hpp> #endif //......................................................................... namespace svt { //......................................................................... // -------------------------------------------------------------------- SVL_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > GetTopMostFolderPicker( ); SVL_DLLPUBLIC ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > GetTopMostFilePicker( ); //......................................................................... } // namespace svt //......................................................................... #endif // SVTOOLS_PICKERHISTORY_HXX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: poolio.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-06-27 21:37:41 $ * * 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 <svtools/brdcst.hxx> #ifndef DELETEZ #define DELETEZ(pPtr) { delete pPtr; pPtr = 0; } #endif struct SfxPoolVersion_Impl { USHORT _nVer; USHORT _nStart, _nEnd; USHORT* _pMap; SfxPoolVersion_Impl( USHORT nVer, USHORT nStart, USHORT nEnd, USHORT *pMap ) : _nVer( nVer ), _nStart( nStart ), _nEnd( nEnd ), _pMap( pMap ) {} SfxPoolVersion_Impl( const SfxPoolVersion_Impl &rOrig ) : _nVer( rOrig._nVer ), _nStart( rOrig._nStart ), _nEnd( rOrig._nEnd ), _pMap( rOrig._pMap ) {} }; SV_DECL_PTRARR( SfxPoolItemArrayBase_Impl, SfxPoolItem*, 0, 5 ) SV_DECL_PTRARR_DEL( SfxPoolVersionArr_Impl, SfxPoolVersion_Impl*, 0, 2 ) struct SfxPoolItemArray_Impl: public SfxPoolItemArrayBase_Impl { USHORT nFirstFree; SfxPoolItemArray_Impl (USHORT nInitSize = 0) : SfxPoolItemArrayBase_Impl( nInitSize ), nFirstFree( 0 ) {} }; class SfxStyleSheetIterator; struct SfxItemPool_Impl { SfxBroadcaster aBC; SfxPoolItemArray_Impl** ppPoolItems; SfxPoolVersionArr_Impl aVersions; USHORT nVersion; USHORT nLoadingVersion; USHORT nInitRefCount; // 1, beim Laden ggf. 2 USHORT nVerStart, nVerEnd; // WhichRange in Versions USHORT nStoringStart, nStoringEnd; // zu speichernder Range BYTE nMajorVer, nMinorVer; // Pool selbst SfxMapUnit eDefMetric; FASTBOOL bInSetItem; FASTBOOL bStreaming; // in Load() bzw. Store() SfxItemPool_Impl( USHORT nStart, USHORT nEnd ) : ppPoolItems (new SfxPoolItemArray_Impl*[ nEnd - nStart + 1]) { memset( ppPoolItems, 0, sizeof( SfxPoolItemArray_Impl* ) * ( nEnd - nStart + 1) ); } ~SfxItemPool_Impl() { delete[] ppPoolItems; } void DeleteItems() { delete[] ppPoolItems; ppPoolItems = 0; } }; // ----------------------------------------------------------------------- // IBM-C-Set mag keine doppelten Defines #ifdef DBG # undef DBG #endif #if defined(DBG_UTIL) && defined(MSC) #define SFX_TRACE(s,p) \ { \ ByteString aPtr(RTL_CONSTASCII_STRINGPARAM("0x0000:0x0000")); \ _snprintf(const_cast< sal_Char *>(aPtr.GetBuffer()), aPtr.Len(), \ "%lp", p ); \ aPtr.Insert(s, 0); \ DbgTrace( aPtr.GetBuffer() ); \ } #define DBG(x) x #else #define SFX_TRACE(s,p) #define DBG(x) #endif #define CHECK_FILEFORMAT( rStream, nTag ) \ { USHORT nFileTag; \ rStream >> nFileTag; \ if ( nTag != nFileTag ) \ { \ DBG_ERROR( #nTag ); /*! s.u. */ \ /*! error-code setzen und auswerten! */ \ (rStream).SetError(SVSTREAM_FILEFORMAT_ERROR); \ pImp->bStreaming = FALSE; \ return rStream; \ } \ } #define CHECK_FILEFORMAT2( rStream, nTag1, nTag2 ) \ { USHORT nFileTag; \ rStream >> nFileTag; \ if ( nTag1 != nFileTag && nTag2 != nFileTag ) \ { \ DBG_ERROR( #nTag1 ); /*! s.u. */ \ /*! error-code setzen und auswerten! */ \ (rStream).SetError(SVSTREAM_FILEFORMAT_ERROR); \ pImp->bStreaming = FALSE; \ return rStream; \ } \ } #define SFX_ITEMPOOL_VER_MAJOR BYTE(2) #define SFX_ITEMPOOL_VER_MINOR BYTE(0) #define SFX_ITEMPOOL_TAG_STARTPOOL_4 USHORT(0x1111) #define SFX_ITEMPOOL_TAG_STARTPOOL_5 USHORT(0xBBBB) #define SFX_ITEMPOOL_TAG_ITEMPOOL USHORT(0xAAAA) #define SFX_ITEMPOOL_TAG_ITEMS USHORT(0x2222) #define SFX_ITEMPOOL_TAG_ITEM USHORT(0x7777) #define SFX_ITEMPOOL_TAG_SIZES USHORT(0x3333) #define SFX_ITEMPOOL_TAG_DEFAULTS USHORT(0x4444) #define SFX_ITEMPOOL_TAG_VERSIONMAP USHORT(0x5555) #define SFX_ITEMPOOL_TAG_HEADER USHORT(0x6666) #define SFX_ITEMPOOL_TAG_ENDPOOL USHORT(0xEEEE) #define SFX_ITEMPOOL_TAG_TRICK4OLD USHORT(0xFFFF) #define SFX_ITEMPOOL_REC BYTE(0x01) #define SFX_ITEMPOOL_REC_HEADER BYTE(0x10) #define SFX_ITEMPOOL_REC_VERSIONMAP USHORT(0x0020) #define SFX_ITEMPOOL_REC_WHICHIDS USHORT(0x0030) #define SFX_ITEMPOOL_REC_ITEMS USHORT(0x0040) #define SFX_ITEMPOOL_REC_DEFAULTS USHORT(0x0050) #define SFX_ITEMSET_REC BYTE(0x02) #define SFX_STYLES_REC BYTE(0x03) #define SFX_STYLES_REC_HEADER USHORT(0x0010) #define SFX_STYLES_REC_STYLES USHORT(0x0020) //======================================================================== inline USHORT SfxItemPool::GetIndex_Impl(USHORT nWhich) const { DBG_CHKTHIS(SfxItemPool, 0); DBG_ASSERT(nWhich >= nStart && nWhich <= nEnd, "Which-Id nicht im Pool-Bereich"); return nWhich - nStart; } <commit_msg>INTEGRATION: CWS mba24issues01 (1.5.102); FILE MERGED 2007/11/01 10:59:06 mba 1.5.102.1: #i79179#: memory leak fixed<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: poolio.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2008-01-04 14:57:27 $ * * 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 <svtools/brdcst.hxx> #ifndef DELETEZ #define DELETEZ(pPtr) { delete pPtr; pPtr = 0; } #endif struct SfxPoolVersion_Impl { USHORT _nVer; USHORT _nStart, _nEnd; USHORT* _pMap; SfxPoolVersion_Impl( USHORT nVer, USHORT nStart, USHORT nEnd, USHORT *pMap ) : _nVer( nVer ), _nStart( nStart ), _nEnd( nEnd ), _pMap( pMap ) {} SfxPoolVersion_Impl( const SfxPoolVersion_Impl &rOrig ) : _nVer( rOrig._nVer ), _nStart( rOrig._nStart ), _nEnd( rOrig._nEnd ), _pMap( rOrig._pMap ) {} }; SV_DECL_PTRARR( SfxPoolItemArrayBase_Impl, SfxPoolItem*, 0, 5 ) SV_DECL_PTRARR_DEL( SfxPoolVersionArr_Impl, SfxPoolVersion_Impl*, 0, 2 ) struct SfxPoolItemArray_Impl: public SfxPoolItemArrayBase_Impl { USHORT nFirstFree; SfxPoolItemArray_Impl (USHORT nInitSize = 0) : SfxPoolItemArrayBase_Impl( nInitSize ), nFirstFree( 0 ) {} }; class SfxStyleSheetIterator; struct SfxItemPool_Impl { SfxBroadcaster aBC; SfxPoolItemArray_Impl** ppPoolItems; SfxPoolVersionArr_Impl aVersions; USHORT nVersion; USHORT nLoadingVersion; USHORT nInitRefCount; // 1, beim Laden ggf. 2 USHORT nVerStart, nVerEnd; // WhichRange in Versions USHORT nStoringStart, nStoringEnd; // zu speichernder Range BYTE nMajorVer, nMinorVer; // Pool selbst SfxMapUnit eDefMetric; FASTBOOL bInSetItem; FASTBOOL bStreaming; // in Load() bzw. Store() SfxItemPool_Impl( USHORT nStart, USHORT nEnd ) : ppPoolItems (new SfxPoolItemArray_Impl*[ nEnd - nStart + 1]) { memset( ppPoolItems, 0, sizeof( SfxPoolItemArray_Impl* ) * ( nEnd - nStart + 1) ); } ~SfxItemPool_Impl() { delete[] ppPoolItems; } void DeleteItems() { delete[] ppPoolItems; ppPoolItems = 0; } }; // ----------------------------------------------------------------------- // IBM-C-Set mag keine doppelten Defines #ifdef DBG # undef DBG #endif #if defined(DBG_UTIL) && defined(MSC) #define SFX_TRACE(s,p) \ { \ ByteString aPtr(RTL_CONSTASCII_STRINGPARAM("0x0000:0x0000")); \ _snprintf(const_cast< sal_Char *>(aPtr.GetBuffer()), aPtr.Len(), \ "%lp", p ); \ aPtr.Insert(s, 0); \ DbgTrace( aPtr.GetBuffer() ); \ } #define DBG(x) x #else #define SFX_TRACE(s,p) #define DBG(x) #endif #define CHECK_FILEFORMAT( rStream, nTag ) \ { USHORT nFileTag; \ rStream >> nFileTag; \ if ( nTag != nFileTag ) \ { \ DBG_ERROR( #nTag ); /*! s.u. */ \ /*! error-code setzen und auswerten! */ \ (rStream).SetError(SVSTREAM_FILEFORMAT_ERROR); \ pImp->bStreaming = FALSE; \ return rStream; \ } \ } #define CHECK_FILEFORMAT_RELEASE( rStream, nTag, pPointer ) \ { USHORT nFileTag; \ rStream >> nFileTag; \ if ( nTag != nFileTag ) \ { \ DBG_ERROR( #nTag ); /*! s.u. */ \ /*! error-code setzen und auswerten! */ \ (rStream).SetError(SVSTREAM_FILEFORMAT_ERROR); \ pImp->bStreaming = FALSE; \ delete pPointer; \ return rStream; \ } \ } #define CHECK_FILEFORMAT2( rStream, nTag1, nTag2 ) \ { USHORT nFileTag; \ rStream >> nFileTag; \ if ( nTag1 != nFileTag && nTag2 != nFileTag ) \ { \ DBG_ERROR( #nTag1 ); /*! s.u. */ \ /*! error-code setzen und auswerten! */ \ (rStream).SetError(SVSTREAM_FILEFORMAT_ERROR); \ pImp->bStreaming = FALSE; \ return rStream; \ } \ } #define SFX_ITEMPOOL_VER_MAJOR BYTE(2) #define SFX_ITEMPOOL_VER_MINOR BYTE(0) #define SFX_ITEMPOOL_TAG_STARTPOOL_4 USHORT(0x1111) #define SFX_ITEMPOOL_TAG_STARTPOOL_5 USHORT(0xBBBB) #define SFX_ITEMPOOL_TAG_ITEMPOOL USHORT(0xAAAA) #define SFX_ITEMPOOL_TAG_ITEMS USHORT(0x2222) #define SFX_ITEMPOOL_TAG_ITEM USHORT(0x7777) #define SFX_ITEMPOOL_TAG_SIZES USHORT(0x3333) #define SFX_ITEMPOOL_TAG_DEFAULTS USHORT(0x4444) #define SFX_ITEMPOOL_TAG_VERSIONMAP USHORT(0x5555) #define SFX_ITEMPOOL_TAG_HEADER USHORT(0x6666) #define SFX_ITEMPOOL_TAG_ENDPOOL USHORT(0xEEEE) #define SFX_ITEMPOOL_TAG_TRICK4OLD USHORT(0xFFFF) #define SFX_ITEMPOOL_REC BYTE(0x01) #define SFX_ITEMPOOL_REC_HEADER BYTE(0x10) #define SFX_ITEMPOOL_REC_VERSIONMAP USHORT(0x0020) #define SFX_ITEMPOOL_REC_WHICHIDS USHORT(0x0030) #define SFX_ITEMPOOL_REC_ITEMS USHORT(0x0040) #define SFX_ITEMPOOL_REC_DEFAULTS USHORT(0x0050) #define SFX_ITEMSET_REC BYTE(0x02) #define SFX_STYLES_REC BYTE(0x03) #define SFX_STYLES_REC_HEADER USHORT(0x0010) #define SFX_STYLES_REC_STYLES USHORT(0x0020) //======================================================================== inline USHORT SfxItemPool::GetIndex_Impl(USHORT nWhich) const { DBG_CHKTHIS(SfxItemPool, 0); DBG_ASSERT(nWhich >= nStart && nWhich <= nEnd, "Which-Id nicht im Pool-Bereich"); return nWhich - nStart; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: linkdlg.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2006-10-12 12:18:06 $ * * 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 _LINKDLG_HXX #define _LINKDLG_HXX #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #include <vcl/dialog.hxx> #include <vcl/fixed.hxx> #include <vcl/button.hxx> #include <vcl/edit.hxx> #include <vcl/lstbox.hxx> #include <svtools/svmedit.hxx> // MultiLineEdit #include <svtools/svtabbx.hxx> // MultiLineEdit /********************** SvUpdateLinksDialog ****************************** *************************************************************************/ namespace sfx2 { class SvLinkManager; class SvBaseLink; } class SvBaseLinksDlg : public ModalDialog { using Window::SetType; FixedText aFtFiles; FixedText aFtLinks; FixedText aFtType; FixedText aFtStatus; CancelButton aCancelButton1; HelpButton aHelpButton1; PushButton aPbUpdateNow; PushButton aPbOpenSource; PushButton aPbChangeSource; PushButton aPbBreakLink; FixedText aFtFiles2; FixedText aFtSource2; FixedText aFtType2; FixedText aFtUpdate; RadioButton aRbAutomatic; RadioButton aRbManual; FixedText aFtFullFileName; FixedText aFtFullSourceName; FixedText aFtFullTypeName; String aStrAutolink; String aStrManuallink; String aStrBrokenlink; String aStrGraphiclink; String aStrButtonclose; String aStrCloselinkmsg; String aStrCloselinkmsgMulti; String aStrWaitinglink; sfx2::SvLinkManager* pLinkMgr; BOOL bHtmlMode; SvTabListBox aTbLinks; Timer aUpdateTimer; #if _SOLAR__PRIVATE DECL_LINK( LinksSelectHdl, SvTabListBox * ); DECL_LINK( LinksDoubleClickHdl, SvTabListBox * ); DECL_LINK( AutomaticClickHdl, RadioButton * ); DECL_LINK( ManualClickHdl, RadioButton * ); DECL_LINK( UpdateNowClickHdl, PushButton * ); DECL_LINK( OpenSourceClickHdl, PushButton * ); DECL_LINK( ChangeSourceClickHdl, PushButton * ); DECL_LINK( BreakLinkClickHdl, PushButton * ); DECL_LINK( UpdateWaitingHdl, Timer * ); sfx2::SvBaseLink* GetSelEntry( USHORT* pPos ); String ImplGetStateStr( const sfx2::SvBaseLink& ); void SetType( sfx2::SvBaseLink& rLink, USHORT nPos, USHORT nType ); void InsertEntry( const sfx2::SvBaseLink& rLink, USHORT nPos = LISTBOX_APPEND, sal_Bool bSelect = sal_False); #endif void StartUpdateTimer() { aUpdateTimer.Start(); } SvTabListBox& Links() { return aTbLinks; } FixedText& FileName() { return aFtFullFileName; } FixedText& SourceName() { return aFtFullSourceName; } FixedText& TypeName() { return aFtFullTypeName; } RadioButton& Automatic() { return aRbAutomatic; } RadioButton& Manual() { return aRbManual; } PushButton& UpdateNow() { return aPbUpdateNow; } PushButton& OpenSource() { return aPbOpenSource; } PushButton& ChangeSource() { return aPbChangeSource; } PushButton& BreakLink() { return aPbBreakLink; } String& Autolink() { return aStrAutolink; } String& Manuallink() { return aStrManuallink; } String& Brokenlink() { return aStrBrokenlink; } String& Graphiclink() { return aStrGraphiclink; } String& Buttonclose() { return aStrButtonclose; } String& Closelinkmsg() { return aStrCloselinkmsg; } String& CloselinkmsgMulti() { return aStrCloselinkmsgMulti; } String& Waitinglink() { return aStrWaitinglink; } void SetManager( sfx2::SvLinkManager* ); public: SvBaseLinksDlg( Window * pParent, sfx2::SvLinkManager*, BOOL bHtml = FALSE ); ~SvBaseLinksDlg(); void SetActLink( sfx2::SvBaseLink * pLink ); }; #endif // _LINKDLG_HXX <commit_msg>INTEGRATION: CWS asyncdialogs (1.3.180); FILE MERGED 2006/10/31 15:04:19 pb 1.3.180.2: RESYNC: (1.3-1.4); FILE MERGED 2006/03/22 07:34:44 pb 1.3.180.1: fix: #i57125# EndEditHdl() added<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: linkdlg.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2006-11-22 10:35:39 $ * * 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 _LINKDLG_HXX #define _LINKDLG_HXX #ifndef _LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #include <vcl/dialog.hxx> #include <vcl/fixed.hxx> #include <vcl/button.hxx> #include <vcl/edit.hxx> #include <vcl/lstbox.hxx> #include <svtools/svmedit.hxx> // MultiLineEdit #include <svtools/svtabbx.hxx> // MultiLineEdit /********************** SvUpdateLinksDialog ****************************** *************************************************************************/ namespace sfx2 { class SvLinkManager; class SvBaseLink; } class SvBaseLinksDlg : public ModalDialog { using Window::SetType; FixedText aFtFiles; FixedText aFtLinks; FixedText aFtType; FixedText aFtStatus; CancelButton aCancelButton1; HelpButton aHelpButton1; PushButton aPbUpdateNow; PushButton aPbOpenSource; PushButton aPbChangeSource; PushButton aPbBreakLink; FixedText aFtFiles2; FixedText aFtSource2; FixedText aFtType2; FixedText aFtUpdate; RadioButton aRbAutomatic; RadioButton aRbManual; FixedText aFtFullFileName; FixedText aFtFullSourceName; FixedText aFtFullTypeName; String aStrAutolink; String aStrManuallink; String aStrBrokenlink; String aStrGraphiclink; String aStrButtonclose; String aStrCloselinkmsg; String aStrCloselinkmsgMulti; String aStrWaitinglink; sfx2::SvLinkManager* pLinkMgr; BOOL bHtmlMode; SvTabListBox aTbLinks; Timer aUpdateTimer; #if _SOLAR__PRIVATE DECL_LINK( LinksSelectHdl, SvTabListBox * ); DECL_LINK( LinksDoubleClickHdl, SvTabListBox * ); DECL_LINK( AutomaticClickHdl, RadioButton * ); DECL_LINK( ManualClickHdl, RadioButton * ); DECL_LINK( UpdateNowClickHdl, PushButton * ); DECL_LINK( OpenSourceClickHdl, PushButton * ); DECL_LINK( ChangeSourceClickHdl, PushButton * ); DECL_LINK( BreakLinkClickHdl, PushButton * ); DECL_LINK( UpdateWaitingHdl, Timer * ); DECL_LINK( EndEditHdl, sfx2::SvBaseLink* ); sfx2::SvBaseLink* GetSelEntry( USHORT* pPos ); String ImplGetStateStr( const sfx2::SvBaseLink& ); void SetType( sfx2::SvBaseLink& rLink, USHORT nPos, USHORT nType ); void InsertEntry( const sfx2::SvBaseLink& rLink, USHORT nPos = LISTBOX_APPEND, sal_Bool bSelect = sal_False); #endif void StartUpdateTimer() { aUpdateTimer.Start(); } SvTabListBox& Links() { return aTbLinks; } FixedText& FileName() { return aFtFullFileName; } FixedText& SourceName() { return aFtFullSourceName; } FixedText& TypeName() { return aFtFullTypeName; } RadioButton& Automatic() { return aRbAutomatic; } RadioButton& Manual() { return aRbManual; } PushButton& UpdateNow() { return aPbUpdateNow; } PushButton& OpenSource() { return aPbOpenSource; } PushButton& ChangeSource() { return aPbChangeSource; } PushButton& BreakLink() { return aPbBreakLink; } String& Autolink() { return aStrAutolink; } String& Manuallink() { return aStrManuallink; } String& Brokenlink() { return aStrBrokenlink; } String& Graphiclink() { return aStrGraphiclink; } String& Buttonclose() { return aStrButtonclose; } String& Closelinkmsg() { return aStrCloselinkmsg; } String& CloselinkmsgMulti() { return aStrCloselinkmsgMulti; } String& Waitinglink() { return aStrWaitinglink; } void SetManager( sfx2::SvLinkManager* ); public: SvBaseLinksDlg( Window * pParent, sfx2::SvLinkManager*, BOOL bHtml = FALSE ); ~SvBaseLinksDlg(); void SetActLink( sfx2::SvBaseLink * pLink ); }; #endif // _LINKDLG_HXX <|endoftext|>
<commit_before><commit_msg>tdf#89666: vcl: speed up HbLayoutEngine line layout for large paragraphs<commit_after><|endoftext|>
<commit_before><commit_msg>This is an int, not float<commit_after><|endoftext|>
<commit_before><commit_msg>Fixed premature wrapping, black spot in A1 and scrollbar and button position.<commit_after><|endoftext|>
<commit_before>// RUN: %check_clang_tidy %s readability-static-accessed-through-instance %t struct C { static void foo(); static int x; int nsx; void mf() { (void)&x; // OK, x is accessed inside the struct. (void)&C::x; // OK, x is accessed using a qualified-id. foo(); // OK, foo() is accessed inside the struct. } void ns() const; }; int C::x = 0; struct CC { void foo(); int x; }; template <typename T> struct CT { static T foo(); static T x; int nsx; void mf() { (void)&x; // OK, x is accessed inside the struct. (void)&C::x; // OK, x is accessed using a qualified-id. foo(); // OK, foo() is accessed inside the struct. } }; // Expressions with side effects C &f(int, int, int, int); void g() { f(1, 2, 3, 4).x; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member accessed through instance [readability-static-accessed-through-instance] // CHECK-FIXES: {{^}} f(1, 2, 3, 4).x;{{$}} } int i(int &); void j(int); C h(); bool a(); int k(bool); void f(C c) { j(i(h().x)); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: static member // CHECK-FIXES: {{^}} j(i(h().x));{{$}} // The execution of h() depends on the return value of a(). j(k(a() && h().x)); // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: static member // CHECK-FIXES: {{^}} j(k(a() && h().x));{{$}} if ([c]() { c.ns(); return c; }().x == 15) ; // CHECK-MESSAGES: :[[@LINE-5]]:7: warning: static member // CHECK-FIXES: {{^}} if ([c]() {{{$}} } // Nested specifiers namespace N { struct V { static int v; struct T { static int t; struct U { static int u; }; }; }; } void f(N::V::T::U u) { N::V v; v.v = 12; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} N::V::v = 12;{{$}} N::V::T w; w.t = 12; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} N::V::T::t = 12;{{$}} // u.u is not changed to N::V::T::U::u; because the nesting level is over 3. u.u = 12; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} u.u = 12;{{$}} using B = N::V::T::U; B b; b.u; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} B::u;{{$}} } // Templates template <typename T> T CT<T>::x; template <typename T> struct CCT { T foo(); T x; }; typedef C D; using E = D; #define FOO(c) c.foo() #define X(c) c.x template <typename T> void f(T t, C c) { t.x; // OK, t is a template parameter. c.x; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} C::x; // 1{{$}} } template <int N> struct S { static int x; }; template <> struct S<0> { int x; }; template <int N> void h() { S<N> sN; sN.x; // OK, value of N affects whether x is static or not. S<2> s2; s2.x; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} S<2>::x;{{$}} } void static_through_instance() { C *c1 = new C(); c1->foo(); // 1 // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} C::foo(); // 1{{$}} c1->x; // 2 // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} C::x; // 2{{$}} c1->nsx; // OK, nsx is a non-static member. const C *c2 = new C(); c2->foo(); // 2 // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} C::foo(); // 2{{$}} C::foo(); // OK, foo() is accessed using a qualified-id. C::x; // OK, x is accessed using a qualified-id. D d; d.foo(); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} D::foo();{{$}} d.x; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} D::x;{{$}} E e; e.foo(); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} E::foo();{{$}} e.x; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} E::x;{{$}} CC *cc = new CC; f(*c1, *c1); f(*cc, *c1); // Macros: OK, macros are not checked. FOO((*c1)); X((*c1)); FOO((*cc)); X((*cc)); // Templates CT<int> ct; ct.foo(); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} CT<int>::foo();{{$}} ct.x; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} CT<int>::x;{{$}} ct.nsx; // OK, nsx is a non-static member CCT<int> cct; cct.foo(); // OK, CCT has no static members. cct.x; // OK, CCT has no static members. h<4>(); } // Overloaded member access operator struct Q { static int K; int y = 0; }; int Q::K = 0; struct Qptr { Q *q; explicit Qptr(Q *qq) : q(qq) {} Q *operator->() { ++q->y; return q; } }; int func(Qptr qp) { qp->y = 10; // OK, the overloaded operator might have side-effects. qp->K = 10; // } <commit_msg>[clang-tidy] Fix a check-fixes line<commit_after>// RUN: %check_clang_tidy %s readability-static-accessed-through-instance %t struct C { static void foo(); static int x; int nsx; void mf() { (void)&x; // OK, x is accessed inside the struct. (void)&C::x; // OK, x is accessed using a qualified-id. foo(); // OK, foo() is accessed inside the struct. } void ns() const; }; int C::x = 0; struct CC { void foo(); int x; }; template <typename T> struct CT { static T foo(); static T x; int nsx; void mf() { (void)&x; // OK, x is accessed inside the struct. (void)&C::x; // OK, x is accessed using a qualified-id. foo(); // OK, foo() is accessed inside the struct. } }; // Expressions with side effects C &f(int, int, int, int); void g() { f(1, 2, 3, 4).x; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member accessed through instance [readability-static-accessed-through-instance] // CHECK-FIXES: {{^}} f(1, 2, 3, 4).x;{{$}} } int i(int &); void j(int); C h(); bool a(); int k(bool); void f(C c) { j(i(h().x)); // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: static member // CHECK-FIXES: {{^}} j(i(h().x));{{$}} // The execution of h() depends on the return value of a(). j(k(a() && h().x)); // CHECK-MESSAGES: :[[@LINE-1]]:14: warning: static member // CHECK-FIXES: {{^}} j(k(a() && h().x));{{$}} if ([c]() { c.ns(); return c; }().x == 15) ; // CHECK-MESSAGES: :[[@LINE-5]]:7: warning: static member // CHECK-FIXES: {{^}} if ([c]() {{{$}} } // Nested specifiers namespace N { struct V { static int v; struct T { static int t; struct U { static int u; }; }; }; } void f(N::V::T::U u) { N::V v; v.v = 12; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} N::V::v = 12;{{$}} N::V::T w; w.t = 12; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} N::V::T::t = 12;{{$}} // u.u is not changed to N::V::T::U::u; because the nesting level is over 3. u.u = 12; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} u.u = 12;{{$}} using B = N::V::T::U; B b; b.u; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} B::u;{{$}} } // Templates template <typename T> T CT<T>::x; template <typename T> struct CCT { T foo(); T x; }; typedef C D; using E = D; #define FOO(c) c.foo() #define X(c) c.x template <typename T> void f(T t, C c) { t.x; // OK, t is a template parameter. c.x; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} C::x;{{$}} } template <int N> struct S { static int x; }; template <> struct S<0> { int x; }; template <int N> void h() { S<N> sN; sN.x; // OK, value of N affects whether x is static or not. S<2> s2; s2.x; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} S<2>::x;{{$}} } void static_through_instance() { C *c1 = new C(); c1->foo(); // 1 // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} C::foo(); // 1{{$}} c1->x; // 2 // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} C::x; // 2{{$}} c1->nsx; // OK, nsx is a non-static member. const C *c2 = new C(); c2->foo(); // 2 // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} C::foo(); // 2{{$}} C::foo(); // OK, foo() is accessed using a qualified-id. C::x; // OK, x is accessed using a qualified-id. D d; d.foo(); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} D::foo();{{$}} d.x; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} D::x;{{$}} E e; e.foo(); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} E::foo();{{$}} e.x; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} E::x;{{$}} CC *cc = new CC; f(*c1, *c1); f(*cc, *c1); // Macros: OK, macros are not checked. FOO((*c1)); X((*c1)); FOO((*cc)); X((*cc)); // Templates CT<int> ct; ct.foo(); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} CT<int>::foo();{{$}} ct.x; // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: static member // CHECK-FIXES: {{^}} CT<int>::x;{{$}} ct.nsx; // OK, nsx is a non-static member CCT<int> cct; cct.foo(); // OK, CCT has no static members. cct.x; // OK, CCT has no static members. h<4>(); } // Overloaded member access operator struct Q { static int K; int y = 0; }; int Q::K = 0; struct Qptr { Q *q; explicit Qptr(Q *qq) : q(qq) {} Q *operator->() { ++q->y; return q; } }; int func(Qptr qp) { qp->y = 10; // OK, the overloaded operator might have side-effects. qp->K = 10; // } <|endoftext|>
<commit_before><commit_msg>dr78: #i106108# SetDocumentModified also for page margins<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: svditer.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2004-04-02 14:12:49 $ * * 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 _SVDITER_HXX #include "svditer.hxx" #endif #ifndef _SVDPAGE_HXX #include "svdpage.hxx" #endif #ifndef _SVDOGRP_HXX #include "svdogrp.hxx" #endif #ifndef _SVDOBJ_HXX #include "svdobj.hxx" #endif // #99190# #ifndef _E3D_SCENE3D_HXX #include "scene3d.hxx" #endif SdrObjListIter::SdrObjListIter(const SdrObjList& rObjList, SdrIterMode eMode, BOOL bReverse) : maObjList(1024, 64, 64), mnIndex(0L), mbReverse(bReverse) { ImpProcessObjectList(rObjList, eMode); Reset(); } SdrObjListIter::SdrObjListIter( const SdrObject& rObj, SdrIterMode eMode, BOOL bReverse ) : maObjList(1024, 64, 64), mnIndex(0L), mbReverse(bReverse) { if ( rObj.ISA( SdrObjGroup ) ) ImpProcessObjectList(*rObj.GetSubList(), eMode); else maObjList.Insert( (void*)&rObj, LIST_APPEND ); Reset(); } void SdrObjListIter::ImpProcessObjectList(const SdrObjList& rObjList, SdrIterMode eMode) { for(sal_uInt32 a(0L); a < rObjList.GetObjCount(); a++) { SdrObject* pObj = rObjList.GetObj(a); sal_Bool bIsGroup(pObj->IsGroupObject()); // #99190# 3D objects are no group objects, IsGroupObject() // only tests if pSub is not null ptr :-( if(bIsGroup && pObj->ISA(E3dObject) && !pObj->ISA(E3dScene)) bIsGroup = sal_False; if(eMode != IM_DEEPNOGROUPS || !bIsGroup) maObjList.Insert(pObj, LIST_APPEND); if(bIsGroup && eMode != IM_FLAT) ImpProcessObjectList(*pObj->GetSubList(), eMode); } } <commit_msg>INTEGRATION: CWS ooo19126 (1.4.952); FILE MERGED 2005/09/05 14:27:10 rt 1.4.952.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: svditer.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 00:29:46 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVDITER_HXX #include "svditer.hxx" #endif #ifndef _SVDPAGE_HXX #include "svdpage.hxx" #endif #ifndef _SVDOGRP_HXX #include "svdogrp.hxx" #endif #ifndef _SVDOBJ_HXX #include "svdobj.hxx" #endif // #99190# #ifndef _E3D_SCENE3D_HXX #include "scene3d.hxx" #endif SdrObjListIter::SdrObjListIter(const SdrObjList& rObjList, SdrIterMode eMode, BOOL bReverse) : maObjList(1024, 64, 64), mnIndex(0L), mbReverse(bReverse) { ImpProcessObjectList(rObjList, eMode); Reset(); } SdrObjListIter::SdrObjListIter( const SdrObject& rObj, SdrIterMode eMode, BOOL bReverse ) : maObjList(1024, 64, 64), mnIndex(0L), mbReverse(bReverse) { if ( rObj.ISA( SdrObjGroup ) ) ImpProcessObjectList(*rObj.GetSubList(), eMode); else maObjList.Insert( (void*)&rObj, LIST_APPEND ); Reset(); } void SdrObjListIter::ImpProcessObjectList(const SdrObjList& rObjList, SdrIterMode eMode) { for(sal_uInt32 a(0L); a < rObjList.GetObjCount(); a++) { SdrObject* pObj = rObjList.GetObj(a); sal_Bool bIsGroup(pObj->IsGroupObject()); // #99190# 3D objects are no group objects, IsGroupObject() // only tests if pSub is not null ptr :-( if(bIsGroup && pObj->ISA(E3dObject) && !pObj->ISA(E3dScene)) bIsGroup = sal_False; if(eMode != IM_DEEPNOGROUPS || !bIsGroup) maObjList.Insert(pObj, LIST_APPEND); if(bIsGroup && eMode != IM_FLAT) ImpProcessObjectList(*pObj->GetSubList(), eMode); } } <|endoftext|>
<commit_before><commit_msg>disable borders for tabbar in Calc (ScTabControl)<commit_after><|endoftext|>
<commit_before><commit_msg>Resolves: #i123003# Corrected Handle/Overlay visualization...<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: tabvwsh.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2004-08-12 09:30:33 $ * * 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 PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ // INCLUDE --------------------------------------------------------------- #include "scitems.hxx" #include <svx/galbrws.hxx> #include <svx/imapdlg.hxx> #include <svx/srchitem.hxx> #include <sfx2/templdlg.hxx> #include <sfx2/app.hxx> #include <avmedia/mediaplayer.hxx> #include "tabvwsh.hxx" #include "docsh.hxx" #include "reffact.hxx" #include "scresid.hxx" #include "dwfunctr.hxx" #include "sc.hrc" // -> SID_TOOL_xxx #include "drawattr.hxx" // -> SvxDrawToolItem #define ScTabViewShell #include "scslots.hxx" #define SearchSettings #include <svx/svxslots.hxx> TYPEINIT2(ScTabViewShell,SfxViewShell,SfxListener); SFX_IMPL_INTERFACE(ScTabViewShell,SfxViewShell,ScResId(SCSTR_TABVIEWSHELL)) { SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_TOOLS | SFX_VISIBILITY_STANDARD | SFX_VISIBILITY_FULLSCREEN | SFX_VISIBILITY_SERVER, ScResId(RID_OBJECTBAR_TOOLS) ); SFX_CHILDWINDOW_REGISTRATION(FID_INPUTLINE_STATUS); SFX_CHILDWINDOW_REGISTRATION(SfxTemplateDialogWrapper::GetChildWindowId()); SFX_CHILDWINDOW_CONTEXT_REGISTRATION(SID_NAVIGATOR); SFX_CHILDWINDOW_REGISTRATION(ScNameDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScSolverDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScPivotLayoutWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScTabOpDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScFilterDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScSpecialFilterDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScDbNameDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScConsolidateDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScChartDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScPrintAreasDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScCondFormatDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScColRowNameRangesDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScFormulaDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(SvxIMapDlgChildWindow::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScFunctionChildWindow::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScFormulaDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScAcceptChgDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScHighlightChgDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScSimpleRefDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(SID_SEARCH_DLG); SFX_CHILDWINDOW_REGISTRATION(SID_HYPERLINK_DIALOG); SFX_CHILDWINDOW_REGISTRATION(GalleryChildWindow::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION( ::avmedia::MediaPlayer::GetChildWindowId() ); } SFX_IMPL_VIEWFACTORY( ScTabViewShell, ScResId(STR_NONAME) ) { SFX_VIEW_REGISTRATION(ScDocShell); } //------------------------------------------------------------------ <commit_msg>INTEGRATION: CWS os19 (1.6.104); FILE MERGED 2004/09/12 16:46:56 os 1.6.104.2: RESYNC: (1.6-1.7); FILE MERGED 2004/06/10 13:20:12 dr 1.6.104.1: #i22092# new spellcheck dialog, first step<commit_after>/************************************************************************* * * $RCSfile: tabvwsh.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2004-09-17 13:56:01 $ * * 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 PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ // INCLUDE --------------------------------------------------------------- #include "scitems.hxx" #include <svx/galbrws.hxx> #include <svx/imapdlg.hxx> #include <svx/srchitem.hxx> #include <sfx2/templdlg.hxx> #include <sfx2/app.hxx> #include <avmedia/mediaplayer.hxx> #include "tabvwsh.hxx" #include "docsh.hxx" #include "reffact.hxx" #include "scresid.hxx" #include "dwfunctr.hxx" #include "sc.hrc" // -> SID_TOOL_xxx #include "drawattr.hxx" // -> SvxDrawToolItem #include "spelldialog.hxx" #define ScTabViewShell #include "scslots.hxx" #define SearchSettings #include <svx/svxslots.hxx> TYPEINIT2(ScTabViewShell,SfxViewShell,SfxListener); SFX_IMPL_INTERFACE(ScTabViewShell,SfxViewShell,ScResId(SCSTR_TABVIEWSHELL)) { SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_TOOLS | SFX_VISIBILITY_STANDARD | SFX_VISIBILITY_FULLSCREEN | SFX_VISIBILITY_SERVER, ScResId(RID_OBJECTBAR_TOOLS) ); SFX_CHILDWINDOW_REGISTRATION(FID_INPUTLINE_STATUS); SFX_CHILDWINDOW_REGISTRATION(SfxTemplateDialogWrapper::GetChildWindowId()); SFX_CHILDWINDOW_CONTEXT_REGISTRATION(SID_NAVIGATOR); SFX_CHILDWINDOW_REGISTRATION(ScNameDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScSolverDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScPivotLayoutWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScTabOpDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScFilterDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScSpecialFilterDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScDbNameDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScConsolidateDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScChartDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScPrintAreasDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScCondFormatDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScColRowNameRangesDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScFormulaDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(SvxIMapDlgChildWindow::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScFunctionChildWindow::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScFormulaDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScAcceptChgDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScHighlightChgDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScSimpleRefDlgWrapper::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(SID_SEARCH_DLG); SFX_CHILDWINDOW_REGISTRATION(SID_HYPERLINK_DIALOG); SFX_CHILDWINDOW_REGISTRATION(GalleryChildWindow::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION(ScSpellDialogChildWindow::GetChildWindowId()); SFX_CHILDWINDOW_REGISTRATION( ::avmedia::MediaPlayer::GetChildWindowId() ); } SFX_IMPL_VIEWFACTORY( ScTabViewShell, ScResId(STR_NONAME) ) { SFX_VIEW_REGISTRATION(ScDocShell); } //------------------------------------------------------------------ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tabfrm.hxx,v $ * * $Revision: 1.18 $ * * last change: $Author: hr $ $Date: 2007-09-27 08:58:50 $ * * 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 _TABFRM_HXX #define _TABFRM_HXX #ifndef _SVMEMPOOL_HXX //autogen #include <tools/mempool.hxx> #endif #include "layfrm.hxx" #include "flowfrm.hxx" class SwTable; class SwBorderAttrs; class SwAttrSetChg; class SwTabFrm: public SwLayoutFrm, public SwFlowFrm { // OD 14.03.2003 #i11760# - adjustment, because of method signature change //darf mit den Flags spielen. friend void CalcCntnt( SwLayoutFrm *pLay, bool bNoColl, bool bNoCalcFollow ); //Fuert Spezialbehandlung fuer _Get[Next|Prev]Leaf() durch. using SwFrm::GetLeaf; SwLayoutFrm *GetLeaf( MakePageType eMakePage, BOOL bFwd ); SwTable* pTable; BOOL bComplete :1; //Eintrage als Repaint ohne das CompletePaint //der Basisklasse gesetzt werden muss. Damit //sollen unertraegliche Tabellen-Repaints //vermieden werden. BOOL bCalcLowers :1; //Im MakeAll auf jedenfall auch fuer Stabilitaet //des Inhaltes sorgen. BOOL bLowersFormatted :1;//Kommunikation zwischen MakeAll und Layact BOOL bLockBackMove :1; //BackMove-Test hat der Master erledigt. BOOL bResizeHTMLTable :1; //Resize des HTMLTableLayout rufen im MakeAll //Zur Optimierung, damit dies nicht im //CntntFrm::Grow gerufen werden muss, denn dann //wird es ggf. fuer jede Zelle gerufen #47483# BOOL bONECalcLowers :1; //Primaer fuer die StarONE-SS. Beim MakeAll werden //die Cntnts auf jedenfall per Calc() formatiert. //es finden keine zusaetzlichen Invalidierungen //statt und dieser Weg kann auch kaum garantien //geben. BOOL bHasFollowFlowLine :1; // Means that the first line in the follow // is indented to contain content from a broken // cell BOOL bIsRebuildLastLine :1; // Means that currently the last line of the // TabFrame is rebuilded. In this case we // do not want any notification to the master // table BOOL bRestrictTableGrowth :1; // Usually, the table may grow infinite, // because the table can be split in // SwTabFrm::MakeAll. In MakeAll, this // flag is set to indicate that the table // may only grow inside its upper. This // is necessary, in order to let the text // flow into the FollowFlowLine BOOL bRemoveFollowFlowLinePending :1; // --> OD 2004-10-04 #i26945# BOOL bConsiderObjsForMinCellHeight :1; // Usually, the floating screen objects // are considered on the calculation // for the minimal cell height. // For splitting table rows algorithm // it's needed not to consider floating // screen object for the preparation // of the re-calculation of the // last table row. // <-- // --> OD 2004-10-15 #i26945# BOOL bObjsDoesFit :1; // For splitting table rows algorithm, this boolean // indicates, if the floating screen objects fits // <-- BOOL bDummy4 :1; //Split() spaltet den Frm an der angegebenen Stelle, es wird ein //Follow erzeugt und aufgebaut und direkt hinter this gepastet. //Join() Holt sich den Inhalt aus dem Follow und vernichtet diesen. bool Split( const SwTwips nCutPos, bool bTryToSplit, bool bTableRowKeep ); bool Join(); void _UpdateAttr( SfxPoolItem*, SfxPoolItem*, BYTE &, SwAttrSetChg *pa = 0, SwAttrSetChg *pb = 0 ); virtual BOOL ShouldBwdMoved( SwLayoutFrm *pNewUpper, BOOL bHead, BOOL &rReformat ); protected: virtual void MakeAll(); virtual void Format( const SwBorderAttrs *pAttrs = 0 ); //Aendert nur die Framesize, nicht die PrtArea-SSize virtual SwTwips GrowFrm ( SwTwips, BOOL bTst = FALSE, BOOL bInfo = FALSE ); public: SwTabFrm( SwTable & ); //Immer nach dem erzeugen _und_ pasten das //Regist Flys rufen! SwTabFrm( SwTabFrm & ); //_Nur_ zum erzeugen von Follows ~SwTabFrm(); void JoinAndDelFollows(); //Fuer DelFrms des TableNodes! //Ruft das RegistFlys der Zeilen. void RegistFlys(); inline const SwTabFrm *GetFollow() const; inline SwTabFrm *GetFollow(); SwTabFrm* FindMaster( bool bFirstMaster = false ) const; virtual void Modify( SfxPoolItem*, SfxPoolItem* ); virtual BOOL GetInfo( SfxPoolItem &rHnt ) const; virtual void Paint( const SwRect& ) const; virtual void CheckDirection( BOOL bVert ); virtual void Cut(); virtual void Paste( SwFrm* pParent, SwFrm* pSibling = 0 ); virtual void Prepare( const PrepareHint ePrep = PREP_CLEAR, const void *pVoid = 0, sal_Bool bNotify = sal_True ); SwCntntFrm *FindLastCntnt(); inline const SwCntntFrm *FindLastCntnt() const; const SwTable *GetTable() const { return pTable; } SwTable *GetTable() { return pTable; } BOOL IsComplete() { return bComplete; } void SetComplete() { bComplete = TRUE; } void ResetComplete() { bComplete = FALSE; } BOOL IsLowersFormatted() const { return bLowersFormatted; } void SetLowersFormatted( BOOL b ) { bLowersFormatted = b; } void SetCalcLowers() { bCalcLowers = TRUE; } //Sparsam einsetzen! void SetResizeHTMLTable() { bResizeHTMLTable = TRUE; } //dito void SetONECalcLowers() { bONECalcLowers = TRUE; } // // Start: New stuff for breaking table rows // BOOL HasFollowFlowLine() const { return bHasFollowFlowLine; } void SetFollowFlowLine( BOOL bNew ) { bHasFollowFlowLine = bNew; } BOOL IsRebuildLastLine() const { return bIsRebuildLastLine; } void SetRebuildLastLine( BOOL bNew ) { bIsRebuildLastLine = bNew; } BOOL IsRestrictTableGrowth() const { return bRestrictTableGrowth; } void SetRestrictTableGrowth( BOOL bNew ) { bRestrictTableGrowth = bNew; } BOOL IsRemoveFollowFlowLinePending() const { return bRemoveFollowFlowLinePending; } void SetRemoveFollowFlowLinePending( BOOL bNew ) { bRemoveFollowFlowLinePending = bNew; } // --> OD 2004-10-04 #i26945# BOOL IsConsiderObjsForMinCellHeight() const { return bConsiderObjsForMinCellHeight; } void SetConsiderObjsForMinCellHeight( BOOL _bNewConsiderObjsForMinCellHeight ) { bConsiderObjsForMinCellHeight = _bNewConsiderObjsForMinCellHeight; } // <-- // --> OD 2004-10-04 #i26945# BOOL DoesObjsFit() const { return bObjsDoesFit; } void SetDoesObjsFit( BOOL _bNewObjsDoesFit ) { bObjsDoesFit = _bNewObjsDoesFit; } // <-- bool RemoveFollowFlowLine(); // // End: New stuff for breaking table rows // BOOL CalcFlyOffsets( SwTwips& rUpper, long& rLeftOffset, long& rRightOffset ) const; SwTwips CalcHeightOfFirstContentLine() const; bool IsInHeadline( const SwFrm& rFrm ) const; SwRowFrm* GetFirstNonHeadlineRow() const; bool IsLayoutSplitAllowed() const; // --> collapsing borders FME 2005-05-27 #i29550# bool IsCollapsingBorders() const; // used for collapsing border lines: USHORT GetBottomLineSize() const; // <-- collapsing DECL_FIXEDMEMPOOL_NEWDEL(SwTabFrm) }; inline const SwCntntFrm *SwTabFrm::FindLastCntnt() const { return ((SwTabFrm*)this)->FindLastCntnt(); } inline const SwTabFrm *SwTabFrm::GetFollow() const { return (const SwTabFrm*)SwFlowFrm::GetFollow(); } inline SwTabFrm *SwTabFrm::GetFollow() { return (SwTabFrm*)SwFlowFrm::GetFollow(); } #endif //_TABFRM_HXX <commit_msg>INTEGRATION: CWS swusing (1.18.38); FILE MERGED 2007/10/10 14:15:08 tl 1.18.38.1: #i82476# make newly added 'using' declarations private<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tabfrm.hxx,v $ * * $Revision: 1.19 $ * * last change: $Author: vg $ $Date: 2007-10-22 15:11:06 $ * * 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 _TABFRM_HXX #define _TABFRM_HXX #ifndef _SVMEMPOOL_HXX //autogen #include <tools/mempool.hxx> #endif #include "layfrm.hxx" #include "flowfrm.hxx" class SwTable; class SwBorderAttrs; class SwAttrSetChg; class SwTabFrm: public SwLayoutFrm, public SwFlowFrm { // OD 14.03.2003 #i11760# - adjustment, because of method signature change //darf mit den Flags spielen. friend void CalcCntnt( SwLayoutFrm *pLay, bool bNoColl, bool bNoCalcFollow ); //Fuert Spezialbehandlung fuer _Get[Next|Prev]Leaf() durch. using SwFrm::GetLeaf; SwLayoutFrm *GetLeaf( MakePageType eMakePage, BOOL bFwd ); SwTable* pTable; BOOL bComplete :1; //Eintrage als Repaint ohne das CompletePaint //der Basisklasse gesetzt werden muss. Damit //sollen unertraegliche Tabellen-Repaints //vermieden werden. BOOL bCalcLowers :1; //Im MakeAll auf jedenfall auch fuer Stabilitaet //des Inhaltes sorgen. BOOL bLowersFormatted :1;//Kommunikation zwischen MakeAll und Layact BOOL bLockBackMove :1; //BackMove-Test hat der Master erledigt. BOOL bResizeHTMLTable :1; //Resize des HTMLTableLayout rufen im MakeAll //Zur Optimierung, damit dies nicht im //CntntFrm::Grow gerufen werden muss, denn dann //wird es ggf. fuer jede Zelle gerufen #47483# BOOL bONECalcLowers :1; //Primaer fuer die StarONE-SS. Beim MakeAll werden //die Cntnts auf jedenfall per Calc() formatiert. //es finden keine zusaetzlichen Invalidierungen //statt und dieser Weg kann auch kaum garantien //geben. BOOL bHasFollowFlowLine :1; // Means that the first line in the follow // is indented to contain content from a broken // cell BOOL bIsRebuildLastLine :1; // Means that currently the last line of the // TabFrame is rebuilded. In this case we // do not want any notification to the master // table BOOL bRestrictTableGrowth :1; // Usually, the table may grow infinite, // because the table can be split in // SwTabFrm::MakeAll. In MakeAll, this // flag is set to indicate that the table // may only grow inside its upper. This // is necessary, in order to let the text // flow into the FollowFlowLine BOOL bRemoveFollowFlowLinePending :1; // --> OD 2004-10-04 #i26945# BOOL bConsiderObjsForMinCellHeight :1; // Usually, the floating screen objects // are considered on the calculation // for the minimal cell height. // For splitting table rows algorithm // it's needed not to consider floating // screen object for the preparation // of the re-calculation of the // last table row. // <-- // --> OD 2004-10-15 #i26945# BOOL bObjsDoesFit :1; // For splitting table rows algorithm, this boolean // indicates, if the floating screen objects fits // <-- BOOL bDummy4 :1; //Split() spaltet den Frm an der angegebenen Stelle, es wird ein //Follow erzeugt und aufgebaut und direkt hinter this gepastet. //Join() Holt sich den Inhalt aus dem Follow und vernichtet diesen. bool Split( const SwTwips nCutPos, bool bTryToSplit, bool bTableRowKeep ); bool Join(); void _UpdateAttr( SfxPoolItem*, SfxPoolItem*, BYTE &, SwAttrSetChg *pa = 0, SwAttrSetChg *pb = 0 ); virtual BOOL ShouldBwdMoved( SwLayoutFrm *pNewUpper, BOOL bHead, BOOL &rReformat ); protected: virtual void MakeAll(); virtual void Format( const SwBorderAttrs *pAttrs = 0 ); //Aendert nur die Framesize, nicht die PrtArea-SSize virtual SwTwips GrowFrm ( SwTwips, BOOL bTst = FALSE, BOOL bInfo = FALSE ); public: SwTabFrm( SwTable & ); //Immer nach dem erzeugen _und_ pasten das //Regist Flys rufen! SwTabFrm( SwTabFrm & ); //_Nur_ zum erzeugen von Follows ~SwTabFrm(); void JoinAndDelFollows(); //Fuer DelFrms des TableNodes! //Ruft das RegistFlys der Zeilen. void RegistFlys(); inline const SwTabFrm *GetFollow() const; inline SwTabFrm *GetFollow(); SwTabFrm* FindMaster( bool bFirstMaster = false ) const; virtual void Modify( SfxPoolItem*, SfxPoolItem* ); virtual BOOL GetInfo( SfxPoolItem &rHnt ) const; virtual void Paint( const SwRect& ) const; virtual void CheckDirection( BOOL bVert ); virtual void Cut(); virtual void Paste( SwFrm* pParent, SwFrm* pSibling = 0 ); virtual void Prepare( const PrepareHint ePrep = PREP_CLEAR, const void *pVoid = 0, sal_Bool bNotify = sal_True ); SwCntntFrm *FindLastCntnt(); inline const SwCntntFrm *FindLastCntnt() const; const SwTable *GetTable() const { return pTable; } SwTable *GetTable() { return pTable; } BOOL IsComplete() { return bComplete; } void SetComplete() { bComplete = TRUE; } void ResetComplete() { bComplete = FALSE; } BOOL IsLowersFormatted() const { return bLowersFormatted; } void SetLowersFormatted( BOOL b ) { bLowersFormatted = b; } void SetCalcLowers() { bCalcLowers = TRUE; } //Sparsam einsetzen! void SetResizeHTMLTable() { bResizeHTMLTable = TRUE; } //dito void SetONECalcLowers() { bONECalcLowers = TRUE; } // // Start: New stuff for breaking table rows // BOOL HasFollowFlowLine() const { return bHasFollowFlowLine; } void SetFollowFlowLine( BOOL bNew ) { bHasFollowFlowLine = bNew; } BOOL IsRebuildLastLine() const { return bIsRebuildLastLine; } void SetRebuildLastLine( BOOL bNew ) { bIsRebuildLastLine = bNew; } BOOL IsRestrictTableGrowth() const { return bRestrictTableGrowth; } void SetRestrictTableGrowth( BOOL bNew ) { bRestrictTableGrowth = bNew; } BOOL IsRemoveFollowFlowLinePending() const { return bRemoveFollowFlowLinePending; } void SetRemoveFollowFlowLinePending( BOOL bNew ) { bRemoveFollowFlowLinePending = bNew; } // --> OD 2004-10-04 #i26945# BOOL IsConsiderObjsForMinCellHeight() const { return bConsiderObjsForMinCellHeight; } void SetConsiderObjsForMinCellHeight( BOOL _bNewConsiderObjsForMinCellHeight ) { bConsiderObjsForMinCellHeight = _bNewConsiderObjsForMinCellHeight; } // <-- // --> OD 2004-10-04 #i26945# BOOL DoesObjsFit() const { return bObjsDoesFit; } void SetDoesObjsFit( BOOL _bNewObjsDoesFit ) { bObjsDoesFit = _bNewObjsDoesFit; } // <-- bool RemoveFollowFlowLine(); // // End: New stuff for breaking table rows // BOOL CalcFlyOffsets( SwTwips& rUpper, long& rLeftOffset, long& rRightOffset ) const; SwTwips CalcHeightOfFirstContentLine() const; bool IsInHeadline( const SwFrm& rFrm ) const; SwRowFrm* GetFirstNonHeadlineRow() const; bool IsLayoutSplitAllowed() const; // --> collapsing borders FME 2005-05-27 #i29550# bool IsCollapsingBorders() const; // used for collapsing border lines: USHORT GetBottomLineSize() const; // <-- collapsing DECL_FIXEDMEMPOOL_NEWDEL(SwTabFrm) }; inline const SwCntntFrm *SwTabFrm::FindLastCntnt() const { return ((SwTabFrm*)this)->FindLastCntnt(); } inline const SwTabFrm *SwTabFrm::GetFollow() const { return (const SwTabFrm*)SwFlowFrm::GetFollow(); } inline SwTabFrm *SwTabFrm::GetFollow() { return (SwTabFrm*)SwFlowFrm::GetFollow(); } #endif //_TABFRM_HXX <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: cfgitems.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: kz $ $Date: 2004-02-26 15:43:00 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CFGITEMS_HXX #define _CFGITEMS_HXX #ifndef _SFXPOOLITEM_HXX //autogen #include <svtools/poolitem.hxx> #endif #ifndef _AUTHRATR_HXX #include <authratr.hxx> #endif #ifndef _SW_PRINTDATA_HXX #include <printdata.hxx> #endif class SwWriterApp; class SwModule; #ifndef PRODUCT class SwTestTabPage; #endif class SwAddPrinterTabPage; class SfxPrinter; class ViewShell; class SwViewOption; class SwContentOptPage; class SwShdwCrsrOptionsTabPage; class SwDocEditDialog; SfxPrinter* GetPrt( ViewShell* ); void SetPrt( SfxPrinter* ); /*--------OS 12.01.95 ----------------------------------- Item fuer Einstellungsdialog - Dokumentanzeige --------------------------------------------------------- */ class SwDocDisplayItem : public SfxPoolItem { friend class SwWriterApp; friend class SwShdwCrsrOptionsTabPage; friend class SwModule; BOOL bParagraphEnd :1; BOOL bTab :1; BOOL bSpace :1; BOOL bNonbreakingSpace :1; BOOL bSoftHyphen :1; BOOL bCharHiddenText :1; BOOL bFldHiddenText :1; BOOL bManualBreak :1; BOOL bShowHiddenPara :1; Color aIndexBackgrndCol; public: TYPEINFO(); SwDocDisplayItem( USHORT nWhich = FN_PARAM_DOCDISP ); SwDocDisplayItem( const SwDocDisplayItem& rSwDocDisplayItem ); SwDocDisplayItem( const SwViewOption& rVOpt, USHORT nWhich ); virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual int operator==( const SfxPoolItem& ) const; void operator=( const SwDocDisplayItem& ); void FillViewOptions( SwViewOption& rVOpt) const; }; /*--------OS 12.01.95 ----------------------------------- Item fuer Einstellungsdialog, Elementeseite --------------------------------------------------------- */ class SwElemItem : public SfxPoolItem { //view BOOL bHorzScrollbar :1; BOOL bVertScrollbar :1; BOOL bAnyRuler : 1; BOOL bHorzRuler :1; BOOL bVertRuler :1; BOOL bVertRulerRight:1; BOOL bSmoothScroll :1; //visual aids BOOL bCrosshair :1; BOOL bHandles :1; BOOL bBigHandles :1; //display BOOL bTable :1; BOOL bGraphic :1; BOOL bDrawing :1; BOOL bFieldName :1; BOOL bNotes :1; friend class SwContentOptPage; public: TYPEINFO(); SwElemItem( USHORT nWhich = FN_PARAM_ELEM ); SwElemItem(const SwElemItem& rElemItem); SwElemItem(const SwViewOption& rVOpt, USHORT nWhich); virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual int operator==( const SfxPoolItem& ) const; void operator=( const SwElemItem& ); void FillViewOptions( SwViewOption& rVOpt) const; }; /*--------OS 12.01.95 ----------------------------------- Item fuer Einstellungsdialog - Drucker/Zusaetze --------------------------------------------------------- */ class SwAddPrinterItem : public SfxPoolItem, public SwPrintData { friend class SwAddPrinterTabPage; public: TYPEINFO(); SwAddPrinterItem( USHORT nWhich = FN_PARAM_ADDPRINTER ); SwAddPrinterItem( USHORT nWhich, const SwPrintData& rPrtData ); SwAddPrinterItem( const SwAddPrinterItem& rAddPrinterItem); virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual int operator==( const SfxPoolItem& ) const; const rtl::OUString &GetFax() const { return sFaxName; } void SetFax( const String& rFax) { sFaxName = rFax; } BOOL IsPrintProspect() const { return bPrintProspect; } void SetPrintProspect(BOOL bFlag ){ bPrintProspect = bFlag; } BOOL IsPrintGraphic () const { return bPrintGraphic; } BOOL IsPrintTable () const { return bPrintTable; } BOOL IsPrintDraw () const { return bPrintDraw; } BOOL IsPrintControl () const { return bPrintControl; } BOOL IsPrintLeftPage () const { return bPrintLeftPage; } BOOL IsPrintRightPage() const { return bPrintRightPage; } BOOL IsPrintReverse () const { return bPrintReverse; } BOOL IsPaperFromSetup() const { return bPaperFromSetup; } BOOL IsPrintPageBackground() const { return bPrintPageBackground; } BOOL IsPrintBlackFont() const { return bPrintBlackFont; } BOOL IsPrintSingleJobs() const { return bPrintSingleJobs; } ULONG GetPrintPostIts () const { return nPrintPostIts; } }; /*--------OS 12.01.95 ----------------------------------- Item fuer Einstellungsdialog, ShadowCursorSeite --------------------------------------------------------- */ class SwShadowCursorItem : public SfxPoolItem { BYTE eMode; BOOL bOn; public: TYPEINFO(); SwShadowCursorItem( USHORT nWhich = FN_PARAM_SHADOWCURSOR ); SwShadowCursorItem( const SwShadowCursorItem& rElemItem ); SwShadowCursorItem( const SwViewOption& rVOpt, USHORT nWhich ); virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual int operator==( const SfxPoolItem& ) const; void operator=( const SwShadowCursorItem& ); void FillViewOptions( SwViewOption& rVOpt) const; BYTE GetMode() const { return eMode; } BOOL IsOn() const { return bOn; } void SetMode( BYTE eM ) { eMode = eM; } void SetOn( BOOL bFlag ) { bOn = bFlag; } }; #ifndef PRODUCT /*--------OS 12.01.95 ----------------------------------- Item fuer Einstellungsdialog - Testeinstellungen --------------------------------------------------------- */ class SwTestItem : public SfxPoolItem { friend class SwModule; friend class SwWriterApp; friend class SwTestTabPage; friend class SwDocEditDialog; BOOL bTest1:1; BOOL bTest2:1; BOOL bTest3:1; BOOL bTest4:1; BOOL bTest5:1; BOOL bTest6:1; BOOL bTest7:1; BOOL bTest8:1; BOOL bTest9:1; BOOL bTest10:1; public: SwTestItem( USHORT nWhich): SfxPoolItem(nWhich){}; SwTestItem( const SwTestItem& pTestItem); virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual int operator==( const SfxPoolItem& ) const; }; #endif #endif <commit_msg>INTEGRATION: CWS tune03 (1.8.182); FILE MERGED 2004/07/19 19:11:24 mhu 1.8.182.1: #i29979# Added SW_DLLPUBLIC/PRIVATE (see swdllapi.h) to exported symbols/classes.<commit_after>/************************************************************************* * * $RCSfile: cfgitems.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2004-08-23 08:57:09 $ * * 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 _CFGITEMS_HXX #define _CFGITEMS_HXX #ifndef _SFXPOOLITEM_HXX //autogen #include <svtools/poolitem.hxx> #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif #ifndef _AUTHRATR_HXX #include <authratr.hxx> #endif #ifndef _SW_PRINTDATA_HXX #include <printdata.hxx> #endif class SwWriterApp; class SwModule; #ifndef PRODUCT class SwTestTabPage; #endif class SwAddPrinterTabPage; class SfxPrinter; class ViewShell; class SwViewOption; class SwContentOptPage; class SwShdwCrsrOptionsTabPage; class SwDocEditDialog; SfxPrinter* GetPrt( ViewShell* ); void SetPrt( SfxPrinter* ); /*--------OS 12.01.95 ----------------------------------- Item fuer Einstellungsdialog - Dokumentanzeige --------------------------------------------------------- */ class SW_DLLPUBLIC SwDocDisplayItem : public SfxPoolItem { friend class SwWriterApp; friend class SwShdwCrsrOptionsTabPage; friend class SwModule; BOOL bParagraphEnd :1; BOOL bTab :1; BOOL bSpace :1; BOOL bNonbreakingSpace :1; BOOL bSoftHyphen :1; BOOL bCharHiddenText :1; BOOL bFldHiddenText :1; BOOL bManualBreak :1; BOOL bShowHiddenPara :1; Color aIndexBackgrndCol; public: TYPEINFO(); SwDocDisplayItem( USHORT nWhich = FN_PARAM_DOCDISP ); SwDocDisplayItem( const SwDocDisplayItem& rSwDocDisplayItem ); SwDocDisplayItem( const SwViewOption& rVOpt, USHORT nWhich ); virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual int operator==( const SfxPoolItem& ) const; void operator=( const SwDocDisplayItem& ); void FillViewOptions( SwViewOption& rVOpt) const; }; /*--------OS 12.01.95 ----------------------------------- Item fuer Einstellungsdialog, Elementeseite --------------------------------------------------------- */ class SW_DLLPUBLIC SwElemItem : public SfxPoolItem { //view BOOL bHorzScrollbar :1; BOOL bVertScrollbar :1; BOOL bAnyRuler : 1; BOOL bHorzRuler :1; BOOL bVertRuler :1; BOOL bVertRulerRight:1; BOOL bSmoothScroll :1; //visual aids BOOL bCrosshair :1; BOOL bHandles :1; BOOL bBigHandles :1; //display BOOL bTable :1; BOOL bGraphic :1; BOOL bDrawing :1; BOOL bFieldName :1; BOOL bNotes :1; friend class SwContentOptPage; public: TYPEINFO(); SwElemItem( USHORT nWhich = FN_PARAM_ELEM ); SwElemItem(const SwElemItem& rElemItem); SwElemItem(const SwViewOption& rVOpt, USHORT nWhich); virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual int operator==( const SfxPoolItem& ) const; void operator=( const SwElemItem& ); void FillViewOptions( SwViewOption& rVOpt) const; }; /*--------OS 12.01.95 ----------------------------------- Item fuer Einstellungsdialog - Drucker/Zusaetze --------------------------------------------------------- */ class SW_DLLPUBLIC SwAddPrinterItem : public SfxPoolItem, public SwPrintData { friend class SwAddPrinterTabPage; public: TYPEINFO(); SwAddPrinterItem( USHORT nWhich = FN_PARAM_ADDPRINTER ); SwAddPrinterItem( USHORT nWhich, const SwPrintData& rPrtData ); SwAddPrinterItem( const SwAddPrinterItem& rAddPrinterItem); virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual int operator==( const SfxPoolItem& ) const; const rtl::OUString &GetFax() const { return sFaxName; } void SetFax( const String& rFax) { sFaxName = rFax; } BOOL IsPrintProspect() const { return bPrintProspect; } void SetPrintProspect(BOOL bFlag ){ bPrintProspect = bFlag; } BOOL IsPrintGraphic () const { return bPrintGraphic; } BOOL IsPrintTable () const { return bPrintTable; } BOOL IsPrintDraw () const { return bPrintDraw; } BOOL IsPrintControl () const { return bPrintControl; } BOOL IsPrintLeftPage () const { return bPrintLeftPage; } BOOL IsPrintRightPage() const { return bPrintRightPage; } BOOL IsPrintReverse () const { return bPrintReverse; } BOOL IsPaperFromSetup() const { return bPaperFromSetup; } BOOL IsPrintPageBackground() const { return bPrintPageBackground; } BOOL IsPrintBlackFont() const { return bPrintBlackFont; } BOOL IsPrintSingleJobs() const { return bPrintSingleJobs; } ULONG GetPrintPostIts () const { return nPrintPostIts; } }; /*--------OS 12.01.95 ----------------------------------- Item fuer Einstellungsdialog, ShadowCursorSeite --------------------------------------------------------- */ class SW_DLLPUBLIC SwShadowCursorItem : public SfxPoolItem { BYTE eMode; BOOL bOn; public: TYPEINFO(); SwShadowCursorItem( USHORT nWhich = FN_PARAM_SHADOWCURSOR ); SwShadowCursorItem( const SwShadowCursorItem& rElemItem ); SwShadowCursorItem( const SwViewOption& rVOpt, USHORT nWhich ); virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual int operator==( const SfxPoolItem& ) const; void operator=( const SwShadowCursorItem& ); void FillViewOptions( SwViewOption& rVOpt) const; BYTE GetMode() const { return eMode; } BOOL IsOn() const { return bOn; } void SetMode( BYTE eM ) { eMode = eM; } void SetOn( BOOL bFlag ) { bOn = bFlag; } }; #ifndef PRODUCT /*--------OS 12.01.95 ----------------------------------- Item fuer Einstellungsdialog - Testeinstellungen --------------------------------------------------------- */ class SwTestItem : public SfxPoolItem { friend class SwModule; friend class SwWriterApp; friend class SwTestTabPage; friend class SwDocEditDialog; BOOL bTest1:1; BOOL bTest2:1; BOOL bTest3:1; BOOL bTest4:1; BOOL bTest5:1; BOOL bTest6:1; BOOL bTest7:1; BOOL bTest8:1; BOOL bTest9:1; BOOL bTest10:1; public: SwTestItem( USHORT nWhich): SfxPoolItem(nWhich){}; SwTestItem( const SwTestItem& pTestItem); virtual SfxPoolItem* Clone( SfxItemPool *pPool = 0 ) const; virtual int operator==( const SfxPoolItem& ) const; }; #endif #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: labelcfg.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-08-23 08:59:52 $ * * 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 _LABELCFG_HXX #define _LABELCFG_HXX #ifndef _UTL_CONFIGITEM_HXX_ #include <unotools/configitem.hxx> #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif class SwLabRecs; class SwLabRec; class SW_DLLPUBLIC SwLabelConfig : public utl::ConfigItem { com::sun::star::uno::Sequence<rtl::OUString> aNodeNames; SW_DLLPRIVATE com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames(); public: SwLabelConfig(); virtual ~SwLabelConfig(); virtual void Commit(); void FillLabels(const rtl::OUString& rManufacturer, SwLabRecs& rLabArr); const com::sun::star::uno::Sequence<rtl::OUString>& GetManufacturers() const {return aNodeNames;} sal_Bool HasLabel(const rtl::OUString& rManufacturer, const rtl::OUString& rType); void SaveLabel(const rtl::OUString& rManufacturer, const rtl::OUString& rType, const SwLabRec& rRec); }; #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.3.596); FILE MERGED 2005/09/05 13:45:19 rt 1.3.596.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: labelcfg.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 09:24:13 $ * * 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 _LABELCFG_HXX #define _LABELCFG_HXX #ifndef _UTL_CONFIGITEM_HXX_ #include <unotools/configitem.hxx> #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif class SwLabRecs; class SwLabRec; class SW_DLLPUBLIC SwLabelConfig : public utl::ConfigItem { com::sun::star::uno::Sequence<rtl::OUString> aNodeNames; SW_DLLPRIVATE com::sun::star::uno::Sequence<rtl::OUString> GetPropertyNames(); public: SwLabelConfig(); virtual ~SwLabelConfig(); virtual void Commit(); void FillLabels(const rtl::OUString& rManufacturer, SwLabRecs& rLabArr); const com::sun::star::uno::Sequence<rtl::OUString>& GetManufacturers() const {return aNodeNames;} sal_Bool HasLabel(const rtl::OUString& rManufacturer, const rtl::OUString& rType); void SaveLabel(const rtl::OUString& rManufacturer, const rtl::OUString& rType, const SwLabRec& rRec); }; #endif <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2014. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file stop_watch.hpp * \brief Contains stop watches implementation to measure duration */ #ifndef CPP_STOP_WATCH_HPP #define CPP_STOP_WATCH_HPP #include <chrono> #include <iostream> namespace cpp { /*! * \brief Default clock type used by the library */ using clock_type = std::chrono::high_resolution_clock; /*! * \class stop_watch * \brief A stop watch * \tparam P The std::chrono precision used by the watch. * * The watch automatically starts when the constructor is called */ template<typename P = std::chrono::milliseconds> class stop_watch { public: /*! * \brief The std::chrono precision used by the watch. */ using precision = P; /*! * \brief Constructs a new stop_watch and starts it. */ stop_watch(){ start_point = clock_type::now(); } /*! * \brief Return the elapsed time since construction. * \return the elapsed time since construction. */ double elapsed(){ auto end_point = clock_type::now(); auto time = std::chrono::duration_cast<precision>(end_point - start_point); return time.count(); } private: clock_type::time_point start_point; }; /*! * \class auto_stop_watch * \brief An automatic stop watch * \tparam P The std::chrono precision used by the watch. * * The watch automatically starts when the constructor is called and display the duration when destructed. */ template<typename P = std::chrono::milliseconds> class auto_stop_watch { public: /*! * \brief The std::chrono precision used by the watch. */ using precision = P; /*! * \brief Constructs a new auto_stop_watch and starts it. * \param title The title that will be displayed when the watch is over. */ auto_stop_watch(std::string title) : title(std::move(title)) { //Empty } /*! * \brief Destroys the auto_stop_watch and display the elapsed time. */ ~auto_stop_watch(){ std::cout << title << " took " << watch.elapsed() << std::endl; } private: std::string title; stop_watch<precision> watch; }; } //end of cpp namespace #endif //CPP_STOP_WATCH_HPP <commit_msg>Make 1-arg constructor explicit<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2014. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= /*! * \file stop_watch.hpp * \brief Contains stop watches implementation to measure duration */ #ifndef CPP_STOP_WATCH_HPP #define CPP_STOP_WATCH_HPP #include <chrono> #include <iostream> namespace cpp { /*! * \brief Default clock type used by the library */ using clock_type = std::chrono::high_resolution_clock; /*! * \class stop_watch * \brief A stop watch * \tparam P The std::chrono precision used by the watch. * * The watch automatically starts when the constructor is called */ template<typename P = std::chrono::milliseconds> class stop_watch { public: /*! * \brief The std::chrono precision used by the watch. */ using precision = P; /*! * \brief Constructs a new stop_watch and starts it. */ stop_watch(){ start_point = clock_type::now(); } /*! * \brief Return the elapsed time since construction. * \return the elapsed time since construction. */ double elapsed(){ auto end_point = clock_type::now(); auto time = std::chrono::duration_cast<precision>(end_point - start_point); return time.count(); } private: clock_type::time_point start_point; }; /*! * \class auto_stop_watch * \brief An automatic stop watch * \tparam P The std::chrono precision used by the watch. * * The watch automatically starts when the constructor is called and display the duration when destructed. */ template<typename P = std::chrono::milliseconds> class auto_stop_watch { public: /*! * \brief The std::chrono precision used by the watch. */ using precision = P; /*! * \brief Constructs a new auto_stop_watch and starts it. * \param title The title that will be displayed when the watch is over. */ explicit auto_stop_watch(std::string title) : title(std::move(title)) { //Empty } /*! * \brief Destroys the auto_stop_watch and display the elapsed time. */ ~auto_stop_watch(){ std::cout << title << " took " << watch.elapsed() << std::endl; } private: std::string title; stop_watch<precision> watch; }; } //end of cpp namespace #endif //CPP_STOP_WATCH_HPP <|endoftext|>
<commit_before>#include <vector> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <aslam/cameras/GridCalibrationTargetCheckerboard.hpp> #include <sm/eigen/serialization.hpp> namespace aslam { namespace cameras { /// \brief Construct a calibration target /// rows: number of internal corners (8x8 chessboard would be 7x7 internal corners) /// cols: number of internal corners /// rowSpacingMeters: spacing in y-direction [m] /// colSpacingMeters: spacing in x-direction [m] /// /// point ordering in _points: (e.g. 2x2 grid) /// *-------*-------*-------* /// | BLACK | WHITE | BLACK | /// *------(3)-----(4)------* /// | WHITE | BLACK | WHITE | /// *------(1)-----(2)------* /// y | BLACK | WHITE | BLACK | /// ^ *-------*-------*-------* /// |-->x GridCalibrationTargetCheckerboard::GridCalibrationTargetCheckerboard( size_t rows, size_t cols, double rowSpacingMeters, double colSpacingMeters, const CheckerboardOptions &options) : GridCalibrationTargetBase(rows, cols), _rowSpacingMeters(rowSpacingMeters), _colSpacingMeters(colSpacingMeters), _options(options) { SM_ASSERT_GT(Exception, rowSpacingMeters, 0.0, "rowSpacingMeters has to be positive"); SM_ASSERT_GT(Exception, colSpacingMeters, 0.0, "colSpacingMeters has to be positive"); // allocate memory for the grid points _points.resize(size(), 3); //initialize a normal grid (checkerboard and circlegrids) createGridPoints(); //start the output window if requested initialize(); } /// \brief initialize the object void GridCalibrationTargetCheckerboard::initialize() { if (_options.showExtractionVideo) { cv::namedWindow("Checkerboard corners", CV_WINDOW_AUTOSIZE); cvStartWindowThread(); } } /// \brief initialize a checkerboard grid (cols*rows = (cols)*(rows) internal grid points) /// point ordering: (e.g. 2x2 grid) /// *-------*-------*-------* /// | BLACK | WHITE | BLACK | /// *------(3)-----(4)------* /// | WHITE | BLACK | WHITE | /// *------(1)-----(2)------* /// y | BLACK | WHITE | BLACK | /// ^ *-------*-------*-------* /// |-->x /// void GridCalibrationTargetCheckerboard::createGridPoints() { for (unsigned int r = 0; r < _rows; r++) for (unsigned int c = 0; c < _cols; c++) _points.row(gridCoordinatesToPoint(r, c)) = Eigen::Matrix<double, 1, 3>( _rowSpacingMeters * r, _colSpacingMeters * c, 0.0); } /// \brief extract the calibration target points from an image and write to an observation bool GridCalibrationTargetCheckerboard::computeObservation(const cv::Mat & image, Eigen::MatrixXd & outImagePoints, std::vector<bool> &outCornerObserved) const { // set the open cv flags int flags = cv::CALIB_CB_FAST_CHECK; if (_options.useAdaptiveThreshold) flags += cv::CALIB_CB_ADAPTIVE_THRESH; if ( _options.normalizeImage) flags += cv::CALIB_CB_NORMALIZE_IMAGE; if (_options.filterQuads) flags += cv::CALIB_CB_FILTER_QUADS; // extract the checkerboard corners cv::Size patternSize(cols(), rows()); cv::Mat centers(size(), 2, CV_64FC1); bool success = cv::findChessboardCorners(image, patternSize, centers, flags); // do optional subpixel refinement if (_options.doSubpixelRefinement && success) { cv::cornerSubPix( image, centers, cv::Size(11, 11), cv::Size(-1, -1), cv::TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1)); } //draw corners if (_options.showExtractionVideo) { //image with refined (blue) and raw corners (red) cv::Mat imageCopy1 = image.clone(); cv::cvtColor(imageCopy1, imageCopy1, CV_GRAY2RGB); cv::drawChessboardCorners(imageCopy1, cv::Size(rows(), cols()), centers, true); // write error msg if (!success) cv::putText(imageCopy1, "Detection failed! (frame not used)", cv::Point(50, 50), CV_FONT_HERSHEY_SIMPLEX, 0.8, CV_RGB(255,0,0), 3, 8, false); cv::imshow("Checkerboard corners", imageCopy1); // OpenCV call } //exit here if there is an error if (!success) return success; //set all points as observed (checkerboard is only usable in that case) std::vector<bool> allGood(size(), true); outCornerObserved = allGood; //convert to eigen for output outImagePoints.resize(size(), 2); for (unsigned int i = 0; i < size(); i++) outImagePoints.row(i) = Eigen::Matrix<double, 1, 2>( centers.row(i).at<float>(0), centers.row(i).at<float>(1)); return success; } } // namespace cameras } // namespace aslam //export explicit instantions for all included archives #include <sm/boost/serialization.hpp> #include <boost/serialization/export.hpp> BOOST_CLASS_EXPORT_IMPLEMENT(aslam::cameras::GridCalibrationTargetCheckerboard); BOOST_CLASS_EXPORT_IMPLEMENT(aslam::cameras::GridCalibrationTargetCheckerboard::CheckerboardOptions); <commit_msg>consistent checkerboard pattern size<commit_after>#include <vector> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <aslam/cameras/GridCalibrationTargetCheckerboard.hpp> #include <sm/eigen/serialization.hpp> namespace aslam { namespace cameras { /// \brief Construct a calibration target /// rows: number of internal corners (8x8 chessboard would be 7x7 internal corners) /// cols: number of internal corners /// rowSpacingMeters: spacing in y-direction [m] /// colSpacingMeters: spacing in x-direction [m] /// /// point ordering in _points: (e.g. 2x2 grid) /// *-------*-------*-------* /// | BLACK | WHITE | BLACK | /// *------(3)-----(4)------* /// | WHITE | BLACK | WHITE | /// *------(1)-----(2)------* /// y | BLACK | WHITE | BLACK | /// ^ *-------*-------*-------* /// |-->x GridCalibrationTargetCheckerboard::GridCalibrationTargetCheckerboard( size_t rows, size_t cols, double rowSpacingMeters, double colSpacingMeters, const CheckerboardOptions &options) : GridCalibrationTargetBase(rows, cols), _rowSpacingMeters(rowSpacingMeters), _colSpacingMeters(colSpacingMeters), _options(options) { SM_ASSERT_GT(Exception, rowSpacingMeters, 0.0, "rowSpacingMeters has to be positive"); SM_ASSERT_GT(Exception, colSpacingMeters, 0.0, "colSpacingMeters has to be positive"); // allocate memory for the grid points _points.resize(size(), 3); //initialize a normal grid (checkerboard and circlegrids) createGridPoints(); //start the output window if requested initialize(); } /// \brief initialize the object void GridCalibrationTargetCheckerboard::initialize() { if (_options.showExtractionVideo) { cv::namedWindow("Checkerboard corners", CV_WINDOW_AUTOSIZE); cvStartWindowThread(); } } /// \brief initialize a checkerboard grid (cols*rows = (cols)*(rows) internal grid points) /// point ordering: (e.g. 2x2 grid) /// *-------*-------*-------* /// | BLACK | WHITE | BLACK | /// *------(3)-----(4)------* /// | WHITE | BLACK | WHITE | /// *------(1)-----(2)------* /// y | BLACK | WHITE | BLACK | /// ^ *-------*-------*-------* /// |-->x /// void GridCalibrationTargetCheckerboard::createGridPoints() { for (unsigned int r = 0; r < _rows; r++) for (unsigned int c = 0; c < _cols; c++) _points.row(gridCoordinatesToPoint(r, c)) = Eigen::Matrix<double, 1, 3>( _rowSpacingMeters * r, _colSpacingMeters * c, 0.0); } /// \brief extract the calibration target points from an image and write to an observation bool GridCalibrationTargetCheckerboard::computeObservation(const cv::Mat & image, Eigen::MatrixXd & outImagePoints, std::vector<bool> &outCornerObserved) const { // set the open cv flags int flags = cv::CALIB_CB_FAST_CHECK; if (_options.useAdaptiveThreshold) flags += cv::CALIB_CB_ADAPTIVE_THRESH; if ( _options.normalizeImage) flags += cv::CALIB_CB_NORMALIZE_IMAGE; if (_options.filterQuads) flags += cv::CALIB_CB_FILTER_QUADS; // extract the checkerboard corners cv::Size patternSize(cols(), rows()); cv::Mat centers(size(), 2, CV_64FC1); bool success = cv::findChessboardCorners(image, patternSize, centers, flags); // do optional subpixel refinement if (_options.doSubpixelRefinement && success) { cv::cornerSubPix( image, centers, cv::Size(11, 11), cv::Size(-1, -1), cv::TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1)); } //draw corners if (_options.showExtractionVideo) { //image with refined (blue) and raw corners (red) cv::Mat imageCopy1 = image.clone(); cv::cvtColor(imageCopy1, imageCopy1, CV_GRAY2RGB); cv::drawChessboardCorners(imageCopy1, patternSize, centers, true); // write error msg if (!success) cv::putText(imageCopy1, "Detection failed! (frame not used)", cv::Point(50, 50), CV_FONT_HERSHEY_SIMPLEX, 0.8, CV_RGB(255,0,0), 3, 8, false); cv::imshow("Checkerboard corners", imageCopy1); // OpenCV call } //exit here if there is an error if (!success) return success; //set all points as observed (checkerboard is only usable in that case) std::vector<bool> allGood(size(), true); outCornerObserved = allGood; //convert to eigen for output outImagePoints.resize(size(), 2); for (unsigned int i = 0; i < size(); i++) outImagePoints.row(i) = Eigen::Matrix<double, 1, 2>( centers.row(i).at<float>(0), centers.row(i).at<float>(1)); return success; } } // namespace cameras } // namespace aslam //export explicit instantions for all included archives #include <sm/boost/serialization.hpp> #include <boost/serialization/export.hpp> BOOST_CLASS_EXPORT_IMPLEMENT(aslam::cameras::GridCalibrationTargetCheckerboard); BOOST_CLASS_EXPORT_IMPLEMENT(aslam::cameras::GridCalibrationTargetCheckerboard::CheckerboardOptions); <|endoftext|>
<commit_before>/* * Promise2 * * Copyright (c) 2015-2016 "0of" Magnus * Licensed under the MIT license. * https://github.com/0of/Promise2/blob/master/LICENSE */ #ifndef PROMISE2_API_CPP #define PROMISE2_API_CPP #define NESTING_PROMISE 1 #define DEFERRED_PROMISE 1 #ifdef __APPLE__ # define USE_DISPATCH 1 #endif // __APPLE__ /* * testing APIs */ #include "Promise.h" #include "entry.h" #include "ThreadContext_STL.h" class CurrentContext : public Promise2::ThreadContext { public: static ThreadContext *New() { return new CurrentContext; } public: virtual void scheduleToRun(std::function<void()>&& task) override { task(); } }; #ifdef __APPLE__ #include <cstdlib> #include <dispatch/dispatch.h> class GCDContainer : public DefaultContainer { private: std::atomic_int _runningTestCount; private: using Runnable = std::pair<GCDContainer *, LTest::SharedTestRunnable>; static void InvokeRunnable(void *context) { std::unique_ptr<Runnable> runnable{ static_cast<Runnable *>(context) }; runnable->second->run(*runnable->first); } static void quit(void *) { std::exit(0); } public: virtual void scheduleToRun(const LTest::SharedTestRunnable& runnable) override { dispatch_async_f(dispatch_get_main_queue(), new Runnable{ this, runnable }, InvokeRunnable); ++_runningTestCount; } virtual void endRun() override { DefaultContainer::endRun(); if (--_runningTestCount == 0) { dispatch_async_f(dispatch_get_main_queue(), nullptr, quit); } } protected: virtual void startTheLoop() override { dispatch_main(); } }; # define CONTAINER_TYPE GCDContainer #include "ThreadContext_GCD.h" using MainThreadContext = ThreadContextImpl::GCD::MainThreadContext; #else # define CONTAINER_TYPE DefaultContainer #endif // __APPLE__ class UserException : public std::exception {}; class AssertionFailed : public std::exception {}; using STLThreadContext = ThreadContextImpl::STL::DetachedThreadContext; namespace SpecFixedValue { void passUserException(const LTest::SharedCaseEndNotifier& notifier, std::exception_ptr e) { if (e) { try { std::rethrow_exception(e); } catch(const UserException&) { // pass notifier->done(); } catch(...) { notifier->fail(std::make_exception_ptr(AssertionFailed())); } } else { notifier->fail(std::make_exception_ptr(AssertionFailed())); } } #define INIT(context, tag) \ spec \ /* ==> */ \ .it(#tag"should acquire the fulfilled value", [](const LTest::SharedCaseEndNotifier& notifier){ \ constexpr bool truth = true; \ Promise2::Promise<bool>::Resolved(truth).then([=](bool fulfilled){ \ if (truth != fulfilled) { \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ return; \ } \ notifier->done(); \ }, [=](std::exception_ptr) { \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ }, context::New()); \ }) \ \ /* ==> */ \ .it(#tag"should transfer the exception downstream", [](const LTest::SharedCaseEndNotifier& notifier){ \ Promise2::Promise<bool>::Rejected(std::make_exception_ptr(UserException())).then([=](bool){ \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ }, std::bind(passUserException, notifier, std::placeholders::_1), context::New()); \ }) \ \ /* ==> */ \ .it(#tag"should acquire the fulfilled value from returned task", [](const LTest::SharedCaseEndNotifier& notifier){ \ constexpr bool truth = true; \ Promise2::Promise<bool>::New([=]{ return truth; }, context::New()).then([=](bool fulfilled){ \ if (truth != fulfilled) { \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ return; \ } \ notifier->done(); \ }, [=](std::exception_ptr) { \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ }, context::New()); \ }) \ \ /* ==> */ \ .it(#tag"should transfer the exception downstream from returned task", [](const LTest::SharedCaseEndNotifier& notifier){ \ Promise2::Promise<bool>::New([]() -> bool { throw UserException(); }, context::New()).then([=](bool){ \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ }, std::bind(passUserException, notifier, std::placeholders::_1), context::New()); \ }) \ \ /* ==> */ \ .it(#tag"should acquire the fulfilled value from nesting promise", [](const LTest::SharedCaseEndNotifier& notifier){ \ constexpr bool truth = true; \ Promise2::Promise<bool>::New([=]{ return Promise2::Promise<bool>::Resolved(truth); }, context::New()).then([=](bool fulfilled){ \ if (truth != fulfilled) { \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ return; \ } \ notifier->done(); \ }, [=](std::exception_ptr) { \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ }, context::New()); \ }) \ \ /* ==> */ \ .it(#tag"should transfer the exception downstream from nesting promise", [](const LTest::SharedCaseEndNotifier& notifier){ \ Promise2::Promise<bool>::New([]{ \ return Promise2::Promise<bool>::Rejected(std::make_exception_ptr(UserException())); \ }, context::New()).then([=](bool fulfilled){ \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ }, std::bind(passUserException, notifier, std::placeholders::_1), context::New()); \ }) \ \ /* ==> */ \ .it(#tag"should acquire the fulfilled value from deferred promise", [](const LTest::SharedCaseEndNotifier& notifier){ \ constexpr bool truth = true; \ Promise2::Promise<bool>::New([=](Promise2::PromiseDefer<bool>&& deferred){ \ deferred.setResult(truth); \ }, context::New()).then([=](bool fulfilled){ \ if (truth != fulfilled) { \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ return; \ } \ notifier->done(); \ }, [=](std::exception_ptr) { \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ }, context::New()); \ }) \ \ /* ==> */ \ .it(#tag"should transfer the exception downstream from deferred promise", [](const LTest::SharedCaseEndNotifier& notifier){ \ Promise2::Promise<bool>::New([](Promise2::PromiseDefer<bool>&& deferred){ \ deferred.setException(std::make_exception_ptr(UserException())); \ }, context::New()).then([=](bool fulfilled){ \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ }, std::bind(passUserException, notifier, std::placeholders::_1), context::New()); \ }); template<typename T> void init(T& spec) { INIT(CurrentContext, CurrentContext:) INIT(STLThreadContext, STLThreadContext:) #ifdef __APPLE__ INIT(MainThreadContext, GCDThreadContext:) #endif // __APPLE__ // end of the init spec } } // SpecFixedValue TEST_ENTRY(CONTAINER_TYPE, SPEC_TFN(SpecFixedValue::init)) #endif // PROMISE2_API_CPP <commit_msg>add `isFulfilled` & `isRejected` test cases<commit_after>/* * Promise2 * * Copyright (c) 2015-2016 "0of" Magnus * Licensed under the MIT license. * https://github.com/0of/Promise2/blob/master/LICENSE */ #ifndef PROMISE2_API_CPP #define PROMISE2_API_CPP #define NESTING_PROMISE 1 #define DEFERRED_PROMISE 1 #ifdef __APPLE__ # define USE_DISPATCH 1 #endif // __APPLE__ /* * testing APIs */ #include "Promise.h" #include "entry.h" #include "ThreadContext_STL.h" class CurrentContext : public Promise2::ThreadContext { public: static ThreadContext *New() { return new CurrentContext; } public: virtual void scheduleToRun(std::function<void()>&& task) override { task(); } }; #ifdef __APPLE__ #include <cstdlib> #include <dispatch/dispatch.h> class GCDContainer : public DefaultContainer { private: std::atomic_int _runningTestCount; private: using Runnable = std::pair<GCDContainer *, LTest::SharedTestRunnable>; static void InvokeRunnable(void *context) { std::unique_ptr<Runnable> runnable{ static_cast<Runnable *>(context) }; runnable->second->run(*runnable->first); } static void quit(void *) { std::exit(0); } public: virtual void scheduleToRun(const LTest::SharedTestRunnable& runnable) override { dispatch_async_f(dispatch_get_main_queue(), new Runnable{ this, runnable }, InvokeRunnable); ++_runningTestCount; } virtual void endRun() override { DefaultContainer::endRun(); if (--_runningTestCount == 0) { dispatch_async_f(dispatch_get_main_queue(), nullptr, quit); } } protected: virtual void startTheLoop() override { dispatch_main(); } }; # define CONTAINER_TYPE GCDContainer #include "ThreadContext_GCD.h" using MainThreadContext = ThreadContextImpl::GCD::MainThreadContext; #else # define CONTAINER_TYPE DefaultContainer #endif // __APPLE__ class UserException : public std::exception {}; class AssertionFailed : public std::exception {}; using STLThreadContext = ThreadContextImpl::STL::DetachedThreadContext; namespace SpecFixedValue { void passUserException(const LTest::SharedCaseEndNotifier& notifier, std::exception_ptr e) { if (e) { try { std::rethrow_exception(e); } catch(const UserException&) { // pass notifier->done(); } catch(...) { notifier->fail(std::make_exception_ptr(AssertionFailed())); } } else { notifier->fail(std::make_exception_ptr(AssertionFailed())); } } #define INIT(context, tag) \ spec \ /* ==> */ \ .it(#tag"should acquire the fulfilled value", [](const LTest::SharedCaseEndNotifier& notifier){ \ constexpr bool truth = true; \ Promise2::Promise<bool>::Resolved(truth).then([=](bool fulfilled){ \ if (truth != fulfilled) { \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ return; \ } \ notifier->done(); \ }, [=](std::exception_ptr) { \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ }, context::New()); \ }) \ \ /* ==> */ \ .it(#tag"should transfer the exception downstream", [](const LTest::SharedCaseEndNotifier& notifier){ \ Promise2::Promise<bool>::Rejected(std::make_exception_ptr(UserException())).then([=](bool){ \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ }, std::bind(passUserException, notifier, std::placeholders::_1), context::New()); \ }) \ \ /* ==> */ \ .it(#tag"should acquire the fulfilled value from returned task", [](const LTest::SharedCaseEndNotifier& notifier){ \ constexpr bool truth = true; \ Promise2::Promise<bool>::New([=]{ return truth; }, context::New()).then([=](bool fulfilled){ \ if (truth != fulfilled) { \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ return; \ } \ notifier->done(); \ }, [=](std::exception_ptr) { \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ }, context::New()); \ }) \ \ /* ==> */ \ .it(#tag"should transfer the exception downstream from returned task", [](const LTest::SharedCaseEndNotifier& notifier){ \ Promise2::Promise<bool>::New([]() -> bool { throw UserException(); }, context::New()).then([=](bool){ \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ }, std::bind(passUserException, notifier, std::placeholders::_1), context::New()); \ }) \ \ /* ==> */ \ .it(#tag"should acquire the fulfilled value from nesting promise", [](const LTest::SharedCaseEndNotifier& notifier){ \ constexpr bool truth = true; \ Promise2::Promise<bool>::New([=]{ return Promise2::Promise<bool>::Resolved(truth); }, context::New()).then([=](bool fulfilled){ \ if (truth != fulfilled) { \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ return; \ } \ notifier->done(); \ }, [=](std::exception_ptr) { \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ }, context::New()); \ }) \ \ /* ==> */ \ .it(#tag"should transfer the exception downstream from nesting promise", [](const LTest::SharedCaseEndNotifier& notifier){ \ Promise2::Promise<bool>::New([]{ \ return Promise2::Promise<bool>::Rejected(std::make_exception_ptr(UserException())); \ }, context::New()).then([=](bool fulfilled){ \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ }, std::bind(passUserException, notifier, std::placeholders::_1), context::New()); \ }) \ \ /* ==> */ \ .it(#tag"should acquire the fulfilled value from deferred promise", [](const LTest::SharedCaseEndNotifier& notifier){ \ constexpr bool truth = true; \ Promise2::Promise<bool>::New([=](Promise2::PromiseDefer<bool>&& deferred){ \ deferred.setResult(truth); \ }, context::New()).then([=](bool fulfilled){ \ if (truth != fulfilled) { \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ return; \ } \ notifier->done(); \ }, [=](std::exception_ptr) { \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ }, context::New()); \ }) \ \ /* ==> */ \ .it(#tag"should transfer the exception downstream from deferred promise", [](const LTest::SharedCaseEndNotifier& notifier){ \ Promise2::Promise<bool>::New([](Promise2::PromiseDefer<bool>&& deferred){ \ deferred.setException(std::make_exception_ptr(UserException())); \ }, context::New()).then([=](bool fulfilled){ \ notifier->fail(std::make_exception_ptr(AssertionFailed())); \ }, std::bind(passUserException, notifier, std::placeholders::_1), context::New()); \ }); template<typename T> void init(T& spec) { INIT(CurrentContext, CurrentContext:) INIT(STLThreadContext, STLThreadContext:) #ifdef __APPLE__ INIT(MainThreadContext, GCDThreadContext:) #endif // __APPLE__ spec /* ==> */ .it("should be fulfilled", []{ auto p = Promise2::Promise<int>::Resolved(1); if (!p.isFulfilled()) throw AssertionFailed(); }) /* ==> */ .it("should be fulfilled", []{ auto p = Promise2::Promise<int>::Rejected(std::make_exception_ptr(UserException())); if (!p.isRejected()) throw AssertionFailed(); }); // end of the init spec } } // SpecFixedValue TEST_ENTRY(CONTAINER_TYPE, SPEC_TFN(SpecFixedValue::init)) #endif // PROMISE2_API_CPP <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_SD_SOURCE_UI_INC_VIEW_HXX #define INCLUDED_SD_SOURCE_UI_INC_VIEW_HXX #include <boost/ptr_container/ptr_vector.hpp> #include "pres.hxx" #include <tools/gen.hxx> #include <svtools/transfer.hxx> #include <svx/fmview.hxx> #include <svx/svdmark.hxx> #include <svx/svdpage.hxx> #include <vcl/idle.hxx> #include "fupoor.hxx" #include "smarttag.hxx" #include <editeng/numitem.hxx> class SdDrawDocument; class SdPage; class SdrOle2Obj; class SdrGrafObj; class SdrMediaObj; class OutputDevice; class ImageMap; class Point; class Graphic; class SdrOutliner; class TransferableDataHelper; struct StyleRequestData; class Outliner; namespace sd { class DrawDocShell; struct SdNavigatorDropEvent; class ViewShell; class Window; class ViewClipboard; // SdViewRedrawRec struct SdViewRedrawRec { VclPtr<OutputDevice> mpOut; Rectangle aRect; }; //For master view we want to force that master //textboxes have readonly text, because the //text is the auto-generated click-here-to-edit //and it doesn't help to change it class OutlinerMasterViewFilter { private: SdrOutliner *m_pOutl; bool m_bReadOnly; public: OutlinerMasterViewFilter() : m_pOutl(0) , m_bReadOnly(false) { } void Start(SdrOutliner *pOutl); void End(); }; class View : public FmFormView { public: TYPEINFO_OVERRIDE(); View ( SdDrawDocument& rDrawDoc, OutputDevice* pOutDev, ViewShell* pViewSh=NULL); virtual ~View(); void CompleteRedraw( OutputDevice* pOutDev, const vcl::Region& rReg, sdr::contact::ViewObjectContactRedirector* pRedirector = 0L) SAL_OVERRIDE; virtual bool GetAttributes( SfxItemSet& rTargetSet, bool bOnlyHardAttr = false ) const; virtual bool SetAttributes(const SfxItemSet& rSet, bool bReplaceAll = false); virtual void MarkListHasChanged() SAL_OVERRIDE; virtual void ModelHasChanged() SAL_OVERRIDE; void SelectAll(); void DoCut(vcl::Window* pWindow=NULL); void DoCopy(vcl::Window* pWindow=NULL); void DoPaste(vcl::Window* pWindow=NULL); virtual void DoConnect(SdrOle2Obj* pOleObj) SAL_OVERRIDE; virtual bool SetStyleSheet(SfxStyleSheet* pStyleSheet, bool bDontRemoveHardAttr = false); void StartDrag( const Point& rStartPos, vcl::Window* pWindow ); virtual void DragFinished( sal_Int8 nDropAction ); virtual sal_Int8 AcceptDrop ( const AcceptDropEvent& rEvt, DropTargetHelper& rTargetHelper, ::sd::Window* pTargetWindow = NULL, sal_uInt16 nPage = SDRPAGE_NOTFOUND, sal_uInt16 nLayer = SDRPAGE_NOTFOUND); virtual sal_Int8 ExecuteDrop ( const ExecuteDropEvent& rEvt, DropTargetHelper& rTargetHelper, ::sd::Window* pTargetWindow = NULL, sal_uInt16 nPage = SDRPAGE_NOTFOUND, sal_uInt16 nLayer = SDRPAGE_NOTFOUND); ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable> CreateClipboardDataObject (::sd::View*, vcl::Window& rWindow); ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable> CreateDragDataObject (::sd::View*, vcl::Window& rWindow, const Point& rDragPos); ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable> CreateSelectionDataObject (::sd::View*, vcl::Window& rWindow); void UpdateSelectionClipboard( bool bForceDeselect ); inline DrawDocShell* GetDocSh() const { return mpDocSh; } inline SdDrawDocument& GetDoc() const; inline ViewShell* GetViewShell() const { return mpViewSh; } virtual bool SdrBeginTextEdit(SdrObject* pObj, SdrPageView* pPV = 0L, vcl::Window* pWin = 0L, bool bIsNewObj = false, SdrOutliner* pGivenOutliner = 0L, OutlinerView* pGivenOutlinerView = 0L, bool bDontDeleteOutliner = false, bool bOnlyOneView = false, bool bGrabFocus = true) SAL_OVERRIDE; virtual SdrEndTextEditKind SdrEndTextEdit(bool bDontDeleteReally = false) SAL_OVERRIDE; bool RestoreDefaultText( SdrTextObj* pTextObj ); bool InsertData( const TransferableDataHelper& rDataHelper, const Point& rPos, sal_Int8& rDnDAction, bool bDrag, SotClipboardFormatId nFormat = SotClipboardFormatId::NONE, sal_uInt16 nPage = SDRPAGE_NOTFOUND, sal_uInt16 nLayer = SDRLAYER_NOTFOUND ); /** gets the metafile from the given transferable helper and insert it as a graphic shape. @param bOptimize if set to true, the metafile is analyzed and if only one bitmap action is present, then is inserted as a single graphic. */ bool InsertMetaFile( TransferableDataHelper& rDataHelper, const Point& rInsertPos, ImageMap* pImageMap, bool bOptimize ); SdrGrafObj* InsertGraphic( const Graphic& rGraphic, sal_Int8& rAction, const Point& rPos, SdrObject* pSelectedObj, ImageMap* pImageMap ); SdrMediaObj* InsertMediaURL( const OUString& rMediaURL, sal_Int8& rAction, const Point& rPos, const Size& rSize, bool const bLink ); SdrMediaObj* Insert3DModelURL( const OUString& rModelURL, sal_Int8& rAction, const Point& rPos, const Size& rSize, bool const bLink ); SdrMediaObj* InsertMediaObj( const OUString& rURL, const OUString& rMimeType, sal_Int8& rAction, const Point& rPos, const Size& rSize ); bool PasteRTFTable( ::tools::SvRef<SotStorageStream> xStm, SdrPage* pPage, SdrInsertFlags nPasteOptions ); bool IsPresObjSelected(bool bOnPage = true, bool bOnMasterPage = true, bool bCheckPresObjListOnly = false, bool bCheckLayoutOnly = false) const; void SetMarkedOriginalSize(); bool IsMorphingAllowed() const; bool IsVectorizeAllowed() const; virtual SfxStyleSheet* GetStyleSheet() const; /** return parameter: pExchangeList == NULL -> all names are unique bNameOK == false -> cancel by user nType == 0 -> pages nType == 1 -> objects nType == 2 -> pages and objects */ bool GetExchangeList( std::vector<OUString> &rExchangeList, std::vector<OUString> &rBookmarkList, const sal_uInt16 nType ); virtual void onAccessibilityOptionsChanged() SAL_OVERRIDE; virtual SdrModel* GetMarkedObjModel() const SAL_OVERRIDE; virtual bool Paste( const SdrModel& rMod, const Point& rPos, SdrObjList* pLst, SdrInsertFlags nOptions, const OUString& rSrcShellID, const OUString& rDestShellID ) SAL_OVERRIDE; using SdrExchangeView::Paste; /** returns true if we have an undo manager and there is an open list undo action */ bool isRecordingUndo() const; virtual void AddCustomHdl() SAL_OVERRIDE; SmartTagSet& getSmartTags() { return maSmartTags; } void selectSmartTag( const SmartTagReference& xTag ); void updateHandles(); virtual SdrViewContext GetContext() const SAL_OVERRIDE; virtual bool HasMarkablePoints() const SAL_OVERRIDE; virtual sal_uLong GetMarkablePointCount() const SAL_OVERRIDE; virtual bool HasMarkedPoints() const SAL_OVERRIDE; virtual sal_uLong GetMarkedPointCount() const SAL_OVERRIDE; virtual bool IsPointMarkable(const SdrHdl& rHdl) const SAL_OVERRIDE; virtual bool MarkPoint(SdrHdl& rHdl, bool bUnmark=false) SAL_OVERRIDE; virtual void CheckPossibilities() SAL_OVERRIDE; virtual bool MarkPoints(const ::Rectangle* pRect, bool bUnmark) SAL_OVERRIDE; using SdrMarkView::MarkPoints; bool ShouldToggleOn( const bool bBulletOnOffMode, const bool bNormalBullet); /** change the bullets/numbering of the marked objects @param bToggle true: just toggle the current bullets/numbering on --> off resp. off --> on @param bHandleBullets true: handle bullets false: handle numbering @param pNumRule numbering rule which needs to be applied. can be 0. @param bSwitchOff true: switch off bullets/numbering */ void ChangeMarkedObjectsBulletsNumbering( const bool bToggle, const bool bHandleBullets, const SvxNumRule* pNumRule); void SetPossibilitiesDirty() { bPossibilitiesDirty = true; } void SetMoveAllowed( bool bSet ) { bMoveAllowed = bSet; } void SetMoveProtected( bool bSet ) { bMoveProtect = bSet; } void SetResizeFreeAllowed( bool bSet ) { bResizeFreeAllowed = bSet; } void SetResizePropAllowed( bool bSet ) { bResizePropAllowed = bSet; } void SetResizeProtected( bool bSet ) { bResizeProtect = bSet; } void SetMarkedPointsSmoothPossible( bool bSet ) { bSetMarkedPointsSmoothPossible = bSet; } void SetMarkedSegmentsKindPossible( bool bSet ) { bSetMarkedSegmentsKindPossible = bSet; } SdrObject* GetEmptyPresentationObject( PresObjKind eKind ); SdPage* GetPage(); SdrObject* GetSelectedSingleObject(SdPage* pPage); protected: DECL_LINK( OnParagraphInsertedHdl, ::Outliner * ); DECL_LINK( OnParagraphRemovingHdl, ::Outliner * ); virtual void OnBeginPasteOrDrop( PasteOrDropInfos* pInfos ) SAL_OVERRIDE; virtual void OnEndPasteOrDrop( PasteOrDropInfos* pInfos ) SAL_OVERRIDE; SdDrawDocument& mrDoc; DrawDocShell* mpDocSh; ViewShell* mpViewSh; SdrMarkList* mpDragSrcMarkList; SdrObject* mpDropMarkerObj; SdrDropMarkerOverlay* mpDropMarker; sal_uInt16 mnDragSrcPgNum; Point maDropPos; ::std::vector<OUString> maDropFileVector; sal_Int8 mnAction; Idle maDropErrorIdle; Idle maDropInsertFileIdle; sal_uInt16 mnLockRedrawSmph; boost::ptr_vector<SdViewRedrawRec> maLockedRedraws; bool mbIsDropAllowed; DECL_LINK_TYPED( DropErrorHdl, Idle*, void ); DECL_LINK_TYPED( DropInsertFileHdl, Idle*, void ); DECL_LINK( ExecuteNavigatorDrop, SdNavigatorDropEvent* pSdNavigatorDropEvent ); void ImplClearDrawDropMarker(); SmartTagSet maSmartTags; private: ::std::unique_ptr<ViewClipboard> mpClipboard; OutlinerMasterViewFilter maMasterViewFilter; }; SdDrawDocument& View::GetDoc() const { return mrDoc; } } // end of namespace sd #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Fix comment<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_SD_SOURCE_UI_INC_VIEW_HXX #define INCLUDED_SD_SOURCE_UI_INC_VIEW_HXX #include <boost/ptr_container/ptr_vector.hpp> #include "pres.hxx" #include <tools/gen.hxx> #include <svtools/transfer.hxx> #include <svx/fmview.hxx> #include <svx/svdmark.hxx> #include <svx/svdpage.hxx> #include <vcl/idle.hxx> #include "fupoor.hxx" #include "smarttag.hxx" #include <editeng/numitem.hxx> class SdDrawDocument; class SdPage; class SdrOle2Obj; class SdrGrafObj; class SdrMediaObj; class OutputDevice; class ImageMap; class Point; class Graphic; class SdrOutliner; class TransferableDataHelper; struct StyleRequestData; class Outliner; namespace sd { class DrawDocShell; struct SdNavigatorDropEvent; class ViewShell; class Window; class ViewClipboard; // SdViewRedrawRec struct SdViewRedrawRec { VclPtr<OutputDevice> mpOut; Rectangle aRect; }; //For master view we want to force that master //textboxes have readonly text, because the //text is the auto-generated click-here-to-edit //and it doesn't help to change it class OutlinerMasterViewFilter { private: SdrOutliner *m_pOutl; bool m_bReadOnly; public: OutlinerMasterViewFilter() : m_pOutl(0) , m_bReadOnly(false) { } void Start(SdrOutliner *pOutl); void End(); }; class View : public FmFormView { public: TYPEINFO_OVERRIDE(); View ( SdDrawDocument& rDrawDoc, OutputDevice* pOutDev, ViewShell* pViewSh=NULL); virtual ~View(); void CompleteRedraw( OutputDevice* pOutDev, const vcl::Region& rReg, sdr::contact::ViewObjectContactRedirector* pRedirector = 0L) SAL_OVERRIDE; virtual bool GetAttributes( SfxItemSet& rTargetSet, bool bOnlyHardAttr = false ) const; virtual bool SetAttributes(const SfxItemSet& rSet, bool bReplaceAll = false); virtual void MarkListHasChanged() SAL_OVERRIDE; virtual void ModelHasChanged() SAL_OVERRIDE; void SelectAll(); void DoCut(vcl::Window* pWindow=NULL); void DoCopy(vcl::Window* pWindow=NULL); void DoPaste(vcl::Window* pWindow=NULL); virtual void DoConnect(SdrOle2Obj* pOleObj) SAL_OVERRIDE; virtual bool SetStyleSheet(SfxStyleSheet* pStyleSheet, bool bDontRemoveHardAttr = false); void StartDrag( const Point& rStartPos, vcl::Window* pWindow ); virtual void DragFinished( sal_Int8 nDropAction ); virtual sal_Int8 AcceptDrop ( const AcceptDropEvent& rEvt, DropTargetHelper& rTargetHelper, ::sd::Window* pTargetWindow = NULL, sal_uInt16 nPage = SDRPAGE_NOTFOUND, sal_uInt16 nLayer = SDRPAGE_NOTFOUND); virtual sal_Int8 ExecuteDrop ( const ExecuteDropEvent& rEvt, DropTargetHelper& rTargetHelper, ::sd::Window* pTargetWindow = NULL, sal_uInt16 nPage = SDRPAGE_NOTFOUND, sal_uInt16 nLayer = SDRPAGE_NOTFOUND); ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable> CreateClipboardDataObject (::sd::View*, vcl::Window& rWindow); ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable> CreateDragDataObject (::sd::View*, vcl::Window& rWindow, const Point& rDragPos); ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable> CreateSelectionDataObject (::sd::View*, vcl::Window& rWindow); void UpdateSelectionClipboard( bool bForceDeselect ); inline DrawDocShell* GetDocSh() const { return mpDocSh; } inline SdDrawDocument& GetDoc() const; inline ViewShell* GetViewShell() const { return mpViewSh; } virtual bool SdrBeginTextEdit(SdrObject* pObj, SdrPageView* pPV = 0L, vcl::Window* pWin = 0L, bool bIsNewObj = false, SdrOutliner* pGivenOutliner = 0L, OutlinerView* pGivenOutlinerView = 0L, bool bDontDeleteOutliner = false, bool bOnlyOneView = false, bool bGrabFocus = true) SAL_OVERRIDE; virtual SdrEndTextEditKind SdrEndTextEdit(bool bDontDeleteReally = false) SAL_OVERRIDE; bool RestoreDefaultText( SdrTextObj* pTextObj ); bool InsertData( const TransferableDataHelper& rDataHelper, const Point& rPos, sal_Int8& rDnDAction, bool bDrag, SotClipboardFormatId nFormat = SotClipboardFormatId::NONE, sal_uInt16 nPage = SDRPAGE_NOTFOUND, sal_uInt16 nLayer = SDRLAYER_NOTFOUND ); /** gets the metafile from the given transferable helper and insert it as a graphic shape. @param bOptimize if set to true, the metafile is analyzed and if only one bitmap action is present, then is inserted as a single graphic. */ bool InsertMetaFile( TransferableDataHelper& rDataHelper, const Point& rInsertPos, ImageMap* pImageMap, bool bOptimize ); SdrGrafObj* InsertGraphic( const Graphic& rGraphic, sal_Int8& rAction, const Point& rPos, SdrObject* pSelectedObj, ImageMap* pImageMap ); SdrMediaObj* InsertMediaURL( const OUString& rMediaURL, sal_Int8& rAction, const Point& rPos, const Size& rSize, bool const bLink ); SdrMediaObj* Insert3DModelURL( const OUString& rModelURL, sal_Int8& rAction, const Point& rPos, const Size& rSize, bool const bLink ); SdrMediaObj* InsertMediaObj( const OUString& rURL, const OUString& rMimeType, sal_Int8& rAction, const Point& rPos, const Size& rSize ); bool PasteRTFTable( ::tools::SvRef<SotStorageStream> xStm, SdrPage* pPage, SdrInsertFlags nPasteOptions ); bool IsPresObjSelected(bool bOnPage = true, bool bOnMasterPage = true, bool bCheckPresObjListOnly = false, bool bCheckLayoutOnly = false) const; void SetMarkedOriginalSize(); bool IsMorphingAllowed() const; bool IsVectorizeAllowed() const; virtual SfxStyleSheet* GetStyleSheet() const; /** return parameter: pExchangeList == NULL -> all names are unique bNameOK == false -> cancel by user nType == 0 -> pages nType == 1 -> objects nType == 2 -> pages and objects */ bool GetExchangeList( std::vector<OUString> &rExchangeList, std::vector<OUString> &rBookmarkList, const sal_uInt16 nType ); virtual void onAccessibilityOptionsChanged() SAL_OVERRIDE; virtual SdrModel* GetMarkedObjModel() const SAL_OVERRIDE; virtual bool Paste( const SdrModel& rMod, const Point& rPos, SdrObjList* pLst, SdrInsertFlags nOptions, const OUString& rSrcShellID, const OUString& rDestShellID ) SAL_OVERRIDE; using SdrExchangeView::Paste; /** returns true if we have an undo manager and there is an open list undo action */ bool isRecordingUndo() const; virtual void AddCustomHdl() SAL_OVERRIDE; SmartTagSet& getSmartTags() { return maSmartTags; } void selectSmartTag( const SmartTagReference& xTag ); void updateHandles(); virtual SdrViewContext GetContext() const SAL_OVERRIDE; virtual bool HasMarkablePoints() const SAL_OVERRIDE; virtual sal_uLong GetMarkablePointCount() const SAL_OVERRIDE; virtual bool HasMarkedPoints() const SAL_OVERRIDE; virtual sal_uLong GetMarkedPointCount() const SAL_OVERRIDE; virtual bool IsPointMarkable(const SdrHdl& rHdl) const SAL_OVERRIDE; virtual bool MarkPoint(SdrHdl& rHdl, bool bUnmark=false) SAL_OVERRIDE; virtual void CheckPossibilities() SAL_OVERRIDE; virtual bool MarkPoints(const ::Rectangle* pRect, bool bUnmark) SAL_OVERRIDE; using SdrMarkView::MarkPoints; bool ShouldToggleOn( const bool bBulletOnOffMode, const bool bNormalBullet); /** change the bullets/numbering of the marked objects @param bToggle true: just toggle the current bullets/numbering on --> off resp. off --> on @param bHandleBullets true: handle bullets false: handle numbering @param pNumRule numbering rule which needs to be applied. can be 0. */ void ChangeMarkedObjectsBulletsNumbering( const bool bToggle, const bool bHandleBullets, const SvxNumRule* pNumRule); void SetPossibilitiesDirty() { bPossibilitiesDirty = true; } void SetMoveAllowed( bool bSet ) { bMoveAllowed = bSet; } void SetMoveProtected( bool bSet ) { bMoveProtect = bSet; } void SetResizeFreeAllowed( bool bSet ) { bResizeFreeAllowed = bSet; } void SetResizePropAllowed( bool bSet ) { bResizePropAllowed = bSet; } void SetResizeProtected( bool bSet ) { bResizeProtect = bSet; } void SetMarkedPointsSmoothPossible( bool bSet ) { bSetMarkedPointsSmoothPossible = bSet; } void SetMarkedSegmentsKindPossible( bool bSet ) { bSetMarkedSegmentsKindPossible = bSet; } SdrObject* GetEmptyPresentationObject( PresObjKind eKind ); SdPage* GetPage(); SdrObject* GetSelectedSingleObject(SdPage* pPage); protected: DECL_LINK( OnParagraphInsertedHdl, ::Outliner * ); DECL_LINK( OnParagraphRemovingHdl, ::Outliner * ); virtual void OnBeginPasteOrDrop( PasteOrDropInfos* pInfos ) SAL_OVERRIDE; virtual void OnEndPasteOrDrop( PasteOrDropInfos* pInfos ) SAL_OVERRIDE; SdDrawDocument& mrDoc; DrawDocShell* mpDocSh; ViewShell* mpViewSh; SdrMarkList* mpDragSrcMarkList; SdrObject* mpDropMarkerObj; SdrDropMarkerOverlay* mpDropMarker; sal_uInt16 mnDragSrcPgNum; Point maDropPos; ::std::vector<OUString> maDropFileVector; sal_Int8 mnAction; Idle maDropErrorIdle; Idle maDropInsertFileIdle; sal_uInt16 mnLockRedrawSmph; boost::ptr_vector<SdViewRedrawRec> maLockedRedraws; bool mbIsDropAllowed; DECL_LINK_TYPED( DropErrorHdl, Idle*, void ); DECL_LINK_TYPED( DropInsertFileHdl, Idle*, void ); DECL_LINK( ExecuteNavigatorDrop, SdNavigatorDropEvent* pSdNavigatorDropEvent ); void ImplClearDrawDropMarker(); SmartTagSet maSmartTags; private: ::std::unique_ptr<ViewClipboard> mpClipboard; OutlinerMasterViewFilter maMasterViewFilter; }; SdDrawDocument& View::GetDoc() const { return mrDoc; } } // end of namespace sd #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* * * Copyright 2015-2016, Google 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <memory> #include <set> #include <gflags/gflags.h> #include <grpc/support/log.h> #include "test/cpp/qps/driver.h" #include "test/cpp/qps/report.h" #include "test/cpp/util/benchmark_config.h" DEFINE_int32(num_clients, 1, "Number of client binaries"); DEFINE_int32(num_servers, 1, "Number of server binaries"); DEFINE_int32(warmup_seconds, 5, "Warmup time (in seconds)"); DEFINE_int32(benchmark_seconds, 30, "Benchmark time (in seconds)"); DEFINE_int32(local_workers, 0, "Number of local workers to start"); // Common config DEFINE_string(rpc_type, "UNARY", "Type of RPC: UNARY or STREAMING"); // Server config DEFINE_int32(async_server_threads, 1, "Number of threads for async servers"); DEFINE_string(server_type, "SYNC_SERVER", "Server type"); // Client config DEFINE_int32(outstanding_rpcs_per_channel, 1, "Number of outstanding rpcs per channel"); DEFINE_int32(client_channels, 1, "Number of client channels"); DEFINE_int32(simple_req_size, -1, "Simple proto request payload size"); DEFINE_int32(simple_resp_size, -1, "Simple proto response payload size"); DEFINE_int32(bbuf_req_size, -1, "Byte-buffer request payload size"); DEFINE_int32(bbuf_resp_size, -1, "Byte-buffer response payload size"); DEFINE_string(client_type, "SYNC_CLIENT", "Client type"); DEFINE_int32(async_client_threads, 1, "Async client threads"); DEFINE_double(poisson_load, -1.0, "Poisson offered load (qps)"); DEFINE_double(uniform_lo, -1.0, "Uniform low interarrival time (us)"); DEFINE_double(uniform_hi, -1.0, "Uniform high interarrival time (us)"); DEFINE_double(determ_load, -1.0, "Deterministic offered load (qps)"); DEFINE_double(pareto_base, -1.0, "Pareto base interarrival time (us)"); DEFINE_double(pareto_alpha, -1.0, "Pareto alpha value"); DEFINE_bool(secure_test, false, "Run a secure test"); using grpc::testing::ClientConfig; using grpc::testing::ServerConfig; using grpc::testing::ClientType; using grpc::testing::ServerType; using grpc::testing::RpcType; using grpc::testing::ResourceUsage; using grpc::testing::SecurityParams; namespace grpc { namespace testing { static void QpsDriver() { RpcType rpc_type; GPR_ASSERT(RpcType_Parse(FLAGS_rpc_type, &rpc_type)); ClientType client_type; ServerType server_type; GPR_ASSERT(ClientType_Parse(FLAGS_client_type, &client_type)); GPR_ASSERT(ServerType_Parse(FLAGS_server_type, &server_type)); ClientConfig client_config; client_config.set_client_type(client_type); client_config.set_outstanding_rpcs_per_channel( FLAGS_outstanding_rpcs_per_channel); client_config.set_client_channels(FLAGS_client_channels); // Decide which type to use based on the response type if (FLAGS_simple_resp_size >= 0) { auto params = client_config.mutable_payload_config()->mutable_simple_params(); params->set_resp_size(FLAGS_simple_resp_size); if (FLAGS_simple_req_size >= 0) { params->set_req_size(FLAGS_simple_req_size); } } else if (FLAGS_bbuf_resp_size >= 0) { auto params = client_config.mutable_payload_config()->mutable_bytebuf_params(); params->set_resp_size(FLAGS_bbuf_resp_size); if (FLAGS_bbuf_req_size >= 0) { params->set_req_size(FLAGS_bbuf_req_size); } } else { // set a reasonable default: proto but no payload client_config.mutable_payload_config()->mutable_simple_params(); } client_config.set_async_client_threads(FLAGS_async_client_threads); client_config.set_rpc_type(rpc_type); // set up the load parameters if (FLAGS_poisson_load > 0.0) { auto poisson = client_config.mutable_load_params()->mutable_poisson(); poisson->set_offered_load(FLAGS_poisson_load); } else if (FLAGS_uniform_lo > 0.0) { auto uniform = client_config.mutable_load_params()->mutable_uniform(); uniform->set_interarrival_lo(FLAGS_uniform_lo / 1e6); uniform->set_interarrival_hi(FLAGS_uniform_hi / 1e6); } else if (FLAGS_determ_load > 0.0) { auto determ = client_config.mutable_load_params()->mutable_determ(); determ->set_offered_load(FLAGS_determ_load); } else if (FLAGS_pareto_base > 0.0) { auto pareto = client_config.mutable_load_params()->mutable_pareto(); pareto->set_interarrival_base(FLAGS_pareto_base / 1e6); pareto->set_alpha(FLAGS_pareto_alpha); } else { client_config.mutable_load_params()->mutable_closed_loop(); // No further load parameters to set up for closed loop } client_config.mutable_histogram_params()->set_resolution( Histogram::default_resolution()); client_config.mutable_histogram_params()->set_max_possible( Histogram::default_max_possible()); ServerConfig server_config; server_config.set_server_type(server_type); server_config.set_host("::"); // Use the wildcard server address server_config.set_async_server_threads(FLAGS_async_server_threads); if (FLAGS_secure_test) { // Set up security params SecurityParams security; security.set_use_test_ca(true); security.set_server_host_override("foo.test.google.fr"); client_config.mutable_security_params()->CopyFrom(security); server_config.mutable_security_params()->CopyFrom(security); } // Make sure that if we are performing a generic (bytebuf) test // that we are also using async streaming GPR_ASSERT(!client_config.payload_config().has_bytebuf_params() || (client_config.client_type() == ASYNC_CLIENT && client_config.rpc_type() == STREAMING && server_config.server_type() == ASYNC_SERVER)); const auto result = RunScenario( client_config, FLAGS_num_clients, server_config, FLAGS_num_servers, FLAGS_warmup_seconds, FLAGS_benchmark_seconds, FLAGS_local_workers); GetReporter()->ReportQPS(*result); GetReporter()->ReportQPSPerCore(*result); GetReporter()->ReportLatency(*result); GetReporter()->ReportTimes(*result); } } // namespace testing } // namespace grpc int main(int argc, char** argv) { grpc::testing::InitBenchmark(&argc, &argv, true); grpc::testing::QpsDriver(); return 0; } <commit_msg>clang-format<commit_after>/* * * Copyright 2015-2016, Google 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <memory> #include <set> #include <gflags/gflags.h> #include <grpc/support/log.h> #include "test/cpp/qps/driver.h" #include "test/cpp/qps/report.h" #include "test/cpp/util/benchmark_config.h" DEFINE_int32(num_clients, 1, "Number of client binaries"); DEFINE_int32(num_servers, 1, "Number of server binaries"); DEFINE_int32(warmup_seconds, 5, "Warmup time (in seconds)"); DEFINE_int32(benchmark_seconds, 30, "Benchmark time (in seconds)"); DEFINE_int32(local_workers, 0, "Number of local workers to start"); // Common config DEFINE_string(rpc_type, "UNARY", "Type of RPC: UNARY or STREAMING"); // Server config DEFINE_int32(async_server_threads, 1, "Number of threads for async servers"); DEFINE_string(server_type, "SYNC_SERVER", "Server type"); // Client config DEFINE_int32(outstanding_rpcs_per_channel, 1, "Number of outstanding rpcs per channel"); DEFINE_int32(client_channels, 1, "Number of client channels"); DEFINE_int32(simple_req_size, -1, "Simple proto request payload size"); DEFINE_int32(simple_resp_size, -1, "Simple proto response payload size"); DEFINE_int32(bbuf_req_size, -1, "Byte-buffer request payload size"); DEFINE_int32(bbuf_resp_size, -1, "Byte-buffer response payload size"); DEFINE_string(client_type, "SYNC_CLIENT", "Client type"); DEFINE_int32(async_client_threads, 1, "Async client threads"); DEFINE_double(poisson_load, -1.0, "Poisson offered load (qps)"); DEFINE_double(uniform_lo, -1.0, "Uniform low interarrival time (us)"); DEFINE_double(uniform_hi, -1.0, "Uniform high interarrival time (us)"); DEFINE_double(determ_load, -1.0, "Deterministic offered load (qps)"); DEFINE_double(pareto_base, -1.0, "Pareto base interarrival time (us)"); DEFINE_double(pareto_alpha, -1.0, "Pareto alpha value"); DEFINE_bool(secure_test, false, "Run a secure test"); using grpc::testing::ClientConfig; using grpc::testing::ServerConfig; using grpc::testing::ClientType; using grpc::testing::ServerType; using grpc::testing::RpcType; using grpc::testing::ResourceUsage; using grpc::testing::SecurityParams; namespace grpc { namespace testing { static void QpsDriver() { RpcType rpc_type; GPR_ASSERT(RpcType_Parse(FLAGS_rpc_type, &rpc_type)); ClientType client_type; ServerType server_type; GPR_ASSERT(ClientType_Parse(FLAGS_client_type, &client_type)); GPR_ASSERT(ServerType_Parse(FLAGS_server_type, &server_type)); ClientConfig client_config; client_config.set_client_type(client_type); client_config.set_outstanding_rpcs_per_channel( FLAGS_outstanding_rpcs_per_channel); client_config.set_client_channels(FLAGS_client_channels); // Decide which type to use based on the response type if (FLAGS_simple_resp_size >= 0) { auto params = client_config.mutable_payload_config()->mutable_simple_params(); params->set_resp_size(FLAGS_simple_resp_size); if (FLAGS_simple_req_size >= 0) { params->set_req_size(FLAGS_simple_req_size); } } else if (FLAGS_bbuf_resp_size >= 0) { auto params = client_config.mutable_payload_config()->mutable_bytebuf_params(); params->set_resp_size(FLAGS_bbuf_resp_size); if (FLAGS_bbuf_req_size >= 0) { params->set_req_size(FLAGS_bbuf_req_size); } } else { // set a reasonable default: proto but no payload client_config.mutable_payload_config()->mutable_simple_params(); } client_config.set_async_client_threads(FLAGS_async_client_threads); client_config.set_rpc_type(rpc_type); // set up the load parameters if (FLAGS_poisson_load > 0.0) { auto poisson = client_config.mutable_load_params()->mutable_poisson(); poisson->set_offered_load(FLAGS_poisson_load); } else if (FLAGS_uniform_lo > 0.0) { auto uniform = client_config.mutable_load_params()->mutable_uniform(); uniform->set_interarrival_lo(FLAGS_uniform_lo / 1e6); uniform->set_interarrival_hi(FLAGS_uniform_hi / 1e6); } else if (FLAGS_determ_load > 0.0) { auto determ = client_config.mutable_load_params()->mutable_determ(); determ->set_offered_load(FLAGS_determ_load); } else if (FLAGS_pareto_base > 0.0) { auto pareto = client_config.mutable_load_params()->mutable_pareto(); pareto->set_interarrival_base(FLAGS_pareto_base / 1e6); pareto->set_alpha(FLAGS_pareto_alpha); } else { client_config.mutable_load_params()->mutable_closed_loop(); // No further load parameters to set up for closed loop } client_config.mutable_histogram_params()->set_resolution( Histogram::default_resolution()); client_config.mutable_histogram_params()->set_max_possible( Histogram::default_max_possible()); ServerConfig server_config; server_config.set_server_type(server_type); server_config.set_host("::"); // Use the wildcard server address server_config.set_async_server_threads(FLAGS_async_server_threads); if (FLAGS_secure_test) { // Set up security params SecurityParams security; security.set_use_test_ca(true); security.set_server_host_override("foo.test.google.fr"); client_config.mutable_security_params()->CopyFrom(security); server_config.mutable_security_params()->CopyFrom(security); } // Make sure that if we are performing a generic (bytebuf) test // that we are also using async streaming GPR_ASSERT(!client_config.payload_config().has_bytebuf_params() || (client_config.client_type() == ASYNC_CLIENT && client_config.rpc_type() == STREAMING && server_config.server_type() == ASYNC_SERVER)); const auto result = RunScenario( client_config, FLAGS_num_clients, server_config, FLAGS_num_servers, FLAGS_warmup_seconds, FLAGS_benchmark_seconds, FLAGS_local_workers); GetReporter()->ReportQPS(*result); GetReporter()->ReportQPSPerCore(*result); GetReporter()->ReportLatency(*result); GetReporter()->ReportTimes(*result); } } // namespace testing } // namespace grpc int main(int argc, char** argv) { grpc::testing::InitBenchmark(&argc, &argv, true); grpc::testing::QpsDriver(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: pam.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: vg $ $Date: 2005-02-22 08:16:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _PAM_HXX #define _PAM_HXX #include <stddef.h> // fuer MemPool #ifndef _GEN_HXX //autogen #include <tools/gen.hxx> #endif #ifndef _SVMEMPOOL_HXX //autogen #include <tools/mempool.hxx> #endif #ifndef _CSHTYP_HXX #include <cshtyp.hxx> // fuer die Funktions-Definitionen #endif #ifndef _RING_HXX #include <ring.hxx> // Superklasse #endif #ifndef _INDEX_HXX #include <index.hxx> // fuer SwIndex #endif #ifndef _NDINDEX_HXX #include <ndindex.hxx> // fuer SwNodeIndex #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif class SwFmt; class SfxPoolItem; class SfxItemSet; class SwDoc; class SwNode; class SwCntntNode; class SwNodes; class SwPaM; namespace com { namespace sun { namespace star { namespace util { struct SearchOptions; } } } } namespace utl { class TextSearch; }; struct SwPosition { SwNodeIndex nNode; SwIndex nContent; SwPosition( const SwNode& rNode ); SwPosition( const SwNodeIndex &rNode ); SwPosition( const SwNodeIndex &rNode, const SwIndex &rCntnt ); SwPosition( const SwPosition & ); SwPosition &operator=(const SwPosition &); // #111827# /** Returns the document this position is in. @return the document this position is in. */ SwDoc * GetDoc() const; FASTBOOL operator < (const SwPosition &) const; FASTBOOL operator > (const SwPosition &) const; FASTBOOL operator <=(const SwPosition &) const; FASTBOOL operator >=(const SwPosition &) const; FASTBOOL operator ==(const SwPosition &) const; FASTBOOL operator !=(const SwPosition &) const; }; // das Ergebnis eines Positions Vergleiches enum SwComparePosition { POS_BEFORE, // Pos1 liegt vor Pos2 POS_BEHIND, // Pos1 liegt hinter Pos2 POS_INSIDE, // Pos1 liegt vollstaendig in Pos2 POS_OUTSIDE, // Pos2 liegt vollstaendig in Pos1 POS_EQUAL, // Pos1 ist genauso gross wie Pos2 POS_OVERLAP_BEFORE, // Pos1 ueberlappt Pos2 am Anfang POS_OVERLAP_BEHIND, // Pos1 ueberlappt Pos2 am Ende POS_COLLIDE_START, // Pos1 Start stoesst an Pos2 Ende POS_COLLIDE_END // Pos1 End stoesst an Pos2 Start }; SwComparePosition ComparePosition( const SwPosition& rStt1, const SwPosition& rEnd1, const SwPosition& rStt2, const SwPosition& rEnd2 ); SwComparePosition ComparePosition( const unsigned long nStt1, const unsigned long nEnd1, const unsigned long nStt2, const unsigned long nEnd2 ); // SwPointAndMark / SwPaM struct SwMoveFnCollection; typedef SwMoveFnCollection* SwMoveFn; SW_DLLPUBLIC extern SwMoveFn fnMoveForward; // SwPam::Move()/Find() default argument. extern SwMoveFn fnMoveBackward; typedef FASTBOOL (*SwGoInDoc)( SwPaM& rPam, SwMoveFn fnMove ); extern SwGoInDoc fnGoDoc; extern SwGoInDoc fnGoSection; extern SwGoInDoc fnGoNode; SW_DLLPUBLIC extern SwGoInDoc fnGoCntnt; // SwPam::Move() default argument. extern SwGoInDoc fnGoCntntCells; extern SwGoInDoc fnGoCntntSkipHidden; extern SwGoInDoc fnGoCntntCellsSkipHidden; void _InitPam(); class SwPaM : public Ring { SwPosition aBound1; SwPosition aBound2; SwPosition *pPoint; SwPosition *pMark; FASTBOOL bIsInFrontOfLabel; SwPaM* MakeRegion( SwMoveFn fnMove, const SwPaM * pOrigRg = 0 ); public: SwPaM( const SwPosition& rPos, SwPaM* pRing = 0 ); SwPaM( const SwPosition& rMk, const SwPosition& rPt, SwPaM* pRing = 0 ); SwPaM( const SwNodeIndex& rMk, const SwNodeIndex& rPt, long nMkOffset = 0, long nPtOffset = 0, SwPaM* pRing = 0 ); SwPaM( const SwNode& rMk, const SwNode& rPt, long nMkOffset = 0, long nPtOffset = 0, SwPaM* pRing = 0 ); SwPaM( const SwNodeIndex& rMk, xub_StrLen nMkCntnt, const SwNodeIndex& rPt, xub_StrLen nPtCntnt, SwPaM* pRing = 0 ); SwPaM( const SwNode& rMk, xub_StrLen nMkCntnt, const SwNode& rPt, xub_StrLen nPtCntnt, SwPaM* pRing = 0 ); SwPaM( const SwNode& rNd, xub_StrLen nCntnt = 0, SwPaM* pRing = 0 ); SwPaM( const SwNodeIndex& rNd, xub_StrLen nCntnt = 0, SwPaM* pRing = 0 ); virtual ~SwPaM(); // @@@ semantic: no copy ctor. SwPaM( SwPaM & ); // @@@ semantic: no copy assignment for super class Ring. SwPaM& operator=( const SwPaM & ); // Bewegen des Cursors FASTBOOL Move( SwMoveFn fnMove = fnMoveForward, SwGoInDoc fnGo = fnGoCntnt ); // Suchen BYTE Find( const com::sun::star::util::SearchOptions& rSearchOpt, utl::TextSearch& rSTxt, SwMoveFn fnMove = fnMoveForward, const SwPaM *pPam =0, FASTBOOL bInReadOnly = FALSE); FASTBOOL Find( const SwFmt& rFmt, SwMoveFn fnMove = fnMoveForward, const SwPaM *pPam =0, FASTBOOL bInReadOnly = FALSE); FASTBOOL Find( const SfxPoolItem& rAttr, FASTBOOL bValue = TRUE, SwMoveFn fnMove = fnMoveForward, const SwPaM *pPam =0, FASTBOOL bInReadOnly = FALSE ); FASTBOOL Find( const SfxItemSet& rAttr, FASTBOOL bNoColls = FALSE, SwMoveFn fnMove = fnMoveForward, const SwPaM *pPam =0, FASTBOOL bInReadOnly = FALSE ); inline FASTBOOL IsInFrontOfLabel() const { return bIsInFrontOfLabel; } inline void _SetInFrontOfLabel( FASTBOOL bNew ) { bIsInFrontOfLabel = bNew; } virtual void SetMark(); void DeleteMark() { pMark = pPoint; } #ifdef PRODUCT void Exchange() { if(pPoint != pMark) { SwPosition *pTmp = pPoint; pPoint = pMark; pMark = pTmp; } } #else void Exchange(); #endif /* * Undokumented Feature: Liefert zurueck, ob das Pam ueber * eine Selektion verfuegt oder nicht. Definition einer * Selektion: Point und Mark zeigen auf unterschiedliche * Puffer. */ FASTBOOL HasMark() const { return pPoint == pMark? FALSE : TRUE; } const SwPosition *GetPoint() const { return pPoint; } SwPosition *GetPoint() { return pPoint; } const SwPosition *GetMark() const { return pMark; } SwPosition *GetMark() { return pMark; } const SwPosition *Start() const { return (*pPoint) <= (*pMark)? pPoint: pMark; } SwPosition *Start() { return (*pPoint) <= (*pMark)? pPoint: pMark; } const SwPosition *End() const { return (*pPoint) > (*pMark)? pPoint: pMark; } SwPosition *End() { return (*pPoint) > (*pMark)? pPoint: pMark; } // erfrage vom SwPaM den aktuellen Node/ContentNode am SPoint / Mark SwNode* GetNode( BOOL bPoint = TRUE ) const { return &( bPoint ? pPoint->nNode : pMark->nNode ).GetNode(); } SwCntntNode* GetCntntNode( BOOL bPoint = TRUE ) const { return ( bPoint ? pPoint->nNode : pMark->nNode ).GetNode().GetCntntNode(); } /** Normalizes PaM, i.e. sort point and mark. @param bPointFirst TRUE: If the point is behind the mark then swap. FALSE: If the mark is behind the point then swap. */ SwPaM & Normalize(BOOL bPointFirst = TRUE); // erfrage vom SwPaM das Dokument, in dem er angemeldet ist SwDoc* GetDoc() const { return pPoint->nNode.GetNode().GetDoc(); } SwPosition& GetBound( BOOL bOne = TRUE ) { return bOne ? aBound1 : aBound2; } const SwPosition& GetBound( BOOL bOne = TRUE ) const { return bOne ? aBound1 : aBound2; } // erfrage die Seitennummer auf der der Cursor steht USHORT GetPageNum( BOOL bAtPoint = TRUE, const Point* pLayPos = 0 ); // steht in etwas geschuetztem oder in die Selektion umspannt // etwas geschuetztes. FASTBOOL HasReadonlySel( bool bFormView ) const; DECL_FIXEDMEMPOOL_NEWDEL(SwPaM); String GetTxt() const; }; FASTBOOL CheckNodesRange( const SwNodeIndex&, const SwNodeIndex&, FASTBOOL ); FASTBOOL GoInCntnt( SwPaM & rPam, SwMoveFn fnMove ); #endif // _PAM_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.12.306); FILE MERGED 2005/09/05 13:36:22 rt 1.12.306.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pam.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: rt $ $Date: 2005-09-09 02:04:30 $ * * 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 _PAM_HXX #define _PAM_HXX #include <stddef.h> // fuer MemPool #ifndef _GEN_HXX //autogen #include <tools/gen.hxx> #endif #ifndef _SVMEMPOOL_HXX //autogen #include <tools/mempool.hxx> #endif #ifndef _CSHTYP_HXX #include <cshtyp.hxx> // fuer die Funktions-Definitionen #endif #ifndef _RING_HXX #include <ring.hxx> // Superklasse #endif #ifndef _INDEX_HXX #include <index.hxx> // fuer SwIndex #endif #ifndef _NDINDEX_HXX #include <ndindex.hxx> // fuer SwNodeIndex #endif #ifndef INCLUDED_SWDLLAPI_H #include "swdllapi.h" #endif class SwFmt; class SfxPoolItem; class SfxItemSet; class SwDoc; class SwNode; class SwCntntNode; class SwNodes; class SwPaM; namespace com { namespace sun { namespace star { namespace util { struct SearchOptions; } } } } namespace utl { class TextSearch; }; struct SwPosition { SwNodeIndex nNode; SwIndex nContent; SwPosition( const SwNode& rNode ); SwPosition( const SwNodeIndex &rNode ); SwPosition( const SwNodeIndex &rNode, const SwIndex &rCntnt ); SwPosition( const SwPosition & ); SwPosition &operator=(const SwPosition &); // #111827# /** Returns the document this position is in. @return the document this position is in. */ SwDoc * GetDoc() const; FASTBOOL operator < (const SwPosition &) const; FASTBOOL operator > (const SwPosition &) const; FASTBOOL operator <=(const SwPosition &) const; FASTBOOL operator >=(const SwPosition &) const; FASTBOOL operator ==(const SwPosition &) const; FASTBOOL operator !=(const SwPosition &) const; }; // das Ergebnis eines Positions Vergleiches enum SwComparePosition { POS_BEFORE, // Pos1 liegt vor Pos2 POS_BEHIND, // Pos1 liegt hinter Pos2 POS_INSIDE, // Pos1 liegt vollstaendig in Pos2 POS_OUTSIDE, // Pos2 liegt vollstaendig in Pos1 POS_EQUAL, // Pos1 ist genauso gross wie Pos2 POS_OVERLAP_BEFORE, // Pos1 ueberlappt Pos2 am Anfang POS_OVERLAP_BEHIND, // Pos1 ueberlappt Pos2 am Ende POS_COLLIDE_START, // Pos1 Start stoesst an Pos2 Ende POS_COLLIDE_END // Pos1 End stoesst an Pos2 Start }; SwComparePosition ComparePosition( const SwPosition& rStt1, const SwPosition& rEnd1, const SwPosition& rStt2, const SwPosition& rEnd2 ); SwComparePosition ComparePosition( const unsigned long nStt1, const unsigned long nEnd1, const unsigned long nStt2, const unsigned long nEnd2 ); // SwPointAndMark / SwPaM struct SwMoveFnCollection; typedef SwMoveFnCollection* SwMoveFn; SW_DLLPUBLIC extern SwMoveFn fnMoveForward; // SwPam::Move()/Find() default argument. extern SwMoveFn fnMoveBackward; typedef FASTBOOL (*SwGoInDoc)( SwPaM& rPam, SwMoveFn fnMove ); extern SwGoInDoc fnGoDoc; extern SwGoInDoc fnGoSection; extern SwGoInDoc fnGoNode; SW_DLLPUBLIC extern SwGoInDoc fnGoCntnt; // SwPam::Move() default argument. extern SwGoInDoc fnGoCntntCells; extern SwGoInDoc fnGoCntntSkipHidden; extern SwGoInDoc fnGoCntntCellsSkipHidden; void _InitPam(); class SwPaM : public Ring { SwPosition aBound1; SwPosition aBound2; SwPosition *pPoint; SwPosition *pMark; FASTBOOL bIsInFrontOfLabel; SwPaM* MakeRegion( SwMoveFn fnMove, const SwPaM * pOrigRg = 0 ); public: SwPaM( const SwPosition& rPos, SwPaM* pRing = 0 ); SwPaM( const SwPosition& rMk, const SwPosition& rPt, SwPaM* pRing = 0 ); SwPaM( const SwNodeIndex& rMk, const SwNodeIndex& rPt, long nMkOffset = 0, long nPtOffset = 0, SwPaM* pRing = 0 ); SwPaM( const SwNode& rMk, const SwNode& rPt, long nMkOffset = 0, long nPtOffset = 0, SwPaM* pRing = 0 ); SwPaM( const SwNodeIndex& rMk, xub_StrLen nMkCntnt, const SwNodeIndex& rPt, xub_StrLen nPtCntnt, SwPaM* pRing = 0 ); SwPaM( const SwNode& rMk, xub_StrLen nMkCntnt, const SwNode& rPt, xub_StrLen nPtCntnt, SwPaM* pRing = 0 ); SwPaM( const SwNode& rNd, xub_StrLen nCntnt = 0, SwPaM* pRing = 0 ); SwPaM( const SwNodeIndex& rNd, xub_StrLen nCntnt = 0, SwPaM* pRing = 0 ); virtual ~SwPaM(); // @@@ semantic: no copy ctor. SwPaM( SwPaM & ); // @@@ semantic: no copy assignment for super class Ring. SwPaM& operator=( const SwPaM & ); // Bewegen des Cursors FASTBOOL Move( SwMoveFn fnMove = fnMoveForward, SwGoInDoc fnGo = fnGoCntnt ); // Suchen BYTE Find( const com::sun::star::util::SearchOptions& rSearchOpt, utl::TextSearch& rSTxt, SwMoveFn fnMove = fnMoveForward, const SwPaM *pPam =0, FASTBOOL bInReadOnly = FALSE); FASTBOOL Find( const SwFmt& rFmt, SwMoveFn fnMove = fnMoveForward, const SwPaM *pPam =0, FASTBOOL bInReadOnly = FALSE); FASTBOOL Find( const SfxPoolItem& rAttr, FASTBOOL bValue = TRUE, SwMoveFn fnMove = fnMoveForward, const SwPaM *pPam =0, FASTBOOL bInReadOnly = FALSE ); FASTBOOL Find( const SfxItemSet& rAttr, FASTBOOL bNoColls = FALSE, SwMoveFn fnMove = fnMoveForward, const SwPaM *pPam =0, FASTBOOL bInReadOnly = FALSE ); inline FASTBOOL IsInFrontOfLabel() const { return bIsInFrontOfLabel; } inline void _SetInFrontOfLabel( FASTBOOL bNew ) { bIsInFrontOfLabel = bNew; } virtual void SetMark(); void DeleteMark() { pMark = pPoint; } #ifdef PRODUCT void Exchange() { if(pPoint != pMark) { SwPosition *pTmp = pPoint; pPoint = pMark; pMark = pTmp; } } #else void Exchange(); #endif /* * Undokumented Feature: Liefert zurueck, ob das Pam ueber * eine Selektion verfuegt oder nicht. Definition einer * Selektion: Point und Mark zeigen auf unterschiedliche * Puffer. */ FASTBOOL HasMark() const { return pPoint == pMark? FALSE : TRUE; } const SwPosition *GetPoint() const { return pPoint; } SwPosition *GetPoint() { return pPoint; } const SwPosition *GetMark() const { return pMark; } SwPosition *GetMark() { return pMark; } const SwPosition *Start() const { return (*pPoint) <= (*pMark)? pPoint: pMark; } SwPosition *Start() { return (*pPoint) <= (*pMark)? pPoint: pMark; } const SwPosition *End() const { return (*pPoint) > (*pMark)? pPoint: pMark; } SwPosition *End() { return (*pPoint) > (*pMark)? pPoint: pMark; } // erfrage vom SwPaM den aktuellen Node/ContentNode am SPoint / Mark SwNode* GetNode( BOOL bPoint = TRUE ) const { return &( bPoint ? pPoint->nNode : pMark->nNode ).GetNode(); } SwCntntNode* GetCntntNode( BOOL bPoint = TRUE ) const { return ( bPoint ? pPoint->nNode : pMark->nNode ).GetNode().GetCntntNode(); } /** Normalizes PaM, i.e. sort point and mark. @param bPointFirst TRUE: If the point is behind the mark then swap. FALSE: If the mark is behind the point then swap. */ SwPaM & Normalize(BOOL bPointFirst = TRUE); // erfrage vom SwPaM das Dokument, in dem er angemeldet ist SwDoc* GetDoc() const { return pPoint->nNode.GetNode().GetDoc(); } SwPosition& GetBound( BOOL bOne = TRUE ) { return bOne ? aBound1 : aBound2; } const SwPosition& GetBound( BOOL bOne = TRUE ) const { return bOne ? aBound1 : aBound2; } // erfrage die Seitennummer auf der der Cursor steht USHORT GetPageNum( BOOL bAtPoint = TRUE, const Point* pLayPos = 0 ); // steht in etwas geschuetztem oder in die Selektion umspannt // etwas geschuetztes. FASTBOOL HasReadonlySel( bool bFormView ) const; DECL_FIXEDMEMPOOL_NEWDEL(SwPaM); String GetTxt() const; }; FASTBOOL CheckNodesRange( const SwNodeIndex&, const SwNodeIndex&, FASTBOOL ); FASTBOOL GoInCntnt( SwPaM & rPam, SwMoveFn fnMove ); #endif // _PAM_HXX <|endoftext|>
<commit_before>// Reverse by Predicate // c++11, c++14 #include <algorithm> template <typename I, typename P> void reverse_by_predicate(I begin, I end, P pred) //requires BidirectionalIterator<I> && Predicate<P, ValueType<I>> { while (begin != end) { end = std::rotate(begin, std::find_if(begin, end, pred), end); if (begin == end) { return; } end = std::rotate(begin, std::find_if_not(begin, end, pred), end); } } // Reverse sub-sequences of some larger sequence. // // Useful when elements relate to each other in more complex ways than just // their position in a range. In the attached example, we reverse the words in // a sentence by rotating blocks of "spaces" and "non-spaces" to the end of our // range. `std::rotate` returns the new position of what used to be in // `begin`, which in our case was the start of our block. // // Thus by setting our `end` to this return value, we remove it from the blocks // of text left to reverse. Finally, we know that the next block of text we // are to reverse will be the logical negation (`if -> if_not, if_not -> if`) // of our previous search; hence the alternating rotation points. // // In more mathematical terms: // // * Let `H` be longest _"block"_ of values with consistent predicate // evaluations. // * Let `T` be the rest of the values. // // * Then `reverse(H + T) = reverse(T) + H`; and `T` can be broken up into // its own `H + T` pair. // // // *Note*: This can become more flexible if we allow our predicate to return // any value, and split on non-equal evaluations. This is left as an exercise // for the reader! // #include <algorithm> #include <iostream> #include <string> template <typename I, typename P> void reverse_by_predicate(I begin, I end, P pred) //requires BidirectionalIterator<I> && Predicate<P, ValueType<I>> { while (begin != end) { end = std::rotate(begin, std::find_if(begin + 1, end, pred), end); if (begin == end) { return; } end = std::rotate(begin, std::find_if_not(begin + 1, end, pred), end); } } int main() { std::string str{ "mary had a little lamb whose fleece was white as snow" }; std::cout << '"' << str << '"' << std::endl; reverse_by_predicate(str.begin(), str.end(), ::isspace); std::cout << '"' << str << '"' << std::endl; // `str` is now: "snow as white was fleece whose lamb little a had mary" } <commit_msg>Update reverse-by-predicate.cpp<commit_after>// Reverse by Predicate // c++11, c++14 #include <algorithm> template <typename I, typename P> void reverse_by_predicate(I begin, I end, P pred) //requires BidirectionalIterator<I> && Predicate<P, ValueType<I>> { while (begin != end) { end = std::rotate(begin, std::find_if(begin, end, pred), end); if (begin == end) { return; } end = std::rotate(begin, std::find_if_not(begin, end, pred), end); } } // Reverse sub-sequences of some larger sequence. // // Useful when elements relate to each other in more complex ways than just // their position in a range. In the attached example, we reverse the words in // a sentence by rotating blocks of "spaces" and "non-spaces" to the end of our // range. `std::rotate` returns the new position of what used to be in // `begin`, which in our case was the start of our block. // // Thus by setting our `end` to this return value, we remove it from the blocks // of text left to reverse. Finally, we know that the next block of text we // are to reverse will be the logical negation (`if -> if_not, if_not -> if`) // of our previous search; hence the alternating rotation points. // // In more mathematical terms: // // * Let `H` be longest _"block"_ of values with consistent predicate // evaluations. // * Let `T` be the rest of the values. // // * Then `reverse(H + T) = reverse(T) + H`; and `T` can be broken up into // its own `H + T` pair. // // // *Note*: This can become more flexible if we allow our predicate to return // any value, and split on non-equal evaluations. This is left as an exercise // for the reader! // #include <algorithm> #include <iostream> #include <string> template <typename I, typename P> void reverse_by_predicate(I begin, I end, P pred) //requires BidirectionalIterator<I> && Predicate<P, ValueType<I>> { while (begin != end) { end = std::rotate(begin, std::find_if(begin, end, pred), end); if (begin == end) { return; } end = std::rotate(begin, std::find_if_not(begin, end, pred), end); } } int main() { std::string str{ "mary had a little lamb whose fleece was white as snow" }; std::cout << '"' << str << '"' << std::endl; reverse_by_predicate(str.begin(), str.end(), ::isspace); std::cout << '"' << str << '"' << std::endl; // `str` is now: "snow as white was fleece whose lamb little a had mary" } <|endoftext|>
<commit_before>/** * @file game_object.hpp * @brief Contains methods to game_object class' management. This methods can control the entire * game object, setting the components, free them, loading and playing audio, animations, components, * setting and displaying hitboxes, detecting and notifing collission with other game objects. * * MIT License * Copyright (c) 2017 MindScape * * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md */ //TODO trocar os vectors de componentes para unordered maps //TODO acabar com o primeiro construtor e definir hit box como um componente //TODO colocar todos os estados para usar o SATE MAP #ifndef GAME_OBJECT_H #define GAME_OBJECT_H #include <iostream> #include <map> #include <unordered_map> #include <vector> #include <list> #include <string> #include <utility> #include "SDL2basics.hpp" #include "component.hpp" #include "image.hpp" #include "text.hpp" #include "audio.hpp" #include "hitbox.hpp" #include "keyboard_event.hpp" #include "state_map.hpp" #include "animation.hpp" #include "observer.hpp" #include "observable.hpp" #include "../../include/game_event.hpp" namespace engine { class Animation; /** * @brief A Game class. * * This class can control all the components of the game object. * @warning Limitations: The number of game object in game is limited to the pc memory. All game object after being * used needs to be free. */ class GameObject : public Observer, public Observable { private: std::pair<float, float> speed; std::pair<float, float> position; std::vector<Hitbox *> hitboxes; Animation* actual_animation = NULL; bool active; std::list<Observer *> observers; void run_collisions(GameObject *); protected: virtual void on_collision(GameObject *, Hitbox *, Hitbox *) { }; public: static bool on_limit_of_level; std::string name; int priority; bool collidable; std::vector<Component *> audios; std::vector<Component *> images; std::vector<Component *> texts; std::map<std::string, Animation *> animations; std::map<KeyboardEvent::Key, std::string> translations; std::string state; std::string game_object_direction; StateMap states; GameObject() { }; GameObject( std::string p_name, std::pair<float, float> p_position, int p_priority, std::map<KeyboardEvent::Key,std::string> p_translations, StateMap p_states = StateMap()) :name(p_name), position(p_position), active(false), priority(p_priority), translations(p_translations), states(p_states), speed(std::make_pair(0.0, 0.0)) { }; ~GameObject() { }; bool load(); void free(); void draw(); void add_component(Component *); void add_animation(std::string, Animation *); bool equals(GameObject *); void collide(GameObject *); Audio * get_audio_by_name(std::string); void play_song(std::string); void stop_song(std::string); void set_repetitions(std::string, int repet); void set_music_volume(std::string, int vol); void free_music(std::string); std::pair<float, float> get_position(); float get_position_x(); float get_position_y(); void set_position(std::pair<float, float>); void set_position_x(float); void set_position_y(float); std::pair<float, float> get_speed(); float get_speed_x(); float get_speed_y(); void set_speed(std::pair<float, float>); void set_speed_x(float); void set_speed_y(float); void activate(); void deactivate(); void deactivate_components(); bool is_active(); std::string get_state(std::string); std::vector<Hitbox*> get_hitboxes(); void create_hitbox(std::pair<int, int>, std::pair<int, int>); virtual void on_event(GameEvent) { }; void update_hitboxes(); virtual void update_state(); void set_actual_animation(Animation *); Animation* get_actual_animation(); void attach_observer(Observer *); void detach_observer(Observer *); void notify_observers(); virtual void notify(Observable *) { }; }; } #endif <commit_msg>[INITIALIZATION] Apply initialization in game_object.hpp variables<commit_after>/** * @file game_object.hpp * @brief Contains methods to game_object class' management. This methods can control the entire * game object, setting the components, free them, loading and playing audio, animations, components, * setting and displaying hitboxes, detecting and notifing collission with other game objects. * * MIT License * Copyright (c) 2017 MindScape * * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md */ //TODO trocar os vectors de componentes para unordered maps //TODO acabar com o primeiro construtor e definir hit box como um componente //TODO colocar todos os estados para usar o SATE MAP #ifndef GAME_OBJECT_H #define GAME_OBJECT_H #include <iostream> #include <map> #include <unordered_map> #include <vector> #include <list> #include <string> #include <utility> #include "SDL2basics.hpp" #include "component.hpp" #include "image.hpp" #include "text.hpp" #include "audio.hpp" #include "hitbox.hpp" #include "keyboard_event.hpp" #include "state_map.hpp" #include "animation.hpp" #include "observer.hpp" #include "observable.hpp" #include "../../include/game_event.hpp" namespace engine { class Animation; /** * @brief A Game class. * * This class can control all the components of the game object. * @warning Limitations: The number of game object in game is limited to the pc memory. All game object after being * used needs to be free. */ class GameObject : public Observer, public Observable { private: std::pair<float, float> speed = std::make_pair(0.0, 0.0); std::pair<float, float> position = std::make_pair(0.0, 0.0); std::vector<Hitbox *> hitboxes; Animation* actual_animation = NULL; bool active = true; std::list<Observer *> observers; void run_collisions(GameObject *); protected: virtual void on_collision(GameObject *, Hitbox *, Hitbox *) { }; public: static bool on_limit_of_level; std::string name; int priority; bool collidable; std::vector<Component *> audios; std::vector<Component *> images; std::vector<Component *> texts; std::map<std::string, Animation *> animations; std::map<KeyboardEvent::Key, std::string> translations; std::string state; std::string game_object_direction; StateMap states; GameObject() { }; GameObject( std::string p_name, std::pair<float, float> p_position, int p_priority, std::map<KeyboardEvent::Key,std::string> p_translations, StateMap p_states = StateMap()) :name(p_name), position(p_position), active(false), priority(p_priority), translations(p_translations), states(p_states), speed(std::make_pair(0.0, 0.0)) { }; ~GameObject() { }; bool load(); void free(); void draw(); void add_component(Component *); void add_animation(std::string, Animation *); bool equals(GameObject *); void collide(GameObject *); Audio * get_audio_by_name(std::string); void play_song(std::string); void stop_song(std::string); void set_repetitions(std::string, int repet); void set_music_volume(std::string, int vol); void free_music(std::string); std::pair<float, float> get_position(); float get_position_x(); float get_position_y(); void set_position(std::pair<float, float>); void set_position_x(float); void set_position_y(float); std::pair<float, float> get_speed(); float get_speed_x(); float get_speed_y(); void set_speed(std::pair<float, float>); void set_speed_x(float); void set_speed_y(float); void activate(); void deactivate(); void deactivate_components(); bool is_active(); std::string get_state(std::string); std::vector<Hitbox*> get_hitboxes(); void create_hitbox(std::pair<int, int>, std::pair<int, int>); virtual void on_event(GameEvent) { }; void update_hitboxes(); virtual void update_state(); void set_actual_animation(Animation *); Animation* get_actual_animation(); void attach_observer(Observer *); void detach_observer(Observer *); void notify_observers(); virtual void notify(Observable *) { }; }; } #endif <|endoftext|>
<commit_before>#include "halley/file/path.h" #include <sstream> using namespace Halley; Path::Path() {} Path::Path(const char* name) { setPath(name); } Path::Path(const std::string& name) { setPath(name); } Path::Path(const String& name) { setPath(name); } void Path::setPath(const String& value) { String rawPath = value; #ifdef _WIN32 rawPath.replace("\\", "/"); #endif pathParts = rawPath.split('/'); normalise(); } Path::Path(std::vector<String> parts) : pathParts(parts) { normalise(); } void Path::normalise() { size_t writePos = 0; bool lastIsBack = false; auto write = [&] (const String& p) { pathParts.at(writePos++) = p; lastIsBack = false; }; int n = int(pathParts.size()); for (int i = 0; i < n; ++i) { bool first = i == 0; bool last = i == n - 1; String current = pathParts[i]; // Important: don't make this a reference if (current == "") { if (first) { write(current); } else if (last) { write("."); } } else if (current == ".") { if (first || last) { write(current); } } else if (current == "..") { if (writePos > 0 && pathParts[writePos - 1] != "..") { --writePos; lastIsBack = true; } else { write(current); } } else { write(current); } } if (lastIsBack) { write("."); } pathParts.resize(writePos); } Path& Path::operator=(const std::string& other) { setPath(other); return *this; } Path& Path::operator=(const String& other) { setPath(other); return *this; } Path Path::getFilename() const { return pathParts.back(); } Path Path::getStem() const { String filename = getFilename().pathParts.front(); if (filename == "." || filename == "..") { return filename; } size_t dotPos = filename.find('.'); return filename.substr(0, dotPos); } String Path::getExtension() const { String filename = getFilename().pathParts.front(); if (filename == "." || filename == "..") { return filename; } size_t dotPos = filename.find('.'); return filename.substr(dotPos); } String Path::getString() const { std::stringstream s; bool first = true; for (auto& p : pathParts) { if (first) { first = false; } else { s << "/"; } s << p; } return s.str(); } Path Path::parentPath() const { return Path(getString() + "/.."); } Path Path::replaceExtension(String newExtension) const { auto parts = pathParts; parts.back() = getStem().getString() + newExtension; return Path(parts); } Path Path::operator/(const char* other) const { return operator/(Path(other)); } Path Path::operator/(const Path& other) const { auto parts = pathParts; for (auto& p : other.pathParts) { parts.push_back(p); } return Path(parts); } Path Path::operator/(const String& other) const { return operator/(Path(other)); } Path Path::operator/(const std::string& other) const { return operator/(Path(other)); } bool Path::operator==(const char* other) const { return operator==(Path(other)); } bool Path::operator==(const String& other) const { return operator==(Path(other)); } bool Path::operator==(const Path& other) const { return ! operator!=(other); } bool Path::operator!=(const Path& other) const { if (pathParts.size() != other.pathParts.size()) { return true; } for (size_t i = 0; i < pathParts.size(); ++i) { auto& a = pathParts[i]; auto& b = other.pathParts[i]; #ifdef _WIN32 if (a.asciiLower() != b.asciiLower()) { #else if (a != b) { #endif return true; } } return false; } std::string Path::string() const { return getString().cppStr(); } std::ostream& Halley::operator<<(std::ostream& os, const Path& p) { return (os << p.string()); } Path Path::getRoot() const { return pathParts.front(); } <commit_msg>Fix metafile importing/path extension reading.<commit_after>#include "halley/file/path.h" #include <sstream> using namespace Halley; Path::Path() {} Path::Path(const char* name) { setPath(name); } Path::Path(const std::string& name) { setPath(name); } Path::Path(const String& name) { setPath(name); } void Path::setPath(const String& value) { String rawPath = value; #ifdef _WIN32 rawPath.replace("\\", "/"); #endif pathParts = rawPath.split('/'); normalise(); } Path::Path(std::vector<String> parts) : pathParts(parts) { normalise(); } void Path::normalise() { size_t writePos = 0; bool lastIsBack = false; auto write = [&] (const String& p) { pathParts.at(writePos++) = p; lastIsBack = false; }; int n = int(pathParts.size()); for (int i = 0; i < n; ++i) { bool first = i == 0; bool last = i == n - 1; String current = pathParts[i]; // Important: don't make this a reference if (current == "") { if (first) { write(current); } else if (last) { write("."); } } else if (current == ".") { if (first || last) { write(current); } } else if (current == "..") { if (writePos > 0 && pathParts[writePos - 1] != "..") { --writePos; lastIsBack = true; } else { write(current); } } else { write(current); } } if (lastIsBack) { write("."); } pathParts.resize(writePos); } Path& Path::operator=(const std::string& other) { setPath(other); return *this; } Path& Path::operator=(const String& other) { setPath(other); return *this; } Path Path::getFilename() const { return pathParts.back(); } Path Path::getStem() const { String filename = pathParts.back(); if (filename == "." || filename == "..") { return filename; } size_t dotPos = filename.find_last_of('.'); return filename.substr(0, dotPos); } String Path::getExtension() const { String filename = pathParts.back(); if (filename == "." || filename == "..") { return filename; } size_t dotPos = filename.find_last_of('.'); return filename.substr(dotPos); } String Path::getString() const { std::stringstream s; bool first = true; for (auto& p : pathParts) { if (first) { first = false; } else { s << "/"; } s << p; } return s.str(); } Path Path::parentPath() const { return Path(getString() + "/.."); } Path Path::replaceExtension(String newExtension) const { auto parts = pathParts; parts.back() = getStem().getString() + newExtension; return Path(parts); } Path Path::operator/(const char* other) const { return operator/(Path(other)); } Path Path::operator/(const Path& other) const { auto parts = pathParts; for (auto& p : other.pathParts) { parts.push_back(p); } return Path(parts); } Path Path::operator/(const String& other) const { return operator/(Path(other)); } Path Path::operator/(const std::string& other) const { return operator/(Path(other)); } bool Path::operator==(const char* other) const { return operator==(Path(other)); } bool Path::operator==(const String& other) const { return operator==(Path(other)); } bool Path::operator==(const Path& other) const { return ! operator!=(other); } bool Path::operator!=(const Path& other) const { if (pathParts.size() != other.pathParts.size()) { return true; } for (size_t i = 0; i < pathParts.size(); ++i) { auto& a = pathParts[i]; auto& b = other.pathParts[i]; #ifdef _WIN32 if (a.asciiLower() != b.asciiLower()) { #else if (a != b) { #endif return true; } } return false; } std::string Path::string() const { return getString().cppStr(); } std::ostream& Halley::operator<<(std::ostream& os, const Path& p) { return (os << p.string()); } Path Path::getRoot() const { return pathParts.front(); } <|endoftext|>
<commit_before>/* * Implementation for the mbed library * https://github.com/mbedmicro/mbed * * Copyright (c) 2016 Christopher Haster * * 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 "equeue/equeue_platform.h" #if defined(EQUEUE_PLATFORM_MBED) #include <stdbool.h> #include "mbed.h" // Ticker operations static bool equeue_tick_inited = false; static volatile unsigned equeue_minutes = 0; static unsigned equeue_timer[ (sizeof(Timer)+sizeof(unsigned)-1)/sizeof(unsigned)]; static unsigned equeue_ticker[ (sizeof(Ticker)+sizeof(unsigned)-1)/sizeof(unsigned)]; static void equeue_tick_update() { equeue_minutes += reinterpret_cast<Timer*>(equeue_timer)->read_ms(); reinterpret_cast<Timer*>(equeue_timer)->reset(); } static void equeue_tick_init() { MBED_STATIC_ASSERT(sizeof(equeue_timer) >= sizeof(Timer), "The equeue_timer buffer must fit the class Timer"); MBED_STATIC_ASSERT(sizeof(equeue_ticker) >= sizeof(Ticker), "The equeue_ticker buffer must fit the class Ticker"); new (equeue_timer) Timer; new (equeue_ticker) Ticker; equeue_minutes = 0; reinterpret_cast<Timer*>(equeue_timer)->start(); reinterpret_cast<Ticker*>(equeue_ticker) ->attach_us(equeue_tick_update, 1000 << 16); equeue_tick_inited = true; } unsigned equeue_tick() { if (!equeue_tick_inited) { equeue_tick_init(); } unsigned minutes; unsigned ms; do { minutes = equeue_minutes; ms = reinterpret_cast<Timer*>(equeue_timer)->read_ms(); } while (minutes != equeue_minutes); return minutes + ms; } // Mutex operations int equeue_mutex_create(equeue_mutex_t *m) { return 0; } void equeue_mutex_destroy(equeue_mutex_t *m) { } void equeue_mutex_lock(equeue_mutex_t *m) { core_util_critical_section_enter(); } void equeue_mutex_unlock(equeue_mutex_t *m) { core_util_critical_section_exit(); } // Semaphore operations #ifdef MBED_CONF_RTOS_PRESENT int equeue_sema_create(equeue_sema_t *s) { MBED_STATIC_ASSERT(sizeof(equeue_sema_t) >= sizeof(Semaphore), "The equeue_sema_t must fit the class Semaphore"); new (s) Semaphore(0); return 0; } void equeue_sema_destroy(equeue_sema_t *s) { reinterpret_cast<Semaphore*>(s)->~Semaphore(); } void equeue_sema_signal(equeue_sema_t *s) { reinterpret_cast<Semaphore*>(s)->release(); } bool equeue_sema_wait(equeue_sema_t *s, int ms) { if (ms < 0) { ms = osWaitForever; } return (reinterpret_cast<Semaphore*>(s)->wait(ms) > 0); } #else // Semaphore operations int equeue_sema_create(equeue_sema_t *s) { *s = false; return 0; } void equeue_sema_destroy(equeue_sema_t *s) { } void equeue_sema_signal(equeue_sema_t *s) { *s = 1; } static void equeue_sema_timeout(equeue_sema_t *s) { *s = -1; } bool equeue_sema_wait(equeue_sema_t *s, int ms) { int signal = 0; Timeout timeout; if (ms > 0) { timeout.attach_us(callback(equeue_sema_timeout, s), ms*1000); } core_util_critical_section_enter(); while (!*s) { sleep(); core_util_critical_section_exit(); core_util_critical_section_enter(); } signal = *s; *s = false; core_util_critical_section_exit(); return (signal > 0); } #endif #endif <commit_msg>events: Remove strict-aliasing warning<commit_after>/* * Implementation for the mbed library * https://github.com/mbedmicro/mbed * * Copyright (c) 2016 Christopher Haster * * 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 "equeue/equeue_platform.h" #if defined(EQUEUE_PLATFORM_MBED) #include <stdbool.h> #include "mbed.h" // Ticker operations static bool equeue_tick_inited = false; static volatile unsigned equeue_minutes = 0; static unsigned equeue_timer[ (sizeof(Timer)+sizeof(unsigned)-1)/sizeof(unsigned)]; static unsigned equeue_ticker[ (sizeof(Ticker)+sizeof(unsigned)-1)/sizeof(unsigned)]; static void equeue_tick_update() { equeue_minutes += reinterpret_cast<Timer*>(equeue_timer)->read_ms(); reinterpret_cast<Timer*>(equeue_timer)->reset(); } static void equeue_tick_init() { MBED_STATIC_ASSERT(sizeof(equeue_timer) >= sizeof(Timer), "The equeue_timer buffer must fit the class Timer"); MBED_STATIC_ASSERT(sizeof(equeue_ticker) >= sizeof(Ticker), "The equeue_ticker buffer must fit the class Ticker"); Timer *timer = new (equeue_timer) Timer; Ticker *ticker = new (equeue_ticker) Ticker; equeue_minutes = 0; timer->start(); ticker->attach_us(equeue_tick_update, 1000 << 16); equeue_tick_inited = true; } unsigned equeue_tick() { if (!equeue_tick_inited) { equeue_tick_init(); } unsigned minutes; unsigned ms; do { minutes = equeue_minutes; ms = reinterpret_cast<Timer*>(equeue_timer)->read_ms(); } while (minutes != equeue_minutes); return minutes + ms; } // Mutex operations int equeue_mutex_create(equeue_mutex_t *m) { return 0; } void equeue_mutex_destroy(equeue_mutex_t *m) { } void equeue_mutex_lock(equeue_mutex_t *m) { core_util_critical_section_enter(); } void equeue_mutex_unlock(equeue_mutex_t *m) { core_util_critical_section_exit(); } // Semaphore operations #ifdef MBED_CONF_RTOS_PRESENT int equeue_sema_create(equeue_sema_t *s) { MBED_STATIC_ASSERT(sizeof(equeue_sema_t) >= sizeof(Semaphore), "The equeue_sema_t must fit the class Semaphore"); new (s) Semaphore(0); return 0; } void equeue_sema_destroy(equeue_sema_t *s) { reinterpret_cast<Semaphore*>(s)->~Semaphore(); } void equeue_sema_signal(equeue_sema_t *s) { reinterpret_cast<Semaphore*>(s)->release(); } bool equeue_sema_wait(equeue_sema_t *s, int ms) { if (ms < 0) { ms = osWaitForever; } return (reinterpret_cast<Semaphore*>(s)->wait(ms) > 0); } #else // Semaphore operations int equeue_sema_create(equeue_sema_t *s) { *s = false; return 0; } void equeue_sema_destroy(equeue_sema_t *s) { } void equeue_sema_signal(equeue_sema_t *s) { *s = 1; } static void equeue_sema_timeout(equeue_sema_t *s) { *s = -1; } bool equeue_sema_wait(equeue_sema_t *s, int ms) { int signal = 0; Timeout timeout; if (ms > 0) { timeout.attach_us(callback(equeue_sema_timeout, s), ms*1000); } core_util_critical_section_enter(); while (!*s) { sleep(); core_util_critical_section_exit(); core_util_critical_section_enter(); } signal = *s; *s = false; core_util_critical_section_exit(); return (signal > 0); } #endif #endif <|endoftext|>
<commit_before>/** ========================================================================== * 2014 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes * with no warranties. This code is yours to share, use and modify with no * strings attached and no restrictions or obligations. * * For more information see g3log/LICENSE or refer refer to http://unlicense.org * ============================================================================*/ #include <g2logworker.hpp> #include <g2log.hpp> #include <iostream> #include <cctype> #include <future> #include <vector> #include <string> #include <chrono> #include <thread> namespace { #if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) const std::string path_to_log_file = "./"; #else const std::string path_to_log_file = "/tmp/"; #endif void ToLower(std::string &str) { for (auto &character : str) { character = std::tolower(character); } } void RaiseSIGABRT() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; raise(SIGABRT); LOG(WARNING) << "Expected to have died by now..."; } void RaiseSIGFPE() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; LOGF_IF(INFO, (false != true), "Exiting %s SIGFPE", "by"); raise(SIGFPE); LOG(WARNING) << "Expected to have died by now..."; } void RaiseSIGSEGV() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; LOG(DEBUG) << "Exit by SIGSEGV"; raise(SIGSEGV); LOG(WARNING) << "Expected to have died by now..."; } void RaiseSIGILL() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; LOGF(DEBUG, "Exit by %s", "SIGILL"); raise(SIGILL); LOG(WARNING) << "Expected to have died by now..."; } void RAiseSIGTERM() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; LOGF_IF(INFO, (false != true), "Exiting %s SIGFPE", "by"); raise(SIGTERM); LOG(WARNING) << "Expected to have died by now..."; } int gShouldBeZero = 1; void DivisionByZero() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; std::cout << "Executing DivisionByZero: gShouldBeZero: " << gShouldBeZero << std::endl; LOG(INFO) << "Division by zero is a big no-no"; int value = 3; auto test = value / gShouldBeZero; LOG(WARNING) << "Expected to have died by now..., test value: " << test; } void IllegalPrintf() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; LOG(DEBUG) << "Impending doom due to illeteracy"; LOGF(INFO, "2nd attempt at ILLEGAL PRINTF_SYNTAX %d EXAMPLE. %s %s", "hello", 1); LOG(WARNING) << "Expected to have died by now..."; } void OutOfBoundsArrayIndexing() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; std::vector<int> v; v[0] = 5; LOG(WARNING) << "Expected to have died by now..."; } void AccessViolation() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; char* ptr = 0; LOG(INFO) << "Death by access violation is imminent"; *ptr = 0; LOG(WARNING) << "Expected to have died by now..."; } void NoExitFunction() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; CHECK(false) << "This function should never be called"; } void RaiseSIGABRTAndAccessViolation() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; auto f1 = std::async(std::launch::async, &RaiseSIGABRT); auto f2 = std::async(std::launch::async, &AccessViolation); f1.wait(); f2.wait(); } void CallActualExitFunction(std::function<void()> fatal_function) { fatal_function(); } void CallExitFunction(std::function<void()> fatal_function) { CallActualExitFunction(fatal_function); } void ExecuteDeathFunction(const bool runInNewThread, int fatalChoice) { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; auto exitFunction = &NoExitFunction; switch (fatalChoice) { case 1: exitFunction = &RaiseSIGABRT; break; case 2: exitFunction = &RaiseSIGFPE; break; case 3: exitFunction = &RaiseSIGSEGV; break; case 4: exitFunction = &RaiseSIGILL; break; case 5: exitFunction = &RAiseSIGTERM; break; case 6: exitFunction = &DivisionByZero; gShouldBeZero = 0; DivisionByZero(); break; case 7: exitFunction = &IllegalPrintf; break; case 8: exitFunction = &OutOfBoundsArrayIndexing; break; case 9: exitFunction = &AccessViolation; break; case 10: exitFunction = &RaiseSIGABRTAndAccessViolation; break; case 11: throw 123456789; break; default: break; } if (runInNewThread) { auto dieInNearFuture = std::async(std::launch::async, CallExitFunction, exitFunction); dieInNearFuture.wait(); } else { CallExitFunction(exitFunction); } std::string unexpected = "Expected to exit by FATAL event. That did not happen (printf choice in Windows?)."; unexpected.append("Choice was: ").append(std::to_string(fatalChoice)).append(", async?: ") .append(std::to_string(runInNewThread)).append("\n\n***** TEST WILL RUN AGAIN *****\n\n"); std::cerr << unexpected << std::endl; LOG(WARNING) << unexpected; } bool AskForAsyncDeath() { std::string option; while (true) { option.clear(); std::cout << "Do you want to run the test in a separate thread? [yes/no]" << std::endl; std::getline(std::cin, option); ToLower(option); if (("yes" != option) && ("no" != option)) { std::cout << "\nInvalid value: [" << option << "]\n\n\n"; } else { break; } } return ("yes" == option); } int ChoiceOfFatalExit() { std::string option; int choice = {0}; while (true) { std::cout << "\n\n\n\nChoose your exit" << std::endl; std::cout << "By throwing an fatal signal" << std::endl; std::cout << "or By executing a fatal code snippet" << std::endl; std::cout << "[1] Signal SIGABRT" << std::endl; std::cout << "[2] Signal SIGFPE" << std::endl; std::cout << "[3] Signal SIGSEGV" << std::endl; std::cout << "[4] Signal IGILL" << std::endl; std::cout << "[5] Signal SIGTERM" << std::endl; std::cout << "[6] Division By Zero" << std::endl; std::cout << "[7] Illegal printf" << std::endl; std::cout << "[8] Out of bounds array indexing " << std::endl; std::cout << "[9] Access violation" << std::endl; std::cout << "[10] Rasing SIGABRT + Access Violation in two separate threads" << std::endl; std::cout << "[11] Just throw" << std::endl; std::cout << std::flush; try { std::getline(std::cin, option); choice = std::stoi(option); if (choice <= 0 || choice > 11) { std::cout << "Invalid choice: [" << option << "\n\n"; } else { return choice; } } catch (...) { std::cout << "Invalid choice: [" << option << "\n\n"; } } } void ForwardChoiceForFatalExit(bool runInNewThread, int fatalChoice) { ExecuteDeathFunction(runInNewThread, fatalChoice); } void ChooseFatalExit() { const bool runInNewThread = AskForAsyncDeath(); const int exitChoice = ChoiceOfFatalExit(); ForwardChoiceForFatalExit(runInNewThread, exitChoice); } } // namespace int main(int argc, char** argv) { auto logger_n_handle = g2::LogWorker::createWithDefaultLogger(argv[0], path_to_log_file); g2::initializeLogging(logger_n_handle.worker.get()); std::future<std::string> log_file_name = logger_n_handle.sink->call(&g2::FileSink::fileName); std::cout << "**** G3LOG FATAL EXAMPLE ***\n\n" << "Choose your type of fatal exit, then " << " read the generated log and backtrace.\n" << "The logfile is generated at: [" << log_file_name.get() << "]\n\n" << std::endl; LOGF(DEBUG, "Fatal exit example starts now, it's as easy as %d", 123); LOG(INFO) << "Feel free to read the source code also in g3log/example/main_fatal_choice.cpp"; while (true) { ChooseFatalExit(); } LOG(WARNING) << "Expected to exit by fatal event, this code line should never be reached"; CHECK(false) << "Forced death"; return 0; } <commit_msg>Changed what was thrown<commit_after>/** ========================================================================== * 2014 by KjellKod.cc. This is PUBLIC DOMAIN to use at your own risk and comes * with no warranties. This code is yours to share, use and modify with no * strings attached and no restrictions or obligations. * * For more information see g3log/LICENSE or refer refer to http://unlicense.org * ============================================================================*/ #include <g2logworker.hpp> #include <g2log.hpp> #include <iostream> #include <cctype> #include <future> #include <vector> #include <string> #include <chrono> #include <thread> namespace { #if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) const std::string path_to_log_file = "./"; #else const std::string path_to_log_file = "/tmp/"; #endif void ToLower(std::string &str) { for (auto &character : str) { character = std::tolower(character); } } void RaiseSIGABRT() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; raise(SIGABRT); LOG(WARNING) << "Expected to have died by now..."; } void RaiseSIGFPE() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; LOGF_IF(INFO, (false != true), "Exiting %s SIGFPE", "by"); raise(SIGFPE); LOG(WARNING) << "Expected to have died by now..."; } void RaiseSIGSEGV() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; LOG(DEBUG) << "Exit by SIGSEGV"; raise(SIGSEGV); LOG(WARNING) << "Expected to have died by now..."; } void RaiseSIGILL() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; LOGF(DEBUG, "Exit by %s", "SIGILL"); raise(SIGILL); LOG(WARNING) << "Expected to have died by now..."; } void RAiseSIGTERM() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; LOGF_IF(INFO, (false != true), "Exiting %s SIGFPE", "by"); raise(SIGTERM); LOG(WARNING) << "Expected to have died by now..."; } int gShouldBeZero = 1; void DivisionByZero() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; std::cout << "Executing DivisionByZero: gShouldBeZero: " << gShouldBeZero << std::endl; LOG(INFO) << "Division by zero is a big no-no"; int value = 3; auto test = value / gShouldBeZero; LOG(WARNING) << "Expected to have died by now..., test value: " << test; } void IllegalPrintf() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; LOG(DEBUG) << "Impending doom due to illeteracy"; LOGF(INFO, "2nd attempt at ILLEGAL PRINTF_SYNTAX %d EXAMPLE. %s %s", "hello", 1); LOG(WARNING) << "Expected to have died by now..."; } void OutOfBoundsArrayIndexing() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; std::vector<int> v; v[0] = 5; LOG(WARNING) << "Expected to have died by now..."; } void AccessViolation() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; char* ptr = 0; LOG(INFO) << "Death by access violation is imminent"; *ptr = 0; LOG(WARNING) << "Expected to have died by now..."; } void NoExitFunction() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; CHECK(false) << "This function should never be called"; } void RaiseSIGABRTAndAccessViolation() { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; auto f1 = std::async(std::launch::async, &RaiseSIGABRT); auto f2 = std::async(std::launch::async, &AccessViolation); f1.wait(); f2.wait(); } void CallActualExitFunction(std::function<void()> fatal_function) { fatal_function(); } void CallExitFunction(std::function<void()> fatal_function) { CallActualExitFunction(fatal_function); } void ExecuteDeathFunction(const bool runInNewThread, int fatalChoice) { std::cout << "Calling :" << __FUNCTION__ << " Line: " << __LINE__ << std::endl << std::flush; auto exitFunction = &NoExitFunction; switch (fatalChoice) { case 1: exitFunction = &RaiseSIGABRT; break; case 2: exitFunction = &RaiseSIGFPE; break; case 3: exitFunction = &RaiseSIGSEGV; break; case 4: exitFunction = &RaiseSIGILL; break; case 5: exitFunction = &RAiseSIGTERM; break; case 6: exitFunction = &DivisionByZero; gShouldBeZero = 0; DivisionByZero(); break; case 7: exitFunction = &IllegalPrintf; break; case 8: exitFunction = &OutOfBoundsArrayIndexing; break; case 9: exitFunction = &AccessViolation; break; case 10: exitFunction = &RaiseSIGABRTAndAccessViolation; break; case 11: throw 1233210; break; default: break; } if (runInNewThread) { auto dieInNearFuture = std::async(std::launch::async, CallExitFunction, exitFunction); dieInNearFuture.wait(); } else { CallExitFunction(exitFunction); } std::string unexpected = "Expected to exit by FATAL event. That did not happen (printf choice in Windows?)."; unexpected.append("Choice was: ").append(std::to_string(fatalChoice)).append(", async?: ") .append(std::to_string(runInNewThread)).append("\n\n***** TEST WILL RUN AGAIN *****\n\n"); std::cerr << unexpected << std::endl; LOG(WARNING) << unexpected; } bool AskForAsyncDeath() { std::string option; while (true) { option.clear(); std::cout << "Do you want to run the test in a separate thread? [yes/no]" << std::endl; std::getline(std::cin, option); ToLower(option); if (("yes" != option) && ("no" != option)) { std::cout << "\nInvalid value: [" << option << "]\n\n\n"; } else { break; } } return ("yes" == option); } int ChoiceOfFatalExit() { std::string option; int choice = {0}; while (true) { std::cout << "\n\n\n\nChoose your exit" << std::endl; std::cout << "By throwing an fatal signal" << std::endl; std::cout << "or By executing a fatal code snippet" << std::endl; std::cout << "[1] Signal SIGABRT" << std::endl; std::cout << "[2] Signal SIGFPE" << std::endl; std::cout << "[3] Signal SIGSEGV" << std::endl; std::cout << "[4] Signal IGILL" << std::endl; std::cout << "[5] Signal SIGTERM" << std::endl; std::cout << "[6] Division By Zero" << std::endl; std::cout << "[7] Illegal printf" << std::endl; std::cout << "[8] Out of bounds array indexing " << std::endl; std::cout << "[9] Access violation" << std::endl; std::cout << "[10] Rasing SIGABRT + Access Violation in two separate threads" << std::endl; std::cout << "[11] Just throw" << std::endl; std::cout << std::flush; try { std::getline(std::cin, option); choice = std::stoi(option); if (choice <= 0 || choice > 11) { std::cout << "Invalid choice: [" << option << "\n\n"; } else { return choice; } } catch (...) { std::cout << "Invalid choice: [" << option << "\n\n"; } } } void ForwardChoiceForFatalExit(bool runInNewThread, int fatalChoice) { ExecuteDeathFunction(runInNewThread, fatalChoice); } void ChooseFatalExit() { const bool runInNewThread = AskForAsyncDeath(); const int exitChoice = ChoiceOfFatalExit(); ForwardChoiceForFatalExit(runInNewThread, exitChoice); } } // namespace int main(int argc, char** argv) { auto logger_n_handle = g2::LogWorker::createWithDefaultLogger(argv[0], path_to_log_file); g2::initializeLogging(logger_n_handle.worker.get()); std::future<std::string> log_file_name = logger_n_handle.sink->call(&g2::FileSink::fileName); std::cout << "**** G3LOG FATAL EXAMPLE ***\n\n" << "Choose your type of fatal exit, then " << " read the generated log and backtrace.\n" << "The logfile is generated at: [" << log_file_name.get() << "]\n\n" << std::endl; LOGF(DEBUG, "Fatal exit example starts now, it's as easy as %d", 123); LOG(INFO) << "Feel free to read the source code also in g3log/example/main_fatal_choice.cpp"; while (true) { ChooseFatalExit(); } LOG(WARNING) << "Expected to exit by fatal event, this code line should never be reached"; CHECK(false) << "Forced death"; return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <functional> #include <memory> #include <cmath> #include <cstring> #include "../include/Neuralnet.hpp" #include "../include/Layer.hpp" #include "../include/FullyConnected.hpp" #include "../include/Convolutional.hpp" #include "../include/Pooling.hpp" using namespace std; // pixel normalize function void normalize ( vector<vector<vector<double>>>& image, vector<vector<double>>& ave ) { for( int i = 0; i < image[0].size(); ++i ){ ave.emplace_back(image[0][0].size(), 0.0); for( int j = 0; j < image.size(); ++j ){ for( int k = 0; k < image[0][i].size(); ++k ) ave[i][k] += image[j][i][k]; } for( int j = 0; j < image[0][i].size(); ++j ) ave[i][j] /= image.size(); for( int j = 0; j < image.size(); ++j ) for( int k = 0; k < image[0][i].size(); ++k ) image[j][i][k] -= ave[i][k]; } } int main( int argc, char* argv[] ) { // define mini-batch size. const int BATCH_SIZE = 50; // parallelism for model parallel. int INNER = 1; for( int i = 1; i < argc; ++i ){ if( strcmp(argv[i], "--inner") == 0 ){ sscanf(argv[i+1], "%d", &INNER); ++i; } } MPI_Init(&argc, &argv); MPI_Comm outer_world, inner_world; int world_rank, world_nprocs; // rank and number of processes in all processes. int inner_rank, inner_nprocs; // rank and number of processes in model parallel. int outer_rank, outer_nprocs; // rank and number of processes in data parallel. MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); MPI_Comm_size(MPI_COMM_WORLD, &world_nprocs); // determine model parallel's rank of each processes. MPI_Comm_split(MPI_COMM_WORLD, world_rank / INNER, world_rank, &inner_world); MPI_Comm_rank(inner_world, &inner_rank); MPI_Comm_size(inner_world, &inner_nprocs); // determine data parallel's rank of each processes. MPI_Comm_split(MPI_COMM_WORLD, world_rank % INNER, world_rank, &outer_world); MPI_Comm_rank(outer_world, &outer_rank); MPI_Comm_size(outer_world, &outer_nprocs); // construct neuralnetwork with CrossEntropy. Neuralnet net(shared_ptr<LossFunction>(new CrossEntropy), outer_world, inner_world); vector<shared_ptr<Layer>> layers; // define layers. layers.emplace_back(new Convolutional(1, 28*28, 28, 10, 28*28, 28, 5, 5, 1, shared_ptr<Function>(new ReLU))); layers.emplace_back(new Pooling(10, 28*28, 28, 10, 14*14, 14, 3, 3, 2, shared_ptr<Function>(new Identity))); layers.emplace_back(new Convolutional(10, 14*14, 14, 20, 14*14, 14, 5, 5, 1, shared_ptr<Function>(new ReLU))); layers.emplace_back(new Pooling(20, 14*14, 14, 20, 7*7, 7, 2, 2, 2, shared_ptr<Function>(new Identity))); layers.emplace_back(new FullyConnected(20, 7*7, 1, 512, shared_ptr<Function>(new ReLU))); layers.emplace_back(new FullyConnected(1, 512, 1, 10, shared_ptr<Function>(new Softmax))); // this neuralnet has 7 layers, input, Conv1, MaxPool, Conv2, MaxPool, Fc1 and Fc2; for( int i = 0; i < layers.size(); ++i ){ net.add_layer(layers[i]); } // read a test data of MNIST(http://yann.lecun.com/exdb/mnist/). vector<int> train_lab; vector<vector<vector<double>>> train_x; const int N = 10000 / outer_nprocs; ifstream train_image("train-images-idx3-ubyte", ios_base::binary); ifstream train_image("train-images-idx3-ubyte", ios_base::binary); if( !train_image.is_open() ){ cerr << "\"train-images-idx3-ubyte\" is not found!" << endl; return 1; } ifstream train_label("train-labels-idx1-ubyte", ios_base::binary); if( !train_label.is_open() ){ cerr << "\"train-labels-idx1-ubyte\" is not found!" << endl; return 1; } train_image.seekg(4*4 + 28*28*outer_rank * N, ios_base::beg); train_label.seekg(4*2 + outer_rank * N, ios_base::beg); for( int i = 0; i < N; ++i ){ unsigned char tmp_lab; train_label.read((char*)&tmp_lab, sizeof(unsigned char)); train_lab.push_back(tmp_lab); vector<vector<double>> tmp(1, vector<double>(28*28)); for( int j = 0; j < 28*28; ++j ){ unsigned char c; train_image.read((char*)&c, sizeof(unsigned char)); tmp[0][j] = (c/255.0); } train_x.push_back(tmp); } // set supervised data. vector<vector<vector<double>>> d(N, vector<vector<double>>(1, vector<double>(10, 0.0))); for( int i = 0; i < N; ++i ) d[i][0][train_lab[i]] = 1.0; vector<vector<double>> ave; // normalize train image. normalize(train_x, ave); // read a train data of MNIST. vector<int> test_lab; vector<vector<vector<double>>> test_x; const int M = 5000; ifstream test_image("t10k-images-idx3-ubyte", ios_base::binary); if( !test_image.is_open() ){ cerr << "\"t10k-images-idx3-ubyte\" is not found!" << endl; return 1; } ifstream test_label("t10k-labels-idx1-ubyte", ios_base::binary); if( !test_label.is_open() ){ cerr << "\"t10k-labels-idx1-ubyte\" is not found!" << endl; return 1; } test_image.seekg(4*4, ios_base::beg); test_label.seekg(4*2, ios_base::beg); for( int i = 0; i < M; ++i ){ unsigned char tmp_lab; test_label.read((char*)&tmp_lab, sizeof(unsigned char)); test_lab.push_back(tmp_lab); vector<vector<double>> tmp(1, vector<double>(28*28)); for( int j = 0; j < 28*28; ++j ){ unsigned char c; test_image.read((char*)&c, sizeof(unsigned char)); tmp[0][j] = (c/255.0 - ave[0][j]); } test_x.push_back(tmp); } // train data into Matrix class for checking error. vector<Matrix<double>> X(1, Matrix<double>(28*28, M)), D(1, Matrix<double>(10, M)); for( int i = 0; i < M; ++i ){ for( int j = 0; j < 28*28; ++j ){ X[0](j, i) = test_x[i][0][j]; } D[0](test_lab[i], i) = 1.0; } // checking error function. double prev_time, total_time; auto check_error = [&](const Neuralnet& nn, const int iter, const std::vector<Matrix<double>>& x, const std::vector<Matrix<double>>& d ) -> void { if( iter%((N/BATCH_SIZE)) != 0 || iter == 0 ) return; double tmp_time = MPI_Wtime(); // calculating answer rate among all train data. int train_ans_num = 0; auto y = nn.apply(train_x); for( int i = 0; i < y.size(); ++i ){ int idx, lab; double max_num = 0.0; for( int j = 0; j < 10; ++j ){ if( max_num < y[i][0][j] ){ max_num = y[i][0][j]; idx = j; } } if( idx == train_lab[i] ) ++train_ans_num; } // calculating answer rate among all test data. int test_ans_num = 0; auto Y = nn.apply(X); for( int i = 0; i < Y[0].n; ++i ){ int idx, lab; double max_num = 0.0; for( int j = 0; j < 10; ++j ){ if( max_num < Y[0](j,i) ){ max_num = Y[0](j,i); idx = j; } if( D[0](j, i) == 1.0 ) lab = j; } if( idx == lab ) ++test_ans_num; } // output answer rate each test data batch. if( inner_rank == 0 ){ for( int i = 0; i < outer_nprocs; ++i ){ if( i == outer_rank ){ printf("outer rank : %d\n", outer_rank); printf(" Elapsed time : %.3f, Total time : %.3f\n", MPI_Wtime() - prev_time, MPI_Wtime() - total_time); printf(" Train answer rate : %.2f%%\n", (double)train_ans_num/y.size()*100.0); printf(" Test answer rate : %.2f%%\n", (double)test_ans_num/X[0].n*100.0); } MPI_Barrier(outer_world); } prev_time = MPI_Wtime(); } if( world_rank == 0 ) puts(""); }; // set a hyper parameter. net.set_EPS(1.0E-3); net.set_LAMBDA(0.0); net.set_BATCHSIZE(BATCH_SIZE); net.set_UPDATEITER(N/BATCH_SIZE*2); // learning the neuralnet in 20 EPOCH and output error defined above in each epoch. prev_time = total_time = MPI_Wtime(); net.learning(train_x, d, N/BATCH_SIZE*10, check_error); MPI_Finalize(); } <commit_msg>Fixed compile error.<commit_after>#include <iostream> #include <fstream> #include <functional> #include <memory> #include <cmath> #include <cstring> #include "../include/Neuralnet.hpp" #include "../include/Layer.hpp" #include "../include/FullyConnected.hpp" #include "../include/Convolutional.hpp" #include "../include/Pooling.hpp" using namespace std; // pixel normalize function void normalize ( vector<vector<vector<double>>>& image, vector<vector<double>>& ave ) { for( int i = 0; i < image[0].size(); ++i ){ ave.emplace_back(image[0][0].size(), 0.0); for( int j = 0; j < image.size(); ++j ){ for( int k = 0; k < image[0][i].size(); ++k ) ave[i][k] += image[j][i][k]; } for( int j = 0; j < image[0][i].size(); ++j ) ave[i][j] /= image.size(); for( int j = 0; j < image.size(); ++j ) for( int k = 0; k < image[0][i].size(); ++k ) image[j][i][k] -= ave[i][k]; } } int main( int argc, char* argv[] ) { // define mini-batch size. const int BATCH_SIZE = 50; // parallelism for model parallel. int INNER = 1; for( int i = 1; i < argc; ++i ){ if( strcmp(argv[i], "--inner") == 0 ){ sscanf(argv[i+1], "%d", &INNER); ++i; } } MPI_Init(&argc, &argv); MPI_Comm outer_world, inner_world; int world_rank, world_nprocs; // rank and number of processes in all processes. int inner_rank, inner_nprocs; // rank and number of processes in model parallel. int outer_rank, outer_nprocs; // rank and number of processes in data parallel. MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); MPI_Comm_size(MPI_COMM_WORLD, &world_nprocs); // determine model parallel's rank of each processes. MPI_Comm_split(MPI_COMM_WORLD, world_rank / INNER, world_rank, &inner_world); MPI_Comm_rank(inner_world, &inner_rank); MPI_Comm_size(inner_world, &inner_nprocs); // determine data parallel's rank of each processes. MPI_Comm_split(MPI_COMM_WORLD, world_rank % INNER, world_rank, &outer_world); MPI_Comm_rank(outer_world, &outer_rank); MPI_Comm_size(outer_world, &outer_nprocs); // construct neuralnetwork with CrossEntropy. Neuralnet net(shared_ptr<LossFunction>(new CrossEntropy), outer_world, inner_world); vector<shared_ptr<Layer>> layers; // define layers. layers.emplace_back(new Convolutional(1, 28*28, 28, 10, 28*28, 28, 5, 5, 1, shared_ptr<Function>(new ReLU))); layers.emplace_back(new Pooling(10, 28*28, 28, 10, 14*14, 14, 3, 3, 2, shared_ptr<Function>(new Identity))); layers.emplace_back(new Convolutional(10, 14*14, 14, 20, 14*14, 14, 5, 5, 1, shared_ptr<Function>(new ReLU))); layers.emplace_back(new Pooling(20, 14*14, 14, 20, 7*7, 7, 2, 2, 2, shared_ptr<Function>(new Identity))); layers.emplace_back(new FullyConnected(20, 7*7, 1, 512, shared_ptr<Function>(new ReLU))); layers.emplace_back(new FullyConnected(1, 512, 1, 10, shared_ptr<Function>(new Softmax))); // this neuralnet has 7 layers, input, Conv1, MaxPool, Conv2, MaxPool, Fc1 and Fc2; for( int i = 0; i < layers.size(); ++i ){ net.add_layer(layers[i]); } // read a test data of MNIST(http://yann.lecun.com/exdb/mnist/). vector<int> train_lab; vector<vector<vector<double>>> train_x; const int N = 10000 / outer_nprocs; ifstream train_image("train-images-idx3-ubyte", ios_base::binary); if( !train_image.is_open() ){ cerr << "\"train-images-idx3-ubyte\" is not found!" << endl; return 1; } ifstream train_label("train-labels-idx1-ubyte", ios_base::binary); if( !train_label.is_open() ){ cerr << "\"train-labels-idx1-ubyte\" is not found!" << endl; return 1; } train_image.seekg(4*4 + 28*28*outer_rank * N, ios_base::beg); train_label.seekg(4*2 + outer_rank * N, ios_base::beg); for( int i = 0; i < N; ++i ){ unsigned char tmp_lab; train_label.read((char*)&tmp_lab, sizeof(unsigned char)); train_lab.push_back(tmp_lab); vector<vector<double>> tmp(1, vector<double>(28*28)); for( int j = 0; j < 28*28; ++j ){ unsigned char c; train_image.read((char*)&c, sizeof(unsigned char)); tmp[0][j] = (c/255.0); } train_x.push_back(tmp); } // set supervised data. vector<vector<vector<double>>> d(N, vector<vector<double>>(1, vector<double>(10, 0.0))); for( int i = 0; i < N; ++i ) d[i][0][train_lab[i]] = 1.0; vector<vector<double>> ave; // normalize train image. normalize(train_x, ave); // read a train data of MNIST. vector<int> test_lab; vector<vector<vector<double>>> test_x; const int M = 5000; ifstream test_image("t10k-images-idx3-ubyte", ios_base::binary); if( !test_image.is_open() ){ cerr << "\"t10k-images-idx3-ubyte\" is not found!" << endl; return 1; } ifstream test_label("t10k-labels-idx1-ubyte", ios_base::binary); if( !test_label.is_open() ){ cerr << "\"t10k-labels-idx1-ubyte\" is not found!" << endl; return 1; } test_image.seekg(4*4, ios_base::beg); test_label.seekg(4*2, ios_base::beg); for( int i = 0; i < M; ++i ){ unsigned char tmp_lab; test_label.read((char*)&tmp_lab, sizeof(unsigned char)); test_lab.push_back(tmp_lab); vector<vector<double>> tmp(1, vector<double>(28*28)); for( int j = 0; j < 28*28; ++j ){ unsigned char c; test_image.read((char*)&c, sizeof(unsigned char)); tmp[0][j] = (c/255.0 - ave[0][j]); } test_x.push_back(tmp); } // train data into Matrix class for checking error. vector<Matrix<double>> X(1, Matrix<double>(28*28, M)), D(1, Matrix<double>(10, M)); for( int i = 0; i < M; ++i ){ for( int j = 0; j < 28*28; ++j ){ X[0](j, i) = test_x[i][0][j]; } D[0](test_lab[i], i) = 1.0; } // checking error function. double prev_time, total_time; auto check_error = [&](const Neuralnet& nn, const int iter, const std::vector<Matrix<double>>& x, const std::vector<Matrix<double>>& d ) -> void { if( iter%((N/BATCH_SIZE)) != 0 || iter == 0 ) return; double tmp_time = MPI_Wtime(); // calculating answer rate among all train data. int train_ans_num = 0; auto y = nn.apply(train_x); for( int i = 0; i < y.size(); ++i ){ int idx, lab; double max_num = 0.0; for( int j = 0; j < 10; ++j ){ if( max_num < y[i][0][j] ){ max_num = y[i][0][j]; idx = j; } } if( idx == train_lab[i] ) ++train_ans_num; } // calculating answer rate among all test data. int test_ans_num = 0; auto Y = nn.apply(X); for( int i = 0; i < Y[0].n; ++i ){ int idx, lab; double max_num = 0.0; for( int j = 0; j < 10; ++j ){ if( max_num < Y[0](j,i) ){ max_num = Y[0](j,i); idx = j; } if( D[0](j, i) == 1.0 ) lab = j; } if( idx == lab ) ++test_ans_num; } // output answer rate each test data batch. if( inner_rank == 0 ){ for( int i = 0; i < outer_nprocs; ++i ){ if( i == outer_rank ){ printf("outer rank : %d\n", outer_rank); printf(" Elapsed time : %.3f, Total time : %.3f\n", MPI_Wtime() - prev_time, MPI_Wtime() - total_time); printf(" Train answer rate : %.2f%%\n", (double)train_ans_num/y.size()*100.0); printf(" Test answer rate : %.2f%%\n", (double)test_ans_num/X[0].n*100.0); } MPI_Barrier(outer_world); } prev_time = MPI_Wtime(); } if( world_rank == 0 ) puts(""); }; // set a hyper parameter. net.set_EPS(1.0E-3); net.set_LAMBDA(0.0); net.set_BATCHSIZE(BATCH_SIZE); net.set_UPDATEITER(N/BATCH_SIZE*2); // learning the neuralnet in 20 EPOCH and output error defined above in each epoch. prev_time = total_time = MPI_Wtime(); net.learning(train_x, d, N/BATCH_SIZE*10, check_error); MPI_Finalize(); } <|endoftext|>
<commit_before>#include "gtest/gtest.h" #include "motor_shield.h" #define SPEED_L 1 #define DIR_L 2 #define SPEED_R 3 #define DIR_R 4 MotorShield mshield(SPEED_L, DIR_L, SPEED_R, DIR_R); TEST(MotorShield, Initialization) { ASSERT_EQ(0, mshield.getMinSpeed()); ASSERT_EQ(255, mshield.getMaxSpeed()); ASSERT_EQ(SPEED_L, mshield.getLeftSpeedPin()); ASSERT_EQ(SPEED_R, mshield.getRightSpeedPin()); ASSERT_EQ(DIR_L, mshield.getLeftDirPin()); ASSERT_EQ(DIR_R, mshield.getRightDirPin()); } TEST(MotorShield, Setup) { ArduinoMock mock; EXPECT_CALL(mock, pinMode(SPEED_L, OUTPUT)); EXPECT_CALL(mock, pinMode(DIR_L, OUTPUT)); EXPECT_CALL(mock, pinMode(SPEED_R, OUTPUT)); EXPECT_CALL(mock, pinMode(DIR_R, OUTPUT)); EXPECT_CALL(mock, analogWrite(SPEED_L, 0)); EXPECT_CALL(mock, analogWrite(SPEED_R, 0)); EXPECT_CALL(mock, digitalWrite(DIR_L, LOW)); EXPECT_CALL(mock, digitalWrite(DIR_R, LOW)); mshield.init(); } <commit_msg>Add tests for all methods<commit_after>#include "gtest/gtest.h" #include "motor_shield.h" #define SPEED_L 1 #define DIR_L 2 #define SPEED_R 3 #define DIR_R 4 MotorShield mshield(SPEED_L, DIR_L, SPEED_R, DIR_R); TEST(MotorShield, Initialization) { ASSERT_EQ(0, mshield.getMinSpeed()); ASSERT_EQ(255, mshield.getMaxSpeed()); ASSERT_EQ(SPEED_L, mshield.getLeftSpeedPin()); ASSERT_EQ(SPEED_R, mshield.getRightSpeedPin()); ASSERT_EQ(DIR_L, mshield.getLeftDirPin()); ASSERT_EQ(DIR_R, mshield.getRightDirPin()); } TEST(MotorShield, Setup) { ArduinoMock mock; EXPECT_CALL(mock, pinMode(SPEED_L, OUTPUT)); EXPECT_CALL(mock, pinMode(DIR_L, OUTPUT)); EXPECT_CALL(mock, pinMode(SPEED_R, OUTPUT)); EXPECT_CALL(mock, pinMode(DIR_R, OUTPUT)); EXPECT_CALL(mock, analogWrite(SPEED_L, 0)); EXPECT_CALL(mock, analogWrite(SPEED_R, 0)); EXPECT_CALL(mock, digitalWrite(DIR_L, LOW)); EXPECT_CALL(mock, digitalWrite(DIR_R, LOW)); mshield.init(); } TEST(MotorShield, Forward) { ArduinoMock mock; EXPECT_CALL(mock, digitalWrite(DIR_L, LOW)); EXPECT_CALL(mock, digitalWrite(DIR_R, LOW)); mshield.forward(); } TEST(MotorShield, Backward) { ArduinoMock mock; EXPECT_CALL(mock, digitalWrite(DIR_L, HIGH)); EXPECT_CALL(mock, digitalWrite(DIR_R, HIGH)); mshield.backward(); } TEST(MotorShield, Stop) { ArduinoMock mock; EXPECT_CALL(mock, analogWrite(SPEED_L, 0)); EXPECT_CALL(mock, analogWrite(SPEED_R, 0)); mshield.stop(); } TEST(MotorShield, FullSpeed) { ArduinoMock mock; EXPECT_CALL(mock, analogWrite(SPEED_L, 255)); EXPECT_CALL(mock, analogWrite(SPEED_R, 255)); mshield.fullSpeed(); } TEST(MotorShield, StopLeft) { ArduinoMock mock; EXPECT_CALL(mock, analogWrite(SPEED_L, 0)); mshield.stopLeft(); } TEST(MotorShield, StopRight) { ArduinoMock mock; EXPECT_CALL(mock, analogWrite(SPEED_R, 0)); mshield.stopRight(); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. // // Decodes the blocks generated by block_builder.cc. #include "table/block.h" #include <vector> #include <algorithm> #include "leveldb/comparator.h" #include "util/coding.h" #include "util/logging.h" namespace leveldb { inline uint32_t Block::NumRestarts() const { assert(size_ >= 2*sizeof(uint32_t)); return DecodeFixed32(data_ + size_ - sizeof(uint32_t)); } Block::Block(const char* data, size_t size) : data_(data), size_(size) { if (size_ < sizeof(uint32_t)) { size_ = 0; // Error marker } else { restart_offset_ = size_ - (1 + NumRestarts()) * sizeof(uint32_t); if (restart_offset_ > size_ - sizeof(uint32_t)) { // The size is too small for NumRestarts() and therefore // restart_offset_ wrapped around. size_ = 0; } } } Block::~Block() { delete[] data_; } // Helper routine: decode the next block entry starting at "p", // storing the number of shared key bytes, non_shared key bytes, // and the length of the value in "*shared", "*non_shared", and // "*value_length", respectively. Will not derefence past "limit". // // If any errors are detected, returns NULL. Otherwise, returns a // pointer to the key delta (just past the three decoded values). static inline const char* DecodeEntry(const char* p, const char* limit, uint32_t* shared, uint32_t* non_shared, uint32_t* value_length) { if (limit - p < 3) return NULL; *shared = reinterpret_cast<const unsigned char*>(p)[0]; *non_shared = reinterpret_cast<const unsigned char*>(p)[1]; *value_length = reinterpret_cast<const unsigned char*>(p)[2]; if ((*shared | *non_shared | *value_length) < 128) { // Fast path: all three values are encoded in one byte each p += 3; } else { if ((p = GetVarint32Ptr(p, limit, shared)) == NULL) return NULL; if ((p = GetVarint32Ptr(p, limit, non_shared)) == NULL) return NULL; if ((p = GetVarint32Ptr(p, limit, value_length)) == NULL) return NULL; } if (static_cast<uint32>(limit - p) < (*non_shared + *value_length)) { return NULL; } return p; } class Block::Iter : public Iterator { private: const Comparator* const comparator_; const char* const data_; // underlying block contents uint32_t const restarts_; // Offset of restart array (list of fixed32) uint32_t const num_restarts_; // Number of uint32_t entries in restart array // current_ is offset in data_ of current entry. >= restarts_ if !Valid uint32_t current_; uint32_t restart_index_; // Index of restart block in which current_ falls std::string key_; Slice value_; Status status_; inline int Compare(const Slice& a, const Slice& b) const { return comparator_->Compare(a, b); } // Return the offset in data_ just past the end of the current entry. inline uint32_t NextEntryOffset() const { return (value_.data() + value_.size()) - data_; } uint32_t GetRestartPoint(uint32_t index) { assert(index < num_restarts_); return DecodeFixed32(data_ + restarts_ + index * sizeof(uint32_t)); } void SeekToRestartPoint(uint32_t index) { key_.clear(); restart_index_ = index; // current_ will be fixed by ParseNextKey(); // ParseNextKey() starts at the end of value_, so set value_ accordingly uint32_t offset = GetRestartPoint(index); value_ = Slice(data_ + offset, 0); } public: Iter(const Comparator* comparator, const char* data, uint32_t restarts, uint32_t num_restarts) : comparator_(comparator), data_(data), restarts_(restarts), num_restarts_(num_restarts), current_(restarts_), restart_index_(num_restarts_) { assert(num_restarts_ > 0); } virtual bool Valid() const { return current_ < restarts_; } virtual Status status() const { return status_; } virtual Slice key() const { assert(Valid()); return key_; } virtual Slice value() const { assert(Valid()); return value_; } virtual void Next() { assert(Valid()); ParseNextKey(); } virtual void Prev() { assert(Valid()); // Scan backwards to a restart point before current_ const uint32_t original = current_; while (GetRestartPoint(restart_index_) >= original) { if (restart_index_ == 0) { // No more entries current_ = restarts_; restart_index_ = num_restarts_; return; } restart_index_--; } SeekToRestartPoint(restart_index_); do { // Loop until end of current entry hits the start of original entry } while (ParseNextKey() && NextEntryOffset() < original); } virtual void Seek(const Slice& target) { // Binary search in restart array to find the first restart point // with a key >= target uint32_t left = 0; uint32_t right = num_restarts_ - 1; while (left < right) { uint32_t mid = (left + right + 1) / 2; uint32_t region_offset = GetRestartPoint(mid); uint32_t shared, non_shared, value_length; const char* key_ptr = DecodeEntry(data_ + region_offset, data_ + restarts_, &shared, &non_shared, &value_length); if (key_ptr == NULL || (shared != 0)) { CorruptionError(); return; } Slice mid_key(key_ptr, non_shared); if (Compare(mid_key, target) < 0) { // Key at "mid" is smaller than "target". Therefore all // blocks before "mid" are uninteresting. left = mid; } else { // Key at "mid" is >= "target". Therefore all blocks at or // after "mid" are uninteresting. right = mid - 1; } } // Linear search (within restart block) for first key >= target SeekToRestartPoint(left); while (true) { if (!ParseNextKey()) { return; } if (Compare(key_, target) >= 0) { return; } } } virtual void SeekToFirst() { SeekToRestartPoint(0); ParseNextKey(); } virtual void SeekToLast() { SeekToRestartPoint(num_restarts_ - 1); while (ParseNextKey() && NextEntryOffset() < restarts_) { // Keep skipping } } private: void CorruptionError() { current_ = restarts_; restart_index_ = num_restarts_; status_ = Status::Corruption("bad entry in block"); key_.clear(); value_.clear(); } bool ParseNextKey() { current_ = NextEntryOffset(); const char* p = data_ + current_; const char* limit = data_ + restarts_; // Restarts come right after data if (p >= limit) { // No more entries to return. Mark as invalid. current_ = restarts_; restart_index_ = num_restarts_; return false; } // Decode next entry uint32_t shared, non_shared, value_length; p = DecodeEntry(p, limit, &shared, &non_shared, &value_length); if (p == NULL || key_.size() < shared) { CorruptionError(); return false; } else { key_.resize(shared); key_.append(p, non_shared); value_ = Slice(p + non_shared, value_length); while (restart_index_ + 1 < num_restarts_ && GetRestartPoint(restart_index_ + 1) < current_) { ++restart_index_; } return true; } } }; Iterator* Block::NewIterator(const Comparator* cmp) { if (size_ < 2*sizeof(uint32_t)) { return NewErrorIterator(Status::Corruption("bad block contents")); } const uint32_t num_restarts = NumRestarts(); if (num_restarts == 0) { return NewEmptyIterator(); } else { return new Iter(cmp, data_, restart_offset_, num_restarts); } } } <commit_msg>fix build on at least linux<commit_after>// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. // // Decodes the blocks generated by block_builder.cc. #include "table/block.h" #include <vector> #include <algorithm> #include "leveldb/comparator.h" #include "util/coding.h" #include "util/logging.h" namespace leveldb { inline uint32_t Block::NumRestarts() const { assert(size_ >= 2*sizeof(uint32_t)); return DecodeFixed32(data_ + size_ - sizeof(uint32_t)); } Block::Block(const char* data, size_t size) : data_(data), size_(size) { if (size_ < sizeof(uint32_t)) { size_ = 0; // Error marker } else { restart_offset_ = size_ - (1 + NumRestarts()) * sizeof(uint32_t); if (restart_offset_ > size_ - sizeof(uint32_t)) { // The size is too small for NumRestarts() and therefore // restart_offset_ wrapped around. size_ = 0; } } } Block::~Block() { delete[] data_; } // Helper routine: decode the next block entry starting at "p", // storing the number of shared key bytes, non_shared key bytes, // and the length of the value in "*shared", "*non_shared", and // "*value_length", respectively. Will not derefence past "limit". // // If any errors are detected, returns NULL. Otherwise, returns a // pointer to the key delta (just past the three decoded values). static inline const char* DecodeEntry(const char* p, const char* limit, uint32_t* shared, uint32_t* non_shared, uint32_t* value_length) { if (limit - p < 3) return NULL; *shared = reinterpret_cast<const unsigned char*>(p)[0]; *non_shared = reinterpret_cast<const unsigned char*>(p)[1]; *value_length = reinterpret_cast<const unsigned char*>(p)[2]; if ((*shared | *non_shared | *value_length) < 128) { // Fast path: all three values are encoded in one byte each p += 3; } else { if ((p = GetVarint32Ptr(p, limit, shared)) == NULL) return NULL; if ((p = GetVarint32Ptr(p, limit, non_shared)) == NULL) return NULL; if ((p = GetVarint32Ptr(p, limit, value_length)) == NULL) return NULL; } if (static_cast<uint32_t>(limit - p) < (*non_shared + *value_length)) { return NULL; } return p; } class Block::Iter : public Iterator { private: const Comparator* const comparator_; const char* const data_; // underlying block contents uint32_t const restarts_; // Offset of restart array (list of fixed32) uint32_t const num_restarts_; // Number of uint32_t entries in restart array // current_ is offset in data_ of current entry. >= restarts_ if !Valid uint32_t current_; uint32_t restart_index_; // Index of restart block in which current_ falls std::string key_; Slice value_; Status status_; inline int Compare(const Slice& a, const Slice& b) const { return comparator_->Compare(a, b); } // Return the offset in data_ just past the end of the current entry. inline uint32_t NextEntryOffset() const { return (value_.data() + value_.size()) - data_; } uint32_t GetRestartPoint(uint32_t index) { assert(index < num_restarts_); return DecodeFixed32(data_ + restarts_ + index * sizeof(uint32_t)); } void SeekToRestartPoint(uint32_t index) { key_.clear(); restart_index_ = index; // current_ will be fixed by ParseNextKey(); // ParseNextKey() starts at the end of value_, so set value_ accordingly uint32_t offset = GetRestartPoint(index); value_ = Slice(data_ + offset, 0); } public: Iter(const Comparator* comparator, const char* data, uint32_t restarts, uint32_t num_restarts) : comparator_(comparator), data_(data), restarts_(restarts), num_restarts_(num_restarts), current_(restarts_), restart_index_(num_restarts_) { assert(num_restarts_ > 0); } virtual bool Valid() const { return current_ < restarts_; } virtual Status status() const { return status_; } virtual Slice key() const { assert(Valid()); return key_; } virtual Slice value() const { assert(Valid()); return value_; } virtual void Next() { assert(Valid()); ParseNextKey(); } virtual void Prev() { assert(Valid()); // Scan backwards to a restart point before current_ const uint32_t original = current_; while (GetRestartPoint(restart_index_) >= original) { if (restart_index_ == 0) { // No more entries current_ = restarts_; restart_index_ = num_restarts_; return; } restart_index_--; } SeekToRestartPoint(restart_index_); do { // Loop until end of current entry hits the start of original entry } while (ParseNextKey() && NextEntryOffset() < original); } virtual void Seek(const Slice& target) { // Binary search in restart array to find the first restart point // with a key >= target uint32_t left = 0; uint32_t right = num_restarts_ - 1; while (left < right) { uint32_t mid = (left + right + 1) / 2; uint32_t region_offset = GetRestartPoint(mid); uint32_t shared, non_shared, value_length; const char* key_ptr = DecodeEntry(data_ + region_offset, data_ + restarts_, &shared, &non_shared, &value_length); if (key_ptr == NULL || (shared != 0)) { CorruptionError(); return; } Slice mid_key(key_ptr, non_shared); if (Compare(mid_key, target) < 0) { // Key at "mid" is smaller than "target". Therefore all // blocks before "mid" are uninteresting. left = mid; } else { // Key at "mid" is >= "target". Therefore all blocks at or // after "mid" are uninteresting. right = mid - 1; } } // Linear search (within restart block) for first key >= target SeekToRestartPoint(left); while (true) { if (!ParseNextKey()) { return; } if (Compare(key_, target) >= 0) { return; } } } virtual void SeekToFirst() { SeekToRestartPoint(0); ParseNextKey(); } virtual void SeekToLast() { SeekToRestartPoint(num_restarts_ - 1); while (ParseNextKey() && NextEntryOffset() < restarts_) { // Keep skipping } } private: void CorruptionError() { current_ = restarts_; restart_index_ = num_restarts_; status_ = Status::Corruption("bad entry in block"); key_.clear(); value_.clear(); } bool ParseNextKey() { current_ = NextEntryOffset(); const char* p = data_ + current_; const char* limit = data_ + restarts_; // Restarts come right after data if (p >= limit) { // No more entries to return. Mark as invalid. current_ = restarts_; restart_index_ = num_restarts_; return false; } // Decode next entry uint32_t shared, non_shared, value_length; p = DecodeEntry(p, limit, &shared, &non_shared, &value_length); if (p == NULL || key_.size() < shared) { CorruptionError(); return false; } else { key_.resize(shared); key_.append(p, non_shared); value_ = Slice(p + non_shared, value_length); while (restart_index_ + 1 < num_restarts_ && GetRestartPoint(restart_index_ + 1) < current_) { ++restart_index_; } return true; } } }; Iterator* Block::NewIterator(const Comparator* cmp) { if (size_ < 2*sizeof(uint32_t)) { return NewErrorIterator(Status::Corruption("bad block contents")); } const uint32_t num_restarts = NumRestarts(); if (num_restarts == 0) { return NewEmptyIterator(); } else { return new Iter(cmp, data_, restart_offset_, num_restarts); } } } <|endoftext|>
<commit_before>#include <gl/pogl.h> #include <thread> #include "POGLExampleWindow.h" static const POGL_CHAR SIMPLE_EFFECT_VS[] = { R"( #version 330 layout(location = 0) in vec3 position; layout(location = 1) in vec4 color; out vec4 vs_Color; void main() { vs_Color = color; gl_Position = vec4(position, 1.0); } )"}; static const POGL_CHAR SIMPLE_EFFECT_FS[] = { R"( #version 330 in vec4 vs_Color; void main() { gl_FragColor = vs_Color; } )" }; int main() { // Create a window POGL_HANDLE windowHandle = POGLCreateExampleWindow(POGL_SIZEI(1024, 768), POGL_TOSTRING("Example 2: Create Triangle")); // Create a POGL device based on the supplied information POGL_DEVICE_INFO deviceInfo; #ifdef _DEBUG deviceInfo.flags = POGLDeviceInfoFlags::DEBUG_MODE; #else deviceInfo.flags = 0; #endif deviceInfo.windowHandle = windowHandle; deviceInfo.colorBits = 32; deviceInfo.depthBits = 16; deviceInfo.pixelFormat = POGLPixelFormat::R8G8B8A8; IPOGLDevice* device = POGLCreateDevice(&deviceInfo); try { // Create a device context for main thread IPOGLDeviceContext* context = device->GetDeviceContext(); // Create an effect based on the supplied vertex- and fragment shader IPOGLShaderProgram* vertexShader = context->CreateShaderProgramFromMemory(SIMPLE_EFFECT_VS, sizeof(SIMPLE_EFFECT_VS), POGLShaderProgramType::VERTEX_SHADER); IPOGLShaderProgram* fragmentShader = context->CreateShaderProgramFromMemory(SIMPLE_EFFECT_FS, sizeof(SIMPLE_EFFECT_FS), POGLShaderProgramType::FRAGMENT_SHADER); IPOGLShaderProgram* programs[] = { vertexShader, fragmentShader }; IPOGLEffect* simpleEffect = context->CreateEffectFromPrograms(programs, 2); vertexShader->Release(); fragmentShader->Release(); // Create vertex buffer const POGL_POSITION_COLOR_VERTEX VERTICES[] = { POGL_POSITION_COLOR_VERTEX(POGL_VECTOR3F(-0.5f, -0.5f, 0.0f), POGL_COLOR4F(1.0f, 0.0f, 0.0f, 1.0f)), POGL_POSITION_COLOR_VERTEX(POGL_VECTOR3F(0.0f, 0.5f, 0.0f), POGL_COLOR4F(1.0f, 0.0f, 0.0f, 1.0f)), POGL_POSITION_COLOR_VERTEX(POGL_VECTOR3F(0.5f, -0.5f, 0.0f), POGL_COLOR4F(1.0f, 0.0f, 0.0f, 1.0f)) }; IPOGLVertexBuffer* vertexBuffer = context->CreateVertexBuffer(VERTICES, sizeof(VERTICES), POGLPrimitiveType::TRIANGLE, POGLBufferUsage::STATIC); // Create vertex buffer const POGL_POSITION_COLOR_VERTEX VERTICES_INV[] = { POGL_POSITION_COLOR_VERTEX(POGL_VECTOR3F(0.5f, 0.5f, 0.0f), POGL_COLOR4F(0.0f, 1.0f, 0.0f, 1.0f)), POGL_POSITION_COLOR_VERTEX(POGL_VECTOR3F(0.0f, -0.5f, 0.0f), POGL_COLOR4F(0.0f, 1.0f, 0.0f, 1.0f)), POGL_POSITION_COLOR_VERTEX(POGL_VECTOR3F(-0.5f, 0.5f, 0.0f), POGL_COLOR4F(0.0f, 1.0f, 0.0f, 1.0f)) }; IPOGLVertexBuffer* vertexBufferInv = context->CreateVertexBuffer(VERTICES_INV, sizeof(VERTICES_INV), POGLPrimitiveType::TRIANGLE, POGLBufferUsage::STATIC); // Setup effect properties simpleEffect->SetBlend(true); simpleEffect->SetBlendFunc(POGLSrcFactor::SRC_COLOR, POGLDstFactor::ONE_MINUS_SRC_COLOR); while (POGLProcessEvents()) { // Prepare the simple effect IPOGLRenderState* state = context->Apply(simpleEffect); // Clear the color and depth buffer state->Clear(POGLClearType::COLOR | POGLClearType::DEPTH); // Draw the vertices inside the vertex buffer state->Draw(vertexBuffer); state->Draw(vertexBufferInv); // Nofiy the rendering engine that we are finished using the bound effect this frame state->EndFrame(); // Swap the back buffer with the front buffer device->SwapBuffers(); } // Release resources vertexBuffer->Release(); vertexBufferInv->Release(); simpleEffect->Release(); context->Release(); } catch (POGLException e) { POGLAlert(windowHandle, e); } device->Release(); // Destroy the example window POGLDestroyExampleWindow(windowHandle); // Quit application return 0; } <commit_msg>Updated title<commit_after>#include <gl/pogl.h> #include <thread> #include "POGLExampleWindow.h" static const POGL_CHAR SIMPLE_EFFECT_VS[] = { R"( #version 330 layout(location = 0) in vec3 position; layout(location = 1) in vec4 color; out vec4 vs_Color; void main() { vs_Color = color; gl_Position = vec4(position, 1.0); } )"}; static const POGL_CHAR SIMPLE_EFFECT_FS[] = { R"( #version 330 in vec4 vs_Color; void main() { gl_FragColor = vs_Color; } )" }; int main() { // Create a window POGL_HANDLE windowHandle = POGLCreateExampleWindow(POGL_SIZEI(1024, 768), POGL_TOSTRING("Example 3: Blending")); // Create a POGL device based on the supplied information POGL_DEVICE_INFO deviceInfo; #ifdef _DEBUG deviceInfo.flags = POGLDeviceInfoFlags::DEBUG_MODE; #else deviceInfo.flags = 0; #endif deviceInfo.windowHandle = windowHandle; deviceInfo.colorBits = 32; deviceInfo.depthBits = 16; deviceInfo.pixelFormat = POGLPixelFormat::R8G8B8A8; IPOGLDevice* device = POGLCreateDevice(&deviceInfo); try { // Create a device context for main thread IPOGLDeviceContext* context = device->GetDeviceContext(); // Create an effect based on the supplied vertex- and fragment shader IPOGLShaderProgram* vertexShader = context->CreateShaderProgramFromMemory(SIMPLE_EFFECT_VS, sizeof(SIMPLE_EFFECT_VS), POGLShaderProgramType::VERTEX_SHADER); IPOGLShaderProgram* fragmentShader = context->CreateShaderProgramFromMemory(SIMPLE_EFFECT_FS, sizeof(SIMPLE_EFFECT_FS), POGLShaderProgramType::FRAGMENT_SHADER); IPOGLShaderProgram* programs[] = { vertexShader, fragmentShader }; IPOGLEffect* simpleEffect = context->CreateEffectFromPrograms(programs, 2); vertexShader->Release(); fragmentShader->Release(); // Create vertex buffer const POGL_POSITION_COLOR_VERTEX VERTICES[] = { POGL_POSITION_COLOR_VERTEX(POGL_VECTOR3F(-0.5f, -0.5f, 0.0f), POGL_COLOR4F(1.0f, 0.0f, 0.0f, 1.0f)), POGL_POSITION_COLOR_VERTEX(POGL_VECTOR3F(0.0f, 0.5f, 0.0f), POGL_COLOR4F(1.0f, 0.0f, 0.0f, 1.0f)), POGL_POSITION_COLOR_VERTEX(POGL_VECTOR3F(0.5f, -0.5f, 0.0f), POGL_COLOR4F(1.0f, 0.0f, 0.0f, 1.0f)) }; IPOGLVertexBuffer* vertexBuffer = context->CreateVertexBuffer(VERTICES, sizeof(VERTICES), POGLPrimitiveType::TRIANGLE, POGLBufferUsage::STATIC); // Create vertex buffer const POGL_POSITION_COLOR_VERTEX VERTICES_INV[] = { POGL_POSITION_COLOR_VERTEX(POGL_VECTOR3F(0.5f, 0.5f, 0.0f), POGL_COLOR4F(0.0f, 1.0f, 0.0f, 1.0f)), POGL_POSITION_COLOR_VERTEX(POGL_VECTOR3F(0.0f, -0.5f, 0.0f), POGL_COLOR4F(0.0f, 1.0f, 0.0f, 1.0f)), POGL_POSITION_COLOR_VERTEX(POGL_VECTOR3F(-0.5f, 0.5f, 0.0f), POGL_COLOR4F(0.0f, 1.0f, 0.0f, 1.0f)) }; IPOGLVertexBuffer* vertexBufferInv = context->CreateVertexBuffer(VERTICES_INV, sizeof(VERTICES_INV), POGLPrimitiveType::TRIANGLE, POGLBufferUsage::STATIC); // Setup effect properties simpleEffect->SetBlend(true); simpleEffect->SetBlendFunc(POGLSrcFactor::SRC_COLOR, POGLDstFactor::ONE_MINUS_SRC_COLOR); while (POGLProcessEvents()) { // Prepare the simple effect IPOGLRenderState* state = context->Apply(simpleEffect); // Clear the color and depth buffer state->Clear(POGLClearType::COLOR | POGLClearType::DEPTH); // Draw the vertices inside the vertex buffer state->Draw(vertexBuffer); state->Draw(vertexBufferInv); // Nofiy the rendering engine that we are finished using the bound effect this frame state->EndFrame(); // Swap the back buffer with the front buffer device->SwapBuffers(); } // Release resources vertexBuffer->Release(); vertexBufferInv->Release(); simpleEffect->Release(); context->Release(); } catch (POGLException e) { POGLAlert(windowHandle, e); } device->Release(); // Destroy the example window POGLDestroyExampleWindow(windowHandle); // Quit application return 0; } <|endoftext|>
<commit_before> // Copyright 2010-2012 University of Washington. All Rights Reserved. // LICENSE_PLACEHOLDER // This software was created with Government support under DE // AC05-76RL01830 awarded by the United States Department of // Energy. The Government has certain rights in the software. #ifndef __INCOHERENT_RELEASER_HPP__ #define __INCOHERENT_RELEASER_HPP__ #include "Grappa.hpp" #include "Message.hpp" #include "MessagePool.hpp" #include "tasks/TaskingScheduler.hpp" #ifdef VTRACE #include <vt_user.h> #endif // forward declare for active message templates template< typename T > class IncoherentReleaser; /// Stats for IncoherentReleaser class IRStatistics { private: uint64_t release_ams; uint64_t release_ams_bytes; #ifdef VTRACE_SAMPLED unsigned ir_grp_vt; unsigned release_ams_ev_vt; unsigned release_ams_bytes_ev_vt; #endif public: IRStatistics(); void reset(); inline void count_release_ams( uint64_t bytes ) { release_ams++; release_ams_bytes+=bytes; } void dump( std::ostream& o, const char * terminator ); void sample(); void profiling_sample(); void merge(const IRStatistics * other); }; extern IRStatistics incoherent_releaser_stats; /// IncoherentReleaser behavior for cache. template< typename T > class IncoherentReleaser { private: bool release_started_; bool released_; GlobalAddress< T > * request_address_; size_t * count_; T ** pointer_; Thread * thread_; int num_messages_; int response_count_; public: IncoherentReleaser( GlobalAddress< T > * request_address, size_t * count, T ** pointer ) : request_address_( request_address ) , count_( count ) , pointer_( pointer ) , release_started_( false ) , released_( false ) , thread_(NULL) , num_messages_(0) , response_count_(0) { reset(); } void reset( ) { CHECK( !release_started_ || released_ ) << "inconsistent state for reset"; release_started_ = false; released_ = false; thread_ = NULL; num_messages_ = 0; response_count_ = 0; if( *count_ == 0 ) { DVLOG(5) << "Zero-length release"; release_started_ = true; released_ = true; } else if( request_address_->is_2D() ) { num_messages_ = 1; if( request_address_->node() == Grappa_mynode() ) { release_started_ = true; released_ = true; } } else { DVLOG(5) << "Straddle: block_max is " << (*request_address_ + *count_).block_max() ; DVLOG(5) << ", request_address is " << *request_address_; DVLOG(5) << ", sizeof(T) is " << sizeof(T); DVLOG(5) << ", count is " << *count_; DVLOG(5) << ", block_min is " << request_address_->block_min(); DVLOG(5) << "Straddle: address is " << *request_address_ ; DVLOG(5) << ", address + count is " << *request_address_ + *count_; ptrdiff_t byte_diff = ( (*request_address_ + *count_ - 1).last_byte().block_max() - request_address_->first_byte().block_min() ); DVLOG(5) << "Straddle: address block max is " << request_address_->block_max(); DVLOG(5) << " address + count block max is " << (*request_address_ + *count_).block_max(); DVLOG(5) << " address + count -1 block max is " << (*request_address_ + *count_ - 1).block_max(); DVLOG(5) << " difference is " << ( (*request_address_ + *count_ - 1).block_max() - request_address_->block_min() ); DVLOG(5) << " multiplied difference is " << ( (*request_address_ + *count_ - 1).block_max() - request_address_->block_min() ) * sizeof(T); DVLOG(5) << " address block min " << request_address_->block_min(); DVLOG(5) << "Straddle: diff is " << byte_diff << " bs " << block_size; num_messages_ = byte_diff / block_size; } if( num_messages_ > 1 ) DVLOG(5) << "****************************** MULTI BLOCK CACHE REQUEST ******************************"; DVLOG(5) << "Detecting straddle for sizeof(T):" << sizeof(T) << " count:" << *count_ << " num_messages_:" << num_messages_ << " request_address:" << *request_address_; } void start_release() { if( !release_started_ ) { #ifdef VTRACE_FULL VT_TRACER("incoherent start_release"); #endif DVLOG(5) << "Thread " << CURRENT_THREAD << " issuing release for " << *request_address_ << " * " << *count_ ; release_started_ = true; size_t total_bytes = *count_ * sizeof(T); // allocate enough requests/messages that we don't run out size_t nmsg = total_bytes / block_size + 2; size_t msg_size = sizeof(Grappa::Message<RequestArgs>); if (nmsg*msg_size < Grappa::current_worker().stack_remaining()-8192) { // try to put message storage on stack if there's space char msg_buf[nmsg*msg_size]; Grappa::MessagePool pool(msg_buf, sizeof(msg_buf)); do_release(pool); } else { // fall back on heap-allocating the storage Grappa::MessagePool pool(nmsg*msg_size); do_release(pool); } } } void do_release(Grappa::impl::MessagePoolBase& pool) { size_t total_bytes = *count_ * sizeof(T); RequestArgs args; args.request_address = *request_address_; DVLOG(5) << "Computing request_bytes from block_max " << request_address_->first_byte().block_max() << " and " << *request_address_; args.reply_address = make_global( this ); size_t offset = 0; size_t request_bytes = 0; for( size_t i = 0; offset < total_bytes; offset += request_bytes, i++) { request_bytes = args.request_address.first_byte().block_max() - args.request_address.first_byte(); if( request_bytes > total_bytes - offset ) { request_bytes = total_bytes - offset; } DVLOG(5) << "sending release request with " << request_bytes << " of total bytes = " << *count_ * sizeof(T) << " to " << args.request_address; pool.send_message(args.request_address.core(), [args](void * payload, size_t payload_size) { incoherent_releaser_stats.count_release_ams( payload_size ); DVLOG(5) << "Thread " << CURRENT_THREAD << " received release request to " << args.request_address << " reply to " << args.reply_address; memcpy( args.request_address.pointer(), payload, payload_size ); auto reply_address = args.reply_address; Grappa::send_heap_message(args.reply_address.core(), [reply_address]{ DVLOG(5) << "Thread " << CURRENT_THREAD << " received release reply to " << reply_address; reply_address.pointer()->release_reply(); }); DVLOG(5) << "Thread " << CURRENT_THREAD << " sent release reply to " << reply_address; }, (char*)(*pointer_) + offset, request_bytes ); // TODO: change type so we don't screw with pointer like this args.request_address = GlobalAddress<T>::Raw( args.request_address.raw_bits() + request_bytes ); } DVLOG(5) << "release started for " << args.request_address; // blocks here waiting for messages to be sent } void block_until_released() { if( !released_ ) { start_release(); #ifdef VTRACE_FULL VT_TRACER("incoherent block_until_released"); #endif DVLOG(5) << "Thread " << CURRENT_THREAD << " ready to block on " << *request_address_ << " * " << *count_ ; while( !released_ ) { DVLOG(5) << "Thread " << CURRENT_THREAD << " blocking on " << *request_address_ << " * " << *count_ ; if( !released_ ) { thread_ = CURRENT_THREAD; Grappa_suspend(); thread_ = NULL; } DVLOG(5) << "Thread " << CURRENT_THREAD << " woke up for " << *request_address_ << " * " << *count_ ; } } } void release_reply( ) { DVLOG(5) << "Thread " << CURRENT_THREAD << " received release reply "; ++response_count_; if ( response_count_ == num_messages_ ) { released_ = true; if( thread_ != NULL ) { DVLOG(5) << "Thread " << CURRENT_THREAD << " waking Thread " << thread_; Grappa_wake( thread_ ); } } } bool released() const { return released_; } struct RequestArgs { GlobalAddress< T > request_address; GlobalAddress< IncoherentReleaser > reply_address; }; }; #endif <commit_msg>fix: IncoherentReleaser sends PayloadMessages.<commit_after> // Copyright 2010-2012 University of Washington. All Rights Reserved. // LICENSE_PLACEHOLDER // This software was created with Government support under DE // AC05-76RL01830 awarded by the United States Department of // Energy. The Government has certain rights in the software. #ifndef __INCOHERENT_RELEASER_HPP__ #define __INCOHERENT_RELEASER_HPP__ #include "Grappa.hpp" #include "Message.hpp" #include "MessagePool.hpp" #include "tasks/TaskingScheduler.hpp" #ifdef VTRACE #include <vt_user.h> #endif // forward declare for active message templates template< typename T > class IncoherentReleaser; /// Stats for IncoherentReleaser class IRStatistics { private: uint64_t release_ams; uint64_t release_ams_bytes; #ifdef VTRACE_SAMPLED unsigned ir_grp_vt; unsigned release_ams_ev_vt; unsigned release_ams_bytes_ev_vt; #endif public: IRStatistics(); void reset(); inline void count_release_ams( uint64_t bytes ) { release_ams++; release_ams_bytes+=bytes; } void dump( std::ostream& o, const char * terminator ); void sample(); void profiling_sample(); void merge(const IRStatistics * other); }; extern IRStatistics incoherent_releaser_stats; /// IncoherentReleaser behavior for cache. template< typename T > class IncoherentReleaser { private: bool release_started_; bool released_; GlobalAddress< T > * request_address_; size_t * count_; T ** pointer_; Thread * thread_; int num_messages_; int response_count_; public: IncoherentReleaser( GlobalAddress< T > * request_address, size_t * count, T ** pointer ) : request_address_( request_address ) , count_( count ) , pointer_( pointer ) , release_started_( false ) , released_( false ) , thread_(NULL) , num_messages_(0) , response_count_(0) { reset(); } void reset( ) { CHECK( !release_started_ || released_ ) << "inconsistent state for reset"; release_started_ = false; released_ = false; thread_ = NULL; num_messages_ = 0; response_count_ = 0; if( *count_ == 0 ) { DVLOG(5) << "Zero-length release"; release_started_ = true; released_ = true; } else if( request_address_->is_2D() ) { num_messages_ = 1; if( request_address_->node() == Grappa_mynode() ) { release_started_ = true; released_ = true; } } else { DVLOG(5) << "Straddle: block_max is " << (*request_address_ + *count_).block_max() ; DVLOG(5) << ", request_address is " << *request_address_; DVLOG(5) << ", sizeof(T) is " << sizeof(T); DVLOG(5) << ", count is " << *count_; DVLOG(5) << ", block_min is " << request_address_->block_min(); DVLOG(5) << "Straddle: address is " << *request_address_ ; DVLOG(5) << ", address + count is " << *request_address_ + *count_; ptrdiff_t byte_diff = ( (*request_address_ + *count_ - 1).last_byte().block_max() - request_address_->first_byte().block_min() ); DVLOG(5) << "Straddle: address block max is " << request_address_->block_max(); DVLOG(5) << " address + count block max is " << (*request_address_ + *count_).block_max(); DVLOG(5) << " address + count -1 block max is " << (*request_address_ + *count_ - 1).block_max(); DVLOG(5) << " difference is " << ( (*request_address_ + *count_ - 1).block_max() - request_address_->block_min() ); DVLOG(5) << " multiplied difference is " << ( (*request_address_ + *count_ - 1).block_max() - request_address_->block_min() ) * sizeof(T); DVLOG(5) << " address block min " << request_address_->block_min(); DVLOG(5) << "Straddle: diff is " << byte_diff << " bs " << block_size; num_messages_ = byte_diff / block_size; } if( num_messages_ > 1 ) DVLOG(5) << "****************************** MULTI BLOCK CACHE REQUEST ******************************"; DVLOG(5) << "Detecting straddle for sizeof(T):" << sizeof(T) << " count:" << *count_ << " num_messages_:" << num_messages_ << " request_address:" << *request_address_; } void start_release() { if( !release_started_ ) { #ifdef VTRACE_FULL VT_TRACER("incoherent start_release"); #endif DVLOG(5) << "Thread " << CURRENT_THREAD << " issuing release for " << *request_address_ << " * " << *count_ ; release_started_ = true; size_t total_bytes = *count_ * sizeof(T); // allocate enough requests/messages that we don't run out size_t nmsg = total_bytes / block_size + 2; size_t msg_size = sizeof(Grappa::PayloadMessage<RequestArgs>); if (nmsg*msg_size < Grappa::current_worker().stack_remaining()-8192) { // try to put message storage on stack if there's space char msg_buf[nmsg*msg_size]; Grappa::MessagePool pool(msg_buf, sizeof(msg_buf)); do_release(pool); } else { // fall back on heap-allocating the storage Grappa::MessagePool pool(nmsg*msg_size); do_release(pool); } } } void do_release(Grappa::impl::MessagePoolBase& pool) { size_t total_bytes = *count_ * sizeof(T); RequestArgs args; args.request_address = *request_address_; DVLOG(5) << "Computing request_bytes from block_max " << request_address_->first_byte().block_max() << " and " << *request_address_; args.reply_address = make_global( this ); size_t offset = 0; size_t request_bytes = 0; for( size_t i = 0; offset < total_bytes; offset += request_bytes, i++) { request_bytes = args.request_address.first_byte().block_max() - args.request_address.first_byte(); if( request_bytes > total_bytes - offset ) { request_bytes = total_bytes - offset; } DVLOG(5) << "sending release request with " << request_bytes << " of total bytes = " << *count_ * sizeof(T) << " to " << args.request_address; pool.send_message(args.request_address.core(), [args](void * payload, size_t payload_size) { incoherent_releaser_stats.count_release_ams( payload_size ); DVLOG(5) << "Thread " << CURRENT_THREAD << " received release request to " << args.request_address << " reply to " << args.reply_address; memcpy( args.request_address.pointer(), payload, payload_size ); auto reply_address = args.reply_address; Grappa::send_heap_message(args.reply_address.core(), [reply_address]{ DVLOG(5) << "Thread " << CURRENT_THREAD << " received release reply to " << reply_address; reply_address.pointer()->release_reply(); }); DVLOG(5) << "Thread " << CURRENT_THREAD << " sent release reply to " << reply_address; }, (char*)(*pointer_) + offset, request_bytes ); // TODO: change type so we don't screw with pointer like this args.request_address = GlobalAddress<T>::Raw( args.request_address.raw_bits() + request_bytes ); } DVLOG(5) << "release started for " << args.request_address; // blocks here waiting for messages to be sent } void block_until_released() { if( !released_ ) { start_release(); #ifdef VTRACE_FULL VT_TRACER("incoherent block_until_released"); #endif DVLOG(5) << "Thread " << CURRENT_THREAD << " ready to block on " << *request_address_ << " * " << *count_ ; while( !released_ ) { DVLOG(5) << "Thread " << CURRENT_THREAD << " blocking on " << *request_address_ << " * " << *count_ ; if( !released_ ) { thread_ = CURRENT_THREAD; Grappa_suspend(); thread_ = NULL; } DVLOG(5) << "Thread " << CURRENT_THREAD << " woke up for " << *request_address_ << " * " << *count_ ; } } } void release_reply( ) { DVLOG(5) << "Thread " << CURRENT_THREAD << " received release reply "; ++response_count_; if ( response_count_ == num_messages_ ) { released_ = true; if( thread_ != NULL ) { DVLOG(5) << "Thread " << CURRENT_THREAD << " waking Thread " << thread_; Grappa_wake( thread_ ); } } } bool released() const { return released_; } struct RequestArgs { GlobalAddress< T > request_address; GlobalAddress< IncoherentReleaser > reply_address; }; }; #endif <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #include <gtest/gtest.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl/io/pcd_io.h> #include <pcl/search/search.h> #include <pcl/features/normal_3d.h> #include <pcl/segmentation/extract_polygonal_prism_data.h> #include <pcl/segmentation/segment_differences.h> //#include <pcl/segmentation/region_growing.h> using namespace pcl; using namespace pcl::io; PointCloud<PointXYZ>::Ptr cloud_; PointCloud<PointXYZ>::Ptr cloud_t_; KdTree<PointXYZ>::Ptr tree_; pcl::PointCloud<pcl::PointXYZ>::Ptr another_cloud_; pcl::PointCloud<pcl::Normal>::Ptr normals_; pcl::PointCloud<pcl::Normal>::Ptr another_normals_; //////////////////////////////////////////////////////////////////////////////////////////////// //TEST (//gionGrowingTest, Segment) //{ // pcl::RegionGrowing<pcl::PointXYZ> rg; // rg.setCloud(cloud_); // rg.setNormals(normals_); // // int num_of_segments = rg.segmentPoints(); // EXPECT_NE(0, num_of_segments); // // std::vector<std::list<int>> segments; // segments = rg.getSegments(); // EXPECT_NE(0, segments.size()); //} // //////////////////////////////////////////////////////////////////////////////////////////////// //TEST (RegionGrowingTest, SegmentWithoutCloud) //{ // pcl::RegionGrowing<pcl::PointXYZ> rg; // rg.setNormals(normals_); // // int num_of_segments = rg.segmentPoints(); // EXPECT_EQ(0, num_of_segments); // // std::vector<std::list<int>> segments; // segments = rg.getSegments(); // EXPECT_EQ(0, segments.size()); //} // //////////////////////////////////////////////////////////////////////////////////////////////// //TEST (RegionGrowingTest, SegmentWithoutNormals) //{ // pcl::RegionGrowing<pcl::PointXYZ> rg; // rg.setCloud(cloud_); // // int num_of_segments = rg.segmentPoints(); // EXPECT_EQ(0, num_of_segments); // // std::vector<std::list<int>> segments; // segments = rg.getSegments(); // EXPECT_EQ(0, segments.size()); //} // //////////////////////////////////////////////////////////////////////////////////////////////// //TEST (RegionGrowingTest, SegmentEmptyCloud) //{ // pcl::PointCloud<pcl::PointXYZ>::Ptr empty_cloud(new pcl::PointCloud<pcl::PointXYZ>); // pcl::PointCloud<pcl::Normal>::Ptr empty_normals(new pcl::PointCloud<pcl::Normal>); // // pcl::RegionGrowing<pcl::PointXYZ> rg; // rg.setCloud(empty_cloud); // rg.setNormals(empty_normals); // // int num_of_segments = rg.segmentPoints(); // EXPECT_EQ(0, num_of_segments); // // std::vector<std::list<int>> segments; // segments = rg.getSegments(); // EXPECT_EQ(0, segments.size()); //} // //////////////////////////////////////////////////////////////////////////////////////////////// //TEST (RegionGrowingTest, SegmentWithDifferentNormalAndCloudSize) //{ // pcl::RegionGrowing<pcl::PointXYZ> rg; // rg.setCloud(another_cloud_); // rg.setNormals(normals_); // // int first_cloud_size = cloud_->points.size(); // int second_cloud_size = another_cloud_->points.size(); // ASSERT_NE(first_cloud_size, second_cloud_size); // // int num_of_segments = rg.segmentPoints(); // EXPECT_EQ(0, num_of_segments); // // std::vector<std::list<int>> segments; // segments = rg.getSegments(); // EXPECT_EQ(0, segments.size()); // // rg.setCloud(cloud_); // rg.setNormals(another_normals_); // // num_of_segments = rg.segmentPoints(); // EXPECT_EQ(0, num_of_segments); // // segments = rg.getSegments(); // EXPECT_EQ(0, segments.size()); //} // //////////////////////////////////////////////////////////////////////////////////////////////// //TEST (RegionGrowingTest, SegmentWithWrongThresholdParameters) //{ // pcl::RegionGrowing<pcl::PointXYZ> rg; // rg.setCloud(cloud_); // rg.setNormals(normals_); // // rg.setNumberOfNeighbours(0); // // int num_of_segments = rg.segmentPoints(); // EXPECT_EQ(0, num_of_segments); // // std::vector<std::list<int>> segments; // segments = rg.getSegments(); // EXPECT_EQ(0, segments.size()); // // rg.setNumberOfNeighbours(30); // rg.setResidualThreshold(-10.0); // // num_of_segments = rg.segmentPoints(); // EXPECT_EQ(0, num_of_segments); // // segments = rg.getSegments(); // EXPECT_EQ(0, segments.size()); //} // //////////////////////////////////////////////////////////////////////////////////////////////// //TEST (RegionGrowingTest, SegmentFromPoint) //{ // pcl::RegionGrowing<pcl::PointXYZ> rg; // // std::list<int> segment = rg.getSegmentFromPoint(0); // EXPECT_EQ(0, segment.size()); // // rg.setCloud(cloud_); // rg.setNormals(normals_); // segment = rg.getSegmentFromPoint(0); // EXPECT_NE(0, segment.size()); //} ////////////////////////////////////////////////////////////////////////////////////////////// TEST (SegmentDifferences, Segmentation) { SegmentDifferences<PointXYZ> sd; sd.setInputCloud (cloud_); sd.setDistanceThreshold (0.00005); // Set the target as itself sd.setTargetCloud (cloud_); PointCloud<PointXYZ> output; sd.segment (output); EXPECT_EQ ((int)output.points.size (), 0); // Set a different target sd.setTargetCloud (cloud_t_); sd.segment (output); EXPECT_EQ ((int)output.points.size (), 126); //savePCDFile ("./test/0-t.pcd", output); // Reverse sd.setInputCloud (cloud_t_); sd.setTargetCloud (cloud_); sd.segment (output); EXPECT_EQ ((int)output.points.size (), 127); //savePCDFile ("./test/t-0.pcd", output); } ////////////////////////////////////////////////////////////////////////////////////////////// TEST (ExtractPolygonalPrism, Segmentation) { PointCloud<PointXYZ>::Ptr hull (new PointCloud<PointXYZ>); hull->points.resize (5); for (size_t i = 0; i < hull->points.size (); ++i) { hull->points[i].x = hull->points[i].y = i; hull->points[i].z = 0; } ExtractPolygonalPrismData<PointXYZ> ex; ex.setInputCloud (cloud_); ex.setInputPlanarHull (hull); PointIndices output; ex.segment (output); EXPECT_EQ ((int)output.indices.size (), 0); } /* ---[ */ int main (int argc, char** argv) { if (argc < 3) { std::cerr << "No test file given. Please download `bun0.pcd` and pass its path to the test." << std::endl; std::cerr << "The test needs two files. Please, pass two paths of different pcd files." << std::endl; return (-1); } // Load a standard PCD file from disk PointCloud<PointXYZ> cloud, cloud_t, another_cloud; if (loadPCDFile (argv[1], cloud) < 0) { std::cerr << "Failed to read test file. Please download `bun0.pcd` and pass its path to the test." << std::endl; return (-1); } if (pcl::io::loadPCDFile (argv[2], another_cloud) < 0) { std::cerr << "Failed to read test file. Please download `bun0.pcd` and pass its path to the test." << std::endl; return (-1); } // Tranpose the cloud cloud_t = cloud; for (size_t i = 0; i < cloud.points.size (); ++i) cloud_t.points[i].x += 0.01; cloud_ = cloud.makeShared (); cloud_t_ = cloud_t.makeShared (); another_cloud_ = another_cloud.makeShared(); normals_ = (new pcl::PointCloud<pcl::Normal>)->makeShared(); pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> normal_estimator; normal_estimator.setInputCloud(cloud_); normal_estimator.setKSearch(30); normal_estimator.compute(*normals_); another_normals_ = (new pcl::PointCloud<pcl::Normal>)->makeShared(); normal_estimator.setInputCloud(another_cloud_); normal_estimator.setKSearch(30); normal_estimator.compute(*another_normals_); testing::InitGoogleTest (&argc, argv); return (RUN_ALL_TESTS ()); } /* ]--- */ <commit_msg>* fixed line ending to UNIX like, deleted normal_3d header<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #include <gtest/gtest.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl/io/pcd_io.h> #include <pcl/search/search.h> #include <pcl/features/normal_3d.h> #include <pcl/segmentation/extract_polygonal_prism_data.h> #include <pcl/segmentation/segment_differences.h> #include <pcl/segmentation/region_growing.h> using namespace pcl; using namespace pcl::io; PointCloud<PointXYZ>::Ptr cloud_; PointCloud<PointXYZ>::Ptr cloud_t_; KdTree<PointXYZ>::Ptr tree_; pcl::PointCloud<pcl::PointXYZ>::Ptr another_cloud_; pcl::PointCloud<pcl::Normal>::Ptr normals_; pcl::PointCloud<pcl::Normal>::Ptr another_normals_; //////////////////////////////////////////////////////////////////////////////////////////////// TEST (//gionGrowingTest, Segment) { pcl::RegionGrowing<pcl::PointXYZ> rg; rg.setCloud(cloud_); rg.setNormals(normals_); int num_of_segments = rg.segmentPoints(); EXPECT_NE(0, num_of_segments); std::vector<std::list<int>> segments; segments = rg.getSegments(); EXPECT_NE(0, segments.size()); } //////////////////////////////////////////////////////////////////////////////////////////////// TEST (RegionGrowingTest, SegmentWithoutCloud) { pcl::RegionGrowing<pcl::PointXYZ> rg; rg.setNormals(normals_); int num_of_segments = rg.segmentPoints(); EXPECT_EQ(0, num_of_segments); std::vector<std::list<int>> segments; segments = rg.getSegments(); EXPECT_EQ(0, segments.size()); } //////////////////////////////////////////////////////////////////////////////////////////////// TEST (RegionGrowingTest, SegmentWithoutNormals) { pcl::RegionGrowing<pcl::PointXYZ> rg; rg.setCloud(cloud_); int num_of_segments = rg.segmentPoints(); EXPECT_EQ(0, num_of_segments); std::vector<std::list<int>> segments; segments = rg.getSegments(); EXPECT_EQ(0, segments.size()); } //////////////////////////////////////////////////////////////////////////////////////////////// TEST (RegionGrowingTest, SegmentEmptyCloud) { pcl::PointCloud<pcl::PointXYZ>::Ptr empty_cloud(new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::Normal>::Ptr empty_normals(new pcl::PointCloud<pcl::Normal>); pcl::RegionGrowing<pcl::PointXYZ> rg; rg.setCloud(empty_cloud); rg.setNormals(empty_normals); int num_of_segments = rg.segmentPoints(); EXPECT_EQ(0, num_of_segments); std::vector<std::list<int>> segments; segments = rg.getSegments(); EXPECT_EQ(0, segments.size()); } //////////////////////////////////////////////////////////////////////////////////////////////// TEST (RegionGrowingTest, SegmentWithDifferentNormalAndCloudSize) { pcl::RegionGrowing<pcl::PointXYZ> rg; rg.setCloud(another_cloud_); rg.setNormals(normals_); int first_cloud_size = cloud_->points.size(); int second_cloud_size = another_cloud_->points.size(); ASSERT_NE(first_cloud_size, second_cloud_size); int num_of_segments = rg.segmentPoints(); EXPECT_EQ(0, num_of_segments); std::vector<std::list<int>> segments; segments = rg.getSegments(); EXPECT_EQ(0, segments.size()); rg.setCloud(cloud_); rg.setNormals(another_normals_); num_of_segments = rg.segmentPoints(); EXPECT_EQ(0, num_of_segments); segments = rg.getSegments(); EXPECT_EQ(0, segments.size()); } //////////////////////////////////////////////////////////////////////////////////////////////// TEST (RegionGrowingTest, SegmentWithWrongThresholdParameters) { pcl::RegionGrowing<pcl::PointXYZ> rg; rg.setCloud(cloud_); rg.setNormals(normals_); rg.setNumberOfNeighbours(0); int num_of_segments = rg.segmentPoints(); EXPECT_EQ(0, num_of_segments); std::vector<std::list<int>> segments; segments = rg.getSegments(); EXPECT_EQ(0, segments.size()); rg.setNumberOfNeighbours(30); rg.setResidualThreshold(-10.0); num_of_segments = rg.segmentPoints(); EXPECT_EQ(0, num_of_segments); segments = rg.getSegments(); EXPECT_EQ(0, segments.size()); } //////////////////////////////////////////////////////////////////////////////////////////////// //TEST (RegionGrowingTest, SegmentFromPoint) { pcl::RegionGrowing<pcl::PointXYZ> rg; std::list<int> segment = rg.getSegmentFromPoint(0); EXPECT_EQ(0, segment.size()); rg.setCloud(cloud_); rg.setNormals(normals_); segment = rg.getSegmentFromPoint(0); EXPECT_NE(0, segment.size()); } ////////////////////////////////////////////////////////////////////////////////////////////// TEST (SegmentDifferences, Segmentation) { SegmentDifferences<PointXYZ> sd; sd.setInputCloud (cloud_); sd.setDistanceThreshold (0.00005); // Set the target as itself sd.setTargetCloud (cloud_); PointCloud<PointXYZ> output; sd.segment (output); EXPECT_EQ ((int)output.points.size (), 0); // Set a different target sd.setTargetCloud (cloud_t_); sd.segment (output); EXPECT_EQ ((int)output.points.size (), 126); //savePCDFile ("./test/0-t.pcd", output); // Reverse sd.setInputCloud (cloud_t_); sd.setTargetCloud (cloud_); sd.segment (output); EXPECT_EQ ((int)output.points.size (), 127); //savePCDFile ("./test/t-0.pcd", output); } ////////////////////////////////////////////////////////////////////////////////////////////// TEST (ExtractPolygonalPrism, Segmentation) { PointCloud<PointXYZ>::Ptr hull (new PointCloud<PointXYZ>); hull->points.resize (5); for (size_t i = 0; i < hull->points.size (); ++i) { hull->points[i].x = hull->points[i].y = i; hull->points[i].z = 0; } ExtractPolygonalPrismData<PointXYZ> ex; ex.setInputCloud (cloud_); ex.setInputPlanarHull (hull); PointIndices output; ex.segment (output); EXPECT_EQ ((int)output.indices.size (), 0); } /* ---[ */ int main (int argc, char** argv) { if (argc < 3) { std::cerr << "No test file given. Please download `bun0.pcd` and pass its path to the test." << std::endl; std::cerr << "The test needs two files. Please, pass two paths of different pcd files." << std::endl; return (-1); } // Load a standard PCD file from disk PointCloud<PointXYZ> cloud, cloud_t, another_cloud; if (loadPCDFile (argv[1], cloud) < 0) { std::cerr << "Failed to read test file. Please download `bun0.pcd` and pass its path to the test." << std::endl; return (-1); } if (pcl::io::loadPCDFile (argv[2], another_cloud) < 0) { std::cerr << "Failed to read test file. Please download `bun0.pcd` and pass its path to the test." << std::endl; return (-1); } // Tranpose the cloud cloud_t = cloud; for (size_t i = 0; i < cloud.points.size (); ++i) cloud_t.points[i].x += 0.01; cloud_ = cloud.makeShared (); cloud_t_ = cloud_t.makeShared (); another_cloud_ = another_cloud.makeShared(); normals_ = (new pcl::PointCloud<pcl::Normal>)->makeShared(); pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> normal_estimator; normal_estimator.setInputCloud(cloud_); normal_estimator.setKSearch(30); normal_estimator.compute(*normals_); another_normals_ = (new pcl::PointCloud<pcl::Normal>)->makeShared(); normal_estimator.setInputCloud(another_cloud_); normal_estimator.setKSearch(30); normal_estimator.compute(*another_normals_); testing::InitGoogleTest (&argc, argv); return (RUN_ALL_TESTS ()); } /* ]--- */ <|endoftext|>
<commit_before>#include "../test_helpers.hxx" namespace { enum colour { red, green, blue }; enum class weather : int { hot, cold, wet }; } namespace pqxx { PQXX_DECLARE_ENUM_CONVERSION(colour); PQXX_DECLARE_ENUM_CONVERSION(weather); } namespace { void test_strconv_bool() { PQXX_CHECK_EQUAL(pqxx::to_string(false), "false", "Wrong to_string(false)."); PQXX_CHECK_EQUAL(pqxx::to_string(true), "true", "Wrong to_string(true)."); bool result; pqxx::from_string("false", result); PQXX_CHECK_EQUAL(result, false, "Wrong from_string('false')."); pqxx::from_string("FALSE", result); PQXX_CHECK_EQUAL(result, false, "Wrong from_string('FALSE')."); pqxx::from_string("f", result); PQXX_CHECK_EQUAL(result, false, "Wrong from_string('f')."); pqxx::from_string("F", result); PQXX_CHECK_EQUAL(result, false, "Wrong from_string('F')."); pqxx::from_string("0", result); PQXX_CHECK_EQUAL(result, false, "Wrong from_string('0')."); pqxx::from_string("true", result); PQXX_CHECK_EQUAL(result, true, "Wrong from_string('true')."); pqxx::from_string("TRUE", result); PQXX_CHECK_EQUAL(result, true, "Wrong from_string('TRUE')."); pqxx::from_string("t", result); PQXX_CHECK_EQUAL(result, true, "Wrong from_string('t')."); pqxx::from_string("T", result); PQXX_CHECK_EQUAL(result, true, "Wrong from_string('T')."); pqxx::from_string("1", result); PQXX_CHECK_EQUAL(result, true, "Wrong from_string('1')."); } void test_strconv_enum() { PQXX_CHECK_EQUAL(pqxx::to_string(red), "0", "Enum value did not convert."); PQXX_CHECK_EQUAL(pqxx::to_string(green), "1", "Enum value did not convert."); PQXX_CHECK_EQUAL(pqxx::to_string(blue), "2", "Enum value did not convert."); colour col; pqxx::from_string("2", col); PQXX_CHECK_EQUAL(col, blue, "Could not recover enum value from string."); } void test_strconv_class_enum() { PQXX_CHECK_EQUAL( pqxx::to_string(weather::hot), "0", "Class enum value did not convert."); PQXX_CHECK_EQUAL( pqxx::to_string(weather::wet), "2", "Enum value did not convert."); weather w; pqxx::from_string("2", w); PQXX_CHECK_EQUAL( w, weather::wet, "Could not recover class enum value from string."); } PQXX_REGISTER_TEST(test_strconv_bool); PQXX_REGISTER_TEST(test_strconv_enum); PQXX_REGISTER_TEST(test_strconv_class_enum); } <commit_msg>No need to specify enum's underlying type.<commit_after>#include "../test_helpers.hxx" namespace { enum colour { red, green, blue }; enum class weather { hot, cold, wet }; } namespace pqxx { PQXX_DECLARE_ENUM_CONVERSION(colour); PQXX_DECLARE_ENUM_CONVERSION(weather); } namespace { void test_strconv_bool() { PQXX_CHECK_EQUAL(pqxx::to_string(false), "false", "Wrong to_string(false)."); PQXX_CHECK_EQUAL(pqxx::to_string(true), "true", "Wrong to_string(true)."); bool result; pqxx::from_string("false", result); PQXX_CHECK_EQUAL(result, false, "Wrong from_string('false')."); pqxx::from_string("FALSE", result); PQXX_CHECK_EQUAL(result, false, "Wrong from_string('FALSE')."); pqxx::from_string("f", result); PQXX_CHECK_EQUAL(result, false, "Wrong from_string('f')."); pqxx::from_string("F", result); PQXX_CHECK_EQUAL(result, false, "Wrong from_string('F')."); pqxx::from_string("0", result); PQXX_CHECK_EQUAL(result, false, "Wrong from_string('0')."); pqxx::from_string("true", result); PQXX_CHECK_EQUAL(result, true, "Wrong from_string('true')."); pqxx::from_string("TRUE", result); PQXX_CHECK_EQUAL(result, true, "Wrong from_string('TRUE')."); pqxx::from_string("t", result); PQXX_CHECK_EQUAL(result, true, "Wrong from_string('t')."); pqxx::from_string("T", result); PQXX_CHECK_EQUAL(result, true, "Wrong from_string('T')."); pqxx::from_string("1", result); PQXX_CHECK_EQUAL(result, true, "Wrong from_string('1')."); } void test_strconv_enum() { PQXX_CHECK_EQUAL(pqxx::to_string(red), "0", "Enum value did not convert."); PQXX_CHECK_EQUAL(pqxx::to_string(green), "1", "Enum value did not convert."); PQXX_CHECK_EQUAL(pqxx::to_string(blue), "2", "Enum value did not convert."); colour col; pqxx::from_string("2", col); PQXX_CHECK_EQUAL(col, blue, "Could not recover enum value from string."); } void test_strconv_class_enum() { PQXX_CHECK_EQUAL( pqxx::to_string(weather::hot), "0", "Class enum value did not convert."); PQXX_CHECK_EQUAL( pqxx::to_string(weather::wet), "2", "Enum value did not convert."); weather w; pqxx::from_string("2", w); PQXX_CHECK_EQUAL( w, weather::wet, "Could not recover class enum value from string."); } PQXX_REGISTER_TEST(test_strconv_bool); PQXX_REGISTER_TEST(test_strconv_enum); PQXX_REGISTER_TEST(test_strconv_class_enum); } <|endoftext|>
<commit_before>#include "catch.hpp" #include <mapnik/text/icu_shaper.hpp> #include <mapnik/text/harfbuzz_shaper.hpp> #include <mapnik/text/font_library.hpp> #include <mapnik/unicode.hpp> namespace { void test_shaping( mapnik::font_set const& fontset, mapnik::face_manager& fm, std::vector<std::tuple<unsigned, unsigned>> const& expected, char const* str, bool debug = false) { mapnik::transcoder tr("utf8"); std::map<unsigned,double> width_map; mapnik::text_itemizer itemizer; auto props = std::make_unique<mapnik::detail::evaluated_format_properties>(); props->fontset = fontset; props->text_size = 32; double scale_factor = 1; auto ustr = tr.transcode(str); auto length = ustr.length(); itemizer.add_text(ustr, props); mapnik::text_line line(0, length); mapnik::harfbuzz_shaper::shape_text(line, itemizer, width_map, fm, scale_factor); std::size_t index = 0; for (auto const& g : line) { if (debug) { if (index++ > 0) std::cerr << ","; std::cerr << "{" << g.glyph_index << ", " << g.char_index << "}"; } else { unsigned glyph_index, char_index; CHECK(index < expected.size()); std::tie(glyph_index, char_index) = expected[index++]; REQUIRE(glyph_index == g.glyph_index); REQUIRE(char_index == g.char_index); } } } } TEST_CASE("shaping") { mapnik::freetype_engine::register_font("test/data/fonts/NotoSans-Regular.ttc"); mapnik::freetype_engine::register_fonts("test/data/fonts/Noto"); mapnik::font_set fontset("fontset"); for (auto const& name : mapnik::freetype_engine::face_names()) { fontset.add_face_name(name); } mapnik::font_library fl; mapnik::freetype_engine::font_file_mapping_type font_file_mapping; mapnik::freetype_engine::font_memory_cache_type font_memory_cache; mapnik::face_manager fm(fl, font_file_mapping, font_memory_cache); { std::vector<std::tuple<unsigned, unsigned>> expected = {{0, 0}, {0, 3}, {0, 4}, {0, 7}, {3, 8}, {11, 9}, {68, 10}, {69, 11}, {70, 12}, {12, 13}}; // with default NotoSans-Regular.ttc and NotoNaskhArabic-Regular.ttf ^^^ //std::vector<std::tuple<unsigned, unsigned>> expected = // {{977,0}, {1094,3}, {1038,4}, {1168,4}, {9,7}, {3,8}, {11,9}, {68,10}, {69,11}, {70,12}, {12,13}}; // expected results if "NotoSansTibetan-Regular.ttf is registered^^ test_shaping(fontset, fm, expected, "སྤུ་ཧྲེང (abc)"); } { std::vector<std::tuple<unsigned, unsigned>> expected = {{0, 0}, {0, 3}, {0, 4}, {0, 7}, {3, 8}, {11, 9}, {0, 10}, {0, 11}, {0, 12}, {12, 13}}; test_shaping(fontset, fm, expected, "སྤུ་ཧྲེང (普兰镇)"); } { std::vector<std::tuple<unsigned, unsigned>> expected = {{68, 0}, {69, 1}, {70, 2}, {3, 3}, {11, 4}, {0, 5}, {0, 6}, {0, 7}, {12, 8}}; test_shaping(fontset, fm, expected, "abc (普兰镇)"); } { std::vector<std::tuple<unsigned, unsigned>> expected = {{68, 0}, {69, 1}, {70, 2}, {3, 3}, {11, 4}, {68, 5}, {69, 6}, {70, 7}, {12, 8}}; test_shaping(fontset, fm, expected, "abc (abc)"); } } <commit_msg>add explicit `u8` (utf8) qualifier<commit_after>#include "catch.hpp" #include <mapnik/text/icu_shaper.hpp> #include <mapnik/text/harfbuzz_shaper.hpp> #include <mapnik/text/font_library.hpp> #include <mapnik/unicode.hpp> namespace { void test_shaping( mapnik::font_set const& fontset, mapnik::face_manager& fm, std::vector<std::tuple<unsigned, unsigned>> const& expected, char const* str, bool debug = false) { mapnik::transcoder tr("utf8"); std::map<unsigned,double> width_map; mapnik::text_itemizer itemizer; auto props = std::make_unique<mapnik::detail::evaluated_format_properties>(); props->fontset = fontset; props->text_size = 32; double scale_factor = 1; auto ustr = tr.transcode(str); auto length = ustr.length(); itemizer.add_text(ustr, props); mapnik::text_line line(0, length); mapnik::harfbuzz_shaper::shape_text(line, itemizer, width_map, fm, scale_factor); std::size_t index = 0; for (auto const& g : line) { if (debug) { if (index++ > 0) std::cerr << ","; std::cerr << "{" << g.glyph_index << ", " << g.char_index << "}"; } else { unsigned glyph_index, char_index; CHECK(index < expected.size()); std::tie(glyph_index, char_index) = expected[index++]; REQUIRE(glyph_index == g.glyph_index); REQUIRE(char_index == g.char_index); } } } } TEST_CASE("shaping") { mapnik::freetype_engine::register_font("test/data/fonts/NotoSans-Regular.ttc"); mapnik::freetype_engine::register_fonts("test/data/fonts/Noto"); mapnik::font_set fontset("fontset"); for (auto const& name : mapnik::freetype_engine::face_names()) { fontset.add_face_name(name); } mapnik::font_library fl; mapnik::freetype_engine::font_file_mapping_type font_file_mapping; mapnik::freetype_engine::font_memory_cache_type font_memory_cache; mapnik::face_manager fm(fl, font_file_mapping, font_memory_cache); { std::vector<std::tuple<unsigned, unsigned>> expected = {{0, 0}, {0, 3}, {0, 4}, {0, 7}, {3, 8}, {11, 9}, {68, 10}, {69, 11}, {70, 12}, {12, 13}}; // with default NotoSans-Regular.ttc and NotoNaskhArabic-Regular.ttf ^^^ //std::vector<std::tuple<unsigned, unsigned>> expected = // {{977,0}, {1094,3}, {1038,4}, {1168,4}, {9,7}, {3,8}, {11,9}, {68,10}, {69,11}, {70,12}, {12,13}}; // expected results if "NotoSansTibetan-Regular.ttf is registered^^ test_shaping(fontset, fm, expected, u8"སྤུ་ཧྲེང (abc)"); } { std::vector<std::tuple<unsigned, unsigned>> expected = {{0, 0}, {0, 3}, {0, 4}, {0, 7}, {3, 8}, {11, 9}, {0, 10}, {0, 11}, {0, 12}, {12, 13}}; test_shaping(fontset, fm, expected, u8"སྤུ་ཧྲེང (普兰镇)"); } { std::vector<std::tuple<unsigned, unsigned>> expected = {{68, 0}, {69, 1}, {70, 2}, {3, 3}, {11, 4}, {0, 5}, {0, 6}, {0, 7}, {12, 8}}; test_shaping(fontset, fm, expected, u8"abc (普兰镇)"); } { std::vector<std::tuple<unsigned, unsigned>> expected = {{68, 0}, {69, 1}, {70, 2}, {3, 3}, {11, 4}, {68, 5}, {69, 6}, {70, 7}, {12, 8}}; test_shaping(fontset, fm, expected, "abc (abc)"); } } <|endoftext|>
<commit_before>#include "column_like_table_scan_impl.hpp" #include <algorithm> #include <array> #include <map> #include <memory> #include <regex> #include <sstream> #include <string> #include <utility> #include <vector> #include "storage/create_iterable_from_segment.hpp" #include "storage/resolve_encoded_segment_type.hpp" #include "storage/segment_iterables/create_iterable_from_attribute_vector.hpp" #include "storage/segment_iterate.hpp" #include "storage/value_segment.hpp" #include "storage/value_segment/value_segment_iterable.hpp" #include "utils/ignore_unused_variable.hpp" namespace opossum { ColumnLikeTableScanImpl::ColumnLikeTableScanImpl(const std::shared_ptr<const Table>& in_table, const ColumnID column_id, const PredicateCondition predicate_condition, const pmr_string& pattern) : AbstractDereferencedColumnTableScanImpl{in_table, column_id, predicate_condition}, _matcher{pattern}, _invert_results(predicate_condition == PredicateCondition::NotLike) {} std::string ColumnLikeTableScanImpl::description() const { return "ColumnLike"; } void ColumnLikeTableScanImpl::_scan_non_reference_segment(const BaseSegment& segment, const ChunkID chunk_id, PosList& matches, const std::shared_ptr<const PosList>& position_filter) const { // Select optimized or generic scanning implementation based on segment type if (const auto* dictionary_segment = dynamic_cast<const BaseDictionarySegment*>(&segment)) { _scan_dictionary_segment(*dictionary_segment, chunk_id, matches, position_filter); } else { _scan_generic_segment(segment, chunk_id, matches, position_filter); } } void ColumnLikeTableScanImpl::_scan_generic_segment(const BaseSegment& segment, const ChunkID chunk_id, PosList& matches, const std::shared_ptr<const PosList>& position_filter) const { segment_with_iterators_filtered(segment, position_filter, [&](auto it, [[maybe_unused]] const auto end) { // Don't instantiate this for this for DictionarySegments and ReferenceSegments to save compile time. // DictionarySegments are handled in _scan_dictionary_segment() // ReferenceSegments are handled via position_filter if constexpr (!is_dictionary_segment_iterable_v<typename decltype(it)::IterableType> && !is_reference_segment_iterable_v<typename decltype(it)::IterableType>) { using ColumnDataType = typename decltype(it)::ValueType; if constexpr (std::is_same_v<ColumnDataType, pmr_string>) { _matcher.resolve(_invert_results, [&](const auto& resolved_matcher) { const auto functor = [&](const auto& position) { return resolved_matcher(position.value()); }; _scan_with_iterators<true>(functor, it, end, chunk_id, matches); }); } else { Fail("Can only handle strings"); } } else { Fail("Dictionary and ReferenceSegments have their own code paths and should be handled there"); } }); } void ColumnLikeTableScanImpl::_scan_dictionary_segment(const BaseDictionarySegment& segment, const ChunkID chunk_id, PosList& matches, const std::shared_ptr<const PosList>& position_filter) const { std::pair<size_t, std::vector<bool>> result; if (segment.encoding_type() == EncodingType::Dictionary) { const auto& typed_segment = static_cast<const DictionarySegment<pmr_string>&>(segment); result = _find_matches_in_dictionary(*typed_segment.dictionary()); } else { const auto& typed_segment = static_cast<const FixedStringDictionarySegment<pmr_string>&>(segment); result = _find_matches_in_dictionary(*typed_segment.dictionary()); } const auto& match_count = result.first; const auto& dictionary_matches = result.second; auto attribute_vector_iterable = create_iterable_from_attribute_vector(segment); // LIKE matches all rows, but we still need to check for NULL if (match_count == dictionary_matches.size()) { attribute_vector_iterable.with_iterators(position_filter, [&](auto it, auto end) { static const auto always_true = [](const auto&) { return true; }; _scan_with_iterators<true>(always_true, it, end, chunk_id, matches); }); return; } // LIKE matches no rows if (match_count == 0u) { return; } const auto dictionary_lookup = [&dictionary_matches](const auto& position) { return dictionary_matches[position.value()]; }; attribute_vector_iterable.with_iterators(position_filter, [&](auto it, auto end) { _scan_with_iterators<true>(dictionary_lookup, it, end, chunk_id, matches); }); } std::pair<size_t, std::vector<bool>> ColumnLikeTableScanImpl::_find_matches_in_dictionary( const pmr_vector<pmr_string>& dictionary) const { auto result = std::pair<size_t, std::vector<bool>>{}; auto& count = result.first; auto& dictionary_matches = result.second; count = 0u; dictionary_matches.reserve(dictionary.size()); _matcher.resolve(_invert_results, [&](const auto& matcher) { for (const auto& value : dictionary) { const auto matches = matcher(value); count += static_cast<size_t>(matches); dictionary_matches.push_back(matches); } }); return result; } } // namespace opossum <commit_msg>Fix performance regression in JOB (#1848)<commit_after>#include "column_like_table_scan_impl.hpp" #include <algorithm> #include <array> #include <map> #include <memory> #include <regex> #include <sstream> #include <string> #include <utility> #include <vector> #include "storage/create_iterable_from_segment.hpp" #include "storage/resolve_encoded_segment_type.hpp" #include "storage/segment_iterables/create_iterable_from_attribute_vector.hpp" #include "storage/segment_iterate.hpp" #include "storage/value_segment.hpp" #include "storage/value_segment/value_segment_iterable.hpp" #include "utils/ignore_unused_variable.hpp" namespace opossum { ColumnLikeTableScanImpl::ColumnLikeTableScanImpl(const std::shared_ptr<const Table>& in_table, const ColumnID column_id, const PredicateCondition predicate_condition, const pmr_string& pattern) : AbstractDereferencedColumnTableScanImpl{in_table, column_id, predicate_condition}, _matcher{pattern}, _invert_results(predicate_condition == PredicateCondition::NotLike) {} std::string ColumnLikeTableScanImpl::description() const { return "ColumnLike"; } void ColumnLikeTableScanImpl::_scan_non_reference_segment(const BaseSegment& segment, const ChunkID chunk_id, PosList& matches, const std::shared_ptr<const PosList>& position_filter) const { // For dictionary segments where the number of unique values is not higher than the number of (potentially filtered) // input rows, use an optimized implementation. if (const auto* dictionary_segment = dynamic_cast<const BaseDictionarySegment*>(&segment); dictionary_segment && (!position_filter || dictionary_segment->unique_values_count() <= position_filter->size())) { _scan_dictionary_segment(*dictionary_segment, chunk_id, matches, position_filter); } else { _scan_generic_segment(segment, chunk_id, matches, position_filter); } } void ColumnLikeTableScanImpl::_scan_generic_segment(const BaseSegment& segment, const ChunkID chunk_id, PosList& matches, const std::shared_ptr<const PosList>& position_filter) const { segment_with_iterators_filtered(segment, position_filter, [&](auto it, [[maybe_unused]] const auto end) { // Don't instantiate this for ReferenceSegments to save compile time as ReferenceSegments are handled // via position_filter if constexpr (!is_reference_segment_iterable_v<typename decltype(it)::IterableType>) { using ColumnDataType = typename decltype(it)::ValueType; if constexpr (std::is_same_v<ColumnDataType, pmr_string>) { _matcher.resolve(_invert_results, [&](const auto& resolved_matcher) { const auto functor = [&](const auto& position) { return resolved_matcher(position.value()); }; _scan_with_iterators<true>(functor, it, end, chunk_id, matches); }); } else { Fail("Can only handle strings"); } } else { Fail("ReferenceSegments have their own code paths and should be handled there"); } }); } void ColumnLikeTableScanImpl::_scan_dictionary_segment(const BaseDictionarySegment& segment, const ChunkID chunk_id, PosList& matches, const std::shared_ptr<const PosList>& position_filter) const { // First, build a bitmap containing 1s/0s for matching/non-matching dictionary values. Second, iterate over the // attribute vector and check against the bitmap. If too many input rows have already been removed (are not part of // position_filter), this optimization is detrimental. See caller for that case. std::pair<size_t, std::vector<bool>> result; if (segment.encoding_type() == EncodingType::Dictionary) { const auto& typed_segment = static_cast<const DictionarySegment<pmr_string>&>(segment); result = _find_matches_in_dictionary(*typed_segment.dictionary()); } else { const auto& typed_segment = static_cast<const FixedStringDictionarySegment<pmr_string>&>(segment); result = _find_matches_in_dictionary(*typed_segment.dictionary()); } const auto& match_count = result.first; const auto& dictionary_matches = result.second; auto attribute_vector_iterable = create_iterable_from_attribute_vector(segment); // LIKE matches all rows, but we still need to check for NULL if (match_count == dictionary_matches.size()) { attribute_vector_iterable.with_iterators(position_filter, [&](auto it, auto end) { static const auto always_true = [](const auto&) { return true; }; _scan_with_iterators<true>(always_true, it, end, chunk_id, matches); }); return; } // LIKE matches no rows if (match_count == 0u) { return; } const auto dictionary_lookup = [&dictionary_matches](const auto& position) { return dictionary_matches[position.value()]; }; attribute_vector_iterable.with_iterators(position_filter, [&](auto it, auto end) { _scan_with_iterators<true>(dictionary_lookup, it, end, chunk_id, matches); }); } std::pair<size_t, std::vector<bool>> ColumnLikeTableScanImpl::_find_matches_in_dictionary( const pmr_vector<pmr_string>& dictionary) const { auto result = std::pair<size_t, std::vector<bool>>{}; auto& count = result.first; auto& dictionary_matches = result.second; count = 0u; dictionary_matches.reserve(dictionary.size()); _matcher.resolve(_invert_results, [&](const auto& matcher) { for (const auto& value : dictionary) { const auto matches = matcher(value); count += static_cast<size_t>(matches); dictionary_matches.push_back(matches); } }); return result; } } // namespace opossum <|endoftext|>
<commit_before>/* Copyright 2021 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. ==============================================================================*/ #include <algorithm> #include "llvm/ADT/DenseMapInfo.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Casting.h" #include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.h" #include "mlir-hlo/Dialect/mhlo/transforms/PassDetail.h" #include "mlir-hlo/Dialect/mhlo/transforms/passes.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/Location.h" #include "mlir/IR/MLIRContext.h" #include "mlir/IR/Operation.h" #include "mlir/IR/Value.h" #include "mlir/Pass/Pass.h" namespace mlir { namespace mhlo { namespace { // To avoid duplicate broadcasts, we collect all the intended broadcasts ahead // of realizing any broadcasts in the IR. These are broadcasted versions of // values that we are interested in, and they are uniquely characterized by a // `BroadcastIntent` value. struct BroadcastIntent { RankedTensorType result_type; Value target_value; Value output_dimensions; Attribute broadcast_dimensions; bool operator==(BroadcastIntent rhs) const { return result_type == rhs.result_type && target_value == rhs.target_value && output_dimensions == rhs.output_dimensions && broadcast_dimensions == rhs.broadcast_dimensions; } bool operator!=(BroadcastIntent rhs) const { return !(*this == rhs); } }; } // namespace } // namespace mhlo } // namespace mlir namespace llvm { template <> struct DenseMapInfo<mlir::mhlo::BroadcastIntent> { static mlir::mhlo::BroadcastIntent getEmptyKey() { return {DenseMapInfo<mlir::RankedTensorType>::getEmptyKey(), DenseMapInfo<mlir::Value>::getEmptyKey(), DenseMapInfo<mlir::Value>::getEmptyKey(), DenseMapInfo<mlir::Attribute>::getEmptyKey()}; } static mlir::mhlo::BroadcastIntent getTombstoneKey() { return {DenseMapInfo<mlir::RankedTensorType>::getTombstoneKey(), DenseMapInfo<mlir::Value>::getTombstoneKey(), DenseMapInfo<mlir::Value>::getTombstoneKey(), DenseMapInfo<mlir::Attribute>::getTombstoneKey()}; } static unsigned getHashValue(const mlir::mhlo::BroadcastIntent &intent) { return hash_combine( DenseMapInfo<mlir::RankedTensorType>::getHashValue(intent.result_type), DenseMapInfo<mlir::Value>::getHashValue(intent.target_value), DenseMapInfo<mlir::Value>::getHashValue(intent.output_dimensions), DenseMapInfo<mlir::Attribute>::getHashValue( intent.broadcast_dimensions)); } static bool isEqual(const mlir::mhlo::BroadcastIntent &lhs, const mlir::mhlo::BroadcastIntent &rhs) { return lhs == rhs; } }; } // namespace llvm namespace mlir { namespace mhlo { namespace { bool AllowsForBroadcastPropagation(Operation *op) { if (op->hasTrait<mlir::OpTrait::SameOperandsAndResultShape>() && op->hasTrait<mlir::OpTrait::Elementwise>() && op->getNumResults() == 1) { return true; } if (op->hasTrait<mlir::mhlo::OpTrait::BroadcastingElementwise>() && op->getNumResults() == 1) { return true; } return false; } void TransitivelyEraseUnusedSideEffectFreeOps(Operation *root) { SmallPtrSet<Operation *, 16> ops_to_erase; SmallVector<Operation *, 16> ops_to_erase_ordered; // Find all the ops to erase. SmallVector<Operation *> worklist = {root}; while (!worklist.empty()) { Operation *op = worklist.back(); worklist.pop_back(); // Erase ops only once. if (ops_to_erase.count(op)) continue; // Erase only operations that are unused and free of side effects. if (!MemoryEffectOpInterface::hasNoEffect(op) || !llvm::all_of(op->getUsers(), [&](Operation *user) { return ops_to_erase.count(user); })) { continue; } // Erase and "recur". ops_to_erase.insert(op); ops_to_erase_ordered.push_back(op); for (Value operand : op->getOperands()) { if (Operation *def = operand.getDefiningOp()) worklist.push_back(def); } } // Finally, erase the ops. for (Operation *op : ops_to_erase_ordered) op->erase(); } bool IsAvailableAt(Value value, Operation *op) { if (Operation *def = value.getDefiningOp()) return def->getBlock() == op->getBlock() && def->isBeforeInBlock(op); return value.cast<BlockArgument>().getParentBlock() == op->getBlock(); } // Assumes that all values are defined within the block or dominate the block. void SetInsertionPointToEarliestPointWithAllValuesAvailable(OpBuilder &b, Block *block, ValueRange values) { Operation *last_def = nullptr; for (Value v : values) { Operation *def = v.getDefiningOp(); if (def && def->getBlock() == block) { if (!last_def || last_def->isBeforeInBlock(def)) last_def = def; } } if (last_def) { b.setInsertionPointAfter(last_def); } else { b.setInsertionPointToStart(block); } } void PropagateBroadcast(DynamicBroadcastInDimOp root) { OpBuilder builder(root.getContext()); BroadcastIntent root_bcast_intent = { root.getResult().getType().cast<RankedTensorType>(), root.operand(), root.output_dimensions(), root.broadcast_dimensions()}; // We can move broadcasts up over (broadcasting) element-wise operations and // propagate them through the IR to perform them early. Instead of // broadcasting the result of such an op, we can broadcast the operands and // apply the element-wise operation to them. // // To avoid exponential growth of the IR, we will do this in two phases: // 1) First, we collect all the unique broadcast intents. These are // broadcasted versions of values that we are interested in. They may // later be materialized as an explicit broadcast or they can be the // direct result of an operation over which a broadcast was propagated. // 2) Then, we fulfill every broadcast intent in reverse topological order // to ensure that their dependencies (the broadcasted operands) are // available. // Collect all the broadcast intents, starting with the root. Record // dependencies for later lookups. DenseSet<BroadcastIntent> bcast_intents = {root_bcast_intent}; SmallVector<BroadcastIntent> bcast_intents_ordered = {root_bcast_intent}; DenseMap<BroadcastIntent, SmallVector<BroadcastIntent>> bcast_propagation_dependencies; Block *the_block = root->getBlock(); // We use the ordered broadcast intents as a worklist, the first `i` intents // of which have been processed. auto empty_broadcast_dimensions = builder.getI64TensorAttr({}); for (int i = 0; i < bcast_intents_ordered.size(); ++i) { BroadcastIntent it = bcast_intents_ordered[i]; Operation *producer_op = it.target_value.getDefiningOp(); // We can propagate broadcasts over (broadcasting) element-wise operations // with the restriction that they must be in the same block as they may // depend on assumptions. if (producer_op && producer_op->getBlock() == the_block && AllowsForBroadcastPropagation(producer_op)) { // Collect this broadcast propagation's dependencies: the broadcasted // versions of the operands that we will need in the second phase. SmallVector<BroadcastIntent> dependencies; for (auto operand : producer_op->getOperands()) { auto operand_ty = operand.getType().cast<RankedTensorType>(); auto operand_broadcast_dimensions = operand_ty.getRank() == 0 ? empty_broadcast_dimensions : it.broadcast_dimensions; auto bcasted_operand_ty = RankedTensorType::get( it.result_type.getShape(), operand_ty.getElementType()); BroadcastIntent bcasted_operand_intent = {bcasted_operand_ty, operand, it.output_dimensions, operand_broadcast_dimensions}; dependencies.push_back(bcasted_operand_intent); // If this broadcast intent was not yet seen, add it to the worklist. // Otherwise, we know it will be fulfilled earlier. if (!bcast_intents.count(bcasted_operand_intent)) { bcast_intents_ordered.push_back(bcasted_operand_intent); bcast_intents.insert(bcasted_operand_intent); } } bcast_propagation_dependencies[it] = dependencies; } } // Realize all the broadcast intents in reverse topological order of the // producer ops. We can use the positions in the block for this. All broadcast // intents outside the block (e.g. arguments) will be sorted towards the // front. // This ordering is independent of the output dimensions as dependencies can // only occur between broadcast intents of the same output dimension. DenseMap<BroadcastIntent, Value> realizations; std::sort(bcast_intents_ordered.begin(), bcast_intents_ordered.end(), [&](const BroadcastIntent &a, const BroadcastIntent &b) { Operation *producer_op_a = a.target_value.getDefiningOp(); Operation *producer_op_b = b.target_value.getDefiningOp(); bool a_in_block = producer_op_a && producer_op_a->getBlock() == the_block; bool b_in_block = producer_op_b && producer_op_b->getBlock() == the_block; if (a_in_block && b_in_block) { return producer_op_a->isBeforeInBlock(producer_op_b); } return !a_in_block && b_in_block; }); for (auto it : bcast_intents_ordered) { Operation *producer_op = it.target_value.getDefiningOp(); // Realize broadcast intent for an element-wise operation based on the // broadcasted operands, if possible. if (bcast_propagation_dependencies.count(it)) { assert(producer_op && producer_op->getBlock() == the_block && AllowsForBroadcastPropagation(producer_op) && "expect (broadcasting) element-wise op in the same block"); auto bcasted_operands = llvm::to_vector(llvm::map_range(bcast_propagation_dependencies[it], [&](BroadcastIntent operand_intent) { return realizations[operand_intent]; })); SetInsertionPointToEarliestPointWithAllValuesAvailable(builder, the_block, bcasted_operands); OperationState new_producer_op_state( producer_op->getLoc(), producer_op->getName().getStringRef(), bcasted_operands, it.result_type, producer_op->getAttrs()); Operation *new_producer_op = builder.createOperation(new_producer_op_state); assert(new_producer_op->getNumResults() == 1 && "expect exactly one result"); realizations[it] = new_producer_op->getResults().front(); continue; } // Fall back to explicit broadcasts, otherwise. SetInsertionPointToEarliestPointWithAllValuesAvailable( builder, the_block, ValueRange{it.target_value, it.output_dimensions}); realizations[it] = builder.create<DynamicBroadcastInDimOp>( it.target_value.getLoc(), it.result_type, it.target_value, it.output_dimensions, it.broadcast_dimensions.cast<DenseIntElementsAttr>()); } // Lookup the replacement for the root operation. auto replacement = realizations[root_bcast_intent]; root->replaceAllUsesWith(ValueRange{replacement}); // Erase all the operations that have become redundant as a result of this // rewrite. TransitivelyEraseUnusedSideEffectFreeOps(root); } struct BroadcastPropagationPass : public BroadcastPropagationPassBase<BroadcastPropagationPass> { void getDependentDialects(DialectRegistry &registry) const override { registry.insert<mhlo::MhloDialect>(); } void runOnOperation() override { getOperation().walk( [&](DynamicBroadcastInDimOp bcast) { PropagateBroadcast(bcast); }); } }; } // namespace std::unique_ptr<OperationPass<FuncOp>> createBroadcastPropagationPass() { return std::make_unique<BroadcastPropagationPass>(); } } // namespace mhlo } // namespace mlir <commit_msg>[MHLO] Address clang tidy concerns<commit_after>/* Copyright 2021 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. ==============================================================================*/ #include <algorithm> #include "llvm/ADT/DenseMapInfo.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Casting.h" #include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.h" #include "mlir-hlo/Dialect/mhlo/transforms/PassDetail.h" #include "mlir-hlo/Dialect/mhlo/transforms/passes.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/Location.h" #include "mlir/IR/MLIRContext.h" #include "mlir/IR/Operation.h" #include "mlir/IR/Value.h" #include "mlir/Pass/Pass.h" namespace mlir { namespace mhlo { namespace { // To avoid duplicate broadcasts, we collect all the intended broadcasts ahead // of realizing any broadcasts in the IR. These are broadcasted versions of // values that we are interested in, and they are uniquely characterized by a // `BroadcastIntent` value. struct BroadcastIntent { RankedTensorType result_type; Value target_value; Value output_dimensions; Attribute broadcast_dimensions; bool operator==(BroadcastIntent rhs) const { return result_type == rhs.result_type && target_value == rhs.target_value && output_dimensions == rhs.output_dimensions && broadcast_dimensions == rhs.broadcast_dimensions; } bool operator!=(BroadcastIntent rhs) const { return !(*this == rhs); } }; } // namespace } // namespace mhlo } // namespace mlir namespace llvm { template <> struct DenseMapInfo<mlir::mhlo::BroadcastIntent> { static mlir::mhlo::BroadcastIntent getEmptyKey() { return {DenseMapInfo<mlir::RankedTensorType>::getEmptyKey(), DenseMapInfo<mlir::Value>::getEmptyKey(), DenseMapInfo<mlir::Value>::getEmptyKey(), DenseMapInfo<mlir::Attribute>::getEmptyKey()}; } static mlir::mhlo::BroadcastIntent getTombstoneKey() { return {DenseMapInfo<mlir::RankedTensorType>::getTombstoneKey(), DenseMapInfo<mlir::Value>::getTombstoneKey(), DenseMapInfo<mlir::Value>::getTombstoneKey(), DenseMapInfo<mlir::Attribute>::getTombstoneKey()}; } static unsigned getHashValue(const mlir::mhlo::BroadcastIntent &intent) { return hash_combine( DenseMapInfo<mlir::RankedTensorType>::getHashValue(intent.result_type), DenseMapInfo<mlir::Value>::getHashValue(intent.target_value), DenseMapInfo<mlir::Value>::getHashValue(intent.output_dimensions), DenseMapInfo<mlir::Attribute>::getHashValue( intent.broadcast_dimensions)); } static bool isEqual(const mlir::mhlo::BroadcastIntent &lhs, const mlir::mhlo::BroadcastIntent &rhs) { return lhs == rhs; } }; } // namespace llvm namespace mlir { namespace mhlo { namespace { bool AllowsForBroadcastPropagation(Operation *op) { if (op->hasTrait<mlir::OpTrait::SameOperandsAndResultShape>() && op->hasTrait<mlir::OpTrait::Elementwise>() && op->getNumResults() == 1) { return true; } if (op->hasTrait<mlir::mhlo::OpTrait::BroadcastingElementwise>() && op->getNumResults() == 1) { return true; } return false; } void TransitivelyEraseUnusedSideEffectFreeOps(Operation *root) { SmallPtrSet<Operation *, 16> ops_to_erase; SmallVector<Operation *, 16> ops_to_erase_ordered; // Find all the ops to erase. SmallVector<Operation *> worklist = {root}; while (!worklist.empty()) { Operation *op = worklist.back(); worklist.pop_back(); // Erase ops only once. if (ops_to_erase.count(op)) continue; // Erase only operations that are unused and free of side effects. if (!MemoryEffectOpInterface::hasNoEffect(op) || !llvm::all_of(op->getUsers(), [&](Operation *user) { return ops_to_erase.count(user); })) { continue; } // Erase and "recur". ops_to_erase.insert(op); ops_to_erase_ordered.push_back(op); for (Value operand : op->getOperands()) { if (Operation *def = operand.getDefiningOp()) worklist.push_back(def); } } // Finally, erase the ops. for (Operation *op : ops_to_erase_ordered) op->erase(); } bool IsAvailableAt(Value value, Operation *op) { if (Operation *def = value.getDefiningOp()) return def->getBlock() == op->getBlock() && def->isBeforeInBlock(op); return value.cast<BlockArgument>().getParentBlock() == op->getBlock(); } // Assumes that all values are defined within the block or dominate the block. void SetInsertionPointToEarliestPointWithAllValuesAvailable(OpBuilder &b, Block *block, ValueRange values) { Operation *last_def = nullptr; for (Value v : values) { Operation *def = v.getDefiningOp(); if (def && def->getBlock() == block) { if (!last_def || last_def->isBeforeInBlock(def)) last_def = def; } } if (last_def) { b.setInsertionPointAfter(last_def); } else { b.setInsertionPointToStart(block); } } void PropagateBroadcast(DynamicBroadcastInDimOp root) { OpBuilder builder(root.getContext()); BroadcastIntent root_bcast_intent = { root.getResult().getType().cast<RankedTensorType>(), root.operand(), root.output_dimensions(), root.broadcast_dimensions()}; // We can move broadcasts up over (broadcasting) element-wise operations and // propagate them through the IR to perform them early. Instead of // broadcasting the result of such an op, we can broadcast the operands and // apply the element-wise operation to them. // // To avoid exponential growth of the IR, we will do this in two phases: // 1) First, we collect all the unique broadcast intents. These are // broadcasted versions of values that we are interested in. They may // later be materialized as an explicit broadcast or they can be the // direct result of an operation over which a broadcast was propagated. // 2) Then, we fulfill every broadcast intent in reverse topological order // to ensure that their dependencies (the broadcasted operands) are // available. // Collect all the broadcast intents, starting with the root. Record // dependencies for later lookups. DenseSet<BroadcastIntent> bcast_intents = {root_bcast_intent}; SmallVector<BroadcastIntent> bcast_intents_ordered = {root_bcast_intent}; DenseMap<BroadcastIntent, SmallVector<BroadcastIntent>> bcast_propagation_dependencies; Block *the_block = root->getBlock(); // We use the ordered broadcast intents as a worklist, the first `i` intents // of which have been processed. auto empty_broadcast_dimensions = builder.getI64TensorAttr({}); for (int i = 0; i < bcast_intents_ordered.size(); ++i) { BroadcastIntent it = bcast_intents_ordered[i]; Operation *producer_op = it.target_value.getDefiningOp(); // We can propagate broadcasts over (broadcasting) element-wise operations // with the restriction that they must be in the same block as they may // depend on assumptions. if (producer_op && producer_op->getBlock() == the_block && AllowsForBroadcastPropagation(producer_op)) { // Collect this broadcast propagation's dependencies: the broadcasted // versions of the operands that we will need in the second phase. SmallVector<BroadcastIntent> dependencies; for (auto operand : producer_op->getOperands()) { auto operand_ty = operand.getType().cast<RankedTensorType>(); auto operand_broadcast_dimensions = operand_ty.getRank() == 0 ? empty_broadcast_dimensions : it.broadcast_dimensions; auto bcasted_operand_ty = RankedTensorType::get( it.result_type.getShape(), operand_ty.getElementType()); BroadcastIntent bcasted_operand_intent = {bcasted_operand_ty, operand, it.output_dimensions, operand_broadcast_dimensions}; dependencies.push_back(bcasted_operand_intent); // If this broadcast intent was not yet seen, add it to the worklist. // Otherwise, we know it will be fulfilled earlier. if (!bcast_intents.count(bcasted_operand_intent)) { bcast_intents_ordered.push_back(bcasted_operand_intent); bcast_intents.insert(bcasted_operand_intent); } } bcast_propagation_dependencies[it] = dependencies; } } // Realize all the broadcast intents in reverse topological order of the // producer ops. We can use the positions in the block for this. All broadcast // intents outside the block (e.g. arguments) will be sorted towards the // front. // This ordering is independent of the output dimensions as dependencies can // only occur between broadcast intents of the same output dimension. DenseMap<BroadcastIntent, Value> realizations; std::sort(bcast_intents_ordered.begin(), bcast_intents_ordered.end(), [&](const BroadcastIntent &a, const BroadcastIntent &b) { Operation *producer_op_a = a.target_value.getDefiningOp(); Operation *producer_op_b = b.target_value.getDefiningOp(); bool a_in_block = producer_op_a != nullptr && producer_op_a->getBlock() == the_block; bool b_in_block = producer_op_b != nullptr && producer_op_b->getBlock() == the_block; if (a_in_block && b_in_block) { return producer_op_a->isBeforeInBlock(producer_op_b); } return !a_in_block && b_in_block; }); for (auto it : bcast_intents_ordered) { Operation *producer_op = it.target_value.getDefiningOp(); // Realize broadcast intent for an element-wise operation based on the // broadcasted operands, if possible. if (bcast_propagation_dependencies.count(it)) { assert(producer_op && producer_op->getBlock() == the_block && AllowsForBroadcastPropagation(producer_op) && "expect (broadcasting) element-wise op in the same block"); auto bcasted_operands = llvm::to_vector(llvm::map_range(bcast_propagation_dependencies[it], [&](BroadcastIntent operand_intent) { return realizations[operand_intent]; })); SetInsertionPointToEarliestPointWithAllValuesAvailable(builder, the_block, bcasted_operands); OperationState new_producer_op_state( producer_op->getLoc(), producer_op->getName().getStringRef(), bcasted_operands, it.result_type, producer_op->getAttrs()); Operation *new_producer_op = builder.createOperation(new_producer_op_state); assert(new_producer_op->getNumResults() == 1 && "expect exactly one result"); realizations[it] = new_producer_op->getResults().front(); continue; } // Fall back to explicit broadcasts, otherwise. SetInsertionPointToEarliestPointWithAllValuesAvailable( builder, the_block, ValueRange{it.target_value, it.output_dimensions}); realizations[it] = builder.create<DynamicBroadcastInDimOp>( it.target_value.getLoc(), it.result_type, it.target_value, it.output_dimensions, it.broadcast_dimensions.cast<DenseIntElementsAttr>()); } // Lookup the replacement for the root operation. auto replacement = realizations[root_bcast_intent]; root->replaceAllUsesWith(ValueRange{replacement}); // Erase all the operations that have become redundant as a result of this // rewrite. TransitivelyEraseUnusedSideEffectFreeOps(root); } struct BroadcastPropagationPass : public BroadcastPropagationPassBase<BroadcastPropagationPass> { void getDependentDialects(DialectRegistry &registry) const override { registry.insert<mhlo::MhloDialect>(); } void runOnOperation() override { getOperation().walk( [&](DynamicBroadcastInDimOp bcast) { PropagateBroadcast(bcast); }); } }; } // namespace std::unique_ptr<OperationPass<FuncOp>> createBroadcastPropagationPass() { return std::make_unique<BroadcastPropagationPass>(); } } // namespace mhlo } // namespace mlir <|endoftext|>
<commit_before>// ------------------------------------------------------------------------- // @FileName : NFCProxyServerNet_ClientModule.cpp // @Author : LvSheng.Huang // @Date : 2013-05-06 // @Module : NFCProxyServerNet_ClientModule // // ------------------------------------------------------------------------- //#include "stdafx.h" #include "NFCProxyServerToGameModule.h" #include "NFProxyServerNet_ClientPlugin.h" #include "NFComm/NFCore/NFIHeartBeatManager.h" #include "NFComm/NFCore/NFCHeartBeatManager.h" #include "NFComm/NFPluginModule/NFILogicClassModule.h" bool NFCProxyServerToGameModule::Init() { return true; } bool NFCProxyServerToGameModule::Shut() { //Final(); //Clear(); return true; } bool NFCProxyServerToGameModule::Execute(const float fLasFrametime, const float fStartedTime) { return NFIClusterClientModule::Execute(fLasFrametime, fStartedTime); } bool NFCProxyServerToGameModule::AfterInit() { m_pEventProcessModule = dynamic_cast<NFIEventProcessModule*>(pPluginManager->FindModule("NFCEventProcessModule")); m_pProxyLogicModule = dynamic_cast<NFIProxyLogicModule*>(pPluginManager->FindModule("NFCProxyLogicModule")); m_pKernelModule = dynamic_cast<NFIKernelModule*>(pPluginManager->FindModule("NFCKernelModule")); m_pProxyServerNet_ServerModule = dynamic_cast<NFIProxyServerNet_ServerModule*>(pPluginManager->FindModule("NFCProxyServerNet_ServerModule")); m_pElementInfoModule = dynamic_cast<NFIElementInfoModule*>(pPluginManager->FindModule("NFCElementInfoModule")); m_pLogModule = dynamic_cast<NFILogModule*>(pPluginManager->FindModule("NFCLogModule")); m_pLogicClassModule = dynamic_cast<NFILogicClassModule*>(pPluginManager->FindModule("NFCLogicClassModule")); assert(NULL != m_pEventProcessModule); assert(NULL != m_pProxyLogicModule); assert(NULL != m_pKernelModule); assert(NULL != m_pProxyServerNet_ServerModule); assert(NULL != m_pElementInfoModule); assert(NULL != m_pLogModule); assert(NULL != m_pLogicClassModule); NFIClusterClientModule::Bind(this, &NFCProxyServerToGameModule::OnReciveGSPack, &NFCProxyServerToGameModule::OnSocketGSEvent); NF_SHARE_PTR<NFILogicClass> xLogicClass = m_pLogicClassModule->GetElement("Server"); if (xLogicClass.get()) { NFList<std::string>& xNameList = xLogicClass->GetConfigNameList(); std::string strConfigName; for (bool bRet = xNameList.First(strConfigName); bRet; bRet = xNameList.Next(strConfigName)) { const int nServerType = m_pElementInfoModule->GetPropertyInt(strConfigName, "Type"); const int nServerID = m_pElementInfoModule->GetPropertyInt(strConfigName, "ServerID"); if (nServerType == NF_SERVER_TYPES::NF_ST_GAME) { const int nPort = m_pElementInfoModule->GetPropertyInt(strConfigName, "Port"); const int nMaxConnect = m_pElementInfoModule->GetPropertyInt(strConfigName, "MaxOnline"); const int nCpus = m_pElementInfoModule->GetPropertyInt(strConfigName, "CpuCount"); const std::string& strName = m_pElementInfoModule->GetPropertyString(strConfigName, "Name"); const std::string& strIP = m_pElementInfoModule->GetPropertyString(strConfigName, "IP"); ServerData xServerData; xServerData.nGameID = nServerID; xServerData.eServerType = (NF_SERVER_TYPE)nServerType; xServerData.strIP = strIP; xServerData.nPort = nPort; xServerData.strName = strName; xServerData.eState = NFMsg::EServerState::EST_MAINTEN; NFIClusterClientModule::AddServer(xServerData); } } } return true; } int NFCProxyServerToGameModule::OnReciveGSPack( const NFIPacket& msg ) { switch (msg.GetMsgHead()->GetMsgID()) { case NFMsg::EGMI_ACK_ENTER_GAME: OnAckEnterGame(msg); break; default: m_pProxyServerNet_ServerModule->Transpond(msg); break; } return 0; } int NFCProxyServerToGameModule::OnSocketGSEvent( const int nSockIndex, const NF_NET_EVENT eEvent, NFINet* pNet ) { if (eEvent & NF_NET_EVENT_EOF) { } else if (eEvent & NF_NET_EVENT_ERROR) { } else if (eEvent & NF_NET_EVENT_TIMEOUT) { } else if (eEvent == NF_NET_EVENT_CONNECTED) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFIDENTID(0, nSockIndex), "NF_NET_EVENT_CONNECTED", "connectioned success", __FUNCTION__, __LINE__); Register(pNet); } return 0; } void NFCProxyServerToGameModule::Register(NFINet* pNet) { NF_SHARE_PTR<NFILogicClass> xLogicClass = m_pLogicClassModule->GetElement("Server"); if (xLogicClass.get()) { NFList<std::string>& xNameList = xLogicClass->GetConfigNameList(); std::string strConfigName; for (bool bRet = xNameList.First(strConfigName); bRet; bRet = xNameList.Next(strConfigName)) { const int nServerType = m_pElementInfoModule->GetPropertyInt(strConfigName, "Type"); const int nServerID = m_pElementInfoModule->GetPropertyInt(strConfigName, "ServerID"); if (nServerType == NF_SERVER_TYPES::NF_ST_PROXY && pPluginManager->AppID() == nServerID) { const int nPort = m_pElementInfoModule->GetPropertyInt(strConfigName, "Port"); const int nMaxConnect = m_pElementInfoModule->GetPropertyInt(strConfigName, "MaxOnline"); const int nCpus = m_pElementInfoModule->GetPropertyInt(strConfigName, "CpuCount"); const std::string& strName = m_pElementInfoModule->GetPropertyString(strConfigName, "Name"); const std::string& strIP = m_pElementInfoModule->GetPropertyString(strConfigName, "IP"); NFMsg::ServerInfoReportList xMsg; NFMsg::ServerInfoReport* pData = xMsg.add_server_list(); pData->set_server_id(nServerID); pData->set_server_name(strName); pData->set_server_cur_count(0); pData->set_server_ip(strIP); pData->set_server_port(nPort); pData->set_server_max_online(nMaxConnect); pData->set_server_state(NFMsg::EST_NARMAL); pData->set_server_type(nServerType); NF_SHARE_PTR<ServerData> pServerData = GetServerNetInfo(pNet); if (pServerData) { int nTargetID = pServerData->nGameID; SendToServerByPB(nTargetID, NFMsg::EGameMsgID::EGMI_PTWG_PROXY_REGISTERED, xMsg); m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFIDENTID(0, pData->server_id()), pData->server_name(), "Register"); } } } } } void NFCProxyServerToGameModule::OnAckEnterGame(const NFIPacket& msg) { NFIDENTID nPlayerID; NFMsg::AckEventResult xData; if (!NFINetModule::RecivePB(msg, xData, nPlayerID)) { return; } if (xData.event_code() == NFMsg::EGEC_ENTER_GAME_SUCCESS) { const NFIDENTID& xClient = NFINetModule::PBToNF(xData.event_client()); const NFIDENTID& xPlayer = NFINetModule::PBToNF(xData.event_object()); m_pProxyServerNet_ServerModule->EnterGameSuccessEvent(xClient, nPlayerID); } } void NFCProxyServerToGameModule::LogServerInfo( const std::string& strServerInfo ) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFIDENTID(), strServerInfo, ""); } <commit_msg>fix offline bug<commit_after>// ------------------------------------------------------------------------- // @FileName : NFCProxyServerNet_ClientModule.cpp // @Author : LvSheng.Huang // @Date : 2013-05-06 // @Module : NFCProxyServerNet_ClientModule // // ------------------------------------------------------------------------- //#include "stdafx.h" #include "NFCProxyServerToGameModule.h" #include "NFProxyServerNet_ClientPlugin.h" #include "NFComm/NFCore/NFIHeartBeatManager.h" #include "NFComm/NFCore/NFCHeartBeatManager.h" #include "NFComm/NFPluginModule/NFILogicClassModule.h" bool NFCProxyServerToGameModule::Init() { return true; } bool NFCProxyServerToGameModule::Shut() { //Final(); //Clear(); return true; } bool NFCProxyServerToGameModule::Execute(const float fLasFrametime, const float fStartedTime) { return NFIClusterClientModule::Execute(fLasFrametime, fStartedTime); } bool NFCProxyServerToGameModule::AfterInit() { m_pEventProcessModule = dynamic_cast<NFIEventProcessModule*>(pPluginManager->FindModule("NFCEventProcessModule")); m_pProxyLogicModule = dynamic_cast<NFIProxyLogicModule*>(pPluginManager->FindModule("NFCProxyLogicModule")); m_pKernelModule = dynamic_cast<NFIKernelModule*>(pPluginManager->FindModule("NFCKernelModule")); m_pProxyServerNet_ServerModule = dynamic_cast<NFIProxyServerNet_ServerModule*>(pPluginManager->FindModule("NFCProxyServerNet_ServerModule")); m_pElementInfoModule = dynamic_cast<NFIElementInfoModule*>(pPluginManager->FindModule("NFCElementInfoModule")); m_pLogModule = dynamic_cast<NFILogModule*>(pPluginManager->FindModule("NFCLogModule")); m_pLogicClassModule = dynamic_cast<NFILogicClassModule*>(pPluginManager->FindModule("NFCLogicClassModule")); assert(NULL != m_pEventProcessModule); assert(NULL != m_pProxyLogicModule); assert(NULL != m_pKernelModule); assert(NULL != m_pProxyServerNet_ServerModule); assert(NULL != m_pElementInfoModule); assert(NULL != m_pLogModule); assert(NULL != m_pLogicClassModule); NFIClusterClientModule::Bind(this, &NFCProxyServerToGameModule::OnReciveGSPack, &NFCProxyServerToGameModule::OnSocketGSEvent); NF_SHARE_PTR<NFILogicClass> xLogicClass = m_pLogicClassModule->GetElement("Server"); if (xLogicClass.get()) { NFList<std::string>& xNameList = xLogicClass->GetConfigNameList(); std::string strConfigName; for (bool bRet = xNameList.First(strConfigName); bRet; bRet = xNameList.Next(strConfigName)) { const int nServerType = m_pElementInfoModule->GetPropertyInt(strConfigName, "Type"); const int nServerID = m_pElementInfoModule->GetPropertyInt(strConfigName, "ServerID"); if (nServerType == NF_SERVER_TYPES::NF_ST_GAME) { const int nPort = m_pElementInfoModule->GetPropertyInt(strConfigName, "Port"); const int nMaxConnect = m_pElementInfoModule->GetPropertyInt(strConfigName, "MaxOnline"); const int nCpus = m_pElementInfoModule->GetPropertyInt(strConfigName, "CpuCount"); const std::string& strName = m_pElementInfoModule->GetPropertyString(strConfigName, "Name"); const std::string& strIP = m_pElementInfoModule->GetPropertyString(strConfigName, "IP"); ServerData xServerData; xServerData.nGameID = nServerID; xServerData.eServerType = (NF_SERVER_TYPE)nServerType; xServerData.strIP = strIP; xServerData.nPort = nPort; xServerData.strName = strName; xServerData.eState = NFMsg::EServerState::EST_MAINTEN; NFIClusterClientModule::AddServer(xServerData); } } } return true; } int NFCProxyServerToGameModule::OnReciveGSPack( const NFIPacket& msg ) { switch (msg.GetMsgHead()->GetMsgID()) { case NFMsg::EGMI_ACK_ENTER_GAME: OnAckEnterGame(msg); break; default: m_pProxyServerNet_ServerModule->Transpond(msg); break; } return 0; } int NFCProxyServerToGameModule::OnSocketGSEvent( const int nSockIndex, const NF_NET_EVENT eEvent, NFINet* pNet ) { if (eEvent & NF_NET_EVENT_EOF) { } else if (eEvent & NF_NET_EVENT_ERROR) { } else if (eEvent & NF_NET_EVENT_TIMEOUT) { } else if (eEvent == NF_NET_EVENT_CONNECTED) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFIDENTID(0, nSockIndex), "NF_NET_EVENT_CONNECTED", "connectioned success", __FUNCTION__, __LINE__); Register(pNet); } return 0; } void NFCProxyServerToGameModule::Register(NFINet* pNet) { NF_SHARE_PTR<NFILogicClass> xLogicClass = m_pLogicClassModule->GetElement("Server"); if (xLogicClass.get()) { NFList<std::string>& xNameList = xLogicClass->GetConfigNameList(); std::string strConfigName; for (bool bRet = xNameList.First(strConfigName); bRet; bRet = xNameList.Next(strConfigName)) { const int nServerType = m_pElementInfoModule->GetPropertyInt(strConfigName, "Type"); const int nServerID = m_pElementInfoModule->GetPropertyInt(strConfigName, "ServerID"); if (nServerType == NF_SERVER_TYPES::NF_ST_PROXY && pPluginManager->AppID() == nServerID) { const int nPort = m_pElementInfoModule->GetPropertyInt(strConfigName, "Port"); const int nMaxConnect = m_pElementInfoModule->GetPropertyInt(strConfigName, "MaxOnline"); const int nCpus = m_pElementInfoModule->GetPropertyInt(strConfigName, "CpuCount"); const std::string& strName = m_pElementInfoModule->GetPropertyString(strConfigName, "Name"); const std::string& strIP = m_pElementInfoModule->GetPropertyString(strConfigName, "IP"); NFMsg::ServerInfoReportList xMsg; NFMsg::ServerInfoReport* pData = xMsg.add_server_list(); pData->set_server_id(nServerID); pData->set_server_name(strName); pData->set_server_cur_count(0); pData->set_server_ip(strIP); pData->set_server_port(nPort); pData->set_server_max_online(nMaxConnect); pData->set_server_state(NFMsg::EST_NARMAL); pData->set_server_type(nServerType); NF_SHARE_PTR<ServerData> pServerData = GetServerNetInfo(pNet); if (pServerData) { int nTargetID = pServerData->nGameID; SendToServerByPB(nTargetID, NFMsg::EGameMsgID::EGMI_PTWG_PROXY_REGISTERED, xMsg); m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFIDENTID(0, pData->server_id()), pData->server_name(), "Register"); } } } } } void NFCProxyServerToGameModule::OnAckEnterGame(const NFIPacket& msg) { NFIDENTID nPlayerID; NFMsg::AckEventResult xData; if (!NFINetModule::RecivePB(msg, xData, nPlayerID)) { return; } if (xData.event_code() == NFMsg::EGEC_ENTER_GAME_SUCCESS) { const NFIDENTID& xClient = NFINetModule::PBToNF(xData.event_client()); const NFIDENTID& xPlayer = NFINetModule::PBToNF(xData.event_object()); m_pProxyServerNet_ServerModule->EnterGameSuccessEvent(xClient, xPlayer); } } void NFCProxyServerToGameModule::LogServerInfo( const std::string& strServerInfo ) { m_pLogModule->LogNormal(NFILogModule::NLL_INFO_NORMAL, NFIDENTID(), strServerInfo, ""); } <|endoftext|>
<commit_before>//---------------------------- logtest.cc --------------------------- // $Id: logtest.cc 23710 2011-05-17 04:50:10Z bangerth $ // Version: $Name$ // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2007 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- logtest.cc --------------------------- // document crash in deallog related to missing newline #include "../tests.h" #include <deal.II/base/logstream.h> #include <fstream> #include <iomanip> #include <limits> int main() { std::ofstream logfile("log_crash_01/output"); deallog.attach(logfile); deallog.depth_console(0); deallog.push("1"); { deallog.threshold_double(1.e-10); deallog.push("2"); deallog << "no newline here!"; deallog.pop(); } } <commit_msg>simplify test<commit_after>//---------------------------- logtest.cc --------------------------- // $Id: logtest.cc 23710 2011-05-17 04:50:10Z bangerth $ // Version: $Name$ // // Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2007 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- logtest.cc --------------------------- // document crash in deallog related to missing newline #include "../tests.h" #include <deal.II/base/logstream.h> #include <fstream> #include <iomanip> #include <limits> int main() { std::ofstream logfile("log_crash_01/output"); deallog.attach(logfile); deallog << "no newline here!"; } <|endoftext|>
<commit_before>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE Main #include <boost/test/unit_test.hpp> #include <timedb.h> BOOST_AUTO_TEST_CASE(d_64) { // 10 0000 0000 BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_64(1), 257); BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_64(64), 320); BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_64(63), 319); } BOOST_AUTO_TEST_CASE(d_256) { // 1100 0000 0000 BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_256(256), 3328); BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_256(255), 3327); BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_256(65), 3137); } BOOST_AUTO_TEST_CASE(d_2048) { // 1110 0000 0000 0000 BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_2048(2048), 59392); BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_2048(257), 57601); BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_2048(4095), 61439); } BOOST_AUTO_TEST_CASE(d_big) { // 1111 0000 0000 0000 0000 // 0000 0000 0000 0000 BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_big(2049), 64424511489); BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_big(65535), 64424574975); BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_big(4095), 64424513535); BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_big(4294967295), 68719476735); }<commit_msg>pedanitc build options<commit_after>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE Main #include <boost/test/unit_test.hpp> #include <timedb.h> BOOST_AUTO_TEST_CASE(d_64) { // 10 0000 0000 BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_64(1), (uint16_t)257); BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_64(64), (uint16_t)320); BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_64(63), (uint16_t)319); } BOOST_AUTO_TEST_CASE(d_256) { // 1100 0000 0000 BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_256(256), (uint16_t)3328); BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_256(255), (uint16_t)3327); BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_256(65), (uint16_t)3137); } BOOST_AUTO_TEST_CASE(d_2048) { // 1110 0000 0000 0000 BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_2048(2048), (uint16_t)59392); BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_2048(257), (uint16_t)57601); BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_2048(4095), (uint16_t)61439); } BOOST_AUTO_TEST_CASE(d_big) { // 1111 0000 0000 0000 0000 // 0000 0000 0000 0000 BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_big(2049), (uint64_t)64424511489); BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_big(65535), (uint64_t)64424574975); BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_big(4095), (uint64_t)64424513535); BOOST_CHECK_EQUAL(timedb::Compression::compress_delta_big(4294967295), (uint64_t)68719476735); } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <seastar/core/distributed.hh> #include <seastar/core/app-template.hh> #include <seastar/core/sstring.hh> #include <random> // hack: perf_sstable falsely depends on Boost.Test, but we can't include it with // with statically linked boost #define BOOST_REQUIRE(x) (void)(x) #define BOOST_CHECK_NO_THROW(x) (void)(x) #include "perf_sstable.hh" using namespace sstables; static unsigned iterations = 30; static unsigned parallelism = 1; future<> test_write(distributed<test_env>& dt) { return seastar::async([&dt] { storage_service_for_tests ssft; dt.invoke_on_all([] (test_env &t) { return t.fill_memtable(); }).then([&dt] { return time_runs(iterations, parallelism, dt, &test_env::flush_memtable); }).get(); }); } future<> test_compaction(distributed<test_env>& dt) { return seastar::async([&dt] { storage_service_for_tests ssft; dt.invoke_on_all([] (test_env &t) { return t.fill_memtable(); }).then([&dt] { return time_runs(iterations, parallelism, dt, &test_env::compaction); }).get(); }); } future<> test_index_read(distributed<test_env>& dt) { return time_runs(iterations, parallelism, dt, &test_env::read_all_indexes); } future<> test_sequential_read(distributed<test_env>& dt) { return time_runs(iterations, parallelism, dt, &test_env::read_sequential_partitions); } enum class test_modes { sequential_read, index_read, write, index_write, compaction, }; static std::unordered_map<sstring, test_modes> test_mode = { {"sequential_read", test_modes::sequential_read }, {"index_read", test_modes::index_read }, {"write", test_modes::write }, {"index_write", test_modes::index_write }, {"compaction", test_modes::compaction }, }; int main(int argc, char** argv) { namespace bpo = boost::program_options; app_template app; app.add_options() ("parallelism", bpo::value<unsigned>()->default_value(1), "number parallel requests") ("iterations", bpo::value<unsigned>()->default_value(30), "number of iterations") ("partitions", bpo::value<unsigned>()->default_value(5000000), "number of partitions") ("buffer_size", bpo::value<unsigned>()->default_value(64), "sstable buffer size, in KB") ("key_size", bpo::value<unsigned>()->default_value(128), "size of partition key") ("num_columns", bpo::value<unsigned>()->default_value(5), "number of columns per row") ("column_size", bpo::value<unsigned>()->default_value(64), "size in bytes for each column") ("sstables", bpo::value<unsigned>()->default_value(1), "number of sstables (valid only for compaction mode)") ("mode", bpo::value<sstring>()->default_value("index_write"), "one of: random_read, sequential_read, index_read, write, compaction, index_write (default)") ("testdir", bpo::value<sstring>()->default_value("/var/lib/scylla/perf-tests"), "directory in which to store the sstables"); return app.run_deprecated(argc, argv, [&app] { auto test = make_lw_shared<distributed<test_env>>(); auto cfg = test_env::conf(); iterations = app.configuration()["iterations"].as<unsigned>(); parallelism = app.configuration()["parallelism"].as<unsigned>(); cfg.partitions = app.configuration()["partitions"].as<unsigned>(); cfg.key_size = app.configuration()["key_size"].as<unsigned>(); cfg.buffer_size = app.configuration()["buffer_size"].as<unsigned>() << 10; cfg.sstables = app.configuration()["sstables"].as<unsigned>(); sstring dir = app.configuration()["testdir"].as<sstring>(); cfg.dir = dir; auto mode = test_mode[app.configuration()["mode"].as<sstring>()]; if ((mode == test_modes::index_read) || (mode == test_modes::index_write)) { cfg.num_columns = 0; cfg.column_size = 0; } else { cfg.num_columns = app.configuration()["num_columns"].as<unsigned>(); cfg.column_size = app.configuration()["column_size"].as<unsigned>(); } return test->start(std::move(cfg)).then([mode, dir, test] { engine().at_exit([test] { return test->stop(); }); if ((mode == test_modes::index_read) || (mode == test_modes::sequential_read)) { return test->invoke_on_all([] (test_env &t) { return t.load_sstables(iterations); }).then_wrapped([] (future<> f) { try { f.get(); } catch (...) { std::cerr << "An error occurred when trying to load test sstables. Did you run write mode yet?" << std::endl; throw; } }); } else if ((mode == test_modes::index_write) || (mode == test_modes::write) || (mode == test_modes::compaction)) { return test_setup::create_empty_test_dir(dir); } else { throw std::invalid_argument("Invalid mode"); } }).then([test, mode] { if (mode == test_modes::index_read) { return test_index_read(*test).then([test] {}); } else if (mode == test_modes::sequential_read) { return test_sequential_read(*test).then([test] {}); } else if ((mode == test_modes::index_write) || (mode == test_modes::write)) { return test_write(*test).then([test] {}); } else if (mode == test_modes::compaction) { return test_compaction(*test).then([test] {}); } else { throw std::invalid_argument("Invalid mode"); } }).then([] { return engine().exit(0); }).or_terminate(); }); } <commit_msg>tests: Drop the unsupported random_read mode in perf_sstable<commit_after>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <seastar/core/distributed.hh> #include <seastar/core/app-template.hh> #include <seastar/core/sstring.hh> #include <random> // hack: perf_sstable falsely depends on Boost.Test, but we can't include it with // with statically linked boost #define BOOST_REQUIRE(x) (void)(x) #define BOOST_CHECK_NO_THROW(x) (void)(x) #include "perf_sstable.hh" using namespace sstables; static unsigned iterations = 30; static unsigned parallelism = 1; future<> test_write(distributed<test_env>& dt) { return seastar::async([&dt] { storage_service_for_tests ssft; dt.invoke_on_all([] (test_env &t) { return t.fill_memtable(); }).then([&dt] { return time_runs(iterations, parallelism, dt, &test_env::flush_memtable); }).get(); }); } future<> test_compaction(distributed<test_env>& dt) { return seastar::async([&dt] { storage_service_for_tests ssft; dt.invoke_on_all([] (test_env &t) { return t.fill_memtable(); }).then([&dt] { return time_runs(iterations, parallelism, dt, &test_env::compaction); }).get(); }); } future<> test_index_read(distributed<test_env>& dt) { return time_runs(iterations, parallelism, dt, &test_env::read_all_indexes); } future<> test_sequential_read(distributed<test_env>& dt) { return time_runs(iterations, parallelism, dt, &test_env::read_sequential_partitions); } enum class test_modes { sequential_read, index_read, write, index_write, compaction, }; static std::unordered_map<sstring, test_modes> test_mode = { {"sequential_read", test_modes::sequential_read }, {"index_read", test_modes::index_read }, {"write", test_modes::write }, {"index_write", test_modes::index_write }, {"compaction", test_modes::compaction }, }; int main(int argc, char** argv) { namespace bpo = boost::program_options; app_template app; app.add_options() ("parallelism", bpo::value<unsigned>()->default_value(1), "number parallel requests") ("iterations", bpo::value<unsigned>()->default_value(30), "number of iterations") ("partitions", bpo::value<unsigned>()->default_value(5000000), "number of partitions") ("buffer_size", bpo::value<unsigned>()->default_value(64), "sstable buffer size, in KB") ("key_size", bpo::value<unsigned>()->default_value(128), "size of partition key") ("num_columns", bpo::value<unsigned>()->default_value(5), "number of columns per row") ("column_size", bpo::value<unsigned>()->default_value(64), "size in bytes for each column") ("sstables", bpo::value<unsigned>()->default_value(1), "number of sstables (valid only for compaction mode)") ("mode", bpo::value<sstring>()->default_value("index_write"), "one of: sequential_read, index_read, write, compaction, index_write (default)") ("testdir", bpo::value<sstring>()->default_value("/var/lib/scylla/perf-tests"), "directory in which to store the sstables"); return app.run_deprecated(argc, argv, [&app] { auto test = make_lw_shared<distributed<test_env>>(); auto cfg = test_env::conf(); iterations = app.configuration()["iterations"].as<unsigned>(); parallelism = app.configuration()["parallelism"].as<unsigned>(); cfg.partitions = app.configuration()["partitions"].as<unsigned>(); cfg.key_size = app.configuration()["key_size"].as<unsigned>(); cfg.buffer_size = app.configuration()["buffer_size"].as<unsigned>() << 10; cfg.sstables = app.configuration()["sstables"].as<unsigned>(); sstring dir = app.configuration()["testdir"].as<sstring>(); cfg.dir = dir; auto mode = test_mode[app.configuration()["mode"].as<sstring>()]; if ((mode == test_modes::index_read) || (mode == test_modes::index_write)) { cfg.num_columns = 0; cfg.column_size = 0; } else { cfg.num_columns = app.configuration()["num_columns"].as<unsigned>(); cfg.column_size = app.configuration()["column_size"].as<unsigned>(); } return test->start(std::move(cfg)).then([mode, dir, test] { engine().at_exit([test] { return test->stop(); }); if ((mode == test_modes::index_read) || (mode == test_modes::sequential_read)) { return test->invoke_on_all([] (test_env &t) { return t.load_sstables(iterations); }).then_wrapped([] (future<> f) { try { f.get(); } catch (...) { std::cerr << "An error occurred when trying to load test sstables. Did you run write mode yet?" << std::endl; throw; } }); } else if ((mode == test_modes::index_write) || (mode == test_modes::write) || (mode == test_modes::compaction)) { return test_setup::create_empty_test_dir(dir); } else { throw std::invalid_argument("Invalid mode"); } }).then([test, mode] { if (mode == test_modes::index_read) { return test_index_read(*test).then([test] {}); } else if (mode == test_modes::sequential_read) { return test_sequential_read(*test).then([test] {}); } else if ((mode == test_modes::index_write) || (mode == test_modes::write)) { return test_write(*test).then([test] {}); } else if (mode == test_modes::compaction) { return test_compaction(*test).then([test] {}); } else { throw std::invalid_argument("Invalid mode"); } }).then([] { return engine().exit(0); }).or_terminate(); }); } <|endoftext|>
<commit_before>#include <boost/test/unit_test.hpp> #include <flexcore/pure/event_sinks.hpp> #include <flexcore/pure/event_sources.hpp> #include <flexcore/core/connection.hpp> using namespace fc; namespace fc { namespace pure { template<class T> struct event_sink_value { void operator()(T in) { *storage = in; } std::shared_ptr<T> storage = std::make_shared<T>(); }; template<class T> struct event_sink_vector { void operator()(T in) { storage->push_back(in); } std::shared_ptr<std::vector<T>> storage = std::make_shared<std::vector<T>>(); }; } // namespace pure } // namespace fc BOOST_AUTO_TEST_SUITE(test_events) BOOST_AUTO_TEST_CASE( connections ) { static_assert(is_active<pure::event_source<int>>{}, "event_out_port is active by definition"); static_assert(is_passive<pure::event_sink<int>>{}, "event_in_port is passive by definition"); static_assert(!is_active<pure::event_sink<int>>{}, "event_in_port is not active by definition"); static_assert(!is_passive<pure::event_source<int>>{}, "event_out_port is not passive by definition"); pure::event_source<int> test_event; pure::event_sink_value<int> test_handler; connect(test_event, test_handler); test_event.fire(1); BOOST_CHECK_EQUAL(*(test_handler.storage), 1); auto tmp_connection = test_event >> [](int i){return ++i;}; static_assert(is_instantiation_of< detail::active_connection_proxy, decltype(tmp_connection)>{}, "active port connected with standard connectable gets proxy"); std::move(tmp_connection) >> test_handler; test_event.fire(1); BOOST_CHECK_EQUAL(*(test_handler.storage), 2); auto incr = [](int i){return ++i;}; test_event >> incr >> incr >> incr >> test_handler; test_event.fire(1); BOOST_CHECK_EQUAL(*(test_handler.storage), 4); } BOOST_AUTO_TEST_CASE( merge_events ) { pure::event_source<int> test_event; pure::event_source<int> test_event_2; pure::event_sink_vector<int> test_handler; test_event >> test_handler; test_event_2 >> test_handler; test_event.fire(0); BOOST_CHECK_EQUAL(test_handler.storage->size(), 1); BOOST_CHECK_EQUAL(test_handler.storage->back(), 0); test_event_2.fire(1); BOOST_CHECK_EQUAL(test_handler.storage->size(), 2); BOOST_CHECK_EQUAL(test_handler.storage->front(), 0); BOOST_CHECK_EQUAL(test_handler.storage->back(), 1); } BOOST_AUTO_TEST_CASE( split_events ) { pure::event_source<int> test_event; pure::event_sink_value<int> test_handler_1; pure::event_sink_value<int> test_handler_2; test_event >> test_handler_1; test_event >> test_handler_2; test_event.fire(2); BOOST_CHECK_EQUAL(*(test_handler_1.storage), 2); BOOST_CHECK_EQUAL(*(test_handler_2.storage), 2); } BOOST_AUTO_TEST_CASE( in_port ) { int test_value = 0; auto test_writer = [&](int i) {test_value = i;}; pure::event_sink<int> in_port(test_writer); pure::event_source<int> test_event; test_event >> in_port; test_event.fire(1); BOOST_CHECK_EQUAL(test_value, 1); //test void event auto write_999 = [&]() {test_value = 999;}; pure::event_sink<void> void_in(write_999); pure::event_source<void> void_out; void_out >> void_in; void_out.fire(); BOOST_CHECK_EQUAL(test_value, 999); } BOOST_AUTO_TEST_CASE( lambda ) { int test_value = 0; auto write_666 = [&]() {test_value = 666;}; pure::event_source<void> void_out_2; void_out_2 >> write_666; void_out_2.fire(); BOOST_CHECK_EQUAL(test_value, 666); } namespace { template<class T> void test_connection(const T& connection) { int storage = 0; pure::event_source<int> a; pure::event_sink<int> d{[](int in){ BOOST_CHECK_EQUAL(in, 3);}}; auto c = [&](int i) { storage = i; return i; }; auto b = [](int i) { return i + 1; }; connection(a,b,c,d); a.fire(2); BOOST_CHECK_EQUAL(storage, 3); } } /** * Confirm that connecting ports and connectables * does not depend on any particular order. */ BOOST_AUTO_TEST_CASE( associativity ) { test_connection([](auto& a, auto& b, auto& c, auto& d) { a >> b >> c >> d; }); test_connection([](auto& a, auto& b, auto& c, auto& d) { (a >> b) >> (c >> d); }); test_connection([](auto& a, auto& b, auto& c, auto& d) { a >> ((b >> c) >> d); }); test_connection([](auto& a, auto& b, auto& c, auto& d) { (a >> (b >> c)) >> d; }); } namespace { template<class operation> struct sink_t { typedef void result_t; template <class T> void operator()(T&& in) { op(std::forward<T>(in)); } operation op; }; template<class operation> auto sink(const operation& op ) { return sink_t<operation>{op}; } } BOOST_AUTO_TEST_CASE( test_polymorphic_lambda ) { int test_value = 0; pure::event_source<int> p; auto write = sink([&](auto in) {test_value = in;}); static_assert(is_passive_sink<decltype(write)>{}, ""); p >> write; BOOST_CHECK_EQUAL(test_value, 0); p.fire(4); BOOST_CHECK_EQUAL(test_value, 4); } BOOST_AUTO_TEST_CASE(test_sink_has_callback) { static_assert(has_register_function<pure::event_sink<void>>(0), "type is defined with ability to register a callback"); } template <class T> struct disconnecting_event_sink : public pure::event_sink<T> { disconnecting_event_sink() : pure::event_sink<T>( [&](T in){ *storage = in; } ) { } std::shared_ptr<T> storage = std::make_shared<T>(); }; BOOST_AUTO_TEST_CASE(test_sink_deleted_callback) { disconnecting_event_sink<int> test_sink1; { pure::event_source<int> test_source; disconnecting_event_sink<int> test_sink4; test_source >> test_sink1; test_source.fire(5); BOOST_CHECK_EQUAL(*(test_sink1.storage), 5); { disconnecting_event_sink<int> test_sink2; disconnecting_event_sink<int> test_sink3; test_source >> test_sink2; test_source >> test_sink3; test_source.fire(6); BOOST_CHECK_EQUAL(*(test_sink2.storage), 6); BOOST_CHECK_EQUAL(*(test_sink3.storage), 6); test_source >> test_sink4; test_source.fire(7); BOOST_CHECK_EQUAL(*(test_sink4.storage), 7); BOOST_CHECK_EQUAL(test_source.nr_connected_handlers(), 4); } BOOST_CHECK_EQUAL(test_source.nr_connected_handlers(), 2); // this primarily checks, that no exception is thrown // since the connections from test_source to sink1-3 are deleted. test_source.fire(8); BOOST_CHECK_EQUAL(*(test_sink4.storage), 8); } } BOOST_AUTO_TEST_CASE(test_delete_with_lambda_in_connection) { disconnecting_event_sink<int> test_sink; pure::event_source<int> test_source; (test_source >> [](int i){ return i+1; }) >> test_sink; { disconnecting_event_sink<int> test_sink_2; test_source >> ([](int i){ return i+1; } >> [](int i){ return i+1; }) >> test_sink_2; test_source.fire(10); BOOST_CHECK_EQUAL(*(test_sink_2.storage), 12); BOOST_CHECK_EQUAL(test_source.nr_connected_handlers(), 2); } BOOST_CHECK_EQUAL(test_source.nr_connected_handlers(), 1); test_source.fire(11); BOOST_CHECK_EQUAL(*(test_sink.storage), 12); } BOOST_AUTO_TEST_CASE(test_connect_after_move_of_active) { pure::event_source<int> p; pure::event_source<int> p2 = std::move(p); bool fired = false; pure::event_sink<int> sink([&](int v) { fired = true; BOOST_CHECK_EQUAL(v, 99); }); p2 >> sink; p2.fire(99); BOOST_CHECK(fired); } BOOST_AUTO_TEST_CASE(test_connect_after_move_of_passive) { pure::event_source<int> src; int sink_val = 0; int ctr = 0; pure::event_sink<int> sink1{[](int){}}; { pure::event_sink<int> sink2{[&](int v) { ++ctr; sink_val = v; }}; sink1 = std::move(sink2); src >> sink1; src >> sink2; // after the block ends sink2 should be disconnected } src.fire(99); BOOST_CHECK_EQUAL(sink_val, 99); BOOST_CHECK_EQUAL(ctr, 1); } BOOST_AUTO_TEST_CASE(test_move_active_after_connect) { pure::event_source<int> p; bool fired = false; pure::event_sink<int> sink([&](int v) { fired = true; BOOST_CHECK_EQUAL(v, 99); }); p >> sink; pure::event_source<int> p2 = std::move(p); p2.fire(99); BOOST_CHECK(fired); } BOOST_AUTO_TEST_CASE(lambda_as_sink) { pure::event_source<int> src; int called = 0; auto lambda = [&](auto v) { BOOST_CHECK_EQUAL(v, 99); called++; }; auto mid = [&](auto v) { BOOST_CHECK_EQUAL(v, 99); called++; return v; }; src >> mid >> mid >> std::move(lambda); src.fire(99); BOOST_CHECK_EQUAL(called, 3); bool is_passive_sink_for = fc::is_passive_sink_for<decltype(lambda), int>{}; BOOST_CHECK(is_passive_sink_for); } namespace { struct strongly_typed { explicit strongly_typed(double) {} }; } BOOST_AUTO_TEST_CASE( type_changing_lambdas ) { pure::event_source<double> src; bool called_1 = false; bool called_2 = false; src >> [&](double d) { called_1 = true; return strongly_typed{d}; } >> [&](strongly_typed) { called_2 = true; }; src.fire(1.0); BOOST_CHECK(called_1); BOOST_CHECK(called_2); } BOOST_AUTO_TEST_CASE( type_changing_lambda_with_void ) { pure::event_source<void> src; bool called_1 = false; bool called_2 = false; src >> [&]() { called_1 = true; return strongly_typed{1.0}; } >> [&](strongly_typed) { called_2 = true; }; src.fire(); BOOST_CHECK(called_1); BOOST_CHECK(called_2); } BOOST_AUTO_TEST_CASE( type_changing_lambda_without_void ) { pure::event_source<double> src; bool called_1 = false; bool called_2 = false; src >> [&](double d) { called_1 = true; return strongly_typed{d}; } >> [&](strongly_typed) { called_2 = true; }; src.fire(1.0); BOOST_CHECK(called_1); BOOST_CHECK(called_2); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>removed bad event_tests<commit_after>#include <boost/test/unit_test.hpp> #include <flexcore/pure/event_sinks.hpp> #include <flexcore/pure/event_sources.hpp> #include <flexcore/core/connection.hpp> #include <tests/pure/sink_fixture.hpp> using namespace fc; namespace fc { namespace pure { template<class T> struct event_sink_value { void operator()(T in) { *storage = in; } std::shared_ptr<T> storage = std::make_shared<T>(); }; template<class T> struct event_sink_vector { void operator()(T in) { storage->push_back(in); } std::shared_ptr<std::vector<T>> storage = std::make_shared<std::vector<T>>(); }; } // namespace pure } // namespace fc BOOST_AUTO_TEST_SUITE(test_events) BOOST_AUTO_TEST_CASE( merge_events ) { pure::event_source<int> test_event; pure::event_source<int> test_event_2; pure::event_sink_vector<int> test_handler; test_event >> test_handler; test_event_2 >> test_handler; test_event.fire(0); BOOST_CHECK_EQUAL(test_handler.storage->size(), 1); BOOST_CHECK_EQUAL(test_handler.storage->back(), 0); test_event_2.fire(1); BOOST_CHECK_EQUAL(test_handler.storage->size(), 2); BOOST_CHECK_EQUAL(test_handler.storage->front(), 0); BOOST_CHECK_EQUAL(test_handler.storage->back(), 1); } BOOST_AUTO_TEST_CASE( split_events ) { pure::event_source<int> test_event; pure::event_sink_value<int> test_handler_1; pure::event_sink_value<int> test_handler_2; test_event >> test_handler_1; test_event >> test_handler_2; test_event.fire(2); BOOST_CHECK_EQUAL(*(test_handler_1.storage), 2); BOOST_CHECK_EQUAL(*(test_handler_2.storage), 2); } BOOST_AUTO_TEST_CASE( in_port ) { int test_value = 0; auto test_writer = [&](int i) {test_value = i;}; pure::event_sink<int> in_port(test_writer); pure::event_source<int> test_event; test_event >> in_port; test_event.fire(1); BOOST_CHECK_EQUAL(test_value, 1); //test void event auto write_999 = [&]() {test_value = 999;}; pure::event_sink<void> void_in(write_999); pure::event_source<void> void_out; void_out >> void_in; void_out.fire(); BOOST_CHECK_EQUAL(test_value, 999); } BOOST_AUTO_TEST_CASE( lambda ) { int test_value = 0; auto write_666 = [&]() {test_value = 666;}; pure::event_source<void> void_out_2; void_out_2 >> write_666; void_out_2.fire(); BOOST_CHECK_EQUAL(test_value, 666); } namespace { template<class T> void test_connection(const T& connection) { int storage = 0; pure::event_source<int> a; pure::event_sink<int> d{[](int in){ BOOST_CHECK_EQUAL(in, 3);}}; auto c = [&](int i) { storage = i; return i; }; auto b = [](int i) { return i + 1; }; connection(a,b,c,d); a.fire(2); BOOST_CHECK_EQUAL(storage, 3); } } /** * Confirm that connecting ports and connectables * does not depend on any particular order. */ BOOST_AUTO_TEST_CASE( associativity ) { test_connection([](auto& a, auto& b, auto& c, auto& d) { a >> b >> c >> d; }); test_connection([](auto& a, auto& b, auto& c, auto& d) { (a >> b) >> (c >> d); }); test_connection([](auto& a, auto& b, auto& c, auto& d) { a >> ((b >> c) >> d); }); test_connection([](auto& a, auto& b, auto& c, auto& d) { (a >> (b >> c)) >> d; }); } namespace { template<class operation> struct sink_t { typedef void result_t; template <class T> void operator()(T&& in) { op(std::forward<T>(in)); } operation op; }; template<class operation> auto sink(const operation& op ) { return sink_t<operation>{op}; } } BOOST_AUTO_TEST_CASE( test_polymorphic_lambda ) { int test_value = 0; pure::event_source<int> p; auto write = sink([&](auto in) {test_value = in;}); static_assert(is_passive_sink<decltype(write)>{}, ""); p >> write; BOOST_CHECK_EQUAL(test_value, 0); p.fire(4); BOOST_CHECK_EQUAL(test_value, 4); } BOOST_AUTO_TEST_CASE(test_sink_has_callback) { static_assert(has_register_function<pure::event_sink<void>>(0), "type is defined with ability to register a callback"); } template <class T> struct disconnecting_event_sink : public pure::event_sink<T> { disconnecting_event_sink() : pure::event_sink<T>( [&](T in){ *storage = in; } ) { } std::shared_ptr<T> storage = std::make_shared<T>(); }; BOOST_AUTO_TEST_CASE(test_sink_deleted_callback) { disconnecting_event_sink<int> test_sink1; { pure::event_source<int> test_source; disconnecting_event_sink<int> test_sink4; test_source >> test_sink1; test_source.fire(5); BOOST_CHECK_EQUAL(*(test_sink1.storage), 5); { disconnecting_event_sink<int> test_sink2; disconnecting_event_sink<int> test_sink3; test_source >> test_sink2; test_source >> test_sink3; test_source.fire(6); BOOST_CHECK_EQUAL(*(test_sink2.storage), 6); BOOST_CHECK_EQUAL(*(test_sink3.storage), 6); test_source >> test_sink4; test_source.fire(7); BOOST_CHECK_EQUAL(*(test_sink4.storage), 7); BOOST_CHECK_EQUAL(test_source.nr_connected_handlers(), 4); } BOOST_CHECK_EQUAL(test_source.nr_connected_handlers(), 2); // this primarily checks, that no exception is thrown // since the connections from test_source to sink1-3 are deleted. test_source.fire(8); BOOST_CHECK_EQUAL(*(test_sink4.storage), 8); } } BOOST_AUTO_TEST_CASE(test_delete_with_lambda_in_connection) { disconnecting_event_sink<int> test_sink; pure::event_source<int> test_source; (test_source >> [](int i){ return i+1; }) >> test_sink; { disconnecting_event_sink<int> test_sink_2; test_source >> ([](int i){ return i+1; } >> [](int i){ return i+1; }) >> test_sink_2; test_source.fire(10); BOOST_CHECK_EQUAL(*(test_sink_2.storage), 12); BOOST_CHECK_EQUAL(test_source.nr_connected_handlers(), 2); } BOOST_CHECK_EQUAL(test_source.nr_connected_handlers(), 1); test_source.fire(11); BOOST_CHECK_EQUAL(*(test_sink.storage), 12); } BOOST_AUTO_TEST_CASE(test_connect_after_move_of_active) { pure::event_source<int> p; pure::event_source<int> p2 = std::move(p); bool fired = false; pure::event_sink<int> sink([&](int v) { fired = true; BOOST_CHECK_EQUAL(v, 99); }); p2 >> sink; p2.fire(99); BOOST_CHECK(fired); } BOOST_AUTO_TEST_CASE(test_connect_after_move_of_passive) { pure::event_source<int> src; int sink_val = 0; int ctr = 0; pure::event_sink<int> sink1{[](int){}}; { pure::event_sink<int> sink2{[&](int v) { ++ctr; sink_val = v; }}; sink1 = std::move(sink2); src >> sink1; src >> sink2; // after the block ends sink2 should be disconnected } src.fire(99); BOOST_CHECK_EQUAL(sink_val, 99); BOOST_CHECK_EQUAL(ctr, 1); } BOOST_AUTO_TEST_CASE(test_move_active_after_connect) { pure::event_source<int> p; bool fired = false; pure::event_sink<int> sink([&](int v) { fired = true; BOOST_CHECK_EQUAL(v, 99); }); p >> sink; pure::event_source<int> p2 = std::move(p); p2.fire(99); BOOST_CHECK(fired); } BOOST_AUTO_TEST_CASE(lambda_as_sink) { pure::event_source<int> src; int called = 0; auto lambda = [&](auto v) { BOOST_CHECK_EQUAL(v, 99); called++; }; auto mid = [&](auto v) { BOOST_CHECK_EQUAL(v, 99); called++; return v; }; src >> mid >> mid >> std::move(lambda); src.fire(99); BOOST_CHECK_EQUAL(called, 3); bool is_passive_sink_for = fc::is_passive_sink_for<decltype(lambda), int>{}; BOOST_CHECK(is_passive_sink_for); } namespace { struct strongly_typed { explicit strongly_typed(double) {} }; } BOOST_AUTO_TEST_CASE( type_changing_lambdas ) { pure::event_source<double> src; bool called_1 = false; bool called_2 = false; src >> [&](double d) { called_1 = true; return strongly_typed{d}; } >> [&](strongly_typed) { called_2 = true; }; src.fire(1.0); BOOST_CHECK(called_1); BOOST_CHECK(called_2); } BOOST_AUTO_TEST_CASE( type_changing_lambda_with_void ) { pure::event_source<void> src; bool called_1 = false; bool called_2 = false; src >> [&]() { called_1 = true; return strongly_typed{1.0}; } >> [&](strongly_typed) { called_2 = true; }; src.fire(); BOOST_CHECK(called_1); BOOST_CHECK(called_2); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include "TiglViewerConsole.h" Console::Console(QWidget *parent) : QPlainTextEdit(parent) { prompt = "TiglViewer> "; QPalette p = palette(); p.setColor(QPalette::Base, Qt::black); p.setColor(QPalette::Text, Qt::green); setPalette(p); history = new QStringList; historyPos = 0; insertPrompt(false); isLocked = false; } void Console::keyPressEvent(QKeyEvent *event) { if(isLocked) return; if(event->key() >= 0x20 && event->key() <= 0x7e && (event->modifiers() == Qt::NoModifier || event->modifiers() == Qt::ShiftModifier)) QPlainTextEdit::keyPressEvent(event); if(event->key() == Qt::Key_Backspace && event->modifiers() == Qt::NoModifier && textCursor().positionInBlock() > prompt.length()) QPlainTextEdit::keyPressEvent(event); if(event->key() == Qt::Key_Return && event->modifiers() == Qt::NoModifier) onEnter(); if(event->key() == Qt::Key_Up && event->modifiers() == Qt::NoModifier) historyBack(); if(event->key() == Qt::Key_Down && event->modifiers() == Qt::NoModifier) historyForward(); QString cmd = textCursor().block().text().mid(prompt.length()); emit onChange(cmd); } void Console::mousePressEvent(QMouseEvent *) { setFocus(); } void Console::mouseDoubleClickEvent(QMouseEvent *){} void Console::contextMenuEvent(QContextMenuEvent *){} void Console::onEnter() { if(textCursor().positionInBlock() == prompt.length()) { insertPrompt(); return; } QString cmd = textCursor().block().text().mid(prompt.length()); isLocked = true; historyAdd(cmd); emit onCommand(cmd); } void Console::output(QString s) { appendHtml(QString("<font color=\"white\">%1</font><br/><br/>").arg(s)); insertPrompt(); isLocked = false; } void Console::insertPrompt(bool insertNewBlock) { if(insertNewBlock) textCursor().insertBlock(); QTextCharFormat format; format.setForeground(Qt::green); textCursor().setBlockCharFormat(format); textCursor().insertText(prompt); scrollDown(); } void Console::scrollDown() { QScrollBar *vbar = verticalScrollBar(); vbar->setValue(vbar->maximum()); } void Console::historyAdd(QString cmd) { history->append(cmd); historyPos = history->length(); } void Console::historyBack() { if(!historyPos) return; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::StartOfBlock); cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); cursor.removeSelectedText(); cursor.insertText(prompt + history->at(historyPos-1)); setTextCursor(cursor); historyPos--; } void Console::historyForward() { if(historyPos == history->length()) return; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::StartOfBlock); cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); cursor.removeSelectedText(); if(historyPos == history->length() - 1) cursor.insertText(prompt); else cursor.insertText(prompt + history->at(historyPos + 1)); setTextCursor(cursor); historyPos++; } <commit_msg>Changed code to compile with QT Version < 4.7<commit_after>#include "TiglViewerConsole.h" Console::Console(QWidget *parent) : QPlainTextEdit(parent) { prompt = "TiglViewer> "; QPalette p = palette(); p.setColor(QPalette::Base, Qt::black); p.setColor(QPalette::Text, Qt::green); setPalette(p); history = new QStringList; historyPos = 0; insertPrompt(false); isLocked = false; } void Console::keyPressEvent(QKeyEvent *event) { if(isLocked) return; if(event->key() >= 0x20 && event->key() <= 0x7e && (event->modifiers() == Qt::NoModifier || event->modifiers() == Qt::ShiftModifier)) QPlainTextEdit::keyPressEvent(event); if(event->key() == Qt::Key_Backspace && event->modifiers() == Qt::NoModifier && textCursor().position() - textCursor().block().position() > prompt.length()) QPlainTextEdit::keyPressEvent(event); if(event->key() == Qt::Key_Return && event->modifiers() == Qt::NoModifier) onEnter(); if(event->key() == Qt::Key_Up && event->modifiers() == Qt::NoModifier) historyBack(); if(event->key() == Qt::Key_Down && event->modifiers() == Qt::NoModifier) historyForward(); QString cmd = textCursor().block().text().mid(prompt.length()); emit onChange(cmd); } void Console::mousePressEvent(QMouseEvent *) { setFocus(); } void Console::mouseDoubleClickEvent(QMouseEvent *){} void Console::contextMenuEvent(QContextMenuEvent *){} void Console::onEnter() { if(textCursor().position() - textCursor().block().position() == prompt.length()){ insertPrompt(); return; } QString cmd = textCursor().block().text().mid(prompt.length()); isLocked = true; historyAdd(cmd); emit onCommand(cmd); } void Console::output(QString s) { appendHtml(QString("<font color=\"white\">%1</font><br/><br/>").arg(s)); insertPrompt(); isLocked = false; } void Console::insertPrompt(bool insertNewBlock) { if(insertNewBlock) textCursor().insertBlock(); QTextCharFormat format; format.setForeground(Qt::green); textCursor().setBlockCharFormat(format); textCursor().insertText(prompt); scrollDown(); } void Console::scrollDown() { QScrollBar *vbar = verticalScrollBar(); vbar->setValue(vbar->maximum()); } void Console::historyAdd(QString cmd) { history->append(cmd); historyPos = history->length(); } void Console::historyBack() { if(!historyPos) return; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::StartOfBlock); cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); cursor.removeSelectedText(); cursor.insertText(prompt + history->at(historyPos-1)); setTextCursor(cursor); historyPos--; } void Console::historyForward() { if(historyPos == history->length()) return; QTextCursor cursor = textCursor(); cursor.movePosition(QTextCursor::StartOfBlock); cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor); cursor.removeSelectedText(); if(historyPos == history->length() - 1) cursor.insertText(prompt); else cursor.insertText(prompt + history->at(historyPos + 1)); setTextCursor(cursor); historyPos++; } <|endoftext|>
<commit_before>// // Name: VehicleDlg.cpp // // Copyright (c) 2006 Virtual Terrain Project // Free for all uses, see license.txt for details. // // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #include <wx/colordlg.h> #include "vtlib/vtlib.h" #include "vtlib/core/TerrainScene.h" // for vtGetContent #include "vtui/Helper.h" // for FillWithColor #include "VehicleDlg.h" #include "EnviroGUI.h" // for g_App extern void EnableContinuousRendering(bool bTrue); // WDR: class implementations //---------------------------------------------------------------------------- // VehicleDlg //---------------------------------------------------------------------------- // WDR: event table for VehicleDlg BEGIN_EVENT_TABLE(VehicleDlg,wxDialog) EVT_INIT_DIALOG (VehicleDlg::OnInitDialog) EVT_BUTTON( ID_SET_VEHICLE_COLOR, VehicleDlg::OnSetColor ) EVT_CHOICE( ID_CHOICE_VEHICLES, VehicleDlg::OnChoiceVehicle ) END_EVENT_TABLE() VehicleDlg::VehicleDlg( wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style ) : wxDialog( parent, id, title, position, size, style ) { // WDR: dialog function VehicleDialogFunc for VehicleDlg VehicleDialogFunc( this, TRUE ); m_options.m_Color.Set(255, 255, 0); wxColour rgb(255, 255, 0); m_ColorData.SetChooseFull(true); m_ColorData.SetColour(rgb); } void VehicleDlg::UpdateEnabling() { vtContentManager3d &con = vtGetContent(); GetSetColor()->Enable(false); vtItem *item = con.FindItemByName(m_options.m_Itemname); if (item) { if (item->GetValueBool("colorable")) GetSetColor()->Enable(true); } } void VehicleDlg::ItemChanged() { m_options.m_Itemname = (const char *) GetChoice()->GetStringSelection().mb_str(wxConvUTF8); g_App.SetVehicleOptions(m_options); } void VehicleDlg::UpdateColorControl() { // Case of a single edge, very simple. FillWithColor(GetColor(), m_options.m_Color); } // WDR: handler implementations for VehicleDlg void VehicleDlg::OnChoiceVehicle( wxCommandEvent &event ) { ItemChanged(); UpdateEnabling(); } void VehicleDlg::OnSetColor( wxCommandEvent &event ) { EnableContinuousRendering(false); wxColourDialog dlg(this, &m_ColorData); if (dlg.ShowModal() == wxID_OK) { // Get the color from the dialog m_ColorData = dlg.GetColourData(); wxColour rgb = m_ColorData.GetColour(); m_options.m_Color.Set(rgb.Red(), rgb.Green(), rgb.Blue()); UpdateColorControl(); g_App.SetVehicleOptions(m_options); } EnableContinuousRendering(true); } void VehicleDlg::OnInitDialog(wxInitDialogEvent& event) { GetChoice()->Clear(); // Refresh vehicle list wxString prev = GetChoice()->GetStringSelection(); wxArrayString names; vtContentManager3d &con = vtGetContent(); for (unsigned int i = 0; i < con.NumItems(); i++) { vtItem *item = con.GetItem(i); if (vtString("ground vehicle") == item->GetValueString("type") && 4 == item->GetValueInt("num_wheels")) { GetChoice()->Append(wxString(item->m_name, wxConvUTF8)); } } if (prev != _T("")) GetChoice()->SetStringSelection(prev); else GetChoice()->SetSelection(0); ItemChanged(); UpdateColorControl(); UpdateEnabling(); wxWindow::OnInitDialog(event); } <commit_msg>added non-pre-comp wx header<commit_after>// // Name: VehicleDlg.cpp // // Copyright (c) 2006 Virtual Terrain Project // Free for all uses, see license.txt for details. // // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include <wx/colordlg.h> #include "vtlib/vtlib.h" #include "vtlib/core/TerrainScene.h" // for vtGetContent #include "vtui/Helper.h" // for FillWithColor #include "VehicleDlg.h" #include "EnviroGUI.h" // for g_App extern void EnableContinuousRendering(bool bTrue); // WDR: class implementations //---------------------------------------------------------------------------- // VehicleDlg //---------------------------------------------------------------------------- // WDR: event table for VehicleDlg BEGIN_EVENT_TABLE(VehicleDlg,wxDialog) EVT_INIT_DIALOG (VehicleDlg::OnInitDialog) EVT_BUTTON( ID_SET_VEHICLE_COLOR, VehicleDlg::OnSetColor ) EVT_CHOICE( ID_CHOICE_VEHICLES, VehicleDlg::OnChoiceVehicle ) END_EVENT_TABLE() VehicleDlg::VehicleDlg( wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style ) : wxDialog( parent, id, title, position, size, style ) { // WDR: dialog function VehicleDialogFunc for VehicleDlg VehicleDialogFunc( this, TRUE ); m_options.m_Color.Set(255, 255, 0); wxColour rgb(255, 255, 0); m_ColorData.SetChooseFull(true); m_ColorData.SetColour(rgb); } void VehicleDlg::UpdateEnabling() { vtContentManager3d &con = vtGetContent(); GetSetColor()->Enable(false); vtItem *item = con.FindItemByName(m_options.m_Itemname); if (item) { if (item->GetValueBool("colorable")) GetSetColor()->Enable(true); } } void VehicleDlg::ItemChanged() { m_options.m_Itemname = (const char *) GetChoice()->GetStringSelection().mb_str(wxConvUTF8); g_App.SetVehicleOptions(m_options); } void VehicleDlg::UpdateColorControl() { // Case of a single edge, very simple. FillWithColor(GetColor(), m_options.m_Color); } // WDR: handler implementations for VehicleDlg void VehicleDlg::OnChoiceVehicle( wxCommandEvent &event ) { ItemChanged(); UpdateEnabling(); } void VehicleDlg::OnSetColor( wxCommandEvent &event ) { EnableContinuousRendering(false); wxColourDialog dlg(this, &m_ColorData); if (dlg.ShowModal() == wxID_OK) { // Get the color from the dialog m_ColorData = dlg.GetColourData(); wxColour rgb = m_ColorData.GetColour(); m_options.m_Color.Set(rgb.Red(), rgb.Green(), rgb.Blue()); UpdateColorControl(); g_App.SetVehicleOptions(m_options); } EnableContinuousRendering(true); } void VehicleDlg::OnInitDialog(wxInitDialogEvent& event) { GetChoice()->Clear(); // Refresh vehicle list wxString prev = GetChoice()->GetStringSelection(); wxArrayString names; vtContentManager3d &con = vtGetContent(); for (unsigned int i = 0; i < con.NumItems(); i++) { vtItem *item = con.GetItem(i); if (vtString("ground vehicle") == item->GetValueString("type") && 4 == item->GetValueInt("num_wheels")) { GetChoice()->Append(wxString(item->m_name, wxConvUTF8)); } } if (prev != _T("")) GetChoice()->SetStringSelection(prev); else GetChoice()->SetSelection(0); ItemChanged(); UpdateColorControl(); UpdateEnabling(); wxWindow::OnInitDialog(event); } <|endoftext|>
<commit_before>// // Name: VehicleDlg.cpp // // Copyright (c) 2006 Virtual Terrain Project // Free for all uses, see license.txt for details. // // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include <wx/colordlg.h> #include "vtlib/vtlib.h" #include "vtlib/core/TerrainScene.h" // for vtGetContent #include "vtui/Helper.h" // for FillWithColor #include "VehicleDlg.h" #include "EnviroGUI.h" // for g_App extern void EnableContinuousRendering(bool bTrue); // WDR: class implementations //---------------------------------------------------------------------------- // VehicleDlg //---------------------------------------------------------------------------- // WDR: event table for VehicleDlg BEGIN_EVENT_TABLE(VehicleDlg,wxDialog) EVT_INIT_DIALOG (VehicleDlg::OnInitDialog) EVT_BUTTON( ID_SET_VEHICLE_COLOR, VehicleDlg::OnSetColor ) EVT_CHOICE( ID_CHOICE_VEHICLES, VehicleDlg::OnChoiceVehicle ) END_EVENT_TABLE() VehicleDlg::VehicleDlg( wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style ) : wxDialog( parent, id, title, position, size, style ) { // WDR: dialog function VehicleDialogFunc for VehicleDlg VehicleDialogFunc( this, TRUE ); m_options.m_Color.Set(255, 255, 0); wxColour rgb(255, 255, 0); m_ColorData.SetChooseFull(true); m_ColorData.SetColour(rgb); } void VehicleDlg::UpdateEnabling() { vtContentManager3d &con = vtGetContent(); GetSetColor()->Enable(false); vtItem *item = con.FindItemByName(m_options.m_Itemname); if (item) { if (item->GetValueBool("colorable")) GetSetColor()->Enable(true); } } void VehicleDlg::ItemChanged() { m_options.m_Itemname = (const char *) GetChoice()->GetStringSelection().mb_str(wxConvUTF8); g_App.SetVehicleOptions(m_options); } void VehicleDlg::UpdateColorControl() { // Case of a single edge, very simple. FillWithColor(GetColor(), m_options.m_Color); } // WDR: handler implementations for VehicleDlg void VehicleDlg::OnChoiceVehicle( wxCommandEvent &event ) { ItemChanged(); UpdateEnabling(); } void VehicleDlg::OnSetColor( wxCommandEvent &event ) { EnableContinuousRendering(false); wxColourDialog dlg(this, &m_ColorData); if (dlg.ShowModal() == wxID_OK) { // Get the color from the dialog m_ColorData = dlg.GetColourData(); wxColour rgb = m_ColorData.GetColour(); m_options.m_Color.Set(rgb.Red(), rgb.Green(), rgb.Blue()); UpdateColorControl(); g_App.SetVehicleOptions(m_options); } EnableContinuousRendering(true); } void VehicleDlg::OnInitDialog(wxInitDialogEvent& event) { GetChoice()->Clear(); // Refresh vehicle list wxString prev = GetChoice()->GetStringSelection(); wxArrayString names; vtContentManager3d &con = vtGetContent(); for (unsigned int i = 0; i < con.NumItems(); i++) { vtItem *item = con.GetItem(i); if (vtString("ground vehicle") == item->GetValueString("type") && 4 == item->GetValueInt("num_wheels")) { GetChoice()->Append(wxString(item->m_name, wxConvUTF8)); } } if (prev != _T("")) GetChoice()->SetStringSelection(prev); else GetChoice()->SetSelection(0); ItemChanged(); UpdateColorControl(); UpdateEnabling(); wxWindow::OnInitDialog(event); } <commit_msg>added safety check (RJ)<commit_after>// // Name: VehicleDlg.cpp // // Copyright (c) 2006 Virtual Terrain Project // Free for all uses, see license.txt for details. // // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include <wx/colordlg.h> #include "vtlib/vtlib.h" #include "vtlib/core/TerrainScene.h" // for vtGetContent #include "vtui/Helper.h" // for FillWithColor #include "VehicleDlg.h" #include "EnviroGUI.h" // for g_App extern void EnableContinuousRendering(bool bTrue); // WDR: class implementations //---------------------------------------------------------------------------- // VehicleDlg //---------------------------------------------------------------------------- // WDR: event table for VehicleDlg BEGIN_EVENT_TABLE(VehicleDlg,wxDialog) EVT_INIT_DIALOG (VehicleDlg::OnInitDialog) EVT_BUTTON( ID_SET_VEHICLE_COLOR, VehicleDlg::OnSetColor ) EVT_CHOICE( ID_CHOICE_VEHICLES, VehicleDlg::OnChoiceVehicle ) END_EVENT_TABLE() VehicleDlg::VehicleDlg( wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style ) : wxDialog( parent, id, title, position, size, style ) { // WDR: dialog function VehicleDialogFunc for VehicleDlg VehicleDialogFunc( this, TRUE ); m_options.m_Color.Set(255, 255, 0); wxColour rgb(255, 255, 0); m_ColorData.SetChooseFull(true); m_ColorData.SetColour(rgb); } void VehicleDlg::UpdateEnabling() { vtContentManager3d &con = vtGetContent(); GetSetColor()->Enable(false); vtItem *item = con.FindItemByName(m_options.m_Itemname); if (item) { if (item->GetValueBool("colorable")) GetSetColor()->Enable(true); } } void VehicleDlg::ItemChanged() { m_options.m_Itemname = (const char *) GetChoice()->GetStringSelection().mb_str(wxConvUTF8); g_App.SetVehicleOptions(m_options); } void VehicleDlg::UpdateColorControl() { // Case of a single edge, very simple. FillWithColor(GetColor(), m_options.m_Color); } // WDR: handler implementations for VehicleDlg void VehicleDlg::OnChoiceVehicle( wxCommandEvent &event ) { ItemChanged(); UpdateEnabling(); } void VehicleDlg::OnSetColor( wxCommandEvent &event ) { EnableContinuousRendering(false); wxColourDialog dlg(this, &m_ColorData); if (dlg.ShowModal() == wxID_OK) { // Get the color from the dialog m_ColorData = dlg.GetColourData(); wxColour rgb = m_ColorData.GetColour(); m_options.m_Color.Set(rgb.Red(), rgb.Green(), rgb.Blue()); UpdateColorControl(); g_App.SetVehicleOptions(m_options); } EnableContinuousRendering(true); } void VehicleDlg::OnInitDialog(wxInitDialogEvent& event) { GetChoice()->Clear(); // Refresh vehicle list wxString prev = GetChoice()->GetStringSelection(); wxArrayString names; vtContentManager3d &con = vtGetContent(); for (unsigned int i = 0; i < con.NumItems(); i++) { vtItem *item = con.GetItem(i); const char *type = item->GetValueString("type"); int wheels = item->GetValueInt("num_wheels"); if (type && vtString(type) == "ground vehicle" && wheels == 4) { GetChoice()->Append(wxString(item->m_name, wxConvUTF8)); } } if (prev != _T("")) GetChoice()->SetStringSelection(prev); else GetChoice()->SetSelection(0); ItemChanged(); UpdateColorControl(); UpdateEnabling(); wxWindow::OnInitDialog(event); } <|endoftext|>
<commit_before>#include <iostream> /* allows to perform standard input and output operations */ #include <fstream> #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <ctype.h> /* isxxx() */ #include <termios.h> /* POSIX terminal control definitions */ #include <ros/ros.h> /* ROS */ #include <geometry_msgs/Twist.h> /* ROS Twist message */ #include <base_controller/encoders.h> /* Custom message /encoders */ #include <base_controller/md49data.h> /* Custom message /encoders */ const char* serialport_name="/dev/ttyS2"; /* defines used serialport on BPi. Use "/dev/ttyAMA0" for RPi*/ int serialport_bps=B9600; /* defines used baudrate on serialport */ int fd; /* serial port file descriptor */ struct termios orig; // backuped port options int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ char speed_l=128; char speed_r=128; /* speed to set for MD49 */ char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */ double vr = 0.0; double vl = 0.0; double max_vr = 0.2; double max_vl = 0.2; double min_vr = 0.2; double min_vl = 0.2; double base_width = 0.4; /* Base width in meters */ unsigned char serialBuffer[18]; /* Serial buffer to store uart data */ void read_MD49_Data (void); void set_MD49_speed (void); char* itoa(int value, char* result, int base); int openSerialPort(const char * device, int bps); void writeBytes(int descriptor, int count); void readBytes(int descriptor, int count); base_controller::encoders encoders; base_controller::md49data md49data; void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){ if (vel_cmd.linear.x>0){ speed_l = 255; speed_r = 255; //set_MD49_speed(); } if (vel_cmd.linear.x<0){ speed_l = 0; speed_r = 0; //set_MD49_speed(); } if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){ speed_l = 128; speed_r = 128; //set_MD49_speed(); } if (vel_cmd.angular.z>0){ speed_l = 0; speed_r = 255; //set_MD49_speed(); } if (vel_cmd.angular.z<0){ speed_l = 255; speed_r = 0; //set_MD49_speed(); } /* //ANFANG Alternative if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;} else if(vel_cmd.linear.x == 0){ // turning vr = vel_cmd.angular.z * base_width / 2.0; vl = (-1) * vr; } else if(vel_cmd.angular.z == 0){ // forward / backward vl = vr = vel_cmd.linear.x; } else{ // moving doing arcs vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0; if (vl > max_vl) {vl=max_vl;} if (vl < min_vl) {vl=min_vl;} vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0; if (vr > max_vr) {vr=max_vr;} if (vr < min_vr) {vr=min_vr;} } //ENDE Alternative */ } int main( int argc, char* argv[] ){ ros::init(argc, argv, "base_controller" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback); ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10); ros::Publisher md49data_pub = n.advertise<base_controller::md49data>("md49data",10); // Init node // ********* ros::Rate loop_rate(10); ROS_INFO("base_controller running..."); ROS_INFO("============================="); ROS_INFO("Subscribing to topic /cmd_vel"); ROS_INFO("Publishing to topic /encoders"); ROS_INFO("Publishing to topic /md49data"); // Open serial port // **************** fd = openSerialPort(serialport_name, serialport_bps); if (fd == -1) exit(1); ROS_INFO("Opend serial port at %s with %i Bps",serialport_name,serialport_bps); usleep(10000); // Sleep for UART to power up and set options while(n.ok()) { // Read encoder and other data from MD49 // (data is read from serial_controller_node // and avaiable through md49_data.txt) // ***************************************** // read_MD49_Data(); // set speed as in md49speed.txt // ***************************** if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){ // gewünschte werte in textfile //write_MD49_speed(speed_l,speed_r); set_MD49_speed(); last_speed_l=speed_l; last_speed_r=speed_r; } // Publish encoder values to topic /encoders (custom message) // ********************************************************** encoders.encoder_l=EncoderL; encoders.encoder_r=EncoderR; encoders_pub.publish(encoders); // Publish MD49 data to topic /md49data (custom message) // ***************************************************** md49data.speed_l = serialBuffer[8]; md49data.speed_r = serialBuffer[9]; md49data.volt = serialBuffer[10]; md49data.current_l = serialBuffer[11]; md49data.current_r = serialBuffer[12]; md49data.error = serialBuffer[13]; md49data.acceleration = serialBuffer[14]; md49data.mode = serialBuffer[15]; md49data.regulator = serialBuffer[16]; md49data.timeout = serialBuffer[17]; md49data_pub.publish(md49data); // **** ros::spinOnce(); loop_rate.sleep(); }// end.mainloop return 1; } // end.main void read_MD49_Data (void){ /* // Output MD49 data on screen // ************************** printf("\033[2J"); // clear the screen printf("\033[H"); // position cursor at top-left corner printf ("MD49-Data read from AVR-Master: \n"); printf("========================================\n"); printf("Encoder1 Byte1: %i ",reply[0]); printf("Byte2: %i ",reply[1]); printf("Byte3: % i ",reply[2]); printf("Byte4: %i \n",reply[3]); printf("Encoder2 Byte1: %i ",reply[4]); printf("Byte2: %i ",reply[5]); printf("Byte3: %i ",reply[6]); printf("Byte4: %i \n",reply[7]); printf("EncoderL: %i ",EncoderL); printf("EncoderR: %i \n",EncoderR); printf("========================================\n"); printf("Speed1: %i ",reply[8]); printf("Speed2: %i \n",reply[9]); printf("Volts: %i \n",reply[10]); printf("Current1: %i ",reply[11]); printf("Current2: %i \n",reply[12]); printf("Error: %i \n",reply[13]); printf("Acceleration: %i \n",reply[14]); printf("Mode: %i \n",reply[15]); printf("Regulator: %i \n",reply[16]); printf("Timeout: %i \n",reply[17]); */ } void set_MD49_speed(void){ serialBuffer[0] = 0; serialBuffer[1] = 0x31; // Command to set motor speed serialBuffer[2] = speed_l; // Speed to be set serialBuffer[3] = 0; serialBuffer[4] = 0x32; serialBuffer[5] = speed_r; writeBytes(fd, 6); } // Open serialport // *************** int openSerialPort(const char * device, int bps){ struct termios neu; char buf[128]; //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); fd = open(device, O_RDWR | O_NOCTTY); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcflush(fd, TCIFLUSH); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } char* itoa(int value, char* result, int base) { // check that the base if valid if (base < 2 || base > 36) { *result = '\0'; return result; } char* ptr = result, *ptr1 = result, tmp_char; int tmp_value; do { tmp_value = value; value /= base; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)]; } while ( value ); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while(ptr1 < ptr) { tmp_char = *ptr; *ptr--= *ptr1; *ptr1++ = tmp_char; } return result; } // Write bytes serial to UART // ************************** void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } } // Read bytes serial from UART // *************************** void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } <commit_msg>Update code<commit_after>#include <iostream> /* allows to perform standard input and output operations */ #include <fstream> #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <ctype.h> /* isxxx() */ #include <termios.h> /* POSIX terminal control definitions */ #include <ros/ros.h> /* ROS */ #include <geometry_msgs/Twist.h> /* ROS Twist message */ #include <base_controller/encoders.h> /* Custom message /encoders */ #include <base_controller/md49data.h> /* Custom message /encoders */ const char* serialport_name="/dev/ttyS2"; /* defines used serialport on BPi. Use "/dev/ttyAMA0" for RPi*/ int serialport_bps=B9600; /* defines used baudrate on serialport */ int fd; /* serial port file descriptor */ struct termios orig; // backuped port options int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ char speed_l=128; char speed_r=128; /* speed to set for MD49 */ char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */ double vr = 0.0; double vl = 0.0; double max_vr = 0.2; double max_vl = 0.2; double min_vr = 0.2; double min_vl = 0.2; double base_width = 0.4; /* Base width in meters */ unsigned char serialBuffer[18]; /* Serial buffer to store uart data */ void read_MD49_Data (void); void set_MD49_speed (void); char* itoa(int value, char* result, int base); int openSerialPort(const char * device, int bps); void writeBytes(int descriptor, int count); void readBytes(int descriptor, int count); base_controller::encoders encoders; base_controller::md49data md49data; void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){ if (vel_cmd.linear.x>0){ speed_l = 255; speed_r = 255; //set_MD49_speed(); } if (vel_cmd.linear.x<0){ speed_l = 0; speed_r = 0; //set_MD49_speed(); } if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){ speed_l = 128; speed_r = 128; //set_MD49_speed(); } if (vel_cmd.angular.z>0){ speed_l = 0; speed_r = 255; //set_MD49_speed(); } if (vel_cmd.angular.z<0){ speed_l = 255; speed_r = 0; //set_MD49_speed(); } /* //ANFANG Alternative if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;} else if(vel_cmd.linear.x == 0){ // turning vr = vel_cmd.angular.z * base_width / 2.0; vl = (-1) * vr; } else if(vel_cmd.angular.z == 0){ // forward / backward vl = vr = vel_cmd.linear.x; } else{ // moving doing arcs vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0; if (vl > max_vl) {vl=max_vl;} if (vl < min_vl) {vl=min_vl;} vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0; if (vr > max_vr) {vr=max_vr;} if (vr < min_vr) {vr=min_vr;} } //ENDE Alternative */ } int main( int argc, char* argv[] ){ ros::init(argc, argv, "base_controller" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback); ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10); ros::Publisher md49data_pub = n.advertise<base_controller::md49data>("md49data",10); // Init node // ********* ros::Rate loop_rate(10); ROS_INFO("base_controller running..."); ROS_INFO("============================="); ROS_INFO("Subscribing to topic /cmd_vel"); ROS_INFO("Publishing to topic /encoders"); ROS_INFO("Publishing to topic /md49data"); // Open serial port // **************** fd = openSerialPort(serialport_name, serialport_bps); if (fd == -1) exit(1); ROS_INFO("Opend serial port at %s with %i Bps",serialport_name,serialport_bps); usleep(10000); // Sleep for UART to power up and set options while(n.ok()) { // Read encoder and other data from MD49 // (data is read from serial_controller_node // and avaiable through md49_data.txt) // ***************************************** // read_MD49_Data(); // set speed as in md49speed.txt // ***************************** //if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){ // gewünschte werte in textfile //write_MD49_speed(speed_l,speed_r); set_MD49_speed(); // last_speed_l=speed_l; // last_speed_r=speed_r; //} // Publish encoder values to topic /encoders (custom message) // ********************************************************** encoders.encoder_l=EncoderL; encoders.encoder_r=EncoderR; encoders_pub.publish(encoders); // Publish MD49 data to topic /md49data (custom message) // ***************************************************** md49data.speed_l = serialBuffer[8]; md49data.speed_r = serialBuffer[9]; md49data.volt = serialBuffer[10]; md49data.current_l = serialBuffer[11]; md49data.current_r = serialBuffer[12]; md49data.error = serialBuffer[13]; md49data.acceleration = serialBuffer[14]; md49data.mode = serialBuffer[15]; md49data.regulator = serialBuffer[16]; md49data.timeout = serialBuffer[17]; md49data_pub.publish(md49data); // **** ros::spinOnce(); loop_rate.sleep(); }// end.mainloop return 1; } // end.main void read_MD49_Data (void){ /* // Output MD49 data on screen // ************************** printf("\033[2J"); // clear the screen printf("\033[H"); // position cursor at top-left corner printf ("MD49-Data read from AVR-Master: \n"); printf("========================================\n"); printf("Encoder1 Byte1: %i ",reply[0]); printf("Byte2: %i ",reply[1]); printf("Byte3: % i ",reply[2]); printf("Byte4: %i \n",reply[3]); printf("Encoder2 Byte1: %i ",reply[4]); printf("Byte2: %i ",reply[5]); printf("Byte3: %i ",reply[6]); printf("Byte4: %i \n",reply[7]); printf("EncoderL: %i ",EncoderL); printf("EncoderR: %i \n",EncoderR); printf("========================================\n"); printf("Speed1: %i ",reply[8]); printf("Speed2: %i \n",reply[9]); printf("Volts: %i \n",reply[10]); printf("Current1: %i ",reply[11]); printf("Current2: %i \n",reply[12]); printf("Error: %i \n",reply[13]); printf("Acceleration: %i \n",reply[14]); printf("Mode: %i \n",reply[15]); printf("Regulator: %i \n",reply[16]); printf("Timeout: %i \n",reply[17]); */ } void set_MD49_speed(void){ serialBuffer[0] = 0; serialBuffer[1] = 0x31; // Command to set motor speed serialBuffer[2] = speed_l; // Speed to be set serialBuffer[3] = 0; serialBuffer[4] = 0x32; serialBuffer[5] = speed_r; writeBytes(fd, 6); } // Open serialport // *************** int openSerialPort(const char * device, int bps){ struct termios neu; char buf[128]; //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); fd = open(device, O_RDWR | O_NOCTTY); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcflush(fd, TCIFLUSH); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } char* itoa(int value, char* result, int base) { // check that the base if valid if (base < 2 || base > 36) { *result = '\0'; return result; } char* ptr = result, *ptr1 = result, tmp_char; int tmp_value; do { tmp_value = value; value /= base; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)]; } while ( value ); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while(ptr1 < ptr) { tmp_char = *ptr; *ptr--= *ptr1; *ptr1++ = tmp_char; } return result; } // Write bytes serial to UART // ************************** void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } } // Read bytes serial from UART // *************************** void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } <|endoftext|>
<commit_before>// 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. #ifndef ROCPRIM_ITERATOR_TRANSFORM_ITERATOR_HPP_ #define ROCPRIM_ITERATOR_TRANSFORM_ITERATOR_HPP_ #include <iterator> #include <cstddef> #include <type_traits> #include "../config.hpp" BEGIN_ROCPRIM_NAMESPACE template< class InputIterator, class UnaryFunction, #if defined(__cpp_lib_is_invocable) && !defined(DOXYGEN_SHOULD_SKIP_THIS) // C++17 class ValueType = typename std::invoke_result< UnaryFunction, typename std::iterator_traits<InputIterator>::value_type >::type #else class ValueType = typename std::result_of< UnaryFunction(typename std::iterator_traits<InputIterator>::value_type) >::type #endif > class transform_iterator { private: using input_category = typename std::iterator_traits<InputIterator>::iterator_category; static_assert( std::is_same<input_category, std::random_access_iterator_tag>::value, "InputIterator must be a random-access iterator" ); public: using value_type = ValueType; using reference = const value_type&; using pointer = const value_type*; using difference_type = typename std::iterator_traits<InputIterator>::difference_type; using iterator_category = std::random_access_iterator_tag; using unary_function = UnaryFunction; #ifndef DOXYGEN_SHOULD_SKIP_THIS using self_type = transform_iterator; #endif ROCPRIM_HOST_DEVICE inline ~transform_iterator() = default; ROCPRIM_HOST_DEVICE inline transform_iterator(InputIterator iterator, UnaryFunction transform) : iterator_(iterator), transform_(transform) { } ROCPRIM_HOST_DEVICE inline transform_iterator& operator++() { iterator_++; return *this; } ROCPRIM_HOST_DEVICE inline transform_iterator operator++(int) { transform_iterator old = *this; iterator_++; return old; } ROCPRIM_HOST_DEVICE inline value_type operator*() const { return transform_(*iterator_); } ROCPRIM_HOST_DEVICE inline pointer operator->() const { return &(*(*this)); } ROCPRIM_HOST_DEVICE inline value_type operator[](difference_type distance) const { transform_iterator i = (*this) + distance; return *i; } ROCPRIM_HOST_DEVICE inline transform_iterator operator+(difference_type distance) const { return transform_iterator(iterator_ + distance, transform_); } ROCPRIM_HOST_DEVICE inline transform_iterator& operator+=(difference_type distance) { iterator_ += distance; return *this; } ROCPRIM_HOST_DEVICE inline transform_iterator operator-(difference_type distance) const { return transform_iterator(iterator_ - distance, transform_); } ROCPRIM_HOST_DEVICE inline transform_iterator& operator-=(difference_type distance) { iterator_ -= distance; return *this; } ROCPRIM_HOST_DEVICE inline difference_type operator-(transform_iterator other) const { return iterator_ - other.iterator_; } ROCPRIM_HOST_DEVICE inline bool operator==(transform_iterator other) const { return iterator_ == other.iterator_; } ROCPRIM_HOST_DEVICE inline bool operator!=(transform_iterator other) const { return iterator_ != other.iterator_; } ROCPRIM_HOST_DEVICE inline bool operator<(transform_iterator other) const { return iterator_ < other.iterator_; } ROCPRIM_HOST_DEVICE inline bool operator<=(transform_iterator other) const { return iterator_ <= other.iterator_; } ROCPRIM_HOST_DEVICE inline bool operator>(transform_iterator other) const { return iterator_ > other.iterator_; } ROCPRIM_HOST_DEVICE inline bool operator>=(transform_iterator other) const { return iterator_ >= other.iterator_; } friend std::ostream& operator<<(std::ostream& os, const transform_iterator& /* iter */) { return os; } private: InputIterator iterator_; UnaryFunction transform_; }; template< class InputIterator, class UnaryFunction, class ValueType > ROCPRIM_HOST_DEVICE inline transform_iterator<InputIterator, UnaryFunction, ValueType> operator+(typename transform_iterator<InputIterator, UnaryFunction, ValueType>::difference_type distance, const transform_iterator<InputIterator, UnaryFunction, ValueType>& iterator) { return iterator + distance; } template< class InputIterator, class UnaryFunction > ROCPRIM_HOST_DEVICE inline transform_iterator<InputIterator, UnaryFunction> make_transform_iterator(InputIterator iterator, UnaryFunction transform) { return transform_iterator<InputIterator, UnaryFunction>(iterator, transform); } END_ROCPRIM_NAMESPACE #endif // ROCPRIM_ITERATOR_TRANSFORM_ITERATOR_HPP_ <commit_msg>Add docs for transform_iterator<commit_after>// 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. #ifndef ROCPRIM_ITERATOR_TRANSFORM_ITERATOR_HPP_ #define ROCPRIM_ITERATOR_TRANSFORM_ITERATOR_HPP_ #include <iterator> #include <cstddef> #include <type_traits> #include "../config.hpp" /// \addtogroup iteratormodule /// @{ BEGIN_ROCPRIM_NAMESPACE /// \class transform_iterator /// \brief A random-access input (read-only) iterator adaptor for transforming dereferenced values. /// /// \par Overview /// * A transform_iterator uses functor of type UnaryFunction to transform value obtained /// by dereferencing underlying iterator. /// * Using it for simulating a range filled with results of applying functor of type /// \p UnaryFunction to another range saves memory capacity and/or bandwidth. /// /// \tparam InputIterator - type of the underlying random-access input iterator. Must be /// a random-access iterator. /// \tparam UnaryFunction - type of the transform functor. /// \tparam ValueType - type of value that can be obtained by dereferencing the iterator. /// By default it is the return type of \p UnaryFunction. template< class InputIterator, class UnaryFunction, #if defined(__cpp_lib_is_invocable) && !defined(DOXYGEN_SHOULD_SKIP_THIS) // C++17 class ValueType = typename std::invoke_result< UnaryFunction, typename std::iterator_traits<InputIterator>::value_type >::type #else class ValueType = typename std::result_of< UnaryFunction(typename std::iterator_traits<InputIterator>::value_type) >::type #endif > class transform_iterator { private: using input_category = typename std::iterator_traits<InputIterator>::iterator_category; static_assert( std::is_same<input_category, std::random_access_iterator_tag>::value, "InputIterator must be a random-access iterator" ); public: /// The type of the value that can be obtained by dereferencing the iterator. using value_type = ValueType; /// \brief A reference type of the type iterated over (\p value_type). /// It's `const` since transform_iterator is a read-only iterator. using reference = const value_type&; /// \brief A pointer type of the type iterated over (\p value_type). /// It's `const` since transform_iterator is a read-only iterator. using pointer = const value_type*; /// A type used for identify distance between iterators. using difference_type = typename std::iterator_traits<InputIterator>::difference_type; /// The category of the iterator. using iterator_category = std::random_access_iterator_tag; /// The type of unary function used to transform input range. using unary_function = UnaryFunction; #ifndef DOXYGEN_SHOULD_SKIP_THIS using self_type = transform_iterator; #endif ROCPRIM_HOST_DEVICE inline ~transform_iterator() = default; /// \brief Creates a new transform_iterator. /// /// \param iterator input iterator to iterate over and transform. /// \param transform unary function used to transform values obtained /// from range pointed by \p iterator. ROCPRIM_HOST_DEVICE inline transform_iterator(InputIterator iterator, UnaryFunction transform) : iterator_(iterator), transform_(transform) { } ROCPRIM_HOST_DEVICE inline transform_iterator& operator++() { iterator_++; return *this; } ROCPRIM_HOST_DEVICE inline transform_iterator operator++(int) { transform_iterator old = *this; iterator_++; return old; } ROCPRIM_HOST_DEVICE inline value_type operator*() const { return transform_(*iterator_); } ROCPRIM_HOST_DEVICE inline pointer operator->() const { return &(*(*this)); } ROCPRIM_HOST_DEVICE inline value_type operator[](difference_type distance) const { transform_iterator i = (*this) + distance; return *i; } ROCPRIM_HOST_DEVICE inline transform_iterator operator+(difference_type distance) const { return transform_iterator(iterator_ + distance, transform_); } ROCPRIM_HOST_DEVICE inline transform_iterator& operator+=(difference_type distance) { iterator_ += distance; return *this; } ROCPRIM_HOST_DEVICE inline transform_iterator operator-(difference_type distance) const { return transform_iterator(iterator_ - distance, transform_); } ROCPRIM_HOST_DEVICE inline transform_iterator& operator-=(difference_type distance) { iterator_ -= distance; return *this; } ROCPRIM_HOST_DEVICE inline difference_type operator-(transform_iterator other) const { return iterator_ - other.iterator_; } ROCPRIM_HOST_DEVICE inline bool operator==(transform_iterator other) const { return iterator_ == other.iterator_; } ROCPRIM_HOST_DEVICE inline bool operator!=(transform_iterator other) const { return iterator_ != other.iterator_; } ROCPRIM_HOST_DEVICE inline bool operator<(transform_iterator other) const { return iterator_ < other.iterator_; } ROCPRIM_HOST_DEVICE inline bool operator<=(transform_iterator other) const { return iterator_ <= other.iterator_; } ROCPRIM_HOST_DEVICE inline bool operator>(transform_iterator other) const { return iterator_ > other.iterator_; } ROCPRIM_HOST_DEVICE inline bool operator>=(transform_iterator other) const { return iterator_ >= other.iterator_; } friend std::ostream& operator<<(std::ostream& os, const transform_iterator& /* iter */) { return os; } private: InputIterator iterator_; UnaryFunction transform_; }; template< class InputIterator, class UnaryFunction, class ValueType > ROCPRIM_HOST_DEVICE inline transform_iterator<InputIterator, UnaryFunction, ValueType> operator+(typename transform_iterator<InputIterator, UnaryFunction, ValueType>::difference_type distance, const transform_iterator<InputIterator, UnaryFunction, ValueType>& iterator) { return iterator + distance; } /// make_transform_iterator creates a transform_iterator using \p iterator as /// the underlying iterator and \p transform as the unary function. /// /// \tparam InputIterator - type of the underlying random-access input iterator. /// \tparam UnaryFunction - type of the transform functor. /// /// \param iterator - input iterator. /// \param transform - transform functor to use in created transform_iterator. /// \return A new transform_iterator object which transforms the range pointed /// by \p iterator using \p transform functor. template< class InputIterator, class UnaryFunction > ROCPRIM_HOST_DEVICE inline transform_iterator<InputIterator, UnaryFunction> make_transform_iterator(InputIterator iterator, UnaryFunction transform) { return transform_iterator<InputIterator, UnaryFunction>(iterator, transform); } /// @} // end of group iteratormodule END_ROCPRIM_NAMESPACE #endif // ROCPRIM_ITERATOR_TRANSFORM_ITERATOR_HPP_ <|endoftext|>
<commit_before>// // Created by Ivan Shynkarenka on 09.07.2015. // #include "catch.hpp" #include "benchmark/environment.h" using namespace CppBenchmark; TEST_CASE("Environment information", "[CppBenchmark][Environment]") { REQUIRE((Environment::Is32BitOS() || Environment::Is64BitOS())); REQUIRE((Environment::Is32BitProcess() || Environment::Is64BitProcess())); REQUIRE((Environment::IsDebug() || Environment::IsRelease())); REQUIRE((Environment::IsBigEndian() || Environment::IsLittleEndian())); REQUIRE(Environment::OSVersion().length() > 0); REQUIRE(Environment::Timestamp() > 0); } <commit_msg>Tests<commit_after>// // Created by Ivan Shynkarenka on 09.07.2015. // #include "catch.hpp" #include "benchmark/environment.h" using namespace CppBenchmark; TEST_CASE("Environment information", "[CppBenchmark][Environment]") { REQUIRE((Environment::Is32BitOS() || Environment::Is64BitOS())); REQUIRE((Environment::Is32BitProcess() || Environment::Is64BitProcess())); REQUIRE((Environment::IsDebug() || Environment::IsRelease())); REQUIRE((Environment::IsBigEndian() || Environment::IsLittleEndian())); REQUIRE(Environment::OSVersion().length() > 0); REQUIRE(Environment::EndLine().length() > 0); REQUIRE(Environment::Timestamp() > 0); } <|endoftext|>
<commit_before>/*! \brief serial_controller_node. * Manages serial communications with AVR-Master. * * This node manages serial communications with the AVR-Master. * Therefore it first requests all data from AVR-Master and then sends all * commands to AVR-Master in a Loop. Data read is stored in md49_data.txt, * commands to be send are read from md49_commands.txt. * */ // Includes // ********************************************************* #include <iostream> /* allows to perform standard input and output operations */ #include <fstream> /* Input/output stream class to operate on files. */ #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ #include <ctype.h> /* isxxx() */ #include<ros/ros.h> // Global variables const char* serialport_name="/dev/ttyAMA0"; /* defines used serialport */ int serialport_bps=B38400; /* defines used baudrate on serialport */ //int filedesc; // File descriptor of serial port we will talk to int fd; /* serial port file descriptor */ int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ unsigned char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */ unsigned char serialBuffer[16]; /* Serial buffer to store uart data */ unsigned char md49_data[18]; /* keeps data from MD49, read from AVR-Master */ struct termios orig; // Port options using namespace std; // Declare functions // ********************************************************* int openSerialPort(const char * device, int bps); void writeBytes(int descriptor, int count); void readBytes(int descriptor, int count); void read_MD49_Data_serial (void); void read_md49_commands_txt(void); void set_MD49_speed (unsigned char speed_l, unsigned char speed_r); char* itoa(int value, char* result, int base); int main( int argc, char* argv[] ){ ros::init(argc, argv, "serial_controller"); ros::NodeHandle n; // Open serial port // **************** fd = openSerialPort("/dev/ttyAMA0", serialport_bps); if (fd == -1) exit(1); //ROS_INFO("Opend serial port at %s with %i Bps",serialport_name,serialport_bps); usleep(10000); // Sleep for UART to power up and set options ROS_DEBUG("Starting Mainloop..."); ROS_DEBUG("reading data from MD49 and pushing commands to MD49 @ 10Hz..."); while( 1 ){ // Read encoder and other data from MD49 // serial. Data ist stored in md49_data.txt // **************************************** read_MD49_Data_serial(); usleep(50000); // Read commands from md49_commands.txt: // ************************************* read_md49_commands_txt(); // Set speed and other commands as // read from md49_commands.txt // ************************************ set_MD49_speed(speed_l, speed_r); usleep(50000); }// end.mainloop return 1; } // end.main void read_MD49_Data_serial (void){ serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen writeBytes(fd, 1); //Daten lesen und in Array schreiben readBytes(fd, 18); ofstream myfile; myfile.open ("md49_data.txt"); //myfile << "Writing this to a file.\n"; char buffer[33]; // Put toghether encoder values from their // corresponding bytes, read from MD49 // *************************************** EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); // write read data from MD49 into md49_data.txt // ******************************************** int i=0; for (i=0;i<18;i++){ if (serialBuffer[i]==0){ myfile << "000"; } else if (serialBuffer[i]<10){ myfile << "00"; myfile << itoa(serialBuffer[i],buffer,10); } else if (serialBuffer[i]<100){ myfile << "0"; myfile << itoa(serialBuffer[i],buffer,10); } else{ myfile << itoa(serialBuffer[i],buffer,10); } myfile << "\n"; } printf("\033[2J"); /* clear the screen */ printf("\033[H"); /* position cursor at top-left corner */ printf ("MD49-Data read from AVR-Master: \n"); printf("========================================\n"); printf("Encoder1 Byte1: %i ",serialBuffer[0]); printf("Byte2: %i ",serialBuffer[1]); printf("Byte3: % i ",serialBuffer[2]); printf("Byte4: %i \n",serialBuffer[3]); printf("Encoder2 Byte1: %i ",serialBuffer[4]); printf("Byte2: %i ",serialBuffer[5]); printf("Byte3: %i ",serialBuffer[6]); printf("Byte4: %i \n",serialBuffer[7]); printf("EncoderL: %i ",EncoderL); printf("EncoderR: %i \n",EncoderR); printf("========================================\n"); printf("Speed1: %i ",serialBuffer[8]); printf("Speed2: %i \n",serialBuffer[9]); printf("Volts: %i \n",serialBuffer[10]); printf("Current1: %i ",serialBuffer[11]); printf("Current2: %i \n",serialBuffer[12]); printf("Error: %i \n",serialBuffer[13]); printf("Acceleration: %i \n",serialBuffer[14]); printf("Mode: %i \n",serialBuffer[15]); printf("Regulator: %i \n",serialBuffer[16]); printf("Timeout: %i \n",serialBuffer[17]); printf("speed_l = %i \n",speed_l); printf("speed_r = %i \n",speed_r); myfile.close(); } void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = speed_l; // set speed1 serialBuffer[3] = speed_r; // set speed2 writeBytes(fd, 4); } void read_md49_commands_txt(void){ string line; ifstream myfile ("md49_commands.txt"); if (myfile.is_open()) { int i=0; while ( getline (myfile,line) ) { //cout << line << '\n'; char data[10]; std::copy(line.begin(), line.end(), data); md49_data[i]=atoi(data); i =i++; } myfile.close(); speed_l=md49_data[0]; speed_r=md49_data[1]; } else cout << "Unable to open file"; } int openSerialPort(const char * device, int bps){ struct termios neu; char buf[128]; //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); fd = open(device, O_RDWR | O_NOCTTY); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcflush(fd, TCIFLUSH); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } } void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } char* itoa(int value, char* result, int base) { // check that the base if valid if (base < 2 || base > 36) { *result = '\0'; return result; } char* ptr = result, *ptr1 = result, tmp_char; int tmp_value; do { tmp_value = value; value /= base; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)]; } while ( value ); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while(ptr1 < ptr) { tmp_char = *ptr; *ptr--= *ptr1; *ptr1++ = tmp_char; } return result; } <commit_msg>Update code<commit_after>/*! \brief serial_controller_node. * Manages serial communications with AVR-Master. * * This node manages serial communications with the AVR-Master. * Therefore it first requests all data from AVR-Master and then sends all * commands to AVR-Master in a Loop. Data read is stored in md49_data.txt, * commands to be send are read from md49_commands.txt. * */ // Includes // ********************************************************* #include <iostream> /* allows to perform standard input and output operations */ #include <fstream> /* Input/output stream class to operate on files. */ #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ #include <ctype.h> /* isxxx() */ #include<ros/ros.h> // Global variables const char* serialport_name="/dev/ttyAMA0"; /* defines used serialport */ int serialport_bps=B38400; /* defines used baudrate on serialport */ //int filedesc; // File descriptor of serial port we will talk to int fd; /* serial port file descriptor */ int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ unsigned char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */ unsigned char serialBuffer[16]; /* Serial buffer to store uart data */ unsigned char md49_data[18]; /* keeps data from MD49, read from AVR-Master */ struct termios orig; // Port options using namespace std; // Declare functions // ********************************************************* int openSerialPort(const char * device, int bps); void writeBytes(int descriptor, int count); void readBytes(int descriptor, int count); void read_MD49_Data_serial (void); void read_md49_commands_txt(void); void set_MD49_speed (unsigned char speed_l, unsigned char speed_r); char* itoa(int value, char* result, int base); int main( int argc, char* argv[] ){ ros::init(argc, argv, "serial_controller"); ros::NodeHandle n; // Open serial port // **************** fd = openSerialPort("/dev/ttyAMA0", serialport_bps); if (fd == -1) exit(1); //ROS_INFO("Opend serial port at %s with %i Bps",serialport_name,serialport_bps); usleep(10000); // Sleep for UART to power up and set options ROS_DEBUG("Starting Mainloop..."); ROS_DEBUG("reading data from MD49 and pushing commands to MD49 @ 10Hz..."); while( n.ok() ){ // Read encoder and other data from MD49 // serial. Data ist stored in md49_data.txt // **************************************** read_MD49_Data_serial(); usleep(50000); // Read commands from md49_commands.txt: // ************************************* read_md49_commands_txt(); // Set speed and other commands as // read from md49_commands.txt // ************************************ set_MD49_speed(speed_l, speed_r); usleep(50000); }// end.mainloop return 1; } // end.main void read_MD49_Data_serial (void){ serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen writeBytes(fd, 1); //Daten lesen und in Array schreiben readBytes(fd, 18); ofstream myfile; myfile.open ("md49_data.txt"); //myfile << "Writing this to a file.\n"; char buffer[33]; // Put toghether encoder values from their // corresponding bytes, read from MD49 // *************************************** EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); // write read data from MD49 into md49_data.txt // ******************************************** int i=0; for (i=0;i<18;i++){ if (serialBuffer[i]==0){ myfile << "000"; } else if (serialBuffer[i]<10){ myfile << "00"; myfile << itoa(serialBuffer[i],buffer,10); } else if (serialBuffer[i]<100){ myfile << "0"; myfile << itoa(serialBuffer[i],buffer,10); } else{ myfile << itoa(serialBuffer[i],buffer,10); } myfile << "\n"; } printf("\033[2J"); /* clear the screen */ printf("\033[H"); /* position cursor at top-left corner */ printf ("MD49-Data read from AVR-Master: \n"); printf("========================================\n"); printf("Encoder1 Byte1: %i ",serialBuffer[0]); printf("Byte2: %i ",serialBuffer[1]); printf("Byte3: % i ",serialBuffer[2]); printf("Byte4: %i \n",serialBuffer[3]); printf("Encoder2 Byte1: %i ",serialBuffer[4]); printf("Byte2: %i ",serialBuffer[5]); printf("Byte3: %i ",serialBuffer[6]); printf("Byte4: %i \n",serialBuffer[7]); printf("EncoderL: %i ",EncoderL); printf("EncoderR: %i \n",EncoderR); printf("========================================\n"); printf("Speed1: %i ",serialBuffer[8]); printf("Speed2: %i \n",serialBuffer[9]); printf("Volts: %i \n",serialBuffer[10]); printf("Current1: %i ",serialBuffer[11]); printf("Current2: %i \n",serialBuffer[12]); printf("Error: %i \n",serialBuffer[13]); printf("Acceleration: %i \n",serialBuffer[14]); printf("Mode: %i \n",serialBuffer[15]); printf("Regulator: %i \n",serialBuffer[16]); printf("Timeout: %i \n",serialBuffer[17]); printf("speed_l = %i \n",speed_l); printf("speed_r = %i \n",speed_r); myfile.close(); } void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = speed_l; // set speed1 serialBuffer[3] = speed_r; // set speed2 writeBytes(fd, 4); } void read_md49_commands_txt(void){ string line; ifstream myfile ("md49_commands.txt"); if (myfile.is_open()) { int i=0; while ( getline (myfile,line) ) { //cout << line << '\n'; char data[10]; std::copy(line.begin(), line.end(), data); md49_data[i]=atoi(data); i =i++; } myfile.close(); speed_l=md49_data[0]; speed_r=md49_data[1]; } else cout << "Unable to open file"; } int openSerialPort(const char * device, int bps){ struct termios neu; char buf[128]; //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); fd = open(device, O_RDWR | O_NOCTTY); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcflush(fd, TCIFLUSH); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } } void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } char* itoa(int value, char* result, int base) { // check that the base if valid if (base < 2 || base > 36) { *result = '\0'; return result; } char* ptr = result, *ptr1 = result, tmp_char; int tmp_value; do { tmp_value = value; value /= base; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)]; } while ( value ); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while(ptr1 < ptr) { tmp_char = *ptr; *ptr--= *ptr1; *ptr1++ = tmp_char; } return result; } <|endoftext|>
<commit_before>/*! \brief serial_controller_node. * Manages serial communications with AVR-Master. * * This node manages serial communications with the AVR-Master. * Therefore it first requests all data from AVR-Master and then sends all * commands to AVR-Master in a Loop. Data read is stored in md49_data.txt, * commands to be send are read from md49_commands.txt. * */ // Includes // ********************************************************* #include <iostream> /* allows to perform standard input and output operations */ //#include <fstream> /* Input/output stream class to operate on files. */ #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ //#include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ //#include <ctype.h> /* isxxx() */ //#include<ros/ros.h> #include <sqlite3.h> // switched to experimental, MD49 is now directly connected to RPi // All AVR- Boards discarded for the moment // Global variables const char* serialport_name="//dev/ttyS2"; /* defines used serialport on BPi. Use "/dev/ttyAMA0" for RPi*/ int serialport_bps=B9600; /* defines used baudrate on serialport */ //int filedesc; /* File descriptor of serial port we will talk to*/ int fd; /* serial port file descriptor */ int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ unsigned char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */ unsigned char serialBuffer[16]; /* Serial buffer to store uart data */ struct termios orig; // backuped port options // sqlite globals sqlite3 *db; char *zErrMsg = 0; int rc; const char *sql; const char* data = "Callback function called"; using namespace std; // Declare functions // ********************************************************* int openSerialPort(const char * device, int bps); void writeBytes(int descriptor, int count); void readBytes(int descriptor, int count); void open_sqlite_db_md49data(void); static int sql_callback(void *data, int argc, char **argv, char **azColName); void read_MD49_Data_serial (void); void read_md49_commands(void); void set_MD49_speed (unsigned char speed_l, unsigned char speed_r); int main( int argc, char* argv[] ){ // Init as ROS node // **************** //ros::init(argc, argv, "serial_controller"); //ros::NodeHandle n; // Open sqlite database md49data.db // ******************************** open_sqlite_db_md49data(); // Open serial port // **************** fd = openSerialPort(serialport_name, serialport_bps); if (fd == -1) exit(1); //ROS_INFO("Opend serial port at %s with %i Bps",serialport_name,serialport_bps); usleep(10000); // Sleep for UART to power up and set options //ROS_DEBUG("Starting Mainloop..."); //ROS_DEBUG("reading data from MD49 and pushing commands to MD49 @ 5Hz..."); // Mainloop // *********************************** //while( n.ok() ){ while( 1 ){ // Read encodervalues and other data from MD49 // serial. Data ist stored in md49_data.txt // **************************************** read_MD49_Data_serial(); usleep(200000); // Read commands from md49_commands.txt: // ************************************* read_md49_commands(); // Set speed and other commands as // read from md49_commands.txt // ******************************* if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){ set_MD49_speed(speed_l, speed_r); last_speed_l=speed_l; last_speed_r=speed_r; } usleep(200000); }// end.mainloop sqlite3_close(db); return 1; } // end.main void read_MD49_Data_serial (void){ // Read serial MD49 encoder data from AVR-Master // ********************************************* serialBuffer[0] = 0; serialBuffer[1] = 0x25; // Command to return encoder values writeBytes(fd, 2); readBytes(fd, 8); // Put toghether encoder values from their // corresponding bytes, read from MD49 // *************************************** EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); // Write data read from MD49 into // sqlite3 database md49data.db // ****************************** char sql_buffer[400]; int cx; // EncoderL & EncoderR cx = snprintf (sql_buffer,400,"UPDATE md49data SET EncoderL=%i, EncoderR=%i WHERE ID=1;", EncoderL, EncoderR); rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL message: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ //fprintf(stdout, "Operation done successfully\n"); } // Encoderbytes 1-4 left cx = snprintf (sql_buffer,400,"UPDATE md49data SET Encoderbyte1L=%i, Encoderbyte2L=%i, " \ "Encoderbyte3L=%i, Encoderbyte4L=%i WHERE ID=1;", serialBuffer[0], serialBuffer[1], serialBuffer[2], serialBuffer[3]); rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL message: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ //fprintf(stdout, "Operation done successfully\n"); } // Encoderbytes 1-4 right cx = snprintf (sql_buffer,400,"UPDATE md49data SET Encoderbyte1R=%i, Encoderbyte2R=%i, " \ "Encoderbyte3R=%i, Encoderbyte4R=%i WHERE ID=1;", serialBuffer[4], serialBuffer[5], serialBuffer[6], serialBuffer[7]); rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL message: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ //fprintf(stdout, "Operation done successfully\n"); } /* // SpeedL, SpeedR, Volts, CurrentL, CurrentR, Error, Acceleration, Mode, Regulator, Timeout cx = snprintf (sql_buffer,400,"UPDATE md49data SET SpeedL=%i, SpeedR=%i, " \ "Volts=%i, CurrentL=%i, CurrentR=%i, Error=%i, Acceleration=%i, Mode=%i, " \ "Regulator=%i, Timeout=%i " \ "WHERE ID=1;", serialBuffer[8], serialBuffer[9], serialBuffer[10], serialBuffer[11], serialBuffer[12], serialBuffer[13], serialBuffer[14], serialBuffer[15], serialBuffer[16], serialBuffer[17]); rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL message: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ //fprintf(stdout, "Operation done successfully\n"); } */ // Output MD49 data on screen // ************************** printf("\033[2J"); // clear the screen printf("\033[H"); // position cursor at top-left corner printf ("MD49-Data read from AVR-Master: \n"); printf("========================================\n"); printf("Encoder1 Byte1: %i ",serialBuffer[0]); printf("Byte2: %i ",serialBuffer[1]); printf("Byte3: % i ",serialBuffer[2]); printf("Byte4: %i \n",serialBuffer[3]); printf("Encoder2 Byte1: %i ",serialBuffer[4]); printf("Byte2: %i ",serialBuffer[5]); printf("Byte3: %i ",serialBuffer[6]); printf("Byte4: %i \n",serialBuffer[7]); printf("EncoderL: %i ",EncoderL); printf("EncoderR: %i \n",EncoderR); printf("========================================\n"); //printf("SpeedL: %i ",serialBuffer[8]); //printf("SpeedR: %i \n",serialBuffer[9]); //printf("Volts: %i \n",serialBuffer[10]); //printf("CurrentL: %i ",serialBuffer[11]); //printf("CurrentR: %i \n",serialBuffer[12]); //printf("Error: %i \n",serialBuffer[13]); //printf("Acceleration: %i \n",serialBuffer[14]); //printf("Mode: %i \n",serialBuffer[15]); //printf("Regulator: %i \n",serialBuffer[16]); //printf("Timeout: %i \n",serialBuffer[17]); } // Write serial command to change left and right speed // *************************************************** void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){ serialBuffer[0] = 0; serialBuffer[1] = 0x31; // Command to set motor speed serialBuffer[2] = speed_l; // Speed to be set serialBuffer[3] = 0; serialBuffer[4] = 0x32; serialBuffer[5] = speed_r; writeBytes(fd, 6); } // Read SpeedL and SpeedR from // table md49commands(md49data.db) // ******************************* void read_md49_commands(void){ // Create SQL statement sql = "SELECT * from md49commands WHERE ID=1"; // Execute SQL statement rc = sqlite3_exec(db, sql, sql_callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL message: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ //fprintf(stdout, "Query done successfully\n"); } } // Open serialport // *************** int openSerialPort(const char * device, int bps){ struct termios neu; char buf[128]; //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); fd = open(device, O_RDWR | O_NOCTTY); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcflush(fd, TCIFLUSH); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } // Write bytes serial to UART // ************************** void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } } // Read bytes serial from UART // *************************** void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } // Open sqlite db md49data.db and create // table md49data if not existing // ************************************* void open_sqlite_db_md49data(void){ // Open database md49data.db and add table md49data // ************************************************ rc = sqlite3_open("data/md49data.db", &db); if( rc ){ fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); exit(0); }else{ fprintf(stdout, "Opened database successfully,\n"); } // Create table md49data // ********************* sql = "CREATE TABLE md49data(" \ "ID INT PRIMARY KEY NOT NULL," \ "Encoderbyte1L INT DEFAULT 0, Encoderbyte2L INT DEFAULT 0," \ "Encoderbyte3L INT DEFAULT 0, Encoderbyte4L INT DEFAULT 0," \ "Encoderbyte1R INT DEFAULT 0, Encoderbyte2R INT DEFAULT 0," \ "Encoderbyte3R INT DEFAULT 0, Encoderbyte4R INT DEFAULT 0," \ "EncoderL INT DEFAULT 0, EncoderR INT DEFAULT 0," \ "SpeedL INT DEFAULT 0, SpeedR INT DEFAULT 0," \ "Volts INT DEFAULT 0," \ "CurrentL INT DEFAULT 0, CurrentR INT DEFAULT 0," \ "Error INT DEFAULT 0, Acceleration INT DEFAULT 0," \ "Mode INT DEFAULT 0, Regulator INT DEFAULT 0," \ "Timeout INT DEFAULT 0 );" \ "INSERT INTO md49data (ID) VALUES (1);"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, NULL, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL message: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ fprintf(stdout, "table created successfully\n"); } } // Callbackfunction executed if table md49commands in md49data.db is queried // ************************************************************************* static int sql_callback(void *data, int argc, char **argv, char **azColName){ speed_l= atoi(argv[1]); speed_r= atoi(argv[2]); return 0; } <commit_msg>Update code<commit_after>/*! \brief serial_controller_node. * Manages serial communications with AVR-Master. * * This node manages serial communications with the AVR-Master. * Therefore it first requests all data from AVR-Master and then sends all * commands to AVR-Master in a Loop. Data read is stored in md49_data.txt, * commands to be send are read from md49_commands.txt. * */ // Includes // ********************************************************* #include <iostream> /* allows to perform standard input and output operations */ //#include <fstream> /* Input/output stream class to operate on files. */ #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ //#include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ //#include <ctype.h> /* isxxx() */ //#include<ros/ros.h> #include <sqlite3.h> // switched to experimental, MD49 is now directly connected to RPi // All AVR- Boards discarded for the moment // Global variables const char* serialport_name="/dev/ttyS2"; /* defines used serialport on BPi. Use "/dev/ttyAMA0" for RPi*/ int serialport_bps=B9600; /* defines used baudrate on serialport */ //int filedesc; /* File descriptor of serial port we will talk to*/ int fd; /* serial port file descriptor */ int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ unsigned char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */ unsigned char serialBuffer[16]; /* Serial buffer to store uart data */ struct termios orig; // backuped port options // sqlite globals sqlite3 *db; char *zErrMsg = 0; int rc; const char *sql; const char* data = "Callback function called"; using namespace std; // Declare functions // ********************************************************* int openSerialPort(const char * device, int bps); void writeBytes(int descriptor, int count); void readBytes(int descriptor, int count); void open_sqlite_db_md49data(void); static int sql_callback(void *data, int argc, char **argv, char **azColName); void read_MD49_Data_serial (void); void read_md49_commands(void); void set_MD49_speed (unsigned char speed_l, unsigned char speed_r); int main( int argc, char* argv[] ){ // Init as ROS node // **************** //ros::init(argc, argv, "serial_controller"); //ros::NodeHandle n; // Open sqlite database md49data.db // ******************************** open_sqlite_db_md49data(); // Open serial port // **************** fd = openSerialPort(serialport_name, serialport_bps); if (fd == -1) exit(1); //ROS_INFO("Opend serial port at %s with %i Bps",serialport_name,serialport_bps); usleep(10000); // Sleep for UART to power up and set options //ROS_DEBUG("Starting Mainloop..."); //ROS_DEBUG("reading data from MD49 and pushing commands to MD49 @ 5Hz..."); // Mainloop // *********************************** //while( n.ok() ){ while( 1 ){ // Read encodervalues and other data from MD49 // serial. Data ist stored in md49_data.txt // **************************************** read_MD49_Data_serial(); usleep(200000); // Read commands from md49_commands.txt: // ************************************* read_md49_commands(); // Set speed and other commands as // read from md49_commands.txt // ******************************* if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){ set_MD49_speed(speed_l, speed_r); last_speed_l=speed_l; last_speed_r=speed_r; } usleep(200000); }// end.mainloop sqlite3_close(db); return 1; } // end.main void read_MD49_Data_serial (void){ // Read serial MD49 encoder data from AVR-Master // ********************************************* printf("read serial data"); serialBuffer[0] = 0; serialBuffer[1] = 0x25; // Command to return encoder values writeBytes(fd, 2); readBytes(fd, 8); // Put toghether encoder values from their // corresponding bytes, read from MD49 // *************************************** EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); // Write data read from MD49 into // sqlite3 database md49data.db // ****************************** char sql_buffer[400]; int cx; // EncoderL & EncoderR cx = snprintf (sql_buffer,400,"UPDATE md49data SET EncoderL=%i, EncoderR=%i WHERE ID=1;", EncoderL, EncoderR); rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL message: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ //fprintf(stdout, "Operation done successfully\n"); } // Encoderbytes 1-4 left cx = snprintf (sql_buffer,400,"UPDATE md49data SET Encoderbyte1L=%i, Encoderbyte2L=%i, " \ "Encoderbyte3L=%i, Encoderbyte4L=%i WHERE ID=1;", serialBuffer[0], serialBuffer[1], serialBuffer[2], serialBuffer[3]); rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL message: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ //fprintf(stdout, "Operation done successfully\n"); } // Encoderbytes 1-4 right cx = snprintf (sql_buffer,400,"UPDATE md49data SET Encoderbyte1R=%i, Encoderbyte2R=%i, " \ "Encoderbyte3R=%i, Encoderbyte4R=%i WHERE ID=1;", serialBuffer[4], serialBuffer[5], serialBuffer[6], serialBuffer[7]); rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL message: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ //fprintf(stdout, "Operation done successfully\n"); } /* // SpeedL, SpeedR, Volts, CurrentL, CurrentR, Error, Acceleration, Mode, Regulator, Timeout cx = snprintf (sql_buffer,400,"UPDATE md49data SET SpeedL=%i, SpeedR=%i, " \ "Volts=%i, CurrentL=%i, CurrentR=%i, Error=%i, Acceleration=%i, Mode=%i, " \ "Regulator=%i, Timeout=%i " \ "WHERE ID=1;", serialBuffer[8], serialBuffer[9], serialBuffer[10], serialBuffer[11], serialBuffer[12], serialBuffer[13], serialBuffer[14], serialBuffer[15], serialBuffer[16], serialBuffer[17]); rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL message: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ //fprintf(stdout, "Operation done successfully\n"); } */ // Output MD49 data on screen // ************************** printf("\033[2J"); // clear the screen printf("\033[H"); // position cursor at top-left corner printf ("MD49-Data read from AVR-Master: \n"); printf("========================================\n"); printf("Encoder1 Byte1: %i ",serialBuffer[0]); printf("Byte2: %i ",serialBuffer[1]); printf("Byte3: % i ",serialBuffer[2]); printf("Byte4: %i \n",serialBuffer[3]); printf("Encoder2 Byte1: %i ",serialBuffer[4]); printf("Byte2: %i ",serialBuffer[5]); printf("Byte3: %i ",serialBuffer[6]); printf("Byte4: %i \n",serialBuffer[7]); printf("EncoderL: %i ",EncoderL); printf("EncoderR: %i \n",EncoderR); printf("========================================\n"); //printf("SpeedL: %i ",serialBuffer[8]); //printf("SpeedR: %i \n",serialBuffer[9]); //printf("Volts: %i \n",serialBuffer[10]); //printf("CurrentL: %i ",serialBuffer[11]); //printf("CurrentR: %i \n",serialBuffer[12]); //printf("Error: %i \n",serialBuffer[13]); //printf("Acceleration: %i \n",serialBuffer[14]); //printf("Mode: %i \n",serialBuffer[15]); //printf("Regulator: %i \n",serialBuffer[16]); //printf("Timeout: %i \n",serialBuffer[17]); } // Write serial command to change left and right speed // *************************************************** void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){ serialBuffer[0] = 0; serialBuffer[1] = 0x31; // Command to set motor speed serialBuffer[2] = speed_l; // Speed to be set serialBuffer[3] = 0; serialBuffer[4] = 0x32; serialBuffer[5] = speed_r; writeBytes(fd, 6); } // Read SpeedL and SpeedR from // table md49commands(md49data.db) // ******************************* void read_md49_commands(void){ // Create SQL statement sql = "SELECT * from md49commands WHERE ID=1"; // Execute SQL statement rc = sqlite3_exec(db, sql, sql_callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL message: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ //fprintf(stdout, "Query done successfully\n"); } } // Open serialport // *************** int openSerialPort(const char * device, int bps){ struct termios neu; char buf[128]; //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); fd = open(device, O_RDWR | O_NOCTTY); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcflush(fd, TCIFLUSH); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } // Write bytes serial to UART // ************************** void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } } // Read bytes serial from UART // *************************** void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } // Open sqlite db md49data.db and create // table md49data if not existing // ************************************* void open_sqlite_db_md49data(void){ // Open database md49data.db and add table md49data // ************************************************ rc = sqlite3_open("data/md49data.db", &db); if( rc ){ fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); exit(0); }else{ fprintf(stdout, "Opened database successfully,\n"); } // Create table md49data // ********************* sql = "CREATE TABLE md49data(" \ "ID INT PRIMARY KEY NOT NULL," \ "Encoderbyte1L INT DEFAULT 0, Encoderbyte2L INT DEFAULT 0," \ "Encoderbyte3L INT DEFAULT 0, Encoderbyte4L INT DEFAULT 0," \ "Encoderbyte1R INT DEFAULT 0, Encoderbyte2R INT DEFAULT 0," \ "Encoderbyte3R INT DEFAULT 0, Encoderbyte4R INT DEFAULT 0," \ "EncoderL INT DEFAULT 0, EncoderR INT DEFAULT 0," \ "SpeedL INT DEFAULT 0, SpeedR INT DEFAULT 0," \ "Volts INT DEFAULT 0," \ "CurrentL INT DEFAULT 0, CurrentR INT DEFAULT 0," \ "Error INT DEFAULT 0, Acceleration INT DEFAULT 0," \ "Mode INT DEFAULT 0, Regulator INT DEFAULT 0," \ "Timeout INT DEFAULT 0 );" \ "INSERT INTO md49data (ID) VALUES (1);"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, NULL, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL message: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ fprintf(stdout, "table created successfully\n"); } } // Callbackfunction executed if table md49commands in md49data.db is queried // ************************************************************************* static int sql_callback(void *data, int argc, char **argv, char **azColName){ speed_l= atoi(argv[1]); speed_r= atoi(argv[2]); return 0; } <|endoftext|>
<commit_before>/* ** Author(s): ** - Cedric GESTES <gestes@aldebaran-robotics.com> ** ** Copyright (C) 2012 Aldebaran Robotics */ #include <gtest/gtest.h> #include <qi/signal.hpp> #include <qi/future.hpp> #include <qi/signalspy.hpp> #include <qi/anyobject.hpp> #include <qi/application.hpp> #include <qi/type/objecttypebuilder.hpp> #include <qi/type/dynamicobjectbuilder.hpp> qiLogCategory("test"); class Foo { public: void func(int) { } void func1(qi::Atomic<int>* r, int) { // hackish sleep so that asynchronous trigger detection is safer qi::os::msleep(1); ++*r; } void func2(qi::Atomic<int>* r, int, int) { ++*r; } }; void foo(qi::Atomic<int>* r, int, int) { ++*r; } void foo2(qi::Atomic<int>* r, char, char) { ++*r; } void foo3(qi::Atomic<int>* r, Foo *) { ++*r; } void foolast(int, qi::Promise<void> prom, qi::Atomic<int>* r) { prom.setValue(0); ++*r; } TEST(TestSignal, TestCompilation) { qi::Atomic<int> res = 0; qi::Signal<int> s; Foo* f = (Foo*)1; qi::Promise<void> prom; //do not count s.connect(qi::AnyFunction::from(&Foo::func, f)); s.connect(boost::bind<void>(&Foo::func, f, _1)); s.connect(boost::bind(&foo, &res, 12, _1)); s.connect(boost::bind(&foo2, &res, 12, _1)); s.connect(boost::bind<void>(&Foo::func1, f, &res, _1)); s.connect(boost::bind<void>(&Foo::func2, f, &res, 5, _1)); s.connect(boost::bind(&foo3, &res, f)); s.connect(boost::bind(&foolast, _1, prom, &res)); s(42); while (*res != 6) qi::os::msleep(10); ASSERT_EQ(6, *res); ASSERT_TRUE(prom.future().isFinished()); ASSERT_FALSE(prom.future().hasError()); } void write42(boost::shared_ptr<int> ptr) { *ptr = 42; } TEST(TestSignal, SharedPtr) { // Redundant with Copy test, but just to be sure, check that shared_ptr // is correctly transmited. qi::Signal<boost::shared_ptr<int> > sig; sig.connect(qi::AnyFunction::from(&write42)).setCallType(qi::MetaCallType_Queued); { boost::shared_ptr<int> ptr(new int(12)); sig(ptr); }; } void byRef(int& i, bool* done) { qiLogDebug() <<"byRef " << &i << ' ' << done; i = 12; *done = true; } TEST(TestSignal, AutoDisconnect) { // Test automatic disconnection when passing shared_ptrs qi::Atomic<int> r = 0; boost::shared_ptr<Foo> foo(new Foo()); qi::Signal<qi::Atomic<int>*, int> sig; sig.connect(&Foo::func1, boost::weak_ptr<Foo>(foo), _1, _2).setCallType(qi::MetaCallType_Direct); sig(&r, 0); ASSERT_EQ(1, *r); foo.reset(); sig(&r, 0); ASSERT_EQ(1, *r); } TEST(TestSignal, BadArity) { // Test runtime detection of arity errors qi::Signal<> s; // avoid using s.connect() which will catch the problem at compile-time EXPECT_ANY_THROW(s.connect(qi::SignalSubscriber(qi::AnyFunction::from(&foo)))); EXPECT_ANY_THROW(s.connect(qi::SignalSubscriber(qi::AnyFunction::from(&foo2)))); EXPECT_ANY_THROW(s.connect(qi::AnyFunction::from((boost::function<void(qi::Atomic<int>*, int)>)boost::bind(&Foo::func1, (Foo*)0, _1, _2)))); } void lol(int v, int& target) { target = v; } TEST(TestSignal, SignalSignal) { qi::SignalF<void (int)> sig1; qi::SignalF<void (int)> *sig2 = new qi::SignalF<void (int)>(); int res = 0; sig1.connect(*sig2); sig2->connect(boost::bind<void>(&lol, _1, boost::ref(res))); sig1(10); qi::os::msleep(300); ASSERT_EQ(10, res); // Test autodisconnect delete sig2; sig1(20); qi::os::msleep(300); ASSERT_EQ(10, res); } class SignalTest { public: SignalTest() : payload(0) {} qi::Signal<int> sig; qi::Signal<int> sig2; void callback(int val) { payload = val; } int payload; }; TEST(TestSignal, SignalSignal2) { SignalTest st; st.sig2.connect(&SignalTest::callback, boost::ref(st), _1); st.sig.connect(st.sig2); qiLogDebug() << "sigptrs are " << &st.sig << " " << &st.sig2; st.sig(4242); for (unsigned i=0; i<50 && st.payload != 4242; ++i) qi::os::msleep(20); EXPECT_EQ(st.payload, 4242); } TEST(TestSignal, SignalN) { qi::Signal<int> sig; int res = 0; sig.connect(boost::bind<void>(&lol, _1, boost::ref(res))); sig(5); qi::os::msleep(300); ASSERT_EQ(5, res); } class SigHolder { public: qi::Signal<> s0; qi::Signal<int> s1; qi::Signal<int, int> s2; void fire0() { s0();} void fire1(int i) { s1(i); } void fire2(int i, int j) { s2(i, j);} }; QI_REGISTER_OBJECT(SigHolder, s0, s1, s2, fire0, fire1, fire2); TEST(TestSignal, SignalNBind) { int res = 0; boost::shared_ptr<SigHolder> so(new SigHolder); qi::AnyObject op = qi::AnyReference::from(so).to<qi::AnyObject>(); qi::details::printMetaObject(std::cerr, op.metaObject()); op.connect("s1", (boost::function<void(int)>)boost::bind<void>(&lol, _1, boost::ref(res))); op.post("s1", 2); for (unsigned i=0; i<30 && res!=2; ++i) qi::os::msleep(10); ASSERT_EQ(2, res); so->s1(3); for (unsigned i=0; i<30 && res!=3; ++i) qi::os::msleep(10); ASSERT_EQ(3, res); so->s0.connect( boost::bind<void>(&lol, 42, boost::ref(res))); op.post("s0"); for (unsigned i=0; i<30 && res!=42; ++i) qi::os::msleep(10); ASSERT_EQ(42, res); } void foothrow() { throw 42; } TEST(TestSignal, SignalThrow) { qi::Signal<> sig; sig.connect(boost::bind<void>(&foothrow)); ASSERT_NO_THROW(sig()); qi::os::msleep(50); } void dynTest0(int& tgt) { tgt |= 1;} void dynTest1(int& tgt, int) { tgt |= 2;} void dynTest2(int& tgt, int, int) { tgt |= 4;} void dynTest3(int& tgt, int, std::string) { tgt |= 8;} void dynTestN(int& tgt, const qi::AnyArguments& a) { tgt |= 32;} qi::AnyReference dynTestN2(int& tgt, const std::vector<qi::AnyReference>& a) { tgt |= 16; return qi::AnyReference();} TEST(TestSignal, Dynamic) { qi::SignalBase s(qi::Signature("m")); int trig = 0; s.setCallType(qi::MetaCallType_Direct); s.connect((boost::function<void()>) boost::bind(&dynTest0, boost::ref(trig))); s.connect((boost::function<void(int)>) boost::bind(&dynTest1, boost::ref(trig), _1)); s.connect((boost::function<void(int, int)>) boost::bind(&dynTest2, boost::ref(trig), _1, _2)); s.connect((boost::function<void(int, std::string)>) boost::bind(&dynTest3, boost::ref(trig), _1, _2)); s.connect(qi::AnyFunction::fromDynamicFunction(boost::bind(&dynTestN2, boost::ref(trig), _1))); s.connect((boost::function<void(const qi::AnyArguments&)>)(boost::bind(&dynTestN, boost::ref(trig), _1))); int a, b; std::string c; qi::GenericFunctionParameters params; s.trigger(params); EXPECT_EQ(49, trig); params.push_back(qi::AnyReference::from(a)); trig = 0; s.trigger(params); EXPECT_EQ(50, trig); params.push_back(qi::AnyReference::from(b)); trig = 0; s.trigger(params); EXPECT_EQ(52, trig); params[1] = qi::AnyReference::from(c); trig = 0; s.trigger(params); EXPECT_EQ(56, trig); } void onSubs(boost::atomic<bool>& var, bool subs) { var = subs; } void callback(int i) {} TEST(TestSignal, OnSubscriber) { boost::atomic<bool> subscribers(false); qi::Signal<int> sig(boost::bind(onSubs, boost::ref(subscribers), _1)); ASSERT_FALSE(subscribers); qi::SignalLink l = sig.connect(&callback); ASSERT_TRUE(subscribers); ASSERT_TRUE(sig.disconnect(l)); ASSERT_FALSE(subscribers); } TEST(TestSignalSpy, Counter) { qi::Signal<int> sig; qi::SignalSpy sp(sig); QI_EMIT sig(1); QI_EMIT sig(1); qi::os::sleep(1); ASSERT_EQ(sp.getCounter(), 2); qi::DynamicObjectBuilder ob; ob.advertiseSignal("signal", &sig); qi::AnyObject obj(ob.object()); qi::SignalSpy sp2(obj, "signal"); QI_EMIT sig(1); QI_EMIT sig(1); qi::os::sleep(1); ASSERT_EQ(sp2.getCounter(), 2); } int main(int argc, char **argv) { qi::Application app(argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Signals: remove an extra ";" in tests<commit_after>/* ** Author(s): ** - Cedric GESTES <gestes@aldebaran-robotics.com> ** ** Copyright (C) 2012 Aldebaran Robotics */ #include <gtest/gtest.h> #include <qi/signal.hpp> #include <qi/future.hpp> #include <qi/signalspy.hpp> #include <qi/anyobject.hpp> #include <qi/application.hpp> #include <qi/type/objecttypebuilder.hpp> #include <qi/type/dynamicobjectbuilder.hpp> qiLogCategory("test"); class Foo { public: void func(int) { } void func1(qi::Atomic<int>* r, int) { // hackish sleep so that asynchronous trigger detection is safer qi::os::msleep(1); ++*r; } void func2(qi::Atomic<int>* r, int, int) { ++*r; } }; void foo(qi::Atomic<int>* r, int, int) { ++*r; } void foo2(qi::Atomic<int>* r, char, char) { ++*r; } void foo3(qi::Atomic<int>* r, Foo *) { ++*r; } void foolast(int, qi::Promise<void> prom, qi::Atomic<int>* r) { prom.setValue(0); ++*r; } TEST(TestSignal, TestCompilation) { qi::Atomic<int> res = 0; qi::Signal<int> s; Foo* f = (Foo*)1; qi::Promise<void> prom; //do not count s.connect(qi::AnyFunction::from(&Foo::func, f)); s.connect(boost::bind<void>(&Foo::func, f, _1)); s.connect(boost::bind(&foo, &res, 12, _1)); s.connect(boost::bind(&foo2, &res, 12, _1)); s.connect(boost::bind<void>(&Foo::func1, f, &res, _1)); s.connect(boost::bind<void>(&Foo::func2, f, &res, 5, _1)); s.connect(boost::bind(&foo3, &res, f)); s.connect(boost::bind(&foolast, _1, prom, &res)); s(42); while (*res != 6) qi::os::msleep(10); ASSERT_EQ(6, *res); ASSERT_TRUE(prom.future().isFinished()); ASSERT_FALSE(prom.future().hasError()); } void write42(boost::shared_ptr<int> ptr) { *ptr = 42; } TEST(TestSignal, SharedPtr) { // Redundant with Copy test, but just to be sure, check that shared_ptr // is correctly transmited. qi::Signal<boost::shared_ptr<int> > sig; sig.connect(qi::AnyFunction::from(&write42)).setCallType(qi::MetaCallType_Queued); { boost::shared_ptr<int> ptr(new int(12)); sig(ptr); }; } void byRef(int& i, bool* done) { qiLogDebug() <<"byRef " << &i << ' ' << done; i = 12; *done = true; } TEST(TestSignal, AutoDisconnect) { // Test automatic disconnection when passing shared_ptrs qi::Atomic<int> r = 0; boost::shared_ptr<Foo> foo(new Foo()); qi::Signal<qi::Atomic<int>*, int> sig; sig.connect(&Foo::func1, boost::weak_ptr<Foo>(foo), _1, _2).setCallType(qi::MetaCallType_Direct); sig(&r, 0); ASSERT_EQ(1, *r); foo.reset(); sig(&r, 0); ASSERT_EQ(1, *r); } TEST(TestSignal, BadArity) { // Test runtime detection of arity errors qi::Signal<> s; // avoid using s.connect() which will catch the problem at compile-time EXPECT_ANY_THROW(s.connect(qi::SignalSubscriber(qi::AnyFunction::from(&foo)))); EXPECT_ANY_THROW(s.connect(qi::SignalSubscriber(qi::AnyFunction::from(&foo2)))); EXPECT_ANY_THROW(s.connect(qi::AnyFunction::from((boost::function<void(qi::Atomic<int>*, int)>)boost::bind(&Foo::func1, (Foo*)0, _1, _2)))); } void lol(int v, int& target) { target = v; } TEST(TestSignal, SignalSignal) { qi::SignalF<void (int)> sig1; qi::SignalF<void (int)> *sig2 = new qi::SignalF<void (int)>(); int res = 0; sig1.connect(*sig2); sig2->connect(boost::bind<void>(&lol, _1, boost::ref(res))); sig1(10); qi::os::msleep(300); ASSERT_EQ(10, res); // Test autodisconnect delete sig2; sig1(20); qi::os::msleep(300); ASSERT_EQ(10, res); } class SignalTest { public: SignalTest() : payload(0) {} qi::Signal<int> sig; qi::Signal<int> sig2; void callback(int val) { payload = val; } int payload; }; TEST(TestSignal, SignalSignal2) { SignalTest st; st.sig2.connect(&SignalTest::callback, boost::ref(st), _1); st.sig.connect(st.sig2); qiLogDebug() << "sigptrs are " << &st.sig << " " << &st.sig2; st.sig(4242); for (unsigned i=0; i<50 && st.payload != 4242; ++i) qi::os::msleep(20); EXPECT_EQ(st.payload, 4242); } TEST(TestSignal, SignalN) { qi::Signal<int> sig; int res = 0; sig.connect(boost::bind<void>(&lol, _1, boost::ref(res))); sig(5); qi::os::msleep(300); ASSERT_EQ(5, res); } class SigHolder { public: qi::Signal<> s0; qi::Signal<int> s1; qi::Signal<int, int> s2; void fire0() { s0();} void fire1(int i) { s1(i); } void fire2(int i, int j) { s2(i, j);} }; QI_REGISTER_OBJECT(SigHolder, s0, s1, s2, fire0, fire1, fire2) TEST(TestSignal, SignalNBind) { int res = 0; boost::shared_ptr<SigHolder> so(new SigHolder); qi::AnyObject op = qi::AnyReference::from(so).to<qi::AnyObject>(); qi::details::printMetaObject(std::cerr, op.metaObject()); op.connect("s1", (boost::function<void(int)>)boost::bind<void>(&lol, _1, boost::ref(res))); op.post("s1", 2); for (unsigned i=0; i<30 && res!=2; ++i) qi::os::msleep(10); ASSERT_EQ(2, res); so->s1(3); for (unsigned i=0; i<30 && res!=3; ++i) qi::os::msleep(10); ASSERT_EQ(3, res); so->s0.connect( boost::bind<void>(&lol, 42, boost::ref(res))); op.post("s0"); for (unsigned i=0; i<30 && res!=42; ++i) qi::os::msleep(10); ASSERT_EQ(42, res); } void foothrow() { throw 42; } TEST(TestSignal, SignalThrow) { qi::Signal<> sig; sig.connect(boost::bind<void>(&foothrow)); ASSERT_NO_THROW(sig()); qi::os::msleep(50); } void dynTest0(int& tgt) { tgt |= 1;} void dynTest1(int& tgt, int) { tgt |= 2;} void dynTest2(int& tgt, int, int) { tgt |= 4;} void dynTest3(int& tgt, int, std::string) { tgt |= 8;} void dynTestN(int& tgt, const qi::AnyArguments& a) { tgt |= 32;} qi::AnyReference dynTestN2(int& tgt, const std::vector<qi::AnyReference>& a) { tgt |= 16; return qi::AnyReference();} TEST(TestSignal, Dynamic) { qi::SignalBase s(qi::Signature("m")); int trig = 0; s.setCallType(qi::MetaCallType_Direct); s.connect((boost::function<void()>) boost::bind(&dynTest0, boost::ref(trig))); s.connect((boost::function<void(int)>) boost::bind(&dynTest1, boost::ref(trig), _1)); s.connect((boost::function<void(int, int)>) boost::bind(&dynTest2, boost::ref(trig), _1, _2)); s.connect((boost::function<void(int, std::string)>) boost::bind(&dynTest3, boost::ref(trig), _1, _2)); s.connect(qi::AnyFunction::fromDynamicFunction(boost::bind(&dynTestN2, boost::ref(trig), _1))); s.connect((boost::function<void(const qi::AnyArguments&)>)(boost::bind(&dynTestN, boost::ref(trig), _1))); int a, b; std::string c; qi::GenericFunctionParameters params; s.trigger(params); EXPECT_EQ(49, trig); params.push_back(qi::AnyReference::from(a)); trig = 0; s.trigger(params); EXPECT_EQ(50, trig); params.push_back(qi::AnyReference::from(b)); trig = 0; s.trigger(params); EXPECT_EQ(52, trig); params[1] = qi::AnyReference::from(c); trig = 0; s.trigger(params); EXPECT_EQ(56, trig); } void onSubs(boost::atomic<bool>& var, bool subs) { var = subs; } void callback(int i) {} TEST(TestSignal, OnSubscriber) { boost::atomic<bool> subscribers(false); qi::Signal<int> sig(boost::bind(onSubs, boost::ref(subscribers), _1)); ASSERT_FALSE(subscribers); qi::SignalLink l = sig.connect(&callback); ASSERT_TRUE(subscribers); ASSERT_TRUE(sig.disconnect(l)); ASSERT_FALSE(subscribers); } TEST(TestSignalSpy, Counter) { qi::Signal<int> sig; qi::SignalSpy sp(sig); QI_EMIT sig(1); QI_EMIT sig(1); qi::os::sleep(1); ASSERT_EQ(sp.getCounter(), 2); qi::DynamicObjectBuilder ob; ob.advertiseSignal("signal", &sig); qi::AnyObject obj(ob.object()); qi::SignalSpy sp2(obj, "signal"); QI_EMIT sig(1); QI_EMIT sig(1); qi::os::sleep(1); ASSERT_EQ(sp2.getCounter(), 2); } int main(int argc, char **argv) { qi::Application app(argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>// // CG tests // // g++-mp-7 -O2 -Wall -std=c++11 -I/opt/local/include cg_test.cpp -o cg.test -L/opt/local/lib -loptim -framework Accelerate // g++-mp-7 -O2 -Wall -std=c++11 -I./../../include cg.cpp -o cg.test -L./../.. -loptim -framework Accelerate // #include "optim.hpp" #include "./../test_fns/test_fns.hpp" int main() { // // test 1 optim::optim_opt_settings opt_params; opt_params.iter_max = 2000; opt_params.conv_failure_switch = 1; opt_params.method_cg = 1; arma::vec x_1 = arma::ones(2,1); bool success_1 = optim::cg(x_1,unconstr_test_fn_1,NULL,opt_params); if (success_1) { std::cout << "cg: test_1 completed successfully." << std::endl; } else { std::cout << "cg: test_1 completed unsuccessfully." << std::endl; } arma::cout << "cg: solution to test_1:\n" << x_1 << arma::endl; // // test 2 arma::vec x_2 = arma::zeros(2,1); bool success_2 = optim::cg(x_2,unconstr_test_fn_2,NULL); if (success_2) { std::cout << "cg: test_2 completed successfully." << std::endl; } else { std::cout << "cg: test_2 completed unsuccessfully." << std::endl; } arma::cout << "cg: solution to test_2:\n" << x_2 << arma::endl; // // test 3 int test_3_dim = 5; arma::vec x_3 = arma::ones(test_3_dim,1); bool success_3 = optim::cg(x_3,unconstr_test_fn_3,NULL); if (success_3) { std::cout << "cg: test_3 completed successfully." << std::endl; } else { std::cout << "cg: test_3 completed unsuccessfully." << std::endl; } arma::cout << "cg: solution to test_3:\n" << x_3 << arma::endl; // // test 4 arma::vec x_4 = arma::ones(2,1); bool success_4 = optim::cg(x_4,unconstr_test_fn_4,NULL); if (success_4) { std::cout << "cg: test_4 completed successfully." << std::endl; } else { std::cout << "cg: test_4 completed unsuccessfully." << std::endl; } arma::cout << "cg: solution to test_4:\n" << x_4 << arma::endl; // // for coverage optim::optim_opt_settings opt_settings; opt_settings.method_cg = 3; optim::cg(x_1,unconstr_test_fn_1,NULL,opt_settings); opt_settings.method_cg = 4; optim::cg(x_1,unconstr_test_fn_1,NULL,opt_settings); opt_settings.method_cg = 5; optim::cg(x_1,unconstr_test_fn_1,NULL,opt_settings); opt_settings.method_cg = 6; optim::cg(x_1,unconstr_test_fn_1,NULL,opt_settings); double val_out; optim::cg(x_1,unconstr_test_fn_1,NULL); optim::cg(x_1,unconstr_test_fn_1,NULL,val_out); optim::cg(x_1,unconstr_test_fn_1,NULL,val_out,opt_settings); return 0; } <commit_msg>test update<commit_after>// // CG tests // // g++-mp-7 -O2 -Wall -std=c++11 -I/opt/local/include cg_test.cpp -o cg.test -L/opt/local/lib -loptim -framework Accelerate // g++-mp-7 -O2 -Wall -std=c++11 -I./../../include cg.cpp -o cg.test -L./../.. -loptim -framework Accelerate // #include "optim.hpp" #include "./../test_fns/test_fns.hpp" int main() { // // test 1 optim::optim_opt_settings opt_params; opt_params.iter_max = 2000; opt_params.conv_failure_switch = 1; opt_params.method_cg = 1; arma::vec x_1 = arma::ones(2,1); bool success_1 = optim::cg(x_1,unconstr_test_fn_1,NULL,opt_params); if (success_1) { std::cout << "cg: test_1 completed successfully." << std::endl; } else { std::cout << "cg: test_1 completed unsuccessfully." << std::endl; } arma::cout << "cg: solution to test_1:\n" << x_1 << arma::endl; // // test 2 arma::vec x_2 = arma::zeros(2,1); bool success_2 = optim::cg(x_2,unconstr_test_fn_2,NULL); if (success_2) { std::cout << "cg: test_2 completed successfully." << std::endl; } else { std::cout << "cg: test_2 completed unsuccessfully." << std::endl; } arma::cout << "cg: solution to test_2:\n" << x_2 << arma::endl; // // test 3 int test_3_dim = 5; arma::vec x_3 = arma::ones(test_3_dim,1); bool success_3 = optim::cg(x_3,unconstr_test_fn_3,NULL); if (success_3) { std::cout << "cg: test_3 completed successfully." << std::endl; } else { std::cout << "cg: test_3 completed unsuccessfully." << std::endl; } arma::cout << "cg: solution to test_3:\n" << x_3 << arma::endl; // // test 4 arma::vec x_4 = arma::ones(2,1); bool success_4 = optim::cg(x_4,unconstr_test_fn_4,NULL); if (success_4) { std::cout << "cg: test_4 completed successfully." << std::endl; } else { std::cout << "cg: test_4 completed unsuccessfully." << std::endl; } arma::cout << "cg: solution to test_4:\n" << x_4 << arma::endl; // // for coverage optim::optim_opt_settings opt_settings; x_1 = arma::ones(2,1); opt_settings.method_cg = 3; optim::cg(x_1,unconstr_test_fn_1,NULL,opt_settings); x_1 = arma::ones(2,1); opt_settings.method_cg = 4; optim::cg(x_1,unconstr_test_fn_1,NULL,opt_settings); x_1 = arma::ones(2,1); opt_settings.method_cg = 5; optim::cg(x_1,unconstr_test_fn_1,NULL,opt_settings); x_1 = arma::ones(2,1); opt_settings.method_cg = 6; optim::cg(x_1,unconstr_test_fn_1,NULL,opt_settings); double val_out; optim::cg(x_1,unconstr_test_fn_1,NULL); optim::cg(x_1,unconstr_test_fn_1,NULL,val_out); optim::cg(x_1,unconstr_test_fn_1,NULL,val_out,opt_settings); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2011, Robert Escriva // 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 this project 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. // C #include <stdint.h> // C++ #include <memory> // e #include "th.h" #include "e/buffer.h" #define ASSERT_MEMCMP(X, Y, S) ASSERT_EQ(0, memcmp(X, Y, S)) namespace { TEST(BufferTest, CtorAndDtor) { // Create a buffer without any size std::auto_ptr<e::buffer> a(e::buffer::create(0)); ASSERT_EQ(0U, a->size()); ASSERT_EQ(0U, a->capacity()); // Create a buffer which can pack 2 bytes std::auto_ptr<e::buffer> b(e::buffer::create(2)); ASSERT_EQ(0U, b->size()); ASSERT_EQ(2U, b->capacity()); // Create a buffer with the three bytes "XYZ" std::auto_ptr<e::buffer> c(e::buffer::create("xyz", 3)); ASSERT_EQ(3U, c->size()); ASSERT_EQ(3U, c->capacity()); } TEST(BufferTest, PackBuffer) { uint64_t a = 0xdeadbeefcafebabe; uint32_t b = 0x8badf00d; uint16_t c = 0xface; uint8_t d = '!'; std::auto_ptr<e::buffer> buf(e::buffer::create("the buffer", 10)); std::auto_ptr<e::buffer> packed(e::buffer::create(34)); packed->pack() << a << b << c << d << buf->as_slice(); ASSERT_EQ(26U, packed->size()); ASSERT_MEMCMP(packed->data(), "\xde\xad\xbe\xef\xca\xfe\xba\xbe" "\x8b\xad\xf0\x0d" "\xfa\xce" "!" "\x0athe buffer", 26); packed->pack_at(12) << d << c << buf->as_slice(); ASSERT_EQ(26U, packed->size()); ASSERT_MEMCMP(packed->data(), "\xde\xad\xbe\xef\xca\xfe\xba\xbe" "\x8b\xad\xf0\x0d" "!" "\xfa\xce" "\x0athe buffer", 26); } TEST(BufferTest, UnpackBuffer) { uint64_t a; uint32_t b; uint16_t c; uint8_t d; e::slice sl; std::auto_ptr<e::buffer> packed(e::buffer::create( "\xde\xad\xbe\xef\xca\xfe\xba\xbe" "\x8b\xad\xf0\x0d" "\xfa\xce" "!" "\x0athe buffer", 26)); packed->unpack() >> a >> b >> c >> d >> sl; ASSERT_EQ(0xdeadbeefcafebabeULL, a); ASSERT_EQ(0x8badf00dUL, b); ASSERT_EQ(0xface, c); ASSERT_EQ('!', d); ASSERT_EQ(10U, sl.size()); ASSERT_MEMCMP("the buffer", sl.data(), 10); } TEST(BufferTest, UnpackErrors) { std::auto_ptr<e::buffer> buf(e::buffer::create("\x8b\xad\xf0\x0d" "\xfa\xce", 6)); uint32_t a; e::unpacker up = buf->unpack() >> a; ASSERT_EQ(0x8badf00d, a); ASSERT_EQ(2U, up.remain()); ASSERT_FALSE(up.error()); // "a" should not change even if nup fails e::unpacker nup = up >> a; ASSERT_EQ(0x8badf00d, a); ASSERT_EQ(2U, up.remain()); ASSERT_FALSE(up.error()); ASSERT_TRUE(nup.error()); // Getting the next value should succeed uint16_t b; up = up >> b; ASSERT_EQ(0xface, b); ASSERT_EQ(0U, up.remain()); ASSERT_FALSE(up.error()); } TEST(BufferTest, Hex) { std::auto_ptr<e::buffer> buf1(e::buffer::create("\xde\xad\xbe\xef", 4)); std::auto_ptr<e::buffer> buf2(e::buffer::create("\x00\xff\x0f\xf0", 4)); ASSERT_EQ("deadbeef", buf1->hex()); ASSERT_EQ("00ff0ff0", buf2->hex()); } TEST(BufferTest, VectorPack) { std::auto_ptr<e::buffer> buf(e::buffer::create(12)); std::vector<uint16_t> vector; vector.push_back(0xdead); vector.push_back(0xbeef); vector.push_back(0xcafe); vector.push_back(0xbabe); e::packer p = buf->pack_at(0); p = p << vector; ASSERT_TRUE(buf->cmp("\x00\x00\x00\x04" "\xde\xad\xbe\xef" "\xca\xfe\xba\xbe", 12)); } TEST(BufferTest, VectorUnpack) { std::auto_ptr<e::buffer> buf(e::buffer::create("\x00\x00\x00\x04" "\xde\xad\xbe\xef" "\xca\xfe\xba\xbe", 12)); std::vector<uint16_t> vector; buf->unpack() >> vector; ASSERT_EQ(4U, vector.size()); ASSERT_EQ(0xdead, vector[0]); ASSERT_EQ(0xbeef, vector[1]); ASSERT_EQ(0xcafe, vector[2]); ASSERT_EQ(0xbabe, vector[3]); } TEST(BufferTest, VectorUnpackFail) { std::auto_ptr<e::buffer> buf(e::buffer::create("\x00\x00\x00\x04" "\xde\xad\xbe\xef" "\xca\xfe\xba\xbe", 12)); std::vector<uint32_t> vector_bad; std::vector<uint16_t> vector_good; e::unpacker bad = buf->unpack() >> vector_bad; e::unpacker good = buf->unpack() >> vector_good; ASSERT_TRUE(bad.error()); ASSERT_FALSE(good.error()); ASSERT_EQ(4U, vector_good.size()); ASSERT_EQ(0xdead, vector_good[0]); ASSERT_EQ(0xbeef, vector_good[1]); ASSERT_EQ(0xcafe, vector_good[2]); ASSERT_EQ(0xbabe, vector_good[3]); } } // namespace <commit_msg>Fix tests from prev commit<commit_after>// Copyright (c) 2011, Robert Escriva // 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 this project 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. // C #include <stdint.h> // C++ #include <memory> // e #include "th.h" #include "e/buffer.h" #define ASSERT_MEMCMP(X, Y, S) ASSERT_EQ(0, memcmp(X, Y, S)) namespace { TEST(BufferTest, CtorAndDtor) { // Create a buffer without any size std::auto_ptr<e::buffer> a(e::buffer::create(0)); ASSERT_EQ(0U, a->size()); ASSERT_EQ(0U, a->capacity()); // Create a buffer which can pack 2 bytes std::auto_ptr<e::buffer> b(e::buffer::create(2)); ASSERT_EQ(0U, b->size()); ASSERT_EQ(2U, b->capacity()); // Create a buffer with the three bytes "XYZ" std::auto_ptr<e::buffer> c(e::buffer::create("xyz", 3)); ASSERT_EQ(3U, c->size()); ASSERT_EQ(3U, c->capacity()); } TEST(BufferTest, PackBuffer) { uint64_t a = 0xdeadbeefcafebabe; uint32_t b = 0x8badf00d; uint16_t c = 0xface; uint8_t d = '!'; std::auto_ptr<e::buffer> buf(e::buffer::create("the buffer", 10)); std::auto_ptr<e::buffer> packed(e::buffer::create(34)); packed->pack() << a << b << c << d << buf->as_slice(); ASSERT_EQ(26U, packed->size()); ASSERT_MEMCMP(packed->data(), "\xde\xad\xbe\xef\xca\xfe\xba\xbe" "\x8b\xad\xf0\x0d" "\xfa\xce" "!" "\x0athe buffer", 26); packed->pack_at(12) << d << c << buf->as_slice(); ASSERT_EQ(26U, packed->size()); ASSERT_MEMCMP(packed->data(), "\xde\xad\xbe\xef\xca\xfe\xba\xbe" "\x8b\xad\xf0\x0d" "!" "\xfa\xce" "\x0athe buffer", 26); } TEST(BufferTest, UnpackBuffer) { uint64_t a; uint32_t b; uint16_t c; uint8_t d; e::slice sl; std::auto_ptr<e::buffer> packed(e::buffer::create( "\xde\xad\xbe\xef\xca\xfe\xba\xbe" "\x8b\xad\xf0\x0d" "\xfa\xce" "!" "\x0athe buffer", 26)); packed->unpack() >> a >> b >> c >> d >> sl; ASSERT_EQ(0xdeadbeefcafebabeULL, a); ASSERT_EQ(0x8badf00dUL, b); ASSERT_EQ(0xface, c); ASSERT_EQ('!', d); ASSERT_EQ(10U, sl.size()); ASSERT_MEMCMP("the buffer", sl.data(), 10); } TEST(BufferTest, UnpackErrors) { std::auto_ptr<e::buffer> buf(e::buffer::create("\x8b\xad\xf0\x0d" "\xfa\xce", 6)); uint32_t a; e::unpacker up = buf->unpack() >> a; ASSERT_EQ(0x8badf00d, a); ASSERT_EQ(2U, up.remain()); ASSERT_FALSE(up.error()); // "a" should not change even if nup fails e::unpacker nup = up >> a; ASSERT_EQ(0x8badf00d, a); ASSERT_EQ(2U, up.remain()); ASSERT_FALSE(up.error()); ASSERT_TRUE(nup.error()); // Getting the next value should succeed uint16_t b; up = up >> b; ASSERT_EQ(0xface, b); ASSERT_EQ(0U, up.remain()); ASSERT_FALSE(up.error()); } TEST(BufferTest, Hex) { std::auto_ptr<e::buffer> buf1(e::buffer::create("\xde\xad\xbe\xef", 4)); std::auto_ptr<e::buffer> buf2(e::buffer::create("\x00\xff\x0f\xf0", 4)); ASSERT_EQ("deadbeef", buf1->hex()); ASSERT_EQ("00ff0ff0", buf2->hex()); } TEST(BufferTest, VectorPack) { std::auto_ptr<e::buffer> buf(e::buffer::create(12)); std::vector<uint16_t> vector; vector.push_back(0xdead); vector.push_back(0xbeef); vector.push_back(0xcafe); vector.push_back(0xbabe); e::packer p = buf->pack_at(0); p = p << vector; ASSERT_TRUE(buf->cmp("\x04" "\xde\xad\xbe\xef" "\xca\xfe\xba\xbe", 9)); } TEST(BufferTest, VectorUnpack) { std::auto_ptr<e::buffer> buf(e::buffer::create("\x04" "\xde\xad\xbe\xef" "\xca\xfe\xba\xbe", 9)); std::vector<uint16_t> vector; buf->unpack() >> vector; ASSERT_EQ(4U, vector.size()); ASSERT_EQ(0xdead, vector[0]); ASSERT_EQ(0xbeef, vector[1]); ASSERT_EQ(0xcafe, vector[2]); ASSERT_EQ(0xbabe, vector[3]); } TEST(BufferTest, VectorUnpackFail) { std::auto_ptr<e::buffer> buf(e::buffer::create("\x04" "\xde\xad\xbe\xef" "\xca\xfe\xba\xbe", 9)); std::vector<uint32_t> vector_bad; std::vector<uint16_t> vector_good; e::unpacker bad = buf->unpack() >> vector_bad; e::unpacker good = buf->unpack() >> vector_good; ASSERT_TRUE(bad.error()); ASSERT_FALSE(good.error()); ASSERT_EQ(4U, vector_good.size()); ASSERT_EQ(0xdead, vector_good[0]); ASSERT_EQ(0xbeef, vector_good[1]); ASSERT_EQ(0xcafe, vector_good[2]); ASSERT_EQ(0xbabe, vector_good[3]); } } // namespace <|endoftext|>
<commit_before>#include <limits> #include <cmath> #include <cgo/minimax/minimax_agent.hpp> using namespace cgo::base; using namespace cgo::minimax; MiniMaxAgent::MiniMaxAgent(Marker marker) : Agent(marker), _turnNumber(0) {} /* virtual */ MiniMaxAgent::~MiniMaxAgent() {} Move MiniMaxAgent::makeMove(State& state, const boost::optional< Predecessor >& predecessor) { // Make an intelligent first move. if (this->_turnNumber == 0) { ++this->_turnNumber; return this->makeFirstMove(state); } ++this->_turnNumber; return this->makeMiniMaxMove(state, predecessor); } Action MiniMaxAgent::makeFirstMove(const State& state) const { const int crucialPoint = std::ceil(BOARD_DIMENSION / 3.0f) - 1; Position p1(crucialPoint, crucialPoint); if (state.getBoard()[State::getIndex(p1)] == none) { return Action(this->_marker, p1); } Position p2(crucialPoint, (BOARD_DIMENSION - 1) - crucialPoint); return Action(this->_marker, p2); } Move MiniMaxAgent::makeMiniMaxMove(State& state, const boost::optional< Predecessor >& predecessor) const { int alpha = std::numeric_limits<int>::min(); int beta = std::numeric_limits<int>::max(); int depth = this->getDepth(state); auto maxMoveValue = this->mmAbMax(state, predecessor, alpha, beta, depth); return std::get<0>(maxMoveValue); } std::tuple< Move, int > MiniMaxAgent::mmAbMax(State& state, const boost::optional< Predecessor >& predecessor, int alpha, int beta, int depth) const { Move maxMove = Pass(); int maxValue = this->utility(maxMove, state); if (predecessor) { auto predecessorValue = predecessor.get(); Move predMove = std::get<0>(predecessorValue); const Pass* pass = boost::get< Pass >(&predMove); if ((pass != nullptr) && (maxValue > 0)) { return std::make_tuple(Pass(), maxValue); } } std::vector< Successor > successors = state.getSuccessors(this->_marker, predecessor); if (depth == 0) { if (successors.size() > 0) { Move chosenMove = std::get<0>(successors[0]); int chosenScore = std::numeric_limits<int>::min(); for (auto successor : successors) { auto succMove = std::get<0>(successor); auto succState = std::get<1>(successor); int succScore = this->utility(succMove, succState); if (succScore > chosenScore) { chosenMove = succMove; chosenScore = succScore; } } return std::make_tuple(chosenMove, chosenScore); } else { return std::make_tuple(maxMove, maxValue); } } for (auto successor : successors) { auto succMove = std::get<0>(successor); auto succState = std::get<1>(successor); auto minMoveValue = this->mmAbMin(succState, successor, alpha, beta, depth - 1); auto minMove = std::get<0>(minMoveValue); auto minValue = std::get<1>(minMoveValue); if (minValue > maxValue) { maxMove = minMove; maxValue = minValue; } if (maxValue >= beta) { return std::make_tuple(maxMove, maxValue); } if (alpha < maxValue) { alpha = maxValue; maxMove = succMove; } } return std::make_tuple(maxMove, maxValue); } std::tuple< Move, int > MiniMaxAgent::mmAbMin(State& state, const boost::optional< Predecessor >& predecessor, int alpha, int beta, int depth) const { Move minMove = Pass(); int minValue = this->utility(minMove, state); if (predecessor) { auto predecessorValue = predecessor.get(); Move predMove = std::get<0>(predecessorValue); const Pass* pass = boost::get< Pass >(&predMove); if ((pass != nullptr) && (minValue < 0)) { return std::make_tuple(Pass(), minValue); } } std::vector< Successor > successors = state.getSuccessors(this->_marker, predecessor); if (depth == 0) { if (successors.size() > 0) { Move chosenMove = std::get<0>(successors[0]); int chosenScore = std::numeric_limits<int>::max(); for (auto successor : successors) { auto succMove = std::get<0>(successor); auto succState = std::get<1>(successor); int succScore = this->utility(succMove, succState); if (succScore < chosenScore) { chosenMove = succMove; chosenScore = succScore; } } return std::make_tuple(chosenMove, chosenScore); } else { return std::make_tuple(minMove, minValue); } } for (auto successor : successors) { auto succMove = std::get<0>(successor); auto succState = std::get<1>(successor); auto maxMoveValue = this->mmAbMax(succState, successor, alpha, beta, depth - 1); auto maxMove = std::get<0>(maxMoveValue); auto maxValue = std::get<1>(maxMoveValue); if (maxValue < minValue) { minMove = maxMove; minValue = maxValue; } if (minValue <= beta) { return std::make_tuple(minMove, minValue); } if (beta > minValue) { beta = minValue; minMove = succMove; } } return std::make_tuple(minMove, minValue); } bool MiniMaxAgent::checkBounds(int x, int y) const{ if (x < 0) { return false; } if (x >= BOARD_DIMENSION) { return false; } if (y < 0) { return false; } if (y >= BOARD_DIMENSION) { return false; } return true; } int MiniMaxAgent::pseudoControl(const Board& board) const{ int totalControl = 0; static const int pieceVal = 5; //value for having a piece on a square static const int controlVal = 10; //bonus value for having 'control' over a square static const int weakVal = 10; //value for having weak presence on a square static const int strongVal = 30; //value for having strong presence on a square static const int vStrongVal = 40; //value for having a very strong presence on a square std::array<int, BOARD_DIMENSION * BOARD_DIMENSION> wcontrol; std::array<int, BOARD_DIMENSION * BOARD_DIMENSION> bcontrol; wcontrol.fill(0); bcontrol.fill(0); for (int x = 0; x < BOARD_DIMENSION; ++x) { for (int y = 0; y < BOARD_DIMENSION; ++y) { Marker curr = board[State::getIndex(Position(x, y))]; if (curr == white) { if (checkBounds(x, y)) { wcontrol[State::getIndex(Position(x, y))]++; } if (checkBounds(x, y + 1)) { wcontrol[State::getIndex(Position(x, y + 1))]++; } if (checkBounds(x, y - 1)) { wcontrol[State::getIndex(Position(x, y - 1))]++; } if (checkBounds(x + 1, y)) { wcontrol[State::getIndex(Position(x + 1, y))]++; } if (checkBounds(x - 1, y)) { wcontrol[State::getIndex(Position(x - 1, y))]++; } } if (curr == black) { if (checkBounds(x, y)) { bcontrol[State::getIndex(Position(x, y))]++; } if (checkBounds(x, y + 1)) { bcontrol[State::getIndex(Position(x, y + 1))]++; } if (checkBounds(x, y - 1)) { bcontrol[State::getIndex(Position(x, y - 1))]++; } if (checkBounds(x + 1, y)) { bcontrol[State::getIndex(Position(x + 1, y))]++; } if (checkBounds(x - 1, y)) { bcontrol[State::getIndex(Position(x - 1, y))]++; } } } } for (int x = 0; x < BOARD_DIMENSION; ++x) { for (int y = 0; y < BOARD_DIMENSION; ++y) { Marker curr = board[State::getIndex(Position(x, y))]; int control = 0; if (wcontrol[State::getIndex(Position(x, y))] == 1 || wcontrol[State::getIndex(Position(x, y))] == 5) { control += weakVal; } if (wcontrol[State::getIndex(Position(x, y))] == 2 || wcontrol[State::getIndex(Position(x, y))] == 4) { control += strongVal; } if (wcontrol[State::getIndex(Position(x, y))] == 3) { control += vStrongVal; } if (bcontrol[State::getIndex(Position(x, y))] == 1 || bcontrol[State::getIndex(Position(x, y))] == 5) { control -= weakVal; } if (bcontrol[State::getIndex(Position(x, y))] == 2 || bcontrol[State::getIndex(Position(x, y))] == 4) { control -= strongVal; } if (bcontrol[State::getIndex(Position(x, y))] == 3) { control -= vStrongVal; } if (curr == white ){ if (control > 0) { //control = control * 1.5; } control += pieceVal; } if (curr == black){ if (control < 0) { //control = control * 1.5; } control -= pieceVal; } if (bcontrol[State::getIndex(Position(x, y))] > 0 && wcontrol[State::getIndex(Position(x, y))] > 0) { control *= 2; } if (control > 0) { control += controlVal; } if (control < 0) { control -= controlVal; } totalControl += control; } } return totalControl; } std::tuple< int, int > MiniMaxAgent::edgeCosts(const Board& board) const { int whiteCost = 0; int blackCost = 0; for (int ndx = 0; ndx < BOARD_DIMENSION; ++ndx) { Marker rowMarker1 = board[State::getIndex(Position(ndx, 0))]; Marker rowMarker2 = board[State::getIndex(Position(ndx, BOARD_DIMENSION - 1))]; Marker colMarker1 = board[State::getIndex(Position(0, ndx))]; Marker colMarker2 = board[State::getIndex(Position(BOARD_DIMENSION - 1, ndx))]; if (rowMarker1 == white) { ++whiteCost; } if (rowMarker2 == white) { ++whiteCost; } if (colMarker1 == white) { ++whiteCost; } if (colMarker2 == white) { ++whiteCost; } if (rowMarker1 == black) { ++blackCost; } if (rowMarker2 == black) { ++blackCost; } if (colMarker1 == black) { ++blackCost; } if (colMarker2 == black) { ++blackCost; } } return std::make_tuple(whiteCost, blackCost); } int MiniMaxAgent::utility(const Move& move, const State& state) const { static const int scoreWeight = 1000; static const int edgeWeight = 10; static const int passWeight = 1; auto control = MiniMaxAgent::pseudoControl(state.getBoard()); //control = (this->_marker == white) ? control : -control; auto scores = state.getScores(); int scoreValue = std::get<0>(scores) - std::get<1>(scores); auto edgeCosts = MiniMaxAgent::edgeCosts(state.getBoard()); int edgeValue = (this->_marker == white) ? -std::get<0>(edgeCosts) : std::get<1>(edgeCosts); int passValue = 0; const Pass* pass = boost::get< Pass >(&move); if (pass != nullptr) { passValue = (this->_marker == white) ? 1 : -1; } int totalValue = scoreWeight * scoreValue + edgeWeight * edgeValue + passWeight * passValue + control; return (this->_marker == white) ? totalValue : -totalValue; } int MiniMaxAgent::getDepth(const base::State& state) const { static const int maxNumCases = 5E5; // Count open positions. int numOpenPositions = 0; for (int row = 0; row < BOARD_DIMENSION; ++row) { for (int col = 0; col < BOARD_DIMENSION; ++col) { int index = State::getIndex(Position(row, col)); if (state.getBoard()[index] == none) { ++numOpenPositions; } } } // Factorial. int numPossibleCases = 1; for (int ndx = numOpenPositions; ndx > 0; --ndx) { numPossibleCases *= ndx; if (numPossibleCases > maxNumCases) { return (numOpenPositions - ndx) + 1; } } return numOpenPositions + 1; } <commit_msg>Increase edge avoidance weight<commit_after>#include <limits> #include <cmath> #include <cgo/minimax/minimax_agent.hpp> using namespace cgo::base; using namespace cgo::minimax; MiniMaxAgent::MiniMaxAgent(Marker marker) : Agent(marker), _turnNumber(0) {} /* virtual */ MiniMaxAgent::~MiniMaxAgent() {} Move MiniMaxAgent::makeMove(State& state, const boost::optional< Predecessor >& predecessor) { // Make an intelligent first move. if (this->_turnNumber == 0) { ++this->_turnNumber; return this->makeFirstMove(state); } ++this->_turnNumber; return this->makeMiniMaxMove(state, predecessor); } Action MiniMaxAgent::makeFirstMove(const State& state) const { const int crucialPoint = std::ceil(BOARD_DIMENSION / 3.0f) - 1; Position p1(crucialPoint, crucialPoint); if (state.getBoard()[State::getIndex(p1)] == none) { return Action(this->_marker, p1); } Position p2(crucialPoint, (BOARD_DIMENSION - 1) - crucialPoint); return Action(this->_marker, p2); } Move MiniMaxAgent::makeMiniMaxMove(State& state, const boost::optional< Predecessor >& predecessor) const { int alpha = std::numeric_limits<int>::min(); int beta = std::numeric_limits<int>::max(); int depth = this->getDepth(state); auto maxMoveValue = this->mmAbMax(state, predecessor, alpha, beta, depth); return std::get<0>(maxMoveValue); } std::tuple< Move, int > MiniMaxAgent::mmAbMax(State& state, const boost::optional< Predecessor >& predecessor, int alpha, int beta, int depth) const { Move maxMove = Pass(); int maxValue = this->utility(maxMove, state); if (predecessor) { auto predecessorValue = predecessor.get(); Move predMove = std::get<0>(predecessorValue); const Pass* pass = boost::get< Pass >(&predMove); if ((pass != nullptr) && (maxValue > 0)) { return std::make_tuple(Pass(), maxValue); } } std::vector< Successor > successors = state.getSuccessors(this->_marker, predecessor); if (depth == 0) { if (successors.size() > 0) { Move chosenMove = std::get<0>(successors[0]); int chosenScore = std::numeric_limits<int>::min(); for (auto successor : successors) { auto succMove = std::get<0>(successor); auto succState = std::get<1>(successor); int succScore = this->utility(succMove, succState); if (succScore > chosenScore) { chosenMove = succMove; chosenScore = succScore; } } return std::make_tuple(chosenMove, chosenScore); } else { return std::make_tuple(maxMove, maxValue); } } for (auto successor : successors) { auto succMove = std::get<0>(successor); auto succState = std::get<1>(successor); auto minMoveValue = this->mmAbMin(succState, successor, alpha, beta, depth - 1); auto minMove = std::get<0>(minMoveValue); auto minValue = std::get<1>(minMoveValue); if (minValue > maxValue) { maxMove = minMove; maxValue = minValue; } if (maxValue >= beta) { return std::make_tuple(maxMove, maxValue); } if (alpha < maxValue) { alpha = maxValue; maxMove = succMove; } } return std::make_tuple(maxMove, maxValue); } std::tuple< Move, int > MiniMaxAgent::mmAbMin(State& state, const boost::optional< Predecessor >& predecessor, int alpha, int beta, int depth) const { Move minMove = Pass(); int minValue = this->utility(minMove, state); if (predecessor) { auto predecessorValue = predecessor.get(); Move predMove = std::get<0>(predecessorValue); const Pass* pass = boost::get< Pass >(&predMove); if ((pass != nullptr) && (minValue < 0)) { return std::make_tuple(Pass(), minValue); } } std::vector< Successor > successors = state.getSuccessors(this->_marker, predecessor); if (depth == 0) { if (successors.size() > 0) { Move chosenMove = std::get<0>(successors[0]); int chosenScore = std::numeric_limits<int>::max(); for (auto successor : successors) { auto succMove = std::get<0>(successor); auto succState = std::get<1>(successor); int succScore = this->utility(succMove, succState); if (succScore < chosenScore) { chosenMove = succMove; chosenScore = succScore; } } return std::make_tuple(chosenMove, chosenScore); } else { return std::make_tuple(minMove, minValue); } } for (auto successor : successors) { auto succMove = std::get<0>(successor); auto succState = std::get<1>(successor); auto maxMoveValue = this->mmAbMax(succState, successor, alpha, beta, depth - 1); auto maxMove = std::get<0>(maxMoveValue); auto maxValue = std::get<1>(maxMoveValue); if (maxValue < minValue) { minMove = maxMove; minValue = maxValue; } if (minValue <= beta) { return std::make_tuple(minMove, minValue); } if (beta > minValue) { beta = minValue; minMove = succMove; } } return std::make_tuple(minMove, minValue); } bool MiniMaxAgent::checkBounds(int x, int y) const{ if (x < 0) { return false; } if (x >= BOARD_DIMENSION) { return false; } if (y < 0) { return false; } if (y >= BOARD_DIMENSION) { return false; } return true; } int MiniMaxAgent::pseudoControl(const Board& board) const{ int totalControl = 0; static const int pieceVal = 5; //value for having a piece on a square static const int controlVal = 10; //bonus value for having 'control' over a square static const int weakVal = 10; //value for having weak presence on a square static const int medVal = 20; static const int strongVal = 30; //value for having strong presence on a square static const int vStrongVal = 40; //value for having a very strong presence on a square std::array<int, BOARD_DIMENSION * BOARD_DIMENSION> wcontrol; std::array<int, BOARD_DIMENSION * BOARD_DIMENSION> bcontrol; wcontrol.fill(0); bcontrol.fill(0); for (int x = 0; x < BOARD_DIMENSION; ++x) { for (int y = 0; y < BOARD_DIMENSION; ++y) { Marker curr = board[State::getIndex(Position(x, y))]; if (curr == white) { if (checkBounds(x, y)) { wcontrol[State::getIndex(Position(x, y))]++; } if (checkBounds(x, y + 1)) { wcontrol[State::getIndex(Position(x, y + 1))]++; } if (checkBounds(x, y - 1)) { wcontrol[State::getIndex(Position(x, y - 1))]++; } if (checkBounds(x + 1, y)) { wcontrol[State::getIndex(Position(x + 1, y))]++; } if (checkBounds(x - 1, y)) { wcontrol[State::getIndex(Position(x - 1, y))]++; } } if (curr == black) { if (checkBounds(x, y)) { bcontrol[State::getIndex(Position(x, y))]++; } if (checkBounds(x, y + 1)) { bcontrol[State::getIndex(Position(x, y + 1))]++; } if (checkBounds(x, y - 1)) { bcontrol[State::getIndex(Position(x, y - 1))]++; } if (checkBounds(x + 1, y)) { bcontrol[State::getIndex(Position(x + 1, y))]++; } if (checkBounds(x - 1, y)) { bcontrol[State::getIndex(Position(x - 1, y))]++; } } } } for (int x = 0; x < BOARD_DIMENSION; ++x) { for (int y = 0; y < BOARD_DIMENSION; ++y) { Marker curr = board[State::getIndex(Position(x, y))]; int control = 0; if (wcontrol[State::getIndex(Position(x, y))] == 1) { control += weakVal; } if (wcontrol[State::getIndex(Position(x, y))] == 5) { control += medVal; } if (wcontrol[State::getIndex(Position(x, y))] == 2 || wcontrol[State::getIndex(Position(x, y))] == 4) { control += strongVal; } if (wcontrol[State::getIndex(Position(x, y))] == 3) { control += vStrongVal; } if (bcontrol[State::getIndex(Position(x, y))] == 1) { control -= weakVal; } if (wcontrol[State::getIndex(Position(x, y))] == 5) { control -= medVal; } if (bcontrol[State::getIndex(Position(x, y))] == 2 || bcontrol[State::getIndex(Position(x, y))] == 4) { control -= strongVal; } if (bcontrol[State::getIndex(Position(x, y))] == 3) { control -= vStrongVal; } if (curr == white ){ if (control > 0) { //control = control * 1.5; } control += pieceVal; } if (curr == black){ if (control < 0) { //control = control * 1.5; } control -= pieceVal; } if (bcontrol[State::getIndex(Position(x, y))] > 0 && wcontrol[State::getIndex(Position(x, y))] > 0) { control *= 2; } if (control > 0) { control += controlVal; } if (control < 0) { control -= controlVal; } totalControl += control; } } return totalControl; } std::tuple< int, int > MiniMaxAgent::edgeCosts(const Board& board) const { int whiteCost = 0; int blackCost = 0; for (int ndx = 0; ndx < BOARD_DIMENSION; ++ndx) { Marker rowMarker1 = board[State::getIndex(Position(ndx, 0))]; Marker rowMarker2 = board[State::getIndex(Position(ndx, BOARD_DIMENSION - 1))]; Marker colMarker1 = board[State::getIndex(Position(0, ndx))]; Marker colMarker2 = board[State::getIndex(Position(BOARD_DIMENSION - 1, ndx))]; if (rowMarker1 == white) { ++whiteCost; } if (rowMarker2 == white) { ++whiteCost; } if (colMarker1 == white) { ++whiteCost; } if (colMarker2 == white) { ++whiteCost; } if (rowMarker1 == black) { ++blackCost; } if (rowMarker2 == black) { ++blackCost; } if (colMarker1 == black) { ++blackCost; } if (colMarker2 == black) { ++blackCost; } } return std::make_tuple(whiteCost, blackCost); } int MiniMaxAgent::utility(const Move& move, const State& state) const { static const int scoreWeight = 1000; static const int edgeWeight = 100; static const int passWeight = 1; auto control = MiniMaxAgent::pseudoControl(state.getBoard()); //control = (this->_marker == white) ? control : -control; auto scores = state.getScores(); int scoreValue = std::get<0>(scores) - std::get<1>(scores); auto edgeCosts = MiniMaxAgent::edgeCosts(state.getBoard()); int edgeValue = (this->_marker == white) ? -std::get<0>(edgeCosts) : std::get<1>(edgeCosts); int passValue = 0; const Pass* pass = boost::get< Pass >(&move); if (pass != nullptr) { passValue = (this->_marker == white) ? 1 : -1; } int totalValue = scoreWeight * scoreValue + edgeWeight * edgeValue + passWeight * passValue + control; return (this->_marker == white) ? totalValue : -totalValue; } int MiniMaxAgent::getDepth(const base::State& state) const { static const int maxNumCases = 5E5; // Count open positions. int numOpenPositions = 0; for (int row = 0; row < BOARD_DIMENSION; ++row) { for (int col = 0; col < BOARD_DIMENSION; ++col) { int index = State::getIndex(Position(row, col)); if (state.getBoard()[index] == none) { ++numOpenPositions; } } } // Factorial. int numPossibleCases = 1; for (int ndx = numOpenPositions; ndx > 0; --ndx) { numPossibleCases *= ndx; if (numPossibleCases > maxNumCases) { return (numOpenPositions - ndx) + 1; } } return numOpenPositions + 1; } <|endoftext|>
<commit_before>#include <array> #include <cstdlib> #include <iostream> #include <string> #include "snarkfront.hpp" using namespace snarkfront; using namespace std; void printUsage(const char* exeName) { cout << "usage: " << exeName << " -m keygen|input|proof|verify" << endl; exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { Getopt cmdLine(argc, argv, "m", "", ""); if (!cmdLine || cmdLine.empty()) printUsage(argv[0]); const auto mode = cmdLine.getString('m'); // Barreto-Naehrig 128 bits init_BN128(); typedef BN128_FR FR; typedef BN128_PAIRING PAIRING; // output hash digest is publicly known const auto pubHash = digest(eval::SHA256(), "abc"); if ("keygen" == mode) { //////////////////////////////////////////////////////////// // trusted key generation // input variables (values don't matter here) array<uint32_x<FR>, 8> pubVars; bless(pubVars); // marks end of public input variables end_input<PAIRING>(); // constraint system from circuit assert_true(pubVars == digest(zk::SHA256<FR>(), "")); // generate proving/verification key pair GenericProgressBar progress(cerr, 50); cerr << "generate key pair"; cout << keypair<PAIRING>(progress); // expensive! cerr << endl; } else if ("input" == mode) { //////////////////////////////////////////////////////////// // public inputs // input variables (need values) array<uint32_x<FR>, 8> pubVars; bless(pubVars, pubHash); // marks end of public input variables end_input<PAIRING>(); // publicly known input variables cout << input<PAIRING>(); } else if ("proof" == mode) { //////////////////////////////////////////////////////////// // generate a proof Keypair<PAIRING> keypair; // proving/verification key pair Input<PAIRING> input; // public inputs to circuit cin >> keypair >> input; // check for marshalling errors assert(!keypair.empty() && !input.empty()); // input variables (need values) array<uint32_x<FR>, 8> pubVars; bless(pubVars, input); // marks end of public input variables end_input<PAIRING>(); // perform calculation assert_true(pubVars == digest(zk::SHA256<FR>(), "abc")); // generate proof GenericProgressBar progress(cerr, 50); cerr << "generate proof"; cout << proof(keypair, progress); cerr << endl; } else if ("verify" == mode) { //////////////////////////////////////////////////////////// // verify a proof Keypair<PAIRING> keypair; // proving/verification key pair Input<PAIRING> input; // public inputs to circuit Proof<PAIRING> proof; // zero knowledge proof cin >> keypair >> input >> proof; // check for marshalling errors assert(!keypair.empty() && !input.empty() && !proof.empty()); // verify proof GenericProgressBar progress(cerr); cerr << "verify proof "; const bool valid = verify(keypair, input, proof, progress); cerr << endl; cout << "proof is " << (valid ? "verified" : "rejected") << endl; } else { // no mode specified printUsage(argv[0]); } exit(EXIT_SUCCESS); } <commit_msg>return EXIT_SUCCESS from main()<commit_after>#include <array> #include <cstdlib> #include <iostream> #include <string> #include "snarkfront.hpp" using namespace snarkfront; using namespace std; void printUsage(const char* exeName) { cout << "usage: " << exeName << " -m keygen|input|proof|verify" << endl; exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { Getopt cmdLine(argc, argv, "m", "", ""); if (!cmdLine || cmdLine.empty()) printUsage(argv[0]); const auto mode = cmdLine.getString('m'); // Barreto-Naehrig 128 bits init_BN128(); typedef BN128_FR FR; typedef BN128_PAIRING PAIRING; // output hash digest is publicly known const auto pubHash = digest(eval::SHA256(), "abc"); if ("keygen" == mode) { //////////////////////////////////////////////////////////// // trusted key generation // input variables (values don't matter here) array<uint32_x<FR>, 8> pubVars; bless(pubVars); // marks end of public input variables end_input<PAIRING>(); // constraint system from circuit assert_true(pubVars == digest(zk::SHA256<FR>(), "")); // generate proving/verification key pair GenericProgressBar progress(cerr, 50); cerr << "generate key pair"; cout << keypair<PAIRING>(progress); // expensive! cerr << endl; } else if ("input" == mode) { //////////////////////////////////////////////////////////// // public inputs // input variables (need values) array<uint32_x<FR>, 8> pubVars; bless(pubVars, pubHash); // marks end of public input variables end_input<PAIRING>(); // publicly known input variables cout << input<PAIRING>(); } else if ("proof" == mode) { //////////////////////////////////////////////////////////// // generate a proof Keypair<PAIRING> keypair; // proving/verification key pair Input<PAIRING> input; // public inputs to circuit cin >> keypair >> input; // check for marshalling errors assert(!keypair.empty() && !input.empty()); // input variables (need values) array<uint32_x<FR>, 8> pubVars; bless(pubVars, input); // marks end of public input variables end_input<PAIRING>(); // perform calculation assert_true(pubVars == digest(zk::SHA256<FR>(), "abc")); // generate proof GenericProgressBar progress(cerr, 50); cerr << "generate proof"; cout << proof(keypair, progress); cerr << endl; } else if ("verify" == mode) { //////////////////////////////////////////////////////////// // verify a proof Keypair<PAIRING> keypair; // proving/verification key pair Input<PAIRING> input; // public inputs to circuit Proof<PAIRING> proof; // zero knowledge proof cin >> keypair >> input >> proof; // check for marshalling errors assert(!keypair.empty() && !input.empty() && !proof.empty()); // verify proof GenericProgressBar progress(cerr); cerr << "verify proof "; const bool valid = verify(keypair, input, proof, progress); cerr << endl; cout << "proof is " << (valid ? "verified" : "rejected") << endl; } else { // no mode specified printUsage(argv[0]); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef DELETER_HH_ #define DELETER_HH_ #include <memory> #include <cstdlib> #include <assert.h> #include <type_traits> class deleter final { public: struct impl; struct raw_object_tag {}; private: // if bit 0 set, point to object to be freed directly. impl* _impl = nullptr; public: deleter() = default; deleter(const deleter&) = delete; deleter(deleter&& x) : _impl(x._impl) { x._impl = nullptr; } explicit deleter(impl* i) : _impl(i) {} deleter(raw_object_tag tag, void* object) : _impl(from_raw_object(object)) {} ~deleter(); deleter& operator=(deleter&& x); deleter& operator=(deleter&) = delete; deleter share(); explicit operator bool() const { return bool(_impl); } void reset(impl* i) { this->~deleter(); new (this) deleter(i); } void append(deleter d); private: static bool is_raw_object(impl* i) { auto x = reinterpret_cast<uintptr_t>(i); return x & 1; } bool is_raw_object() const { return is_raw_object(_impl); } static void* to_raw_object(impl* i) { auto x = reinterpret_cast<uintptr_t>(i); return reinterpret_cast<void*>(x & ~uintptr_t(1)); } void* to_raw_object() const { return to_raw_object(_impl); } impl* from_raw_object(void* object) { auto x = reinterpret_cast<uintptr_t>(object); return reinterpret_cast<impl*>(x | 1); } }; struct deleter::impl { unsigned refs = 1; deleter next; impl(deleter next) : next(std::move(next)) {} virtual ~impl() {} }; inline deleter::~deleter() { if (is_raw_object()) { std::free(to_raw_object()); return; } if (_impl && --_impl->refs == 0) { delete _impl; } } inline deleter& deleter::operator=(deleter&& x) { if (this != &x) { this->~deleter(); new (this) deleter(std::move(x)); } return *this; } template <typename Deleter> struct lambda_deleter_impl final : deleter::impl { Deleter del; lambda_deleter_impl(deleter next, Deleter&& del) : impl(std::move(next)), del(std::move(del)) {} virtual ~lambda_deleter_impl() override { del(); } }; template <typename Object> struct object_deleter_impl final : deleter::impl { Object obj; object_deleter_impl(deleter next, Object&& obj) : impl(std::move(next)), obj(std::move(obj)) {} }; template <typename Object> object_deleter_impl<Object>* make_object_deleter_impl(deleter next, Object obj) { return new object_deleter_impl<Object>(std::move(next), std::move(obj)); } template <typename Deleter> deleter make_deleter(deleter next, Deleter d) { return deleter(new lambda_deleter_impl<Deleter>(std::move(next), std::move(d))); } template <typename Deleter> deleter make_deleter(Deleter d) { return make_deleter(deleter(), std::move(d)); } struct free_deleter_impl final : deleter::impl { void* obj; free_deleter_impl(void* obj) : impl(deleter()), obj(obj) {} virtual ~free_deleter_impl() override { std::free(obj); } }; inline deleter deleter::share() { if (!_impl) { return deleter(); } if (is_raw_object()) { _impl = new free_deleter_impl(to_raw_object()); } ++_impl->refs; return deleter(_impl); } // Appends 'd' to the chain of deleters. Avoids allocation if possible. For // performance reasons the current chain should be shorter and 'd' should be // longer. inline void deleter::append(deleter d) { if (!d._impl) { return; } impl* next_impl = _impl; deleter* next_d = this; while (next_impl) { assert(next_impl != d._impl); if (is_raw_object(next_impl)) { next_d->_impl = next_impl = new free_deleter_impl(to_raw_object(next_impl)); } if (next_impl->refs != 1) { next_d->_impl = next_impl = make_object_deleter_impl(std::move(next_impl->next), deleter(next_impl)); } next_d = &next_impl->next; next_impl = next_d->_impl; } next_d->_impl = d._impl; d._impl = nullptr; } inline deleter make_free_deleter(void* obj) { if (!obj) { return deleter(); } return deleter(deleter::raw_object_tag(), obj); } inline deleter make_free_deleter(deleter next, void* obj) { return make_deleter(std::move(next), [obj] () mutable { std::free(obj); }); } #endif /* DELETER_HH_ */ <commit_msg>deleter: introduce make_object_deleter<commit_after>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef DELETER_HH_ #define DELETER_HH_ #include <memory> #include <cstdlib> #include <assert.h> #include <type_traits> class deleter final { public: struct impl; struct raw_object_tag {}; private: // if bit 0 set, point to object to be freed directly. impl* _impl = nullptr; public: deleter() = default; deleter(const deleter&) = delete; deleter(deleter&& x) : _impl(x._impl) { x._impl = nullptr; } explicit deleter(impl* i) : _impl(i) {} deleter(raw_object_tag tag, void* object) : _impl(from_raw_object(object)) {} ~deleter(); deleter& operator=(deleter&& x); deleter& operator=(deleter&) = delete; deleter share(); explicit operator bool() const { return bool(_impl); } void reset(impl* i) { this->~deleter(); new (this) deleter(i); } void append(deleter d); private: static bool is_raw_object(impl* i) { auto x = reinterpret_cast<uintptr_t>(i); return x & 1; } bool is_raw_object() const { return is_raw_object(_impl); } static void* to_raw_object(impl* i) { auto x = reinterpret_cast<uintptr_t>(i); return reinterpret_cast<void*>(x & ~uintptr_t(1)); } void* to_raw_object() const { return to_raw_object(_impl); } impl* from_raw_object(void* object) { auto x = reinterpret_cast<uintptr_t>(object); return reinterpret_cast<impl*>(x | 1); } }; struct deleter::impl { unsigned refs = 1; deleter next; impl(deleter next) : next(std::move(next)) {} virtual ~impl() {} }; inline deleter::~deleter() { if (is_raw_object()) { std::free(to_raw_object()); return; } if (_impl && --_impl->refs == 0) { delete _impl; } } inline deleter& deleter::operator=(deleter&& x) { if (this != &x) { this->~deleter(); new (this) deleter(std::move(x)); } return *this; } template <typename Deleter> struct lambda_deleter_impl final : deleter::impl { Deleter del; lambda_deleter_impl(deleter next, Deleter&& del) : impl(std::move(next)), del(std::move(del)) {} virtual ~lambda_deleter_impl() override { del(); } }; template <typename Object> struct object_deleter_impl final : deleter::impl { Object obj; object_deleter_impl(deleter next, Object&& obj) : impl(std::move(next)), obj(std::move(obj)) {} }; template <typename Object> inline object_deleter_impl<Object>* make_object_deleter_impl(deleter next, Object obj) { return new object_deleter_impl<Object>(std::move(next), std::move(obj)); } template <typename Deleter> deleter make_deleter(deleter next, Deleter d) { return deleter(new lambda_deleter_impl<Deleter>(std::move(next), std::move(d))); } template <typename Deleter> deleter make_deleter(Deleter d) { return make_deleter(deleter(), std::move(d)); } struct free_deleter_impl final : deleter::impl { void* obj; free_deleter_impl(void* obj) : impl(deleter()), obj(obj) {} virtual ~free_deleter_impl() override { std::free(obj); } }; inline deleter deleter::share() { if (!_impl) { return deleter(); } if (is_raw_object()) { _impl = new free_deleter_impl(to_raw_object()); } ++_impl->refs; return deleter(_impl); } // Appends 'd' to the chain of deleters. Avoids allocation if possible. For // performance reasons the current chain should be shorter and 'd' should be // longer. inline void deleter::append(deleter d) { if (!d._impl) { return; } impl* next_impl = _impl; deleter* next_d = this; while (next_impl) { assert(next_impl != d._impl); if (is_raw_object(next_impl)) { next_d->_impl = next_impl = new free_deleter_impl(to_raw_object(next_impl)); } if (next_impl->refs != 1) { next_d->_impl = next_impl = make_object_deleter_impl(std::move(next_impl->next), deleter(next_impl)); } next_d = &next_impl->next; next_impl = next_d->_impl; } next_d->_impl = d._impl; d._impl = nullptr; } inline deleter make_free_deleter(void* obj) { if (!obj) { return deleter(); } return deleter(deleter::raw_object_tag(), obj); } inline deleter make_free_deleter(deleter next, void* obj) { return make_deleter(std::move(next), [obj] () mutable { std::free(obj); }); } template <typename T> inline deleter make_object_deleter(T&& obj) { return deleter{make_object_deleter_impl(deleter(), std::move(obj))}; } template <typename T> inline deleter make_object_deleter(deleter d, T&& obj) { return deleter{make_object_deleter_impl(std::move(d), std::move(obj))}; } #endif /* DELETER_HH_ */ <|endoftext|>
<commit_before>#include "session.h" #include "util.h" Session::Session() { curl_ = {cpr::util::newHolder(), &cpr::util::freeHolder}; auto curl = curl_->handle; if (curl) { // Set up some sensible defaults auto version_info = curl_version_info(CURLVERSION_NOW); auto version = std::string{"curl/"} + std::string{version_info->version}; curl_easy_setopt(curl, CURLOPT_USERAGENT, version.data()); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L); curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 50L); curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); } } void Session::SetUrl(Url url) { auto curl = curl_->handle; if (curl) { curl_easy_setopt(curl, CURLOPT_URL, url.data()); } } void Session::SetUrl(Url url, Parameters parameters) { auto curl = curl_->handle; if (curl) { Url new_url{url + "?"}; for(auto parameter = parameters.cbegin(); parameter != parameters.cend(); ++parameter) { new_url += parameter->first + "=" + parameter->second; } curl_easy_setopt(curl, CURLOPT_URL, new_url.data()); } } void Session::SetHeader(Header header) { auto curl = curl_->handle; if (curl) { struct curl_slist* chunk = NULL; for (auto item = header.cbegin(); item != header.cend(); ++item) { auto header_string = std::string{item->first}; if (item->second.empty()) { header_string += ";"; } else { header_string += ": " + item->second; } chunk = curl_slist_append(chunk, header_string.data()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk); curl_->chunk = chunk; } } } void Session::SetTimeout(long timeout) { auto curl = curl_->handle; if (curl) { curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, timeout); } } void Session::SetAuth(Authentication auth) { auto curl = curl_->handle; if (curl) { curl_easy_setopt(curl, CURLOPT_USERPWD, auth.GetAuthString()); } } void Session::SetPayload(Payload payload) { auto curl = curl_->handle; if (curl) { struct curl_slist* chunk = NULL; auto payload_string = std::string{}; for (auto item = payload.cbegin(); item != payload.cend(); ++item) { if (!payload_string.empty()) { payload_string += "&"; } payload_string += item->first + "=" + item->second; } curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload_string.data()); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, payload_string.length()); } } void Session::SetRedirect(bool redirect) { auto curl = curl_->handle; if (curl) { curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, long(redirect)); } } Response Session::Get() { auto curl = curl_->handle; CURLcode res; if (curl) { curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L); curl_easy_setopt(curl, CURLOPT_POST, 0L); std::string response_string; std::string header_string; curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cpr::util::writeFunction); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string); curl_easy_setopt(curl, CURLOPT_HEADERDATA, &header_string); res = curl_easy_perform(curl); if (res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } char* raw_url; long response_code; double elapsed; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code); curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &elapsed); curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &raw_url); auto header = cpr::util::parseHeader(header_string); Response response{response_code, response_string, header, raw_url, elapsed}; return response; } return Response{0, "Curl could not start", Header{}, Url{}, 0.0}; } Response Session::Post() { auto curl = curl_->handle; CURLcode res; if (curl) { curl_easy_setopt(curl, CURLOPT_HTTPGET, 0L); curl_easy_setopt(curl, CURLOPT_POST, 1L); std::string response_string; std::string header_string; curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cpr::util::writeFunction); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string); curl_easy_setopt(curl, CURLOPT_HEADERDATA, &header_string); res = curl_easy_perform(curl); if (res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } char* raw_url; long response_code; double elapsed; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code); curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &elapsed); curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &raw_url); auto header = cpr::util::parseHeader(header_string); Response response{response_code, response_string, header, raw_url, elapsed}; return response; } return Response{0, "Curl could not start", Header{}, Url{}, 0.0}; } <commit_msg>Use preprocessor symbols to check for proper curl version necessary<commit_after>#include "session.h" #include "util.h" Session::Session() { curl_ = {cpr::util::newHolder(), &cpr::util::freeHolder}; auto curl = curl_->handle; if (curl) { // Set up some sensible defaults auto version_info = curl_version_info(CURLVERSION_NOW); auto version = std::string{"curl/"} + std::string{version_info->version}; curl_easy_setopt(curl, CURLOPT_USERAGENT, version.data()); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L); curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 50L); curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); #if LIBCURL_VERSION_MAJOR >= 7 #if LIBCURL_VERSION_MINOR >= 25 #if LIBCURL_VERSION_PATCH >= 0 curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L); #endif #endif #endif } } void Session::SetUrl(Url url) { auto curl = curl_->handle; if (curl) { curl_easy_setopt(curl, CURLOPT_URL, url.data()); } } void Session::SetUrl(Url url, Parameters parameters) { auto curl = curl_->handle; if (curl) { Url new_url{url + "?"}; for(auto parameter = parameters.cbegin(); parameter != parameters.cend(); ++parameter) { new_url += parameter->first + "=" + parameter->second; } curl_easy_setopt(curl, CURLOPT_URL, new_url.data()); } } void Session::SetHeader(Header header) { auto curl = curl_->handle; if (curl) { struct curl_slist* chunk = NULL; for (auto item = header.cbegin(); item != header.cend(); ++item) { auto header_string = std::string{item->first}; if (item->second.empty()) { header_string += ";"; } else { header_string += ": " + item->second; } chunk = curl_slist_append(chunk, header_string.data()); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk); curl_->chunk = chunk; } } } void Session::SetTimeout(long timeout) { auto curl = curl_->handle; if (curl) { curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT_MS, timeout); } } void Session::SetAuth(Authentication auth) { auto curl = curl_->handle; if (curl) { curl_easy_setopt(curl, CURLOPT_USERPWD, auth.GetAuthString()); } } void Session::SetPayload(Payload payload) { auto curl = curl_->handle; if (curl) { struct curl_slist* chunk = NULL; auto payload_string = std::string{}; for (auto item = payload.cbegin(); item != payload.cend(); ++item) { if (!payload_string.empty()) { payload_string += "&"; } payload_string += item->first + "=" + item->second; } curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload_string.data()); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, payload_string.length()); } } void Session::SetRedirect(bool redirect) { auto curl = curl_->handle; if (curl) { curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, long(redirect)); } } Response Session::Get() { auto curl = curl_->handle; CURLcode res; if (curl) { curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L); curl_easy_setopt(curl, CURLOPT_POST, 0L); std::string response_string; std::string header_string; curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cpr::util::writeFunction); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string); curl_easy_setopt(curl, CURLOPT_HEADERDATA, &header_string); res = curl_easy_perform(curl); if (res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } char* raw_url; long response_code; double elapsed; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code); curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &elapsed); curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &raw_url); auto header = cpr::util::parseHeader(header_string); Response response{response_code, response_string, header, raw_url, elapsed}; return response; } return Response{0, "Curl could not start", Header{}, Url{}, 0.0}; } Response Session::Post() { auto curl = curl_->handle; CURLcode res; if (curl) { curl_easy_setopt(curl, CURLOPT_HTTPGET, 0L); curl_easy_setopt(curl, CURLOPT_POST, 1L); std::string response_string; std::string header_string; curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, cpr::util::writeFunction); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string); curl_easy_setopt(curl, CURLOPT_HEADERDATA, &header_string); res = curl_easy_perform(curl); if (res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } char* raw_url; long response_code; double elapsed; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code); curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &elapsed); curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &raw_url); auto header = cpr::util::parseHeader(header_string); Response response{response_code, response_string, header, raw_url, elapsed}; return response; } return Response{0, "Curl could not start", Header{}, Url{}, 0.0}; } <|endoftext|>
<commit_before>/*********************************************************************** filename: CEGUIFalTextComponent.cpp created: Sun Jun 19 2005 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "falagard/CEGUIFalTextComponent.h" #include "falagard/CEGUIFalXMLEnumHelper.h" #include "CEGUIFontManager.h" #include "CEGUIExceptions.h" #include "CEGUIPropertyHelper.h" #include "CEGUIFont.h" #include "CEGUILeftAlignedRenderedString.h" #include "CEGUIRightAlignedRenderedString.h" #include "CEGUICentredRenderedString.h" #include "CEGUIJustifiedRenderedString.h" #include "CEGUIRenderedStringWordWrapper.h" #include <iostream> #if defined (CEGUI_USE_FRIBIDI) #include "CEGUIFribidiVisualMapping.h" #elif defined (CEGUI_USE_MINIBIDI) #include "CEGUIMinibidiVisualMapping.h" #else #include "CEGUIBiDiVisualMapping.h" #endif // Start of CEGUI namespace section namespace CEGUI { TextComponent::TextComponent() : #ifndef CEGUI_BIDI_SUPPORT d_bidiVisualMapping(0), #elif defined (CEGUI_USE_FRIBIDI) d_bidiVisualMapping(new FribidiVisualMapping), #elif defined (CEGUI_USE_MINIBIDI) d_bidiVisualMapping(new MinibidiVisualMapping), #else #error "BIDI Configuration is inconsistant, check your config!" #endif d_bidiDataValid(false), d_formattedRenderedString(new LeftAlignedRenderedString(d_renderedString)), d_lastHorzFormatting(HTF_LEFT_ALIGNED), d_vertFormatting(VTF_TOP_ALIGNED), d_horzFormatting(HTF_LEFT_ALIGNED) {} const String& TextComponent::getText() const { return d_textLogical; } void TextComponent::setText(const String& text) { d_textLogical = text; d_bidiDataValid = false; } const String& TextComponent::getFont() const { return d_font; } void TextComponent::setFont(const String& font) { d_font = font; } VerticalTextFormatting TextComponent::getVerticalFormatting() const { return d_vertFormatting; } void TextComponent::setVerticalFormatting(VerticalTextFormatting fmt) { d_vertFormatting = fmt; } HorizontalTextFormatting TextComponent::getHorizontalFormatting() const { return d_horzFormatting; } void TextComponent::setHorizontalFormatting(HorizontalTextFormatting fmt) { d_horzFormatting = fmt; } void TextComponent::setupStringFormatter(const Window& window, const RenderedString& rendered_string) const { const HorizontalTextFormatting horzFormatting = d_horzFormatPropertyName.empty() ? d_horzFormatting : FalagardXMLHelper::stringToHorzTextFormat(window.getProperty(d_horzFormatPropertyName)); // no formatting change if (horzFormatting == d_lastHorzFormatting) { d_formattedRenderedString->setRenderedString(rendered_string); return; } d_lastHorzFormatting = horzFormatting; switch(horzFormatting) { case HTF_LEFT_ALIGNED: d_formattedRenderedString = new LeftAlignedRenderedString(rendered_string); break; case HTF_CENTRE_ALIGNED: d_formattedRenderedString = new CentredRenderedString(rendered_string); break; case HTF_RIGHT_ALIGNED: d_formattedRenderedString = new RightAlignedRenderedString(rendered_string); break; case HTF_JUSTIFIED: d_formattedRenderedString = new JustifiedRenderedString(rendered_string); break; case HTF_WORDWRAP_LEFT_ALIGNED: d_formattedRenderedString = new RenderedStringWordWrapper <LeftAlignedRenderedString>(rendered_string); break; case HTF_WORDWRAP_CENTRE_ALIGNED: d_formattedRenderedString = new RenderedStringWordWrapper <CentredRenderedString>(rendered_string); break; case HTF_WORDWRAP_RIGHT_ALIGNED: d_formattedRenderedString = new RenderedStringWordWrapper <RightAlignedRenderedString>(rendered_string); break; case HTF_WORDWRAP_JUSTIFIED: d_formattedRenderedString = new RenderedStringWordWrapper <JustifiedRenderedString>(rendered_string); break; } } void TextComponent::render_impl(Window& srcWindow, Rect& destRect, const CEGUI::ColourRect* modColours, const Rect* clipper, bool /*clipToDisplay*/) const { // get font to use Font* font; try { font = d_fontPropertyName.empty() ? (d_font.empty() ? srcWindow.getFont() : &FontManager::getSingleton().get(d_font)) : &FontManager::getSingleton().get(srcWindow.getProperty(d_fontPropertyName)); } catch (UnknownObjectException&) { font = 0; } // exit if we have no font to use. if (!font) return; const RenderedString* rs = &d_renderedString; // do we fetch text from a property if (!d_textPropertyName.empty()) { // fetch text & do bi-directional reordering as needed String vis; #ifdef CEGUI_BIDI_SUPPORT BiDiVisualMapping::StrIndexList l2v, v2l; d_bidiVisualMapping->reorderFromLogicalToVisual( srcWindow.getProperty(d_textPropertyName), vis, l2v, v2l); #else vis = srcWindow.getProperty(d_textPropertyName); #endif // parse string using parser from Window. d_renderedString = srcWindow.getRenderedStringParser().parse(vis, font, modColours); } // do we use a static text string from the looknfeel else if (!getTextVisual().empty()) // parse string using parser from Window. d_renderedString = srcWindow.getRenderedStringParser(). parse(getTextVisual(), font, modColours); // use ready-made RenderedString from the Window itself else rs = &srcWindow.getRenderedString(); setupStringFormatter(srcWindow, *rs); d_formattedRenderedString->format(destRect.getSize()); // Get total formatted height. const float textHeight = d_formattedRenderedString->getVerticalExtent(); // handle dest area adjustments for vertical formatting. VerticalTextFormatting vertFormatting = d_vertFormatPropertyName.empty() ? d_vertFormatting : FalagardXMLHelper::stringToVertTextFormat(srcWindow.getProperty(d_vertFormatPropertyName)); switch(vertFormatting) { case VTF_CENTRE_ALIGNED: destRect.d_top += (destRect.getHeight() - textHeight) * 0.5f; break; case VTF_BOTTOM_ALIGNED: destRect.d_top = destRect.d_bottom - textHeight; break; default: // default is VTF_TOP_ALIGNED, for which we take no action. break; } // calculate final colours to be used ColourRect finalColours; initColoursRect(srcWindow, modColours, finalColours); // offset the font little down so that it's centered within its own spacing // destRect.d_top += (font->getLineSpacing() - font->getFontHeight()) * 0.5f; // add geometry for text to the target window. d_formattedRenderedString->draw(srcWindow.getGeometryBuffer(), destRect.getPosition(), &finalColours, clipper); } void TextComponent::writeXMLToStream(XMLSerializer& xml_stream) const { // opening tag xml_stream.openTag("TextComponent"); // write out area d_area.writeXMLToStream(xml_stream); // write text element if (!d_font.empty() && !getText().empty()) { xml_stream.openTag("Text"); if (!d_font.empty()) xml_stream.attribute("font", d_font); if (!getText().empty()) xml_stream.attribute("string", getText()); xml_stream.closeTag(); } // write text property element if (!d_textPropertyName.empty()) { xml_stream.openTag("TextProperty") .attribute("name", d_textPropertyName) .closeTag(); } // write font property element if (!d_fontPropertyName.empty()) { xml_stream.openTag("FontProperty") .attribute("name", d_fontPropertyName) .closeTag(); } // get base class to write colours writeColoursXML(xml_stream); // write vert format, allowing base class to do this for us if a propety is in use if (!writeVertFormatXML(xml_stream)) { // was not a property, so write out explicit formatting in use xml_stream.openTag("VertFormat") .attribute("type", FalagardXMLHelper::vertTextFormatToString(d_vertFormatting)) .closeTag(); } // write horz format, allowing base class to do this for us if a propety is in use if (!writeHorzFormatXML(xml_stream)) { // was not a property, so write out explicit formatting in use xml_stream.openTag("HorzFormat") .attribute("type", FalagardXMLHelper::horzTextFormatToString(d_horzFormatting)) .closeTag(); } // closing tag xml_stream.closeTag(); } bool TextComponent::isTextFetchedFromProperty() const { return !d_textPropertyName.empty(); } const String& TextComponent::getTextPropertySource() const { return d_textPropertyName; } void TextComponent::setTextPropertySource(const String& property) { d_textPropertyName = property; } bool TextComponent::isFontFetchedFromProperty() const { return !d_fontPropertyName.empty(); } const String& TextComponent::getFontPropertySource() const { return d_fontPropertyName; } void TextComponent::setFontPropertySource(const String& property) { d_fontPropertyName = property; } const String& TextComponent::getTextVisual() const { // no bidi support if (!d_bidiVisualMapping) return d_textLogical; if (!d_bidiDataValid) { d_bidiVisualMapping->updateVisual(d_textLogical); d_bidiDataValid = true; } return d_bidiVisualMapping->getTextVisual(); } } // End of CEGUI namespace section <commit_msg>FIX: Ensure falagard rules are applied correctly as regards to fonts and text handling.<commit_after>/*********************************************************************** filename: CEGUIFalTextComponent.cpp created: Sun Jun 19 2005 author: Paul D Turner <paul@cegui.org.uk> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "falagard/CEGUIFalTextComponent.h" #include "falagard/CEGUIFalXMLEnumHelper.h" #include "CEGUIFontManager.h" #include "CEGUIExceptions.h" #include "CEGUIPropertyHelper.h" #include "CEGUIFont.h" #include "CEGUILeftAlignedRenderedString.h" #include "CEGUIRightAlignedRenderedString.h" #include "CEGUICentredRenderedString.h" #include "CEGUIJustifiedRenderedString.h" #include "CEGUIRenderedStringWordWrapper.h" #include <iostream> #if defined (CEGUI_USE_FRIBIDI) #include "CEGUIFribidiVisualMapping.h" #elif defined (CEGUI_USE_MINIBIDI) #include "CEGUIMinibidiVisualMapping.h" #else #include "CEGUIBiDiVisualMapping.h" #endif // Start of CEGUI namespace section namespace CEGUI { TextComponent::TextComponent() : #ifndef CEGUI_BIDI_SUPPORT d_bidiVisualMapping(0), #elif defined (CEGUI_USE_FRIBIDI) d_bidiVisualMapping(new FribidiVisualMapping), #elif defined (CEGUI_USE_MINIBIDI) d_bidiVisualMapping(new MinibidiVisualMapping), #else #error "BIDI Configuration is inconsistant, check your config!" #endif d_bidiDataValid(false), d_formattedRenderedString(new LeftAlignedRenderedString(d_renderedString)), d_lastHorzFormatting(HTF_LEFT_ALIGNED), d_vertFormatting(VTF_TOP_ALIGNED), d_horzFormatting(HTF_LEFT_ALIGNED) {} const String& TextComponent::getText() const { return d_textLogical; } void TextComponent::setText(const String& text) { d_textLogical = text; d_bidiDataValid = false; } const String& TextComponent::getFont() const { return d_font; } void TextComponent::setFont(const String& font) { d_font = font; } VerticalTextFormatting TextComponent::getVerticalFormatting() const { return d_vertFormatting; } void TextComponent::setVerticalFormatting(VerticalTextFormatting fmt) { d_vertFormatting = fmt; } HorizontalTextFormatting TextComponent::getHorizontalFormatting() const { return d_horzFormatting; } void TextComponent::setHorizontalFormatting(HorizontalTextFormatting fmt) { d_horzFormatting = fmt; } void TextComponent::setupStringFormatter(const Window& window, const RenderedString& rendered_string) const { const HorizontalTextFormatting horzFormatting = d_horzFormatPropertyName.empty() ? d_horzFormatting : FalagardXMLHelper::stringToHorzTextFormat(window.getProperty(d_horzFormatPropertyName)); // no formatting change if (horzFormatting == d_lastHorzFormatting) { d_formattedRenderedString->setRenderedString(rendered_string); return; } d_lastHorzFormatting = horzFormatting; switch(horzFormatting) { case HTF_LEFT_ALIGNED: d_formattedRenderedString = new LeftAlignedRenderedString(rendered_string); break; case HTF_CENTRE_ALIGNED: d_formattedRenderedString = new CentredRenderedString(rendered_string); break; case HTF_RIGHT_ALIGNED: d_formattedRenderedString = new RightAlignedRenderedString(rendered_string); break; case HTF_JUSTIFIED: d_formattedRenderedString = new JustifiedRenderedString(rendered_string); break; case HTF_WORDWRAP_LEFT_ALIGNED: d_formattedRenderedString = new RenderedStringWordWrapper <LeftAlignedRenderedString>(rendered_string); break; case HTF_WORDWRAP_CENTRE_ALIGNED: d_formattedRenderedString = new RenderedStringWordWrapper <CentredRenderedString>(rendered_string); break; case HTF_WORDWRAP_RIGHT_ALIGNED: d_formattedRenderedString = new RenderedStringWordWrapper <RightAlignedRenderedString>(rendered_string); break; case HTF_WORDWRAP_JUSTIFIED: d_formattedRenderedString = new RenderedStringWordWrapper <JustifiedRenderedString>(rendered_string); break; } } void TextComponent::render_impl(Window& srcWindow, Rect& destRect, const CEGUI::ColourRect* modColours, const Rect* clipper, bool /*clipToDisplay*/) const { // get font to use Font* font; try { font = d_fontPropertyName.empty() ? (d_font.empty() ? srcWindow.getFont() : &FontManager::getSingleton().get(d_font)) : &FontManager::getSingleton().get(srcWindow.getProperty(d_fontPropertyName)); } catch (UnknownObjectException&) { font = 0; } // exit if we have no font to use. if (!font) return; const RenderedString* rs = &d_renderedString; // do we fetch text from a property if (!d_textPropertyName.empty()) { // fetch text & do bi-directional reordering as needed String vis; #ifdef CEGUI_BIDI_SUPPORT BiDiVisualMapping::StrIndexList l2v, v2l; d_bidiVisualMapping->reorderFromLogicalToVisual( srcWindow.getProperty(d_textPropertyName), vis, l2v, v2l); #else vis = srcWindow.getProperty(d_textPropertyName); #endif // parse string using parser from Window. d_renderedString = srcWindow.getRenderedStringParser().parse(vis, font, modColours); } // do we use a static text string from the looknfeel else if (!getTextVisual().empty()) // parse string using parser from Window. d_renderedString = srcWindow.getRenderedStringParser(). parse(getTextVisual(), font, modColours); // do we have to override the font? else if (font != srcWindow.getFont()) d_renderedString = srcWindow.getRenderedStringParser(). parse(srcWindow.getTextVisual(), font, modColours); // use ready-made RenderedString from the Window itself else rs = &srcWindow.getRenderedString(); setupStringFormatter(srcWindow, *rs); d_formattedRenderedString->format(destRect.getSize()); // Get total formatted height. const float textHeight = d_formattedRenderedString->getVerticalExtent(); // handle dest area adjustments for vertical formatting. VerticalTextFormatting vertFormatting = d_vertFormatPropertyName.empty() ? d_vertFormatting : FalagardXMLHelper::stringToVertTextFormat(srcWindow.getProperty(d_vertFormatPropertyName)); switch(vertFormatting) { case VTF_CENTRE_ALIGNED: destRect.d_top += (destRect.getHeight() - textHeight) * 0.5f; break; case VTF_BOTTOM_ALIGNED: destRect.d_top = destRect.d_bottom - textHeight; break; default: // default is VTF_TOP_ALIGNED, for which we take no action. break; } // calculate final colours to be used ColourRect finalColours; initColoursRect(srcWindow, modColours, finalColours); // offset the font little down so that it's centered within its own spacing // destRect.d_top += (font->getLineSpacing() - font->getFontHeight()) * 0.5f; // add geometry for text to the target window. d_formattedRenderedString->draw(srcWindow.getGeometryBuffer(), destRect.getPosition(), &finalColours, clipper); } void TextComponent::writeXMLToStream(XMLSerializer& xml_stream) const { // opening tag xml_stream.openTag("TextComponent"); // write out area d_area.writeXMLToStream(xml_stream); // write text element if (!d_font.empty() && !getText().empty()) { xml_stream.openTag("Text"); if (!d_font.empty()) xml_stream.attribute("font", d_font); if (!getText().empty()) xml_stream.attribute("string", getText()); xml_stream.closeTag(); } // write text property element if (!d_textPropertyName.empty()) { xml_stream.openTag("TextProperty") .attribute("name", d_textPropertyName) .closeTag(); } // write font property element if (!d_fontPropertyName.empty()) { xml_stream.openTag("FontProperty") .attribute("name", d_fontPropertyName) .closeTag(); } // get base class to write colours writeColoursXML(xml_stream); // write vert format, allowing base class to do this for us if a propety is in use if (!writeVertFormatXML(xml_stream)) { // was not a property, so write out explicit formatting in use xml_stream.openTag("VertFormat") .attribute("type", FalagardXMLHelper::vertTextFormatToString(d_vertFormatting)) .closeTag(); } // write horz format, allowing base class to do this for us if a propety is in use if (!writeHorzFormatXML(xml_stream)) { // was not a property, so write out explicit formatting in use xml_stream.openTag("HorzFormat") .attribute("type", FalagardXMLHelper::horzTextFormatToString(d_horzFormatting)) .closeTag(); } // closing tag xml_stream.closeTag(); } bool TextComponent::isTextFetchedFromProperty() const { return !d_textPropertyName.empty(); } const String& TextComponent::getTextPropertySource() const { return d_textPropertyName; } void TextComponent::setTextPropertySource(const String& property) { d_textPropertyName = property; } bool TextComponent::isFontFetchedFromProperty() const { return !d_fontPropertyName.empty(); } const String& TextComponent::getFontPropertySource() const { return d_fontPropertyName; } void TextComponent::setFontPropertySource(const String& property) { d_fontPropertyName = property; } const String& TextComponent::getTextVisual() const { // no bidi support if (!d_bidiVisualMapping) return d_textLogical; if (!d_bidiDataValid) { d_bidiVisualMapping->updateVisual(d_textLogical); d_bidiDataValid = true; } return d_bidiVisualMapping->getTextVisual(); } } // End of CEGUI namespace section <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/boot_times_loader.h" #include <vector> #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/process_util.h" #include "base/string_util.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_thread.h" #include "chrome/common/chrome_switches.h" namespace { typedef struct Stats { std::string uptime; std::string disk; Stats() : uptime(std::string()), disk(std::string()) {} }; } namespace chromeos { // File uptime logs are located in. static const char kLogPath[] = "/tmp"; // Prefix for the time measurement files. static const char kUptimePrefix[] = "uptime-"; // Prefix for the disk usage files. static const char kDiskPrefix[] = "disk-"; // Name of the time that Chrome's main() is called. static const char kChromeMain[] = "chrome-main"; // Delay in milliseconds between file read attempts. static const int64 kReadAttemptDelayMs = 250; BootTimesLoader::BootTimesLoader() : backend_(new Backend()) { } BootTimesLoader::Handle BootTimesLoader::GetBootTimes( CancelableRequestConsumerBase* consumer, BootTimesLoader::GetBootTimesCallback* callback) { if (!g_browser_process->file_thread()) { // This should only happen if Chrome is shutting down, so we don't do // anything. return 0; } const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kTestType)) { // TODO(davemoore) This avoids boottimes for tests. This needs to be // replaced with a mock of BootTimesLoader. return 0; } scoped_refptr<CancelableRequest<GetBootTimesCallback> > request( new CancelableRequest<GetBootTimesCallback>(callback)); AddRequest(request, consumer); ChromeThread::PostTask( ChromeThread::FILE, FROM_HERE, NewRunnableMethod(backend_.get(), &Backend::GetBootTimes, request)); return request->handle(); } // Extracts the uptime value from files located in /tmp, returning the // value as a double in value. static bool GetTime(const std::string& log, double* value) { FilePath log_dir(kLogPath); FilePath log_file = log_dir.Append(log); std::string contents; *value = 0.0; if (file_util::ReadFileToString(log_file, &contents)) { size_t space_index = contents.find(' '); size_t chars_left = space_index != std::string::npos ? space_index : std::string::npos; std::string value_string = contents.substr(0, chars_left); return StringToDouble(value_string, value); } return false; } void BootTimesLoader::Backend::GetBootTimes( scoped_refptr<GetBootTimesRequest> request) { const char* kFirmwareBootTime = "firmware-boot-time"; const char* kPreStartup = "pre-startup"; const char* kChromeExec = "chrome-exec"; const char* kChromeMain = "chrome-main"; const char* kXStarted = "x-started"; const char* kLoginPromptReady = "login-prompt-ready"; std::string uptime_prefix = kUptimePrefix; if (request->canceled()) return; // Wait until login_prompt_ready is output by reposting. FilePath log_dir(kLogPath); FilePath log_file = log_dir.Append(kLoginPromptReady); if (!file_util::PathExists(log_file)) { ChromeThread::PostDelayedTask( ChromeThread::FILE, FROM_HERE, NewRunnableMethod(this, &Backend::GetBootTimes, request), kReadAttemptDelayMs); return; } BootTimes boot_times; GetTime(kFirmwareBootTime, &boot_times.firmware); GetTime(uptime_prefix + kPreStartup, &boot_times.pre_startup); GetTime(uptime_prefix + kXStarted, &boot_times.x_started); GetTime(uptime_prefix + kChromeExec, &boot_times.chrome_exec); GetTime(uptime_prefix + kChromeMain, &boot_times.chrome_main); GetTime(uptime_prefix + kLoginPromptReady, &boot_times.login_prompt_ready); request->ForwardResult( GetBootTimesCallback::TupleType(request->handle(), boot_times)); } static void RecordStatsDelayed( const std::string& name, const std::string& uptime, const std::string& disk) { const FilePath log_path(kLogPath); std::string disk_prefix = kDiskPrefix; const FilePath uptime_output = log_path.Append(FilePath(kUptimePrefix + name)); const FilePath disk_output = log_path.Append(FilePath(kDiskPrefix + name)); // Write out the files, ensuring that they don't exist already. if (!file_util::PathExists(uptime_output)) file_util::WriteFile(uptime_output, uptime.data(), uptime.size()); if (!file_util::PathExists(disk_output)) file_util::WriteFile(disk_output, disk.data(), disk.size()); } static void RecordStats( const std::string& name, const Stats& stats) { ChromeThread::PostTask( ChromeThread::FILE, FROM_HERE, NewRunnableFunction(RecordStatsDelayed, name, stats.uptime, stats.disk)); } static Stats GetCurrentStats() { const FilePath kProcUptime("/proc/uptime"); const FilePath kDiskStat("/sys/block/sda/stat"); Stats stats; file_util::ReadFileToString(kProcUptime, &stats.uptime); file_util::ReadFileToString(kDiskStat, &stats.disk); return stats; } // static void BootTimesLoader::RecordCurrentStats(const std::string& name) { Stats stats = GetCurrentStats(); RecordStats(name, stats); } // Used to hold the stats at main(). static Stats chrome_main_stats_; void BootTimesLoader::SaveChromeMainStats() { chrome_main_stats_ = GetCurrentStats(); } void BootTimesLoader::RecordChromeMainStats() { RecordStats(kChromeMain, chrome_main_stats_); } } // namespace chromeos <commit_msg>Fix new gcc error. This only happens on the ARM build, using a different compiler.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/boot_times_loader.h" #include <vector> #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/process_util.h" #include "base/string_util.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_thread.h" #include "chrome/common/chrome_switches.h" namespace { typedef struct Stats { std::string uptime; std::string disk; Stats() : uptime(std::string()), disk(std::string()) {} } Stats; } namespace chromeos { // File uptime logs are located in. static const char kLogPath[] = "/tmp"; // Prefix for the time measurement files. static const char kUptimePrefix[] = "uptime-"; // Prefix for the disk usage files. static const char kDiskPrefix[] = "disk-"; // Name of the time that Chrome's main() is called. static const char kChromeMain[] = "chrome-main"; // Delay in milliseconds between file read attempts. static const int64 kReadAttemptDelayMs = 250; BootTimesLoader::BootTimesLoader() : backend_(new Backend()) { } BootTimesLoader::Handle BootTimesLoader::GetBootTimes( CancelableRequestConsumerBase* consumer, BootTimesLoader::GetBootTimesCallback* callback) { if (!g_browser_process->file_thread()) { // This should only happen if Chrome is shutting down, so we don't do // anything. return 0; } const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kTestType)) { // TODO(davemoore) This avoids boottimes for tests. This needs to be // replaced with a mock of BootTimesLoader. return 0; } scoped_refptr<CancelableRequest<GetBootTimesCallback> > request( new CancelableRequest<GetBootTimesCallback>(callback)); AddRequest(request, consumer); ChromeThread::PostTask( ChromeThread::FILE, FROM_HERE, NewRunnableMethod(backend_.get(), &Backend::GetBootTimes, request)); return request->handle(); } // Extracts the uptime value from files located in /tmp, returning the // value as a double in value. static bool GetTime(const std::string& log, double* value) { FilePath log_dir(kLogPath); FilePath log_file = log_dir.Append(log); std::string contents; *value = 0.0; if (file_util::ReadFileToString(log_file, &contents)) { size_t space_index = contents.find(' '); size_t chars_left = space_index != std::string::npos ? space_index : std::string::npos; std::string value_string = contents.substr(0, chars_left); return StringToDouble(value_string, value); } return false; } void BootTimesLoader::Backend::GetBootTimes( scoped_refptr<GetBootTimesRequest> request) { const char* kFirmwareBootTime = "firmware-boot-time"; const char* kPreStartup = "pre-startup"; const char* kChromeExec = "chrome-exec"; const char* kChromeMain = "chrome-main"; const char* kXStarted = "x-started"; const char* kLoginPromptReady = "login-prompt-ready"; std::string uptime_prefix = kUptimePrefix; if (request->canceled()) return; // Wait until login_prompt_ready is output by reposting. FilePath log_dir(kLogPath); FilePath log_file = log_dir.Append(kLoginPromptReady); if (!file_util::PathExists(log_file)) { ChromeThread::PostDelayedTask( ChromeThread::FILE, FROM_HERE, NewRunnableMethod(this, &Backend::GetBootTimes, request), kReadAttemptDelayMs); return; } BootTimes boot_times; GetTime(kFirmwareBootTime, &boot_times.firmware); GetTime(uptime_prefix + kPreStartup, &boot_times.pre_startup); GetTime(uptime_prefix + kXStarted, &boot_times.x_started); GetTime(uptime_prefix + kChromeExec, &boot_times.chrome_exec); GetTime(uptime_prefix + kChromeMain, &boot_times.chrome_main); GetTime(uptime_prefix + kLoginPromptReady, &boot_times.login_prompt_ready); request->ForwardResult( GetBootTimesCallback::TupleType(request->handle(), boot_times)); } static void RecordStatsDelayed( const std::string& name, const std::string& uptime, const std::string& disk) { const FilePath log_path(kLogPath); std::string disk_prefix = kDiskPrefix; const FilePath uptime_output = log_path.Append(FilePath(kUptimePrefix + name)); const FilePath disk_output = log_path.Append(FilePath(kDiskPrefix + name)); // Write out the files, ensuring that they don't exist already. if (!file_util::PathExists(uptime_output)) file_util::WriteFile(uptime_output, uptime.data(), uptime.size()); if (!file_util::PathExists(disk_output)) file_util::WriteFile(disk_output, disk.data(), disk.size()); } static void RecordStats( const std::string& name, const Stats& stats) { ChromeThread::PostTask( ChromeThread::FILE, FROM_HERE, NewRunnableFunction(RecordStatsDelayed, name, stats.uptime, stats.disk)); } static Stats GetCurrentStats() { const FilePath kProcUptime("/proc/uptime"); const FilePath kDiskStat("/sys/block/sda/stat"); Stats stats; file_util::ReadFileToString(kProcUptime, &stats.uptime); file_util::ReadFileToString(kDiskStat, &stats.disk); return stats; } // static void BootTimesLoader::RecordCurrentStats(const std::string& name) { Stats stats = GetCurrentStats(); RecordStats(name, stats); } // Used to hold the stats at main(). static Stats chrome_main_stats_; void BootTimesLoader::SaveChromeMainStats() { chrome_main_stats_ = GetCurrentStats(); } void BootTimesLoader::RecordChromeMainStats() { RecordStats(kChromeMain, chrome_main_stats_); } } // namespace chromeos <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/find_bar_host.h" #include "chrome/browser/ui/find_bar/find_bar_controller.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/browser/tab_contents/tab_contents_view.h" void FindBarHost::AudibleAlert() { // TODO(davemoore) implement. NOTIMPLEMENTED(); } void FindBarHost::GetWidgetPositionNative(gfx::Rect* avoid_overlapping_rect) { gfx::Rect frame_rect = host()->GetTopLevelWidget()->GetWindowScreenBounds(); TabContentsView* tab_view = find_bar_controller_->tab_contents()->view(); gfx::Rect webcontents_rect; tab_view->GetViewBounds(&webcontents_rect); avoid_overlapping_rect->Offset(0, webcontents_rect.y() - frame_rect.y()); } bool FindBarHost::ShouldForwardKeyEventToWebpageNative( const views::KeyEvent& key_event) { return true; } <commit_msg>Fix overlapping_rect's screen coordinate calculation in find bar<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/find_bar_host.h" #include "chrome/browser/ui/find_bar/find_bar_controller.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/browser/tab_contents/tab_contents_view.h" #if defined(TOUCH_UI) #include "chrome/browser/ui/views/tab_contents/tab_contents_view_touch.h" #endif void FindBarHost::AudibleAlert() { // TODO(davemoore) implement. NOTIMPLEMENTED(); } void FindBarHost::GetWidgetPositionNative(gfx::Rect* avoid_overlapping_rect) { gfx::Rect frame_rect = host()->GetTopLevelWidget()->GetWindowScreenBounds(); TabContentsView* tab_view = find_bar_controller_->tab_contents()->view(); gfx::Rect webcontents_rect; #if defined(TOUCH_UI) webcontents_rect = static_cast<TabContentsViewTouch*>(tab_view)->GetScreenBounds(); #else tab_view->GetViewBounds(&webcontents_rect); #endif avoid_overlapping_rect->Offset(0, webcontents_rect.y() - frame_rect.y()); } bool FindBarHost::ShouldForwardKeyEventToWebpageNative( const views::KeyEvent& key_event) { return true; } <|endoftext|>
<commit_before>// Copyright (c) 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <windows.h> #include "base/at_exit.h" #include "base/command_line.h" #include "base/logging_win.h" #include "base/process/process.h" #include "base/synchronization/waitable_event.h" #include "base/template_util.h" #include "components/browser_watcher/exit_code_watcher_win.h" #include "components/browser_watcher/exit_funnel_win.h" #include "components/browser_watcher/watcher_main_api_win.h" namespace { // Use the same log facility as Chrome for convenience. // {7FE69228-633E-4f06-80C1-527FEA23E3A7} const GUID kChromeWatcherTraceProviderName = { 0x7fe69228, 0x633e, 0x4f06, { 0x80, 0xc1, 0x52, 0x7f, 0xea, 0x23, 0xe3, 0xa7 } }; // The data shared from the main function to the console handler. struct HandlerData { HandlerData() : handler_done(true /* manual_reset */, false /* initially_signaled */) { } base::WaitableEvent handler_done; base::ProcessHandle process; const base::char16* registry_path; }; HandlerData *g_handler_data = nullptr; BOOL CALLBACK ConsoleCtrlHandler(DWORD ctl_type) { if (g_handler_data && ctl_type == CTRL_LOGOFF_EVENT) { // Record the watcher logoff event in the browser's exit funnel. browser_watcher::ExitFunnel funnel; funnel.Init(g_handler_data->registry_path, g_handler_data->process); funnel.RecordEvent(L"WatcherLogoff"); // Release the main function. g_handler_data->handler_done.Signal(); } // Fall through to the next handler in turn. return FALSE; } } // namespace // The main entry point to the watcher, declared as extern "C" to avoid name // mangling. extern "C" int WatcherMain(const base::char16* registry_path, HANDLE process_handle) { base::Process process(process_handle); // The exit manager is in charge of calling the dtors of singletons. base::AtExitManager exit_manager; // Initialize the commandline singleton from the environment. base::CommandLine::Init(0, nullptr); logging::LogEventProvider::Initialize(kChromeWatcherTraceProviderName); // Arrange to be shut down as late as possible, as we want to outlive // chrome.exe in order to report its exit status. // TODO(siggi): Does this (windowless) process need to register a console // handler too, in order to get notice of logoff events? ::SetProcessShutdownParameters(0x100, SHUTDOWN_NORETRY); browser_watcher::ExitCodeWatcher exit_code_watcher(registry_path); int ret = 1; // Attempt to wait on our parent process, and record its exit status. if (exit_code_watcher.Initialize(process.Duplicate())) { // Set up a console control handler, and provide it the data it needs // to record into the browser's exit funnel. HandlerData data; data.process = process.Handle(); data.registry_path = registry_path; g_handler_data = &data; ::SetConsoleCtrlHandler(&ConsoleCtrlHandler, TRUE /* Add */); // Wait on the process. exit_code_watcher.WaitForExit(); browser_watcher::ExitFunnel funnel; funnel.Init(registry_path, process.Handle()); funnel.RecordEvent(L"BrowserExit"); // Chrome/content exit codes are currently in the range of 0-28. // Anything outside this range is strange, so watch harder. int exit_code = exit_code_watcher.exit_code(); if (exit_code < 0 || exit_code > 28) { // Wait for a max of 30 seconds to see whether we get notified of logoff. data.handler_done.TimedWait(base::TimeDelta::FromSeconds(30)); } // Remove the console control handler. // There is a potential race here, where the handler might be executing // already as we fall through here. Hopefully SetConsoleCtrlHandler is // synchronizing against handler execution, for there's no other way to // close the race. Thankfully we'll just get snuffed out, as this is logoff. ::SetConsoleCtrlHandler(&ConsoleCtrlHandler, FALSE /* Add */); g_handler_data = nullptr; ret = 0; } // Wind logging down. logging::LogEventProvider::Uninitialize(); return ret; } static_assert(base::is_same<decltype(&WatcherMain), browser_watcher::WatcherMainFunction>::value, "WatcherMain() has wrong type"); <commit_msg>Use a window to catch WM_ENDSESSION.<commit_after>// Copyright (c) 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <windows.h> #include "base/at_exit.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/logging_win.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop_proxy.h" #include "base/process/process.h" #include "base/run_loop.h" #include "base/sequenced_task_runner.h" #include "base/synchronization/waitable_event.h" #include "base/template_util.h" #include "base/threading/thread.h" #include "base/time/time.h" #include "components/browser_watcher/endsession_watcher_window_win.h" #include "components/browser_watcher/exit_code_watcher_win.h" #include "components/browser_watcher/exit_funnel_win.h" #include "components/browser_watcher/watcher_main_api_win.h" namespace { // Use the same log facility as Chrome for convenience. // {7FE69228-633E-4f06-80C1-527FEA23E3A7} const GUID kChromeWatcherTraceProviderName = { 0x7fe69228, 0x633e, 0x4f06, { 0x80, 0xc1, 0x52, 0x7f, 0xea, 0x23, 0xe3, 0xa7 } }; // Takes care of monitoring a browser. This class watches for a browser's exit // code, as well as listening for WM_ENDSESSION messages. Events are recorded // in an exit funnel, for reporting the next time Chrome runs. class BrowserMonitor { public: BrowserMonitor(base::RunLoop* run_loop, const base::char16* registry_path); ~BrowserMonitor(); // Starts the monitor, returns true on success. bool StartWatching(const base::char16* registry_path, base::Process process); private: // Called from EndSessionWatcherWindow on a WM_ENDSESSION message. void OnEndSession(LPARAM lparam); // Blocking function that runs on |background_thread_|. void Watch(); // Posted to main thread from Watch when browser exits. void BrowserExited(); // True if BrowserExited has run. bool browser_exited_; // The funnel used to record events for this browser. browser_watcher::ExitFunnel exit_funnel_; browser_watcher::ExitCodeWatcher exit_code_watcher_; browser_watcher::EndSessionWatcherWindow end_session_watcher_window_; // The thread that runs Watch(). base::Thread background_thread_; // The run loop for the main thread and its task runner. base::RunLoop* run_loop_; scoped_refptr<base::SequencedTaskRunner> main_thread_; DISALLOW_COPY_AND_ASSIGN(BrowserMonitor); }; BrowserMonitor::BrowserMonitor(base::RunLoop* run_loop, const base::char16* registry_path) : browser_exited_(false), exit_code_watcher_(registry_path), end_session_watcher_window_( base::Bind(&BrowserMonitor::OnEndSession, base::Unretained(this))), background_thread_("BrowserWatcherThread"), run_loop_(run_loop), main_thread_(base::MessageLoopProxy::current()) { } BrowserMonitor::~BrowserMonitor() { } bool BrowserMonitor::StartWatching(const base::char16* registry_path, base::Process process) { if (!exit_code_watcher_.Initialize(process.Pass())) return false; if (!exit_funnel_.Init(registry_path, exit_code_watcher_.process().Handle())) { return false; } if (!background_thread_.StartWithOptions( base::Thread::Options(base::MessageLoop::TYPE_IO, 0))) { return false; } if (!background_thread_.task_runner()->PostTask(FROM_HERE, base::Bind(&BrowserMonitor::Watch, base::Unretained(this)))) { background_thread_.Stop(); return false; } return true; } void BrowserMonitor::OnEndSession(LPARAM lparam) { DCHECK_EQ(main_thread_, base::MessageLoopProxy::current()); exit_funnel_.RecordEvent(L"WatcherLogoff"); // Belt-and-suspenders; make sure our message loop exits ASAP. if (browser_exited_) run_loop_->Quit(); } void BrowserMonitor::Watch() { // This needs to run on an IO thread. DCHECK_NE(main_thread_, base::MessageLoopProxy::current()); exit_code_watcher_.WaitForExit(); exit_funnel_.RecordEvent(L"BrowserExit"); main_thread_->PostTask(FROM_HERE, base::Bind(&BrowserMonitor::BrowserExited, base::Unretained(this))); } void BrowserMonitor::BrowserExited() { // This runs in the main thread. DCHECK_EQ(main_thread_, base::MessageLoopProxy::current()); // Note that the browser has exited. browser_exited_ = true; // Our background thread has served it's purpose. background_thread_.Stop(); const int exit_code = exit_code_watcher_.exit_code(); if (exit_code >= 0 && exit_code <= 28) { // The browser exited with a well-known exit code, quit this process // immediately. run_loop_->Quit(); } else { // The browser exited abnormally, wait around for a little bit to see // whether this instance will get a logoff message. main_thread_->PostDelayedTask(FROM_HERE, run_loop_->QuitClosure(), base::TimeDelta::FromSeconds(30)); } } } // namespace // The main entry point to the watcher, declared as extern "C" to avoid name // mangling. extern "C" int WatcherMain(const base::char16* registry_path, HANDLE process_handle) { base::Process process(process_handle); // The exit manager is in charge of calling the dtors of singletons. base::AtExitManager exit_manager; // Initialize the commandline singleton from the environment. base::CommandLine::Init(0, nullptr); logging::LogEventProvider::Initialize(kChromeWatcherTraceProviderName); // Arrange to be shut down as late as possible, as we want to outlive // chrome.exe in order to report its exit status. ::SetProcessShutdownParameters(0x100, SHUTDOWN_NORETRY); // Run a UI message loop on the main thread. base::MessageLoop msg_loop(base::MessageLoop::TYPE_UI); msg_loop.set_thread_name("WatcherMainThread"); base::RunLoop run_loop; BrowserMonitor monitor(&run_loop, registry_path); if (!monitor.StartWatching(registry_path, process.Pass())) return 1; run_loop.Run(); // Wind logging down. logging::LogEventProvider::Uninitialize(); return 0; } static_assert(base::is_same<decltype(&WatcherMain), browser_watcher::WatcherMainFunction>::value, "WatcherMain() has wrong type"); <|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/renderer/media/video_renderer_impl.h" #include "media/base/buffers.h" #include "media/base/yuv_convert.h" VideoRendererImpl::VideoRendererImpl(WebMediaPlayerImpl* delegate) : delegate_(delegate), last_converted_frame_(NULL) { // TODO(hclam): decide whether to do the following line in this thread or // in the render thread. delegate_->SetVideoRenderer(this); } // static bool VideoRendererImpl::IsMediaFormatSupported( const media::MediaFormat& media_format) { int width = 0; int height = 0; return ParseMediaFormat(media_format, &width, &height); } void VideoRendererImpl::Stop() { VideoThread::Stop(); delegate_->SetVideoRenderer(NULL); } bool VideoRendererImpl::OnInitialize(media::VideoDecoder* decoder) { int width = 0; int height = 0; if (!ParseMediaFormat(decoder->media_format(), &width, &height)) return false; video_size_.SetSize(width, height); bitmap_.setConfig(SkBitmap::kARGB_8888_Config, width, height); if (bitmap_.allocPixels(NULL, NULL)) { bitmap_.eraseRGB(0x00, 0x00, 0x00); return true; } NOTREACHED(); return false; } void VideoRendererImpl::SetRect(const gfx::Rect& rect) {} void VideoRendererImpl::OnFrameAvailable() { delegate_->PostRepaintTask(); } // This method is always called on the renderer's thread. void VideoRendererImpl::Paint(skia::PlatformCanvas* canvas, const gfx::Rect& dest_rect) { scoped_refptr<media::VideoFrame> video_frame; GetCurrentFrame(&video_frame); if (video_frame) { if (CanFastPaint(canvas, dest_rect)) { FastPaint(video_frame, canvas, dest_rect); } else { SlowPaint(video_frame, canvas, dest_rect); } video_frame = NULL; } } // CanFastPaint is a helper method to determine the conditions for fast // painting. The conditions are: // 1. No skew in canvas matrix. // 2. Canvas has pixel format ARGB8888. // 3. Canvas is opaque. bool VideoRendererImpl::CanFastPaint(skia::PlatformCanvas* canvas, const gfx::Rect& dest_rect) { const SkMatrix& total_matrix = canvas->getTotalMatrix(); if (SkScalarNearlyZero(total_matrix.getSkewX()) && SkScalarNearlyZero(total_matrix.getSkewY())) { // Get the properties of the SkDevice and the clip rect. SkDevice* device = canvas->getDevice(); // Get the boundary of the device. SkIRect device_rect; device->getBounds(&device_rect); // Get the pixel config of the device. const SkBitmap::Config config = device->config(); // Get the total clip rect associated with the canvas. const SkRegion& total_clip = canvas->getTotalClip(); SkIRect dest_irect; TransformToSkIRect(canvas->getTotalMatrix(), dest_rect, &dest_irect); if (config == SkBitmap::kARGB_8888_Config && device->isOpaque() && device_rect.contains(total_clip.getBounds())) { return true; } } return false; } void VideoRendererImpl::SlowPaint(media::VideoFrame* video_frame, skia::PlatformCanvas* canvas, const gfx::Rect& dest_rect) { // 1. Convert YUV frame to RGB. base::TimeDelta timestamp = video_frame->GetTimestamp(); if (video_frame != last_converted_frame_ || timestamp != last_converted_timestamp_) { last_converted_frame_ = video_frame; last_converted_timestamp_ = timestamp; media::VideoSurface frame_in; if (video_frame->Lock(&frame_in)) { // TODO(hclam): Support more video formats than just YV12. DCHECK(frame_in.format == media::VideoSurface::YV12); DCHECK(frame_in.strides[media::VideoSurface::kUPlane] == frame_in.strides[media::VideoSurface::kVPlane]); DCHECK(frame_in.planes == media::VideoSurface::kNumYUVPlanes); bitmap_.lockPixels(); media::ConvertYUVToRGB32(frame_in.data[media::VideoSurface::kYPlane], frame_in.data[media::VideoSurface::kUPlane], frame_in.data[media::VideoSurface::kVPlane], static_cast<uint8*>(bitmap_.getPixels()), frame_in.width, frame_in.height, frame_in.strides[media::VideoSurface::kYPlane], frame_in.strides[media::VideoSurface::kUPlane], bitmap_.rowBytes(), media::YV12); bitmap_.unlockPixels(); video_frame->Unlock(); } else { NOTREACHED(); } } // 2. Paint the bitmap to canvas. SkMatrix matrix; matrix.setTranslate(static_cast<SkScalar>(dest_rect.x()), static_cast<SkScalar>(dest_rect.y())); if (dest_rect.width() != video_size_.width() || dest_rect.height() != video_size_.height()) { matrix.preScale(SkIntToScalar(dest_rect.width()) / SkIntToScalar(video_size_.width()), SkIntToScalar(dest_rect.height()) / SkIntToScalar(video_size_.height())); } canvas->drawBitmapMatrix(bitmap_, matrix, NULL); } void VideoRendererImpl::FastPaint(media::VideoFrame* video_frame, skia::PlatformCanvas* canvas, const gfx::Rect& dest_rect) { media::VideoSurface frame_in; if (video_frame->Lock(&frame_in)) { // TODO(hclam): Support more video formats than just YV12. DCHECK(frame_in.format == media::VideoSurface::YV12); DCHECK(frame_in.strides[media::VideoSurface::kUPlane] == frame_in.strides[media::VideoSurface::kVPlane]); DCHECK(frame_in.planes == media::VideoSurface::kNumYUVPlanes); const SkBitmap& bitmap = canvas->getDevice()->accessBitmap(true); // Create a rectangle backed by SkScalar. SkRect scalar_dest_rect; scalar_dest_rect.iset(dest_rect.x(), dest_rect.y(), dest_rect.right(), dest_rect.bottom()); // Transform the destination rectangle to local coordinates. const SkMatrix& local_matrix = canvas->getTotalMatrix(); SkRect local_dest_rect; local_matrix.mapRect(&local_dest_rect, scalar_dest_rect); // After projecting the destination rectangle to local coordinates, round // the projected rectangle to integer values, this will give us pixel values // of the rectangle. SkIRect local_dest_irect, local_dest_irect_saved; local_dest_rect.round(&local_dest_irect); local_dest_rect.round(&local_dest_irect_saved); // Only does the paint if the destination rect intersects with the clip // rect. if (local_dest_irect.intersect(canvas->getTotalClip().getBounds())) { // At this point |local_dest_irect| contains the rect that we should draw // to within the clipping rect. // Calculate the address for the top left corner of destination rect in // the canvas that we will draw to. The address is obtained by the base // address of the canvas shifted by "left" and "top" of the rect. uint8* dest_rect_pointer = static_cast<uint8*>(bitmap.getPixels()) + local_dest_irect.fTop * bitmap.rowBytes() + local_dest_irect.fLeft * 4; // Project the clip rect to the original video frame, obtains the // dimensions of the projected clip rect, "left" and "top" of the rect. // The math here are all integer math so we won't have rounding error and // write outside of the canvas. // We have the assumptions of dest_rect.width() and dest_rect.height() // being non-zero, these are valid assumptions since finding intersection // above rejects empty rectangle so we just do a DCHECK here. DCHECK_NE(0, dest_rect.width()); DCHECK_NE(0, dest_rect.height()); size_t frame_clip_width = local_dest_irect.width() * frame_in.width / dest_rect.width(); size_t frame_clip_height = local_dest_irect.height() * frame_in.height / dest_rect.height(); // Project the "left" and "top" of the final destination rect to local // coordinates of the video frame, use these values to find the offsets // in the video frame to start reading. size_t frame_clip_left = (local_dest_irect.fLeft - local_dest_irect_saved.fLeft) * frame_in.width / dest_rect.width(); size_t frame_clip_top = (local_dest_irect.fTop - local_dest_irect_saved.fTop) * frame_in.height / dest_rect.height(); // Use the "left" and "top" of the destination rect to locate the offset // in Y, U and V planes. size_t y_offset = frame_in.strides[media::VideoSurface::kYPlane] * frame_clip_top + frame_clip_left; // Since the format is YV12, there is one U, V value per 2x2 block, thus // the math here. // TODO(hclam): handle formats other than YV12. size_t uv_offset = (frame_in.strides[media::VideoSurface::kUPlane] * frame_clip_top + frame_clip_left) / 2; uint8* frame_clip_y = frame_in.data[media::VideoSurface::kYPlane] + y_offset; uint8* frame_clip_u = frame_in.data[media::VideoSurface::kUPlane] + uv_offset; uint8* frame_clip_v = frame_in.data[media::VideoSurface::kVPlane] + uv_offset; bitmap.lockPixels(); // TODO(hclam): do rotation and mirroring here. media::ScaleYUVToRGB32(frame_clip_y, frame_clip_u, frame_clip_v, dest_rect_pointer, frame_clip_width, frame_clip_height, local_dest_irect.width(), local_dest_irect.height(), frame_in.strides[media::VideoSurface::kYPlane], frame_in.strides[media::VideoSurface::kUPlane], bitmap.rowBytes(), media::YV12, media::ROTATE_0); bitmap.unlockPixels(); } video_frame->Unlock(); } else { NOTREACHED(); } } void VideoRendererImpl::TransformToSkIRect(const SkMatrix& matrix, const gfx::Rect& src_rect, SkIRect* dest_rect) { // Transform destination rect to local coordinates. SkRect transformed_rect; SkRect skia_dest_rect; skia_dest_rect.iset(src_rect.x(), src_rect.y(), src_rect.right(), src_rect.bottom()); matrix.mapRect(&transformed_rect, skia_dest_rect); transformed_rect.round(dest_rect); } <commit_msg>Fix a misaligmnet in rendering video frames<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/renderer/media/video_renderer_impl.h" #include "media/base/buffers.h" #include "media/base/yuv_convert.h" VideoRendererImpl::VideoRendererImpl(WebMediaPlayerImpl* delegate) : delegate_(delegate), last_converted_frame_(NULL) { // TODO(hclam): decide whether to do the following line in this thread or // in the render thread. delegate_->SetVideoRenderer(this); } // static bool VideoRendererImpl::IsMediaFormatSupported( const media::MediaFormat& media_format) { int width = 0; int height = 0; return ParseMediaFormat(media_format, &width, &height); } void VideoRendererImpl::Stop() { VideoThread::Stop(); delegate_->SetVideoRenderer(NULL); } bool VideoRendererImpl::OnInitialize(media::VideoDecoder* decoder) { int width = 0; int height = 0; if (!ParseMediaFormat(decoder->media_format(), &width, &height)) return false; video_size_.SetSize(width, height); bitmap_.setConfig(SkBitmap::kARGB_8888_Config, width, height); if (bitmap_.allocPixels(NULL, NULL)) { bitmap_.eraseRGB(0x00, 0x00, 0x00); return true; } NOTREACHED(); return false; } void VideoRendererImpl::SetRect(const gfx::Rect& rect) {} void VideoRendererImpl::OnFrameAvailable() { delegate_->PostRepaintTask(); } // This method is always called on the renderer's thread. void VideoRendererImpl::Paint(skia::PlatformCanvas* canvas, const gfx::Rect& dest_rect) { scoped_refptr<media::VideoFrame> video_frame; GetCurrentFrame(&video_frame); if (video_frame) { if (CanFastPaint(canvas, dest_rect)) { FastPaint(video_frame, canvas, dest_rect); } else { SlowPaint(video_frame, canvas, dest_rect); } video_frame = NULL; } } // CanFastPaint is a helper method to determine the conditions for fast // painting. The conditions are: // 1. No skew in canvas matrix. // 2. Canvas has pixel format ARGB8888. // 3. Canvas is opaque. bool VideoRendererImpl::CanFastPaint(skia::PlatformCanvas* canvas, const gfx::Rect& dest_rect) { const SkMatrix& total_matrix = canvas->getTotalMatrix(); if (SkScalarNearlyZero(total_matrix.getSkewX()) && SkScalarNearlyZero(total_matrix.getSkewY())) { // Get the properties of the SkDevice and the clip rect. SkDevice* device = canvas->getDevice(); // Get the boundary of the device. SkIRect device_rect; device->getBounds(&device_rect); // Get the pixel config of the device. const SkBitmap::Config config = device->config(); // Get the total clip rect associated with the canvas. const SkRegion& total_clip = canvas->getTotalClip(); SkIRect dest_irect; TransformToSkIRect(canvas->getTotalMatrix(), dest_rect, &dest_irect); if (config == SkBitmap::kARGB_8888_Config && device->isOpaque() && device_rect.contains(total_clip.getBounds())) { return true; } } return false; } void VideoRendererImpl::SlowPaint(media::VideoFrame* video_frame, skia::PlatformCanvas* canvas, const gfx::Rect& dest_rect) { // 1. Convert YUV frame to RGB. base::TimeDelta timestamp = video_frame->GetTimestamp(); if (video_frame != last_converted_frame_ || timestamp != last_converted_timestamp_) { last_converted_frame_ = video_frame; last_converted_timestamp_ = timestamp; media::VideoSurface frame_in; if (video_frame->Lock(&frame_in)) { // TODO(hclam): Support more video formats than just YV12. DCHECK(frame_in.format == media::VideoSurface::YV12); DCHECK(frame_in.strides[media::VideoSurface::kUPlane] == frame_in.strides[media::VideoSurface::kVPlane]); DCHECK(frame_in.planes == media::VideoSurface::kNumYUVPlanes); bitmap_.lockPixels(); media::ConvertYUVToRGB32(frame_in.data[media::VideoSurface::kYPlane], frame_in.data[media::VideoSurface::kUPlane], frame_in.data[media::VideoSurface::kVPlane], static_cast<uint8*>(bitmap_.getPixels()), frame_in.width, frame_in.height, frame_in.strides[media::VideoSurface::kYPlane], frame_in.strides[media::VideoSurface::kUPlane], bitmap_.rowBytes(), media::YV12); bitmap_.unlockPixels(); video_frame->Unlock(); } else { NOTREACHED(); } } // 2. Paint the bitmap to canvas. SkMatrix matrix; matrix.setTranslate(static_cast<SkScalar>(dest_rect.x()), static_cast<SkScalar>(dest_rect.y())); if (dest_rect.width() != video_size_.width() || dest_rect.height() != video_size_.height()) { matrix.preScale(SkIntToScalar(dest_rect.width()) / SkIntToScalar(video_size_.width()), SkIntToScalar(dest_rect.height()) / SkIntToScalar(video_size_.height())); } canvas->drawBitmapMatrix(bitmap_, matrix, NULL); } void VideoRendererImpl::FastPaint(media::VideoFrame* video_frame, skia::PlatformCanvas* canvas, const gfx::Rect& dest_rect) { media::VideoSurface frame_in; if (video_frame->Lock(&frame_in)) { // TODO(hclam): Support more video formats than just YV12. DCHECK(frame_in.format == media::VideoSurface::YV12); DCHECK(frame_in.strides[media::VideoSurface::kUPlane] == frame_in.strides[media::VideoSurface::kVPlane]); DCHECK(frame_in.planes == media::VideoSurface::kNumYUVPlanes); const SkBitmap& bitmap = canvas->getDevice()->accessBitmap(true); // Create a rectangle backed by SkScalar. SkRect scalar_dest_rect; scalar_dest_rect.iset(dest_rect.x(), dest_rect.y(), dest_rect.right(), dest_rect.bottom()); // Transform the destination rectangle to local coordinates. const SkMatrix& local_matrix = canvas->getTotalMatrix(); SkRect local_dest_rect; local_matrix.mapRect(&local_dest_rect, scalar_dest_rect); // After projecting the destination rectangle to local coordinates, round // the projected rectangle to integer values, this will give us pixel values // of the rectangle. SkIRect local_dest_irect, local_dest_irect_saved; local_dest_rect.round(&local_dest_irect); local_dest_rect.round(&local_dest_irect_saved); // Only does the paint if the destination rect intersects with the clip // rect. if (local_dest_irect.intersect(canvas->getTotalClip().getBounds())) { // At this point |local_dest_irect| contains the rect that we should draw // to within the clipping rect. // Calculate the address for the top left corner of destination rect in // the canvas that we will draw to. The address is obtained by the base // address of the canvas shifted by "left" and "top" of the rect. uint8* dest_rect_pointer = static_cast<uint8*>(bitmap.getPixels()) + local_dest_irect.fTop * bitmap.rowBytes() + local_dest_irect.fLeft * 4; // Project the clip rect to the original video frame, obtains the // dimensions of the projected clip rect, "left" and "top" of the rect. // The math here are all integer math so we won't have rounding error and // write outside of the canvas. // We have the assumptions of dest_rect.width() and dest_rect.height() // being non-zero, these are valid assumptions since finding intersection // above rejects empty rectangle so we just do a DCHECK here. DCHECK_NE(0, dest_rect.width()); DCHECK_NE(0, dest_rect.height()); size_t frame_clip_width = local_dest_irect.width() * frame_in.width / dest_rect.width(); size_t frame_clip_height = local_dest_irect.height() * frame_in.height / dest_rect.height(); // Project the "left" and "top" of the final destination rect to local // coordinates of the video frame, use these values to find the offsets // in the video frame to start reading. size_t frame_clip_left = (local_dest_irect.fLeft - local_dest_irect_saved.fLeft) * frame_in.width / dest_rect.width(); size_t frame_clip_top = (local_dest_irect.fTop - local_dest_irect_saved.fTop) * frame_in.height / dest_rect.height(); // Use the "left" and "top" of the destination rect to locate the offset // in Y, U and V planes. size_t y_offset = frame_in.strides[media::VideoSurface::kYPlane] * frame_clip_top + frame_clip_left; // Since the format is YV12, there is one U, V value per 2x2 block, thus // the math here. // TODO(hclam): handle formats other than YV12. size_t uv_offset = frame_in.strides[media::VideoSurface::kUPlane] * (frame_clip_top / 2) + frame_clip_left / 2; uint8* frame_clip_y = frame_in.data[media::VideoSurface::kYPlane] + y_offset; uint8* frame_clip_u = frame_in.data[media::VideoSurface::kUPlane] + uv_offset; uint8* frame_clip_v = frame_in.data[media::VideoSurface::kVPlane] + uv_offset; bitmap.lockPixels(); // TODO(hclam): do rotation and mirroring here. media::ScaleYUVToRGB32(frame_clip_y, frame_clip_u, frame_clip_v, dest_rect_pointer, frame_clip_width, frame_clip_height, local_dest_irect.width(), local_dest_irect.height(), frame_in.strides[media::VideoSurface::kYPlane], frame_in.strides[media::VideoSurface::kUPlane], bitmap.rowBytes(), media::YV12, media::ROTATE_0); bitmap.unlockPixels(); } video_frame->Unlock(); } else { NOTREACHED(); } } void VideoRendererImpl::TransformToSkIRect(const SkMatrix& matrix, const gfx::Rect& src_rect, SkIRect* dest_rect) { // Transform destination rect to local coordinates. SkRect transformed_rect; SkRect skia_dest_rect; skia_dest_rect.iset(src_rect.x(), src_rect.y(), src_rect.right(), src_rect.bottom()); matrix.mapRect(&transformed_rect, skia_dest_rect); transformed_rect.round(dest_rect); } <|endoftext|>
<commit_before>//---------------------------------------------------------------------------- // copyright 2012, 2013, 2014 Keean Schupke // compile with -std=c++11 // templateio.h #ifndef TEMPLATEIO_HPP #define TEMPLATEIO_HPP #include <iostream> #include <vector> #include <tuple> using namespace std; //---------------------------------------------------------------------------- // iostream output for tuples. template <size_t> struct idx {}; template <typename T, size_t I> ostream& print_tuple(ostream& out, T const& t, idx<I>) { out << get<tuple_size<T>::value - I>(t) << ", "; return print_tuple(out, t, idx<I - 1>()); } template <typename T> ostream& print_tuple(ostream& out, T const& t, idx<1>) { return out << get<tuple_size<T>::value - 1>(t); } template <typename... T> ostream& operator<< (ostream& out, tuple<T...> const& t) { out << '<'; print_tuple(out, t, idx<sizeof...(T)>()); return out << '>'; } //---------------------------------------------------------------------------- // iostream output for vectors. template <typename T> ostream& operator<< (ostream& out, vector<T> const& v) { out << "["; for (typename vector<T>::const_iterator i = v.begin(); i != v.end(); ++i) { cout << *i; typename vector<T>::const_iterator j = i; if (++j != v.end()) { cout << ", "; } } return out << "]"; } #endif // TEMPLATEIO_HPP <commit_msg>add templateio for maps<commit_after>//---------------------------------------------------------------------------- // copyright 2012, 2013, 2014 Keean Schupke // compile with -std=c++11 // templateio.h #ifndef TEMPLATEIO_HPP #define TEMPLATEIO_HPP #include <iostream> #include <vector> #include <tuple> #include <map> using namespace std; //---------------------------------------------------------------------------- // iostream output for tuples. template <size_t> struct idx {}; template <typename T, size_t I> ostream& print_tuple(ostream& out, T const& t, idx<I>) { out << get<tuple_size<T>::value - I>(t) << ", "; return print_tuple(out, t, idx<I - 1>()); } template <typename T> ostream& print_tuple(ostream& out, T const& t, idx<1>) { return out << get<tuple_size<T>::value - 1>(t); } template <typename... T> ostream& operator<< (ostream& out, tuple<T...> const& t) { out << '<'; print_tuple(out, t, idx<sizeof...(T)>()); return out << '>'; } //---------------------------------------------------------------------------- // iostream output for vectors. template <typename T> ostream& operator<< (ostream& out, vector<T> const& v) { out << "["; for (typename vector<T>::const_iterator i = v.begin(); i != v.end(); ++i) { cout << *i; typename vector<T>::const_iterator j = i; if (++j != v.end()) { cout << ", "; } } return out << "]"; } //---------------------------------------------------------------------------- // iostream output for maps. template <typename S, typename T> ostream& operator<< (ostream& out, map<S, T> const& m) { out << "{"; for (typename map<S, T>::const_iterator i = m.begin(); i != m.end(); ++i) { cout << i->first << " = " << i->second; typename map<S, T>::const_iterator j = i; if (++j != m.end()) { cout << ", "; } } return out << "]"; } #endif // TEMPLATEIO_HPP <|endoftext|>
<commit_before>/* * Copyright (C) 2017 koolkdev * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #include "Wfs.h" #include "DeviceEncryption.h" #include "Area.h" #include "Directory.h" #include "FileDevice.h" #include "MetadataBlock.h" #include "Structs.h" #include <boost/filesystem.hpp> Wfs::Wfs(const std::shared_ptr<Device>& device, std::vector<uint8_t>& key) : device(std::make_shared<DeviceEncryption>(device, key)) { // Read first area this->root_area = Area::LoadRootArea(this->device); } std::shared_ptr<WfsItem> Wfs::GetObject(const std::string& filename) { if (filename == "/") return GetDirectory("/"); boost::filesystem::path path(filename); auto dir = GetDirectory(path.parent_path().string()); if (!dir) return std::shared_ptr<WfsItem>(); return dir->GetObject(path.filename().string()); } std::shared_ptr<File> Wfs::GetFile(const std::string& filename) { boost::filesystem::path path(filename); auto dir = GetDirectory(path.parent_path().string()); if (!dir) return std::shared_ptr<File>(); return dir->GetFile(path.filename().string()); } std::shared_ptr<Directory> Wfs::GetDirectory(const std::string& filename) { boost::filesystem::path path(filename); std::shared_ptr<Directory> current_directory = this->root_area->GetRootDirectory(); for (auto& part : path) { // the first part is "/" if (part == "/") continue; current_directory = current_directory->GetDirectory(part.string()); if (!current_directory) return current_directory; } return current_directory; } void Wfs::DetectDeviceSectorSizeAndCount(const std::shared_ptr<FileDevice>& device, const std::vector<uint8_t>& key) { // The encryption of the blocks depends on the device sector size and count, which builds the IV // We are going to find out the correct first 0x10 bytes, and than xor it with what we read to find out the correct IV // From that IV we extract the sectors count and sector size of the device. // Bytes 0-4 are going to be correct because the first 4 bytes of the IV is the block size, which we read from the first block. // The other bytes are part of the hash, so we will get them once we calculate the hash. So once we get the correct hash we find the correct IV. // So it will fail hash check // Let's read the first block first, ignore the hash and check the wfs version, and read the block size // But lets set the sectors size to 9 and the sector size to 0x10, because this is the max we are going to read right now device->SetSectorsCount(0x10); device->SetLog2SectorSize(9); auto enc_device = std::make_shared<DeviceEncryption>(device, key); auto block = MetadataBlock::LoadBlock(enc_device, 0, Block::BlockSize::Basic, 0, false); auto wfs_header = reinterpret_cast<WfsHeader *>(&block->GetData()[sizeof(MetadataBlockHeader)]); if (wfs_header->version.value() != 0x01010800) throw std::runtime_error("Unexpected WFS version (bad key?)"); auto block_size = Block::BlockSize::Basic; if (!(wfs_header->root_area_attributes.flags.value() & wfs_header->root_area_attributes.Flags::AREA_SIZE_BASIC) && (wfs_header->root_area_attributes.flags.value() & wfs_header->root_area_attributes.Flags::AREA_SIZE_REGULAR)) block_size = Block::BlockSize::Regular; // Now lets read it again, this time with the correct block size block = MetadataBlock::LoadBlock(enc_device, 0, block_size, 0, false); uint32_t xored_sectors_count, xored_sector_size; // The two last dwords of the IV is the sectors count and sector size, right now it is xored with our fake sector size and sector count, and with the hash auto& data = block->GetData(); auto first_4_dwords = reinterpret_cast<boost::endian::big_uint32_buf_t*>(&data[0]); xored_sectors_count = first_4_dwords[2].value(); xored_sector_size = first_4_dwords[3].value(); // Lets calculate the hash of the block enc_device->CalculateHash(data, data.begin() + offsetof(MetadataBlockHeader, hash), true); // Now xor it with the real hash xored_sectors_count ^= first_4_dwords[2].value(); xored_sector_size ^= first_4_dwords[3].value(); // And xor it with our fake sectors count and block size xored_sectors_count ^= 0x10; xored_sector_size ^= 1 << 9; device->SetLog2SectorSize(static_cast<uint32_t>(log2(xored_sector_size))); device->SetSectorsCount(xored_sectors_count); // Now try to fetch block again, this time check the hash, it will raise exception try { block = MetadataBlock::LoadBlock(enc_device, 0, block_size, 0, true); } catch (Block::BadHash) { throw std::runtime_error("Wfs: Failed to detect sector size and sectors count"); } } <commit_msg>wfslib: calculate and verify log2 of the sector size (fixes #3)<commit_after>/* * Copyright (C) 2017 koolkdev * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #include "Wfs.h" #include "DeviceEncryption.h" #include "Area.h" #include "Directory.h" #include "FileDevice.h" #include "MetadataBlock.h" #include "Structs.h" #include <boost/filesystem.hpp> Wfs::Wfs(const std::shared_ptr<Device>& device, std::vector<uint8_t>& key) : device(std::make_shared<DeviceEncryption>(device, key)) { // Read first area this->root_area = Area::LoadRootArea(this->device); } std::shared_ptr<WfsItem> Wfs::GetObject(const std::string& filename) { if (filename == "/") return GetDirectory("/"); boost::filesystem::path path(filename); auto dir = GetDirectory(path.parent_path().string()); if (!dir) return std::shared_ptr<WfsItem>(); return dir->GetObject(path.filename().string()); } std::shared_ptr<File> Wfs::GetFile(const std::string& filename) { boost::filesystem::path path(filename); auto dir = GetDirectory(path.parent_path().string()); if (!dir) return std::shared_ptr<File>(); return dir->GetFile(path.filename().string()); } std::shared_ptr<Directory> Wfs::GetDirectory(const std::string& filename) { boost::filesystem::path path(filename); std::shared_ptr<Directory> current_directory = this->root_area->GetRootDirectory(); for (auto& part : path) { // the first part is "/" if (part == "/") continue; current_directory = current_directory->GetDirectory(part.string()); if (!current_directory) return current_directory; } return current_directory; } void Wfs::DetectDeviceSectorSizeAndCount(const std::shared_ptr<FileDevice>& device, const std::vector<uint8_t>& key) { // The encryption of the blocks depends on the device sector size and count, which builds the IV // We are going to find out the correct first 0x10 bytes, and than xor it with what we read to find out the correct IV // From that IV we extract the sectors count and sector size of the device. // Bytes 0-4 are going to be correct because the first 4 bytes of the IV is the block size, which we read from the first block. // The other bytes are part of the hash, so we will get them once we calculate the hash. So once we get the correct hash we find the correct IV. // So it will fail hash check // Let's read the first block first, ignore the hash and check the wfs version, and read the block size // But lets set the sectors size to 9 and the sector size to 0x10, because this is the max we are going to read right now device->SetSectorsCount(0x10); device->SetLog2SectorSize(9); auto enc_device = std::make_shared<DeviceEncryption>(device, key); auto block = MetadataBlock::LoadBlock(enc_device, 0, Block::BlockSize::Basic, 0, false); auto wfs_header = reinterpret_cast<WfsHeader *>(&block->GetData()[sizeof(MetadataBlockHeader)]); if (wfs_header->version.value() != 0x01010800) throw std::runtime_error("Unexpected WFS version (bad key?)"); auto block_size = Block::BlockSize::Basic; if (!(wfs_header->root_area_attributes.flags.value() & wfs_header->root_area_attributes.Flags::AREA_SIZE_BASIC) && (wfs_header->root_area_attributes.flags.value() & wfs_header->root_area_attributes.Flags::AREA_SIZE_REGULAR)) block_size = Block::BlockSize::Regular; // Now lets read it again, this time with the correct block size block = MetadataBlock::LoadBlock(enc_device, 0, block_size, 0, false); uint32_t xored_sectors_count, xored_sector_size; // The two last dwords of the IV is the sectors count and sector size, right now it is xored with our fake sector size and sector count, and with the hash auto& data = block->GetData(); auto first_4_dwords = reinterpret_cast<boost::endian::big_uint32_buf_t*>(&data[0]); xored_sectors_count = first_4_dwords[2].value(); xored_sector_size = first_4_dwords[3].value(); // Lets calculate the hash of the block enc_device->CalculateHash(data, data.begin() + offsetof(MetadataBlockHeader, hash), true); // Now xor it with the real hash xored_sectors_count ^= first_4_dwords[2].value(); xored_sector_size ^= first_4_dwords[3].value(); // And xor it with our fake sectors count and block size xored_sectors_count ^= 0x10; xored_sector_size ^= 1 << 9; uint32_t sector_size = 0; while (!(xored_sector_size & 1)) { xored_sector_size >>= 1; sector_size++; } if (xored_sector_size >> 1) { // Not pow of 2 throw std::runtime_error("Wfs: Failed to detect sector size and sectors count"); } device->SetLog2SectorSize(sector_size); device->SetSectorsCount(xored_sectors_count); // Now try to fetch block again, this time check the hash, it will raise exception try { block = MetadataBlock::LoadBlock(enc_device, 0, block_size, 0, true); } catch (Block::BadHash) { throw std::runtime_error("Wfs: Failed to detect sector size and sectors count"); } } <|endoftext|>
<commit_before>// Copyright 2018 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iomanip> #include <numeric> // std::iota #include "ortools/base/logging.h" #include "ortools/constraint_solver/constraint_solver.h" // Solve a job shop problem: namespace operations_research { void SolveJobShopExample() { // Instantiate the solver. Solver solver("JobShopExample"); std::array<int, 3> machines; std::iota(std::begin(machines), std::end(machines), 0); { std::ostringstream oss; for (auto i : machines) oss << ' ' << i; LOG(INFO) << "Machines: " << oss.str(); } // Jobs definition using MachineIndex = int; using ProcessingTime = int; using Task = std::pair<MachineIndex, ProcessingTime>; using Job = std::vector<Task>; std::vector<Job> jobs = { {{0, 3}, {1, 2}, {2, 2}}, {{0, 2}, {2, 1}, {1, 4}}, {{1, 4}, {2, 3}}}; LOG(INFO) << "Jobs:"; for (int i = 0; i < jobs.size(); ++i) { std::ostringstream problem; problem << "Job " << i << ": ["; for (const Task& task : jobs[i]) { problem << "(" << task.first << ", " << task.second << ")"; } problem << "]" << std::endl; LOG(INFO) << problem.str(); } // Computes horizon. ProcessingTime horizon = 0; for (const Job& job : jobs) { for (const Task& task : job) { horizon += task.second; } } LOG(INFO) << "Horizon: " << horizon; // Creates tasks. std::vector<std::vector<IntervalVar*>> tasks_matrix(jobs.size()); for (int i = 0; i < jobs.size(); ++i) { for (int j = 0; j < jobs[i].size(); ++j) { std::ostringstream oss; oss << "Job_" << i << "_" << j; tasks_matrix[i].push_back(solver.MakeFixedDurationIntervalVar( 0, horizon, jobs[i][j].second, false, oss.str())); } } // Add conjunctive contraints. for (int i = 0; i < jobs.size(); ++i) { for (int j = 0; j < jobs[i].size() - 1; ++j) { solver.AddConstraint(solver.MakeIntervalVarRelation( tasks_matrix[i][j + 1], Solver::STARTS_AFTER_END, tasks_matrix[i][j])); } } // Creates sequence variables and add disjunctive constraints. std::vector<SequenceVar*> all_sequences; std::vector<IntVar*> all_machines_jobs; for (const auto machine : machines) { std::vector<IntervalVar*> machines_jobs; for (int i = 0; i < jobs.size(); ++i) { for (int j = 0; j < jobs[i].size(); ++j) { if (jobs[i][j].first == machine) machines_jobs.push_back(tasks_matrix[i][j]); } } DisjunctiveConstraint* const disj = solver.MakeDisjunctiveConstraint( machines_jobs, "Machine_" + std::to_string(machine)); solver.AddConstraint(disj); all_sequences.push_back(disj->MakeSequenceVar()); } // Set the objective. std::vector<IntVar*> all_ends; for (const auto& job : tasks_matrix) { IntervalVar* const task = job.back(); all_ends.push_back(task->EndExpr()->Var()); } IntVar* const obj_var = solver.MakeMax(all_ends)->Var(); OptimizeVar* const objective_monitor = solver.MakeMinimize(obj_var, 1); // ----- Search monitors and decision builder ----- // This decision builder will rank all tasks on all machines. DecisionBuilder* const sequence_phase = solver.MakePhase(all_sequences, Solver::SEQUENCE_DEFAULT); // After the ranking of tasks, the schedule is still loose and any // task can be postponed at will. But, because the problem is now a PERT // (http://en.wikipedia.org/wiki/Program_Evaluation_and_Review_Technique), // we can schedule each task at its earliest start time. This is // conveniently done by fixing the objective variable to its // minimum value. DecisionBuilder* const obj_phase = solver.MakePhase( obj_var, Solver::CHOOSE_FIRST_UNBOUND, Solver::ASSIGN_MIN_VALUE); // The main decision builder (ranks all tasks, then fixes the // objective_variable). DecisionBuilder* const main_phase = solver.Compose(sequence_phase, obj_phase); // Search log. const int kLogFrequency = 1000000; SearchMonitor* const search_log = solver.MakeSearchLog(kLogFrequency, objective_monitor); SearchLimit* limit = nullptr; // Create the solution collector. SolutionCollector* const collector = solver.MakeLastSolutionCollector(); collector->Add(all_sequences); collector->AddObjective(obj_var); for (const auto machine : machines) { SequenceVar* const sequence = all_sequences[machine]; for (int i = 0; i < sequence->size(); ++i) { IntervalVar* const t = sequence->Interval(i); collector->Add(t->StartExpr()->Var()); collector->Add(t->EndExpr()->Var()); } } // Solve the problem. if (solver.Solve(main_phase, search_log, objective_monitor, limit, collector)) { LOG(INFO) << "Optimal Schedule Length: " << collector->objective_value(0); LOG(INFO) << ""; LOG(INFO) << "Optimal Schedule:"; std::vector<std::string> machine_intervals_list; for (const auto machine : machines) { std::ostringstream machine_tasks; SequenceVar* seq = all_sequences[machine]; machine_tasks << "Machine " << machine << ": "; for (const auto s : collector->ForwardSequence(0, seq)) { machine_tasks << seq->Interval(s)->name() << " "; } LOG(INFO) << machine_tasks.str(); std::ostringstream machine_intervals; machine_intervals << "Machine " << machine << ": "; for (const auto s : collector->ForwardSequence(0, seq)) { IntervalVar* t = seq->Interval(s); machine_intervals << "[" << std::setw(2) << collector->Value(0, t->StartExpr()->Var()) << ", " << std::setw(2) << collector->Value(0, t->EndExpr()->Var()) << "] "; } machine_intervals_list.push_back(machine_intervals.str()); } LOG(INFO) << "Time Intervals for Tasks: "; for (const auto& intervals : machine_intervals_list) { LOG(INFO) << intervals; } LOG(INFO) << "Advanced usage:"; LOG(INFO) << "Time: " << solver.wall_time() << "ms"; } } } // namespace operations_research int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); absl::SetFlag(&FLAGS_logtostderr, 1); operations_research::SolveJobShopExample(); return EXIT_SUCCESS; } <commit_msg>fix minimal_jobshop_cp.cc<commit_after>// Copyright 2018 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iomanip> #include <numeric> // std::iota #include "ortools/base/logging.h" #include "ortools/constraint_solver/constraint_solver.h" // Solve a job shop problem: namespace operations_research { void SolveJobShopExample() { // Instantiate the solver. Solver solver("JobShopExample"); std::array<int, 3> machines; std::iota(std::begin(machines), std::end(machines), 0); { std::ostringstream oss; for (auto i : machines) oss << ' ' << i; LOG(INFO) << "Machines: " << oss.str(); } // Jobs definition using MachineIndex = int; using ProcessingTime = int; using Task = std::pair<MachineIndex, ProcessingTime>; using Job = std::vector<Task>; std::vector<Job> jobs = { {{0, 3}, {1, 2}, {2, 2}}, {{0, 2}, {2, 1}, {1, 4}}, {{1, 4}, {2, 3}}}; LOG(INFO) << "Jobs:"; for (int i = 0; i < jobs.size(); ++i) { std::ostringstream problem; problem << "Job " << i << ": ["; for (const Task& task : jobs[i]) { problem << "(" << task.first << ", " << task.second << ")"; } problem << "]" << std::endl; LOG(INFO) << problem.str(); } // Computes horizon. ProcessingTime horizon = 0; for (const Job& job : jobs) { for (const Task& task : job) { horizon += task.second; } } LOG(INFO) << "Horizon: " << horizon; // Creates tasks. std::vector<std::vector<IntervalVar*>> tasks_matrix(jobs.size()); for (int i = 0; i < jobs.size(); ++i) { for (int j = 0; j < jobs[i].size(); ++j) { std::ostringstream oss; oss << "Job_" << i << "_" << j; tasks_matrix[i].push_back(solver.MakeFixedDurationIntervalVar( 0, horizon, jobs[i][j].second, false, oss.str())); } } // Add conjunctive contraints. for (int i = 0; i < jobs.size(); ++i) { for (int j = 0; j < jobs[i].size() - 1; ++j) { solver.AddConstraint(solver.MakeIntervalVarRelation( tasks_matrix[i][j + 1], Solver::STARTS_AFTER_END, tasks_matrix[i][j])); } } // Creates sequence variables and add disjunctive constraints. std::vector<SequenceVar*> all_sequences; std::vector<IntVar*> all_machines_jobs; for (const auto machine : machines) { std::vector<IntervalVar*> machines_jobs; for (int i = 0; i < jobs.size(); ++i) { for (int j = 0; j < jobs[i].size(); ++j) { if (jobs[i][j].first == machine) machines_jobs.push_back(tasks_matrix[i][j]); } } DisjunctiveConstraint* const disj = solver.MakeDisjunctiveConstraint( machines_jobs, "Machine_" + std::to_string(machine)); solver.AddConstraint(disj); all_sequences.push_back(disj->MakeSequenceVar()); } // Set the objective. std::vector<IntVar*> all_ends; for (const auto& job : tasks_matrix) { IntervalVar* const task = job.back(); all_ends.push_back(task->EndExpr()->Var()); } IntVar* const obj_var = solver.MakeMax(all_ends)->Var(); OptimizeVar* const objective_monitor = solver.MakeMinimize(obj_var, 1); // ----- Search monitors and decision builder ----- // This decision builder will rank all tasks on all machines. DecisionBuilder* const sequence_phase = solver.MakePhase(all_sequences, Solver::SEQUENCE_DEFAULT); // After the ranking of tasks, the schedule is still loose and any // task can be postponed at will. But, because the problem is now a PERT // (http://en.wikipedia.org/wiki/Program_Evaluation_and_Review_Technique), // we can schedule each task at its earliest start time. This is // conveniently done by fixing the objective variable to its // minimum value. DecisionBuilder* const obj_phase = solver.MakePhase( obj_var, Solver::CHOOSE_FIRST_UNBOUND, Solver::ASSIGN_MIN_VALUE); // The main decision builder (ranks all tasks, then fixes the // objective_variable). DecisionBuilder* const main_phase = solver.Compose(sequence_phase, obj_phase); // Search log. const int kLogFrequency = 1000000; SearchMonitor* const search_log = solver.MakeSearchLog(kLogFrequency, objective_monitor); SearchLimit* limit = nullptr; // Create the solution collector. SolutionCollector* const collector = solver.MakeLastSolutionCollector(); collector->Add(all_sequences); collector->AddObjective(obj_var); for (const auto machine : machines) { SequenceVar* const sequence = all_sequences[machine]; for (int i = 0; i < sequence->size(); ++i) { IntervalVar* const t = sequence->Interval(i); collector->Add(t->StartExpr()->Var()); collector->Add(t->EndExpr()->Var()); } } // Solve the problem. if (solver.Solve(main_phase, search_log, objective_monitor, limit, collector)) { LOG(INFO) << "Optimal Schedule Length: " << collector->objective_value(0); LOG(INFO) << ""; LOG(INFO) << "Optimal Schedule:"; std::vector<std::string> machine_intervals_list; for (const auto machine : machines) { std::ostringstream machine_tasks; SequenceVar* seq = all_sequences[machine]; machine_tasks << "Machine " << machine << ": "; for (const auto s : collector->ForwardSequence(0, seq)) { machine_tasks << seq->Interval(s)->name() << " "; } LOG(INFO) << machine_tasks.str(); std::ostringstream machine_intervals; machine_intervals << "Machine " << machine << ": "; for (const auto s : collector->ForwardSequence(0, seq)) { IntervalVar* t = seq->Interval(s); machine_intervals << "[(" << std::setw(2) << collector->solution(0)->Min(t->StartExpr()->Var()) << ", " << collector->solution(0)->Max(t->StartExpr()->Var()) << "),(" << std::setw(2) << collector->solution(0)->Min(t->EndExpr()->Var()) << ", " << collector->solution(0)->Max(t->EndExpr()->Var()) << ")]"; } machine_intervals_list.push_back(machine_intervals.str()); } LOG(INFO) << "Time Intervals for Tasks: "; for (const auto& intervals : machine_intervals_list) { LOG(INFO) << intervals; } LOG(INFO) << "Advanced usage:"; LOG(INFO) << "Time: " << solver.wall_time() << "ms"; } } } // namespace operations_research int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); absl::SetFlag(&FLAGS_logtostderr, 1); operations_research::SolveJobShopExample(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/**************************************************************************** ** ncs is the backend's server of nodecast ** Copyright (C) 2010-2012 Frédéric Logier <frederic@logier.org> ** ** https://github.com/nodecast/ncs ** ** 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 "worker_api.h" Worker_api::Worker_api() { nosql_ = Nosql::getInstance_front(); zeromq_ = Zeromq::getInstance (); z_message = new zmq::message_t(2); z_message_publish = new zmq::message_t(2); z_receive_api = new zmq::socket_t (*zeromq_->m_context, ZMQ_PULL); uint64_t hwm = 50000; z_receive_api->setsockopt(ZMQ_HWM, &hwm, sizeof (hwm)); z_receive_api->bind("tcp://*:5555"); int socket_receive_fd; size_t socket_size = sizeof(socket_receive_fd); z_receive_api->getsockopt(ZMQ_FD, &socket_receive_fd, &socket_size); qDebug() << "RES getsockopt : " << "res" << " FD : " << socket_receive_fd << " errno : " << zmq_strerror (errno); check_payload = new QSocketNotifier(socket_receive_fd, QSocketNotifier::Read, this); connect(check_payload, SIGNAL(activated(int)), this, SLOT(receive_payload()), Qt::DirectConnection); /********* PUB / SUB *************/ z_publish_api = new zmq::socket_t (*zeromq_->m_context, ZMQ_PUB); z_publish_api->setsockopt(ZMQ_HWM, &hwm, sizeof (hwm)); z_publish_api->bind("tcp://*:5557"); /*********************************/ z_push_api = new zmq::socket_t(*zeromq_->m_context, ZMQ_PUSH); z_push_api->bind("ipc:///tmp/nodecast/workers"); } void Worker_api::pubsub_payload(bson::bo l_payload) { std::cout << "Worker_api::pubsub_payload : " << l_payload << std::endl; BSONElement dest = l_payload.getFieldDotted("payload.dest"); QString payload = QString::fromStdString(dest.str()) + " "; payload.append(QString::fromStdString(l_payload.getFieldDotted("payload.datas").str())); std::cout << "payload send : " << payload.toStdString() << std::endl; /** ALL KIND OF WORKERS ARE CONNECTED TO THE PUB SOCKET SO ZEROMQ CANNOT CHECK IF A DEST WORKER RECEIVE OR NOT THE PAYLOAD. SO, I MUST STORE ALL PAYLOAD THROUGH THE PUB/SUB SOCKET INTO MONGODB, A WORKER CAN RETREIVE LATER A PAYLOAD (TODO) **/ QDateTime timestamp = QDateTime::currentDateTime(); BSONObj t_payload = BSON(GENOID << "dest" << dest.str() << "timestamp" << timestamp.toTime_t() << "data" << payload.toStdString()); nosql_->Insert("pubsub_payloads", t_payload); /****** PUBLISH API PAYLOAD *******/ qDebug() << "Worker_api::publish_payload PUBLISH PAYLOAD"; z_message_publish->rebuild(payload.size()); memcpy(z_message_publish->data(), (char*)payload.data(), payload.size()); z_publish_api->send(*z_message_publish); /************************/ } /********** CREATE PAYLOAD ************/ void Worker_api::receive_payload() { check_payload->setEnabled(false); std::cout << "Worker_api::receive_payload" << std::endl; qint32 events = 0; std::size_t eventsSize = sizeof(events); z_receive_api->getsockopt(ZMQ_EVENTS, &events, &eventsSize); std::cout << "Worker_api::receive_payload ZMQ_EVENTS : " << events << std::endl; if (events & ZMQ_POLLIN) { std::cout << "Worker_api::receive_payload ZMQ_POLLIN" << std::endl; while (true) { zmq::message_t request; bool res = z_receive_api->recv(&request, ZMQ_NOBLOCK); if (!res && zmq_errno () == EAGAIN) break; std::cout << "Worker_api::receive_payload received request: [" << (char*) request.data() << "]" << std::endl; char *plop = (char*) request.data(); if (strlen(plop) == 0) { std::cout << "Worker_api::receive_payload STRLEN received request 0" << std::endl; break; } BSONObj payload; try { payload = BSONObj((char*)request.data()); if (!payload.isValid() || payload.isEmpty()) { qDebug() << "Worker_api::receive_payload PAYLOAD INVALID !!!"; return; } } catch (mongo::MsgAssertionException &e) { std::cout << "error on data : " << payload << std::endl; std::cout << "error on data BSON : " << e.what() << std::endl; break; } std::cout << "Worker_api::receive PAYLOAD : " << payload << std::endl; QString payload_action = QString::fromStdString(payload.getFieldDotted("payload.action").str()); if (payload_action == "publish") { std::cout << "RECEIVE PUBLISH : " << payload << std::endl; pubsub_payload(payload.copy()); } else if (payload_action == "create") { std::cout << "Worker_api::payload CREATE PAYLOAD : " << payload <<std::endl; QDateTime timestamp = QDateTime::currentDateTime(); BSONElement payloadname = payload.getFieldDotted("payload.payloadname"); BSONElement datas = payload.getFieldDotted("payload.datas"); BSONElement node_uuid = payload.getFieldDotted("payload.node_uuid"); BSONElement node_password = payload.getFieldDotted("payload.node_password"); BSONElement workflow_uuid = payload.getFieldDotted("payload.workflow_uuid"); std::cout << "DATA : " << datas << std::endl; std::cout << "NODE UUID : " << node_uuid << std::endl; std::cout << "NODE PASSWORD : " << node_password << std::endl; std::cout << "workflow_uuid : " << workflow_uuid << std::endl; if (datas.size() == 0) { std::cout << "ERROR : DATA EMPTY" << std::endl; return; } if (node_uuid.size() == 0) { std::cout << "ERROR : NODE UUID EMPTY" << std::endl; return; } if (node_password.size() == 0) { std::cout << "ERROR : NODE PASSWORD EMPTY" << std::endl; return; } if (workflow_uuid.size() == 0) { std::cout << "ERROR : WORKFLOW EMPTY" << std::endl; return; } BSONObj workflow_search = BSON("uuid" << workflow_uuid.str()); BSONObj workflow = nosql_->Find("workflows", workflow_search); if (workflow.nFields() == 0) { std::cout << "ERROR : WORKFLOW NOT FOUND" << std::endl; return; } BSONObj auth = BSON("node_uuid" << node_uuid.str() << "node_password" << node_password.str()); BSONObj node = nosql_->Find("nodes", auth); if (node.nFields() == 0) { std::cout << "ERROR : NODE NOT FOUND" << std::endl; return; } BSONObjBuilder payload_builder; payload_builder.genOID(); payload_builder.append("action", "create"); payload_builder.append("timestamp", timestamp.toTime_t()); payload_builder.append("node_uuid", node_uuid.str()); payload_builder.append("node_password", node_password.str()); payload_builder.append("workflow_uuid", workflow_uuid.str()); //bo node_search = BSON("_id" << user.getField("_id") << "nodes.uuid" << node_uuid.toStdString()); BSONObj user_search = BSON("_id" << node.getField("user_id")); BSONObj user_nodes = nosql_->Find("users", user_search); if (user_nodes.nFields() == 0) { std::cout << "ERROR : USER NOT FOUND" << std::endl; return; } BSONObj nodes = user_nodes.getField("nodes").Obj(); list<be> list_nodes; nodes.elems(list_nodes); list<be>::iterator i; /******** Iterate over each user's nodes *******/ /******** find node with uuid and set the node id to payload collection *******/ for(i = list_nodes.begin(); i != list_nodes.end(); ++i) { BSONObj l_node = (*i).embeddedObject (); be node_id; l_node.getObjectID (node_id); //std::cout << "NODE1 => " << node_id.OID() << std::endl; //std::cout << "NODE2 => " << node_uuid.toStdString() << std::endl; if (node_uuid.str().compare(l_node.getField("uuid").str()) == 0) { payload_builder.append("node_id", node_id.OID()); break; } } QUuid payload_uuid = QUuid::createUuid(); QString str_payload_uuid = payload_uuid.toString().mid(1,36); payload_builder.append("payload_uuid", str_payload_uuid.toStdString()); int counter = nosql_->Count("payloads"); payload_builder.append("counter", counter + 1); /*QFile zfile("/tmp/in.dat"); zfile.open(QIODevice::WriteOnly); zfile.write(requestContent); zfile.close();*/ BSONObj t_payload = payload.getField("payload").Obj(); if (t_payload.hasField("gridfs") && t_payload.getField("gridfs").Bool() == false) { payload_builder.append("gridfs", false); payload_builder.append("datas", datas.valuestr()); } else { BSONObj gfs_file_struct = nosql_->WriteFile(payloadname.str(), datas.valuestr(), datas.objsize()); if (gfs_file_struct.nFields() == 0) { qDebug() << "write on gridFS failed !"; break; } std::cout << "writefile : " << gfs_file_struct << std::endl; //std::cout << "writefile id : " << gfs_file_struct.getField("_id") << " date : " << gfs_file_struct.getField("uploadDate") << std::endl; be uploaded_at = gfs_file_struct.getField("uploadDate"); be filename = gfs_file_struct.getField("filename"); be length = gfs_file_struct.getField("length"); std::cout << "uploaded : " << uploaded_at << std::endl; payload_builder.append("created_at", uploaded_at.date()); payload_builder.append("filename", filename.str()); payload_builder.append("length", length.numberLong()); payload_builder.append("gfs_id", gfs_file_struct.getField("_id").OID()); payload_builder.append("gridfs", true); } BSONObj s_payload = payload_builder.obj(); nosql_->Insert("payloads", s_payload); std::cout << "payload inserted" << s_payload << std::endl; /********* CREATE SESSION **********/ QUuid session_uuid = QUuid::createUuid(); QString str_session_uuid = session_uuid.toString().mid(1,36); BSONObjBuilder session_builder; session_builder.genOID(); session_builder.append("uuid", str_session_uuid.toStdString()); session_builder.append("payload_id", s_payload.getField("_id").OID()); session_builder.append("workflow_id", workflow.getField("_id").OID()); session_builder.append("start_timestamp", timestamp.toTime_t()); BSONObj session = session_builder.obj(); nosql_->Insert("sessions", session); /***********************************/ std::cout << "session inserted : " << session << std::endl; BSONObj l_payload = BSON("action" << "create" << "session_uuid" << str_session_uuid.toStdString() << "timestamp" << timestamp.toTime_t()); std::cout << "PUSH WORKER API PAYLOAD : " << l_payload << std::endl; /****** PUSH API PAYLOAD *******/ qDebug() << "PUSH WORKER CREATE PAYLOAD"; z_message->rebuild(l_payload.objsize()); memcpy(z_message->data(), (char*)l_payload.objdata(), l_payload.objsize()); //z_push_api->send(*z_message, ZMQ_NOBLOCK); z_push_api->send(*z_message); /************************/ } else { // WORKER RESPONSE std::cout << "RECEIVE ACTION : " << payload_action.toStdString() << std::endl; BSONObjBuilder b_payload; b_payload.append(payload.getFieldDotted("payload.name")); b_payload.append(payload.getFieldDotted("payload.action")); b_payload.append(payload.getFieldDotted("payload.timestamp")); b_payload.append(payload.getFieldDotted("payload.session_uuid")); /*** ACTION TERMINATE ***/ BSONObj tmp = payload.getField("payload").Obj(); if (tmp.hasField("datas")) b_payload.append(payload.getFieldDotted("payload.datas")); if (tmp.hasField("exitcode")) b_payload.append(payload.getFieldDotted("payload.exitcode")); if (tmp.hasField("exitstatus")) b_payload.append(payload.getFieldDotted("payload.exitstatus")); BSONObj l_payload = b_payload.obj(); std::cout << "PAYLOAD FORWARD : " << l_payload << std::endl; /****** PUSH API PAYLOAD *******/ qDebug() << "PUSH WORKER NEXT PAYLOAD"; z_message->rebuild(l_payload.objsize()); memcpy(z_message->data(), (char*)l_payload.objdata(), l_payload.objsize()); //z_push_api->send(*z_message, ZMQ_NOBLOCK); z_push_api->send(*z_message); /************************/ } } } check_payload->setEnabled(true); } Worker_api::~Worker_api() { z_push_api->close(); } <commit_msg>update payload structure about node<commit_after>/**************************************************************************** ** ncs is the backend's server of nodecast ** Copyright (C) 2010-2012 Frédéric Logier <frederic@logier.org> ** ** https://github.com/nodecast/ncs ** ** 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 "worker_api.h" Worker_api::Worker_api() { nosql_ = Nosql::getInstance_front(); zeromq_ = Zeromq::getInstance (); z_message = new zmq::message_t(2); z_message_publish = new zmq::message_t(2); z_receive_api = new zmq::socket_t (*zeromq_->m_context, ZMQ_PULL); uint64_t hwm = 50000; z_receive_api->setsockopt(ZMQ_HWM, &hwm, sizeof (hwm)); z_receive_api->bind("tcp://*:5555"); int socket_receive_fd; size_t socket_size = sizeof(socket_receive_fd); z_receive_api->getsockopt(ZMQ_FD, &socket_receive_fd, &socket_size); qDebug() << "RES getsockopt : " << "res" << " FD : " << socket_receive_fd << " errno : " << zmq_strerror (errno); check_payload = new QSocketNotifier(socket_receive_fd, QSocketNotifier::Read, this); connect(check_payload, SIGNAL(activated(int)), this, SLOT(receive_payload()), Qt::DirectConnection); /********* PUB / SUB *************/ z_publish_api = new zmq::socket_t (*zeromq_->m_context, ZMQ_PUB); z_publish_api->setsockopt(ZMQ_HWM, &hwm, sizeof (hwm)); z_publish_api->bind("tcp://*:5557"); /*********************************/ z_push_api = new zmq::socket_t(*zeromq_->m_context, ZMQ_PUSH); z_push_api->bind("ipc:///tmp/nodecast/workers"); } void Worker_api::pubsub_payload(bson::bo l_payload) { std::cout << "Worker_api::pubsub_payload : " << l_payload << std::endl; BSONElement dest = l_payload.getFieldDotted("payload.dest"); QString payload = QString::fromStdString(dest.str()) + " "; payload.append(QString::fromStdString(l_payload.getFieldDotted("payload.datas").str())); std::cout << "payload send : " << payload.toStdString() << std::endl; /** ALL KIND OF WORKERS ARE CONNECTED TO THE PUB SOCKET SO ZEROMQ CANNOT CHECK IF A DEST WORKER RECEIVE OR NOT THE PAYLOAD. SO, I MUST STORE ALL PAYLOAD THROUGH THE PUB/SUB SOCKET INTO MONGODB, A WORKER CAN RETREIVE LATER A PAYLOAD (TODO) **/ QDateTime timestamp = QDateTime::currentDateTime(); BSONObj t_payload = BSON(GENOID << "dest" << dest.str() << "timestamp" << timestamp.toTime_t() << "data" << payload.toStdString()); nosql_->Insert("pubsub_payloads", t_payload); /****** PUBLISH API PAYLOAD *******/ qDebug() << "Worker_api::publish_payload PUBLISH PAYLOAD"; z_message_publish->rebuild(payload.size()); memcpy(z_message_publish->data(), (char*)payload.data(), payload.size()); z_publish_api->send(*z_message_publish); /************************/ } /********** CREATE PAYLOAD ************/ void Worker_api::receive_payload() { check_payload->setEnabled(false); std::cout << "Worker_api::receive_payload" << std::endl; qint32 events = 0; std::size_t eventsSize = sizeof(events); z_receive_api->getsockopt(ZMQ_EVENTS, &events, &eventsSize); std::cout << "Worker_api::receive_payload ZMQ_EVENTS : " << events << std::endl; if (events & ZMQ_POLLIN) { std::cout << "Worker_api::receive_payload ZMQ_POLLIN" << std::endl; while (true) { zmq::message_t request; bool res = z_receive_api->recv(&request, ZMQ_NOBLOCK); if (!res && zmq_errno () == EAGAIN) break; std::cout << "Worker_api::receive_payload received request: [" << (char*) request.data() << "]" << std::endl; char *plop = (char*) request.data(); if (strlen(plop) == 0) { std::cout << "Worker_api::receive_payload STRLEN received request 0" << std::endl; break; } BSONObj payload; try { payload = BSONObj((char*)request.data()); if (!payload.isValid() || payload.isEmpty()) { qDebug() << "Worker_api::receive_payload PAYLOAD INVALID !!!"; return; } } catch (mongo::MsgAssertionException &e) { std::cout << "error on data : " << payload << std::endl; std::cout << "error on data BSON : " << e.what() << std::endl; break; } std::cout << "Worker_api::receive PAYLOAD : " << payload << std::endl; QString payload_action = QString::fromStdString(payload.getFieldDotted("payload.action").str()); if (payload_action == "publish") { std::cout << "RECEIVE PUBLISH : " << payload << std::endl; pubsub_payload(payload.copy()); } else if (payload_action == "create") { std::cout << "Worker_api::payload CREATE PAYLOAD : " << payload <<std::endl; QDateTime timestamp = QDateTime::currentDateTime(); BSONElement payloadname = payload.getFieldDotted("payload.payloadname"); BSONElement datas = payload.getFieldDotted("payload.datas"); BSONElement node_uuid = payload.getField("node_uuid"); BSONElement node_password = payload.getField("node_password"); BSONElement workflow_uuid = payload.getFieldDotted("payload.workflow_uuid"); std::cout << "DATA : " << datas << std::endl; std::cout << "NODE UUID : " << node_uuid << std::endl; std::cout << "NODE PASSWORD : " << node_password << std::endl; std::cout << "workflow_uuid : " << workflow_uuid << std::endl; if (datas.size() == 0) { std::cout << "ERROR : DATA EMPTY" << std::endl; return; } if (node_uuid.size() == 0) { std::cout << "ERROR : NODE UUID EMPTY" << std::endl; return; } if (node_password.size() == 0) { std::cout << "ERROR : NODE PASSWORD EMPTY" << std::endl; return; } if (workflow_uuid.size() == 0) { std::cout << "ERROR : WORKFLOW EMPTY" << std::endl; return; } BSONObj workflow_search = BSON("uuid" << workflow_uuid.str()); BSONObj workflow = nosql_->Find("workflows", workflow_search); if (workflow.nFields() == 0) { std::cout << "ERROR : WORKFLOW NOT FOUND" << std::endl; return; } BSONObj auth = BSON("node_uuid" << node_uuid.str() << "node_password" << node_password.str()); BSONObj node = nosql_->Find("nodes", auth); if (node.nFields() == 0) { std::cout << "ERROR : NODE NOT FOUND" << std::endl; return; } BSONObjBuilder payload_builder; payload_builder.genOID(); payload_builder.append("action", "create"); payload_builder.append("timestamp", timestamp.toTime_t()); payload_builder.append("node_uuid", node_uuid.str()); payload_builder.append("node_password", node_password.str()); payload_builder.append("workflow_uuid", workflow_uuid.str()); //bo node_search = BSON("_id" << user.getField("_id") << "nodes.uuid" << node_uuid.toStdString()); BSONObj user_search = BSON("_id" << node.getField("user_id")); BSONObj user_nodes = nosql_->Find("users", user_search); if (user_nodes.nFields() == 0) { std::cout << "ERROR : USER NOT FOUND" << std::endl; return; } BSONObj nodes = user_nodes.getField("nodes").Obj(); list<be> list_nodes; nodes.elems(list_nodes); list<be>::iterator i; /******** Iterate over each user's nodes *******/ /******** find node with uuid and set the node id to payload collection *******/ for(i = list_nodes.begin(); i != list_nodes.end(); ++i) { BSONObj l_node = (*i).embeddedObject (); be node_id; l_node.getObjectID (node_id); //std::cout << "NODE1 => " << node_id.OID() << std::endl; //std::cout << "NODE2 => " << node_uuid.toStdString() << std::endl; if (node_uuid.str().compare(l_node.getField("uuid").str()) == 0) { payload_builder.append("node_id", node_id.OID()); break; } } QUuid payload_uuid = QUuid::createUuid(); QString str_payload_uuid = payload_uuid.toString().mid(1,36); payload_builder.append("payload_uuid", str_payload_uuid.toStdString()); int counter = nosql_->Count("payloads"); payload_builder.append("counter", counter + 1); /*QFile zfile("/tmp/in.dat"); zfile.open(QIODevice::WriteOnly); zfile.write(requestContent); zfile.close();*/ BSONObj t_payload = payload.getField("payload").Obj(); if (t_payload.hasField("gridfs") && t_payload.getField("gridfs").Bool() == false) { payload_builder.append("gridfs", false); payload_builder.append("datas", datas.valuestr()); } else { BSONObj gfs_file_struct = nosql_->WriteFile(payloadname.str(), datas.valuestr(), datas.objsize()); if (gfs_file_struct.nFields() == 0) { qDebug() << "write on gridFS failed !"; break; } std::cout << "writefile : " << gfs_file_struct << std::endl; //std::cout << "writefile id : " << gfs_file_struct.getField("_id") << " date : " << gfs_file_struct.getField("uploadDate") << std::endl; be uploaded_at = gfs_file_struct.getField("uploadDate"); be filename = gfs_file_struct.getField("filename"); be length = gfs_file_struct.getField("length"); std::cout << "uploaded : " << uploaded_at << std::endl; payload_builder.append("created_at", uploaded_at.date()); payload_builder.append("filename", filename.str()); payload_builder.append("length", length.numberLong()); payload_builder.append("gfs_id", gfs_file_struct.getField("_id").OID()); payload_builder.append("gridfs", true); } BSONObj s_payload = payload_builder.obj(); nosql_->Insert("payloads", s_payload); std::cout << "payload inserted" << s_payload << std::endl; /********* CREATE SESSION **********/ QUuid session_uuid = QUuid::createUuid(); QString str_session_uuid = session_uuid.toString().mid(1,36); BSONObjBuilder session_builder; session_builder.genOID(); session_builder.append("uuid", str_session_uuid.toStdString()); session_builder.append("payload_id", s_payload.getField("_id").OID()); session_builder.append("workflow_id", workflow.getField("_id").OID()); session_builder.append("start_timestamp", timestamp.toTime_t()); BSONObj session = session_builder.obj(); nosql_->Insert("sessions", session); /***********************************/ std::cout << "session inserted : " << session << std::endl; BSONObj l_payload = BSON("action" << "create" << "session_uuid" << str_session_uuid.toStdString() << "timestamp" << timestamp.toTime_t()); std::cout << "PUSH WORKER API PAYLOAD : " << l_payload << std::endl; /****** PUSH API PAYLOAD *******/ qDebug() << "PUSH WORKER CREATE PAYLOAD"; z_message->rebuild(l_payload.objsize()); memcpy(z_message->data(), (char*)l_payload.objdata(), l_payload.objsize()); //z_push_api->send(*z_message, ZMQ_NOBLOCK); z_push_api->send(*z_message); /************************/ } else { // WORKER RESPONSE std::cout << "RECEIVE ACTION : " << payload_action.toStdString() << std::endl; BSONObjBuilder b_payload; b_payload.append(payload.getFieldDotted("payload.name")); b_payload.append(payload.getFieldDotted("payload.action")); b_payload.append(payload.getFieldDotted("payload.timestamp")); b_payload.append(payload.getFieldDotted("payload.session_uuid")); /*** ACTION TERMINATE ***/ BSONObj tmp = payload.getField("payload").Obj(); if (tmp.hasField("datas")) b_payload.append(payload.getFieldDotted("payload.datas")); if (tmp.hasField("exitcode")) b_payload.append(payload.getFieldDotted("payload.exitcode")); if (tmp.hasField("exitstatus")) b_payload.append(payload.getFieldDotted("payload.exitstatus")); BSONObj l_payload = b_payload.obj(); std::cout << "PAYLOAD FORWARD : " << l_payload << std::endl; /****** PUSH API PAYLOAD *******/ qDebug() << "PUSH WORKER NEXT PAYLOAD"; z_message->rebuild(l_payload.objsize()); memcpy(z_message->data(), (char*)l_payload.objdata(), l_payload.objsize()); //z_push_api->send(*z_message, ZMQ_NOBLOCK); z_push_api->send(*z_message); /************************/ } } } check_payload->setEnabled(true); } Worker_api::~Worker_api() { z_push_api->close(); } <|endoftext|>
<commit_before>#include <binary_search_tree.hpp> #include <catch.hpp> SCENARIO("default constructor") { BinarySearchTree<int> bst; REQUIRE(bst.root() == nullptr); REQUIRE(bst.count() == 0); } SCENARIO("insertElement") { BinarySearchTree<int> bst; bst.insert(7); REQUIRE(bst.value_() == 7); REQUIRE(bst.leftNode_() == nullptr); REQUIRE(bst.rightNode_() == nullptr); } SCENARIO("insertElement") { BinarySearchTree<int> bst; bst.insert(7); bool a; a = bst.isFound(7); REQUIRE( a == true); } <commit_msg>Update init.cpp<commit_after>#include <binary_search_tree.hpp> #include <catch.hpp> SCENARIO("default constructor") { BinarySearchTree<int> bst; REQUIRE(bst.root() == nullptr); REQUIRE(bst.count() == 0); } SCENARIO("insertElement") { BinarySearchTree<int> bst; bst.insert(7); REQUIRE(bst.value_() == 7); REQUIRE(bst.leftNode_() == nullptr); REQUIRE(bst.rightNode_() == nullptr); } SCENARIO("insertElement") { BinarySearchTree<int> bst; bst.insert(7); bool a; a = bst.isFound(7); REQUIRE( a == 1); } <|endoftext|>
<commit_before>#include <BinaryTree.hpp> #include <catch.hpp> SCENARIO ("init", "[init]") { BinaryTree<int> obj; REQUIRE(obj.root_() == nullptr); } SCENARIO ("output to cout", "<<") { BinaryTree<int> tree; tree.insert_node(3); REQUIRE( std::cout << tree ); } SCENARIO("find_node", "[find_node]") { BinaryTree<int> obj; obj.insert_node(4); obj.insert_node(2); REQUIRE(obj.find_node(2, obj.root_()) != nullptr); REQUIRE(obj.find_node(2, obj.root_())->data == 2); } SCENARIO("insert", "[insert]") { BinaryTree<int> obj; obj.insert_node(3); REQUIRE(obj.find_node(3, obj.root_())->data == 3); } SCENARIO("removeElement", "[remEl]") { BinaryTree<int> obj; obj.insert_node(1); obj.insert_node(2); obj.insert_node(3); obj.remove_element(1); REQUIRE(obj.find_node(1, obj.root_())== nullptr); REQUIRE(obj.find_node(2, obj.root_())== obj.root_()); REQUIRE(obj.root_() != nullptr); } SCENARIO("DEL", "[Del]") { BinaryTree<int> obj; obj.insert_node(1); obj.insert_node(2); obj.remove_element(2); REQUIRE(obj.count() == 1); } <commit_msg>Update init.cpp<commit_after>#include <BinaryTree.hpp> #include <catch.hpp> SCENARIO ("init", "[init]") { BinaryTree<int> obj; REQUIRE(obj.root_() == nullptr); } SCENARIO ("output to cout", "<<") { BinaryTree<int> tree; tree.insert_node(3); REQUIRE( std::cout << tree ); } SCENARIO("find_node", "[find_node]") { BinaryTree<int> obj; obj.insert_node(4); obj.insert_node(2); REQUIRE(obj.find_node(2, obj.root_()) != nullptr); REQUIRE(obj.find_node(2, obj.root_())->data == 2); } SCENARIO("insert", "[insert]") { BinaryTree<int> obj; obj.insert_node(3); REQUIRE(obj.find_node(3, obj.root_())->data == 3); } SCENARIO("removeElement", "[remEl]") { BinaryTree<int> obj; obj.insert_node(1); obj.insert_node(2); obj.insert_node(3); obj.remove_element(1); REQUIRE(obj.find_node(1, obj.root_())== nullptr); REQUIRE(obj.find_node(2, obj.root_())== obj.root_()); REQUIRE(obj.root_() != nullptr); } SCENARIO("DEL", "[Del]") { BinaryTree<int> obj; obj.insert_node(1); obj.insert_node(2); obj.remove_element(2); REQUIRE(obj.getCount() == 1); } <|endoftext|>
<commit_before>#include <matrix.hpp> #include <catch.hpp> SCENARIO("matrix init without parametrs", "[init wp]") { Matrix matrix; REQUIRE(matrix.rows() == 4); REQUIRE(matrix.columns() == 4); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix[i][j] == 0); } } } SCENARIO("matrix init with parametrs", "[init withp]") { Matrix matrix(6,6); REQUIRE(matrix.rows() == 6); REQUIRE(matrix.columns() == 6); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix[i][j] == 0); } } } SCENARIO("matrix init copy", "[init copy]") { Matrix matrix(6,6); Matrix matrix1(matrix); REQUIRE(matrix1.rows() == matrix.rows()); REQUIRE(matrix1.columns() == matrix.columns()); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix[i][j] == matrix1[i][j]); } } } SCENARIO("matrix fill", "[fill]") { Matrix matrix(2,2); ofstream test1("test1.txt"); test1 << "1 2 3 4"; test1.close(); REQUIRE(matrix[0][0] == 1); REQUIRE(matrix[0][1] == 2); REQUIRE(matrix[1][0] == 3); REQUIRE(matrix[1][1] == 4); } <commit_msg>Update init.cpp<commit_after>#include <matrix.hpp> #include <catch.hpp> SCENARIO("matrix init without parametrs", "[init wp]") { Matrix matrix; REQUIRE(matrix.rows() == 4); REQUIRE(matrix.columns() == 4); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix.mas[i][j] == 0); } } } SCENARIO("matrix init with parametrs", "[init withp]") { Matrix matrix(6,6); REQUIRE(matrix.rows() == 6); REQUIRE(matrix.columns() == 6); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix.mas[i][j] == 0); } } } SCENARIO("matrix init copy", "[init copy]") { Matrix matrix(6,6); Matrix matrix1(matrix); REQUIRE(matrix1.rows() == matrix.rows()); REQUIRE(matrix1.columns() == matrix.columns()); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix.mas[i][j] == matrix1.mas[i][j]); } } } SCENARIO("matrix fill", "[fill]") { Matrix matrix(2,2); ofstream test1("test1.txt"); test1 << "1 2 3 4"; test1.close(); REQUIRE(matrix.mas[0][0] == 1); REQUIRE(matrix.mas[0][1] == 2); REQUIRE(matrix.mas[1][0] == 3); REQUIRE(matrix.mas[1][1] == 4); } <|endoftext|>
<commit_before>#include <BinaryTree.hpp> #include <catch.hpp> SCENARIO ("init", "[init]") { BinaryTree<int> obj; REQUIRE(obj.root_() == nullptr); } SCENARIO("insert", "[insert]") { BinaryTree<int> obj; obj.insert_node(3); REQUIRE(obj.find_node(3, obj.root_())->data == 3); } SCENARIO("find_node", "[find_node]") { BinaryTree<int> obj; obj.insert_node(2); REQUIRE(obj.find_node(2, obj.root_()) != nullptr); REQUIRE(obj.find_node(2, obj.root_())->data == 2); } SCENARIO("get root", "[get root]") { BinaryTree<int> obj; obj.insert_node(4); REQUIRE(obj.root_() != 0); } SCENARIO ("reading/writing", "[read/write]") { Tree<int> test1; test1.insert_node(4); test1.insert_node(3); test1.writing("file2.txt"); Tree<int> test2; test2.reading("file2.txt"); REQUIRE(test2.find_node(4, test2.root_())!= nullptr); REQUIRE(test2.find_node(3, test2.root_())!= nullptr); REQUIRE(test1.get_count() == test2.get_count()); } <commit_msg>Update init.cpp<commit_after>#include <BinaryTree.hpp> #include <catch.hpp> SCENARIO ("init", "[init]") { BinaryTree<int> obj; REQUIRE(obj.root_() == nullptr); } SCENARIO("insert", "[insert]") { BinaryTree<int> obj; obj.insert_node(3); REQUIRE(obj.find_node(3, obj.root_())->data == 3); } SCENARIO("find_node", "[find_node]") { BinaryTree<int> obj; obj.insert_node(2); REQUIRE(obj.find_node(2, obj.root_()) != nullptr); REQUIRE(obj.find_node(2, obj.root_())->data == 2); } SCENARIO("get root", "[get root]") { BinaryTree<int> obj; obj.insert_node(4); REQUIRE(obj.root_() != 0); } SCENARIO ("reading/writing", "[read/write]") { BinaryTree<int> obj; obj.insert_node(1); obj.insert_node(2); obj.writing("file2.txt"); Tree<int> obj_1; obj_1.reading("file2.txt"); REQUIRE(obj_1.find_node(1, obj_1.root_())!= nullptr); REQUIRE(obj_1.find_node(2, obj_1.root_())!= nullptr); } <|endoftext|>
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Test memcp * * Copyright (C) 2011 Data Differential, http://datadifferential.com/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not 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. * */ /* Test that we are cycling the servers we are creating during testing. */ #include <mem_config.h> #include <libtest/test.hpp> #include <libmemcached-1.0/memcached.h> #include <sys/stat.h> using namespace libtest; #ifndef __INTEL_COMPILER #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif static std::string executable("./clients/memcp"); static test_return_t help_test(void *) { const char *args[]= { "--help", 0 }; test_compare(EXIT_SUCCESS, exec_cmdline(executable, args, true)); return TEST_SUCCESS; } static test_return_t server_test(void *) { int fd; std::string tmp_file= create_tmpfile("memcp", fd); ASSERT_TRUE(tmp_file.c_str()); struct stat buf; ASSERT_EQ(fstat(fd, &buf), 0); ASSERT_EQ(buf.st_size, 0); char buffer[1024]; snprintf(buffer, sizeof(buffer), "--servers=localhost:%d", int(default_port())); const char *args[]= { buffer, tmp_file.c_str(), 0 }; test_compare(EXIT_SUCCESS, exec_cmdline(executable, args, true)); close(fd); unlink(tmp_file.c_str()); return TEST_SUCCESS; } test_st memcp_tests[] ={ {"--help", true, help_test }, {"--server_test", true, server_test }, {0, 0, 0} }; collection_st collection[] ={ {"memcp", 0, 0, memcp_tests }, {0, 0, 0, 0} }; static void *world_create(server_startup_st& servers, test_return_t& error) { if (libtest::has_memcached() == false) { error= TEST_SKIPPED; return NULL; } if (server_startup(servers, "memcached", libtest::default_port(), NULL) == false) { error= TEST_FAILURE; } return &servers; } void get_world(libtest::Framework* world) { world->collections(collection); world->create(world_create); } <commit_msg>Disable broken test for the moment.<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Test memcp * * Copyright (C) 2011 Data Differential, http://datadifferential.com/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not 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. * */ /* Test that we are cycling the servers we are creating during testing. */ #include <mem_config.h> #include <libtest/test.hpp> #include <libmemcached-1.0/memcached.h> #include <sys/stat.h> using namespace libtest; #ifndef __INTEL_COMPILER #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif static std::string executable("./clients/memcp"); static test_return_t help_test(void *) { const char *args[]= { "--help", 0 }; test_compare(EXIT_SUCCESS, exec_cmdline(executable, args, true)); return TEST_SUCCESS; } #if 0 static test_return_t server_test(void *) { int fd; std::string tmp_file= create_tmpfile("memcp", fd); ASSERT_TRUE(tmp_file.c_str()); struct stat buf; ASSERT_EQ(fstat(fd, &buf), 0); ASSERT_EQ(buf.st_size, 0); char buffer[1024]; snprintf(buffer, sizeof(buffer), "--servers=localhost:%d", int(default_port())); const char *args[]= { buffer, tmp_file.c_str(), 0 }; test_compare(EXIT_SUCCESS, exec_cmdline(executable, args, true)); close(fd); unlink(tmp_file.c_str()); return TEST_SUCCESS; } #endif test_st memcp_tests[] ={ {"--help", true, help_test }, #if 0 {"--server_test", true, server_test }, #endif {0, 0, 0} }; collection_st collection[] ={ {"memcp", 0, 0, memcp_tests }, {0, 0, 0, 0} }; static void *world_create(server_startup_st& servers, test_return_t& error) { if (libtest::has_memcached() == false) { error= TEST_SKIPPED; return NULL; } if (server_startup(servers, "memcached", libtest::default_port(), NULL) == false) { error= TEST_FAILURE; } return &servers; } void get_world(libtest::Framework* world) { world->collections(collection); world->create(world_create); } <|endoftext|>
<commit_before>/* Copyright (C) 2009, Stefan Hacker <dd0t@users.sourceforge.net> Copyright (C) 2005-2009, Thorvald Natvig <thorvald@natvig.com> 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 Mumble Developers 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 FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CustomElements.h" #include "ClientUser.h" /*! \fn int ChatbarLineEdit::completeAtCursor() The bar will try to complete the username, if the nickname is already complete it will try to find a longer match. If there is none it will cycle the nicknames alphabetically. Nothing is done on mismatch. */ void ChatbarLineEdit::focusInEvent(QFocusEvent *) { if (bDefaultVisible) { QFont f = font(); f.setItalic(false); setFont(f); setAlignment(Qt::AlignLeft); setText(QString()); bDefaultVisible = false; } } void ChatbarLineEdit::focusOutEvent(QFocusEvent *) { if (text().trimmed().isEmpty()) { QFont f = font(); f.setItalic(true); setFont(f); setAlignment(Qt::AlignCenter); setText(qsDefaultText); bDefaultVisible = true; } else { bDefaultVisible = false; } } ChatbarLineEdit::ChatbarLineEdit(QWidget *p) : QLineEdit(p) { bDefaultVisible = true; setDefaultText(tr("Type chat message here")); } void ChatbarLineEdit::setDefaultText(const QString &new_default) { qsDefaultText = new_default; if (!hasFocus()) { QFont f = font(); f.setItalic(true); setFont(f); setAlignment(Qt::AlignCenter); setText(qsDefaultText); bDefaultVisible = true; } } bool ChatbarLineEdit::event(QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent *kev = static_cast<QKeyEvent*>(event); if (kev->key() == Qt::Key_Tab) { emit tabPressed(); return true; } else if (kev->key() == Qt::Key_Space && kev->modifiers() == Qt::ControlModifier) { emit ctrlSpacePressed(); return true; } } return QLineEdit::event(event); } unsigned int ChatbarLineEdit::completeAtCursor() { // Get an alphabetically sorted list of usernames unsigned int id = 0; QList<QString> qlsUsernames; if (ClientUser::c_qmUsers.empty()) return id; foreach (ClientUser *usr, ClientUser::c_qmUsers) { qlsUsernames.append(usr->qsName); } qSort(qlsUsernames); QString newtext; newtext = text(); QString target = QString(); if (newtext.isEmpty()) { target = qlsUsernames.first(); newtext = target; } else { // Get the word before the cursor bool bBaseIsName = false; int iend = cursorPosition(); int istart = newtext.lastIndexOf(QLatin1Char(' '), iend - 1) + 1; QString base = newtext.mid(istart, iend - istart); if (qlsUsernames.last() == base) { bBaseIsName = true; target = qlsUsernames.first(); } else { if (qlsUsernames.contains(base)) { // Prevent to complete to what's already there while (qlsUsernames.takeFirst() != base) {} bBaseIsName = true; } foreach (QString name, qlsUsernames) { if (name.startsWith(base, Qt::CaseInsensitive)) { target = name; break; } } } if (bBaseIsName && target.isEmpty() && !qlsUsernames.empty()) { // If autocomplete failed and base was a name get the next one target = qlsUsernames.first(); } if (!target.isEmpty()) { newtext.replace(istart, base.length(), target); } } if (!target.isEmpty()) { foreach (ClientUser *usr, ClientUser::c_qmUsers) { if (usr->qsName == target) { id = usr->uiSession; break; } } setText(newtext); } return id; } DockTitleBar::DockTitleBar() { qtTick = new QTimer(this); qtTick->setSingleShot(true); connect(qtTick, SIGNAL(timeout()), this, SLOT(tick())); size = newsize = 0; } QSize DockTitleBar::sizeHint() const { return minimumSizeHint(); } QSize DockTitleBar::minimumSizeHint() const { return QSize(size,size); } bool DockTitleBar::eventFilter(QObject *, QEvent *evt) { QDockWidget *qdw = qobject_cast<QDockWidget*>(parentWidget()); switch (evt->type()) { case QEvent::Leave: case QEvent::Enter: case QEvent::MouseMove: case QEvent::MouseButtonRelease: { newsize = 0; QPoint p = qdw->mapFromGlobal(QCursor::pos()); if ((p.x() >= iroundf(static_cast<float>(qdw->width()) * 0.1f)) && (p.x() < iroundf(static_cast<float>(qdw->width()) * 0.9f)) && (p.y() >= 0) && (p.y() < 15)) newsize = 15; if (newsize > 0 && !qtTick->isActive()) qtTick->start(500); else if ((newsize == size) && qtTick->isActive()) qtTick->stop(); else if (newsize == 0) tick(); } default: break; } return false; } void DockTitleBar::tick() { QDockWidget *qdw = qobject_cast<QDockWidget*>(parentWidget()); if (newsize == size) return; size = newsize; qdw->setTitleBarWidget(this); } <commit_msg>fix text cursor in chatbar<commit_after>/* Copyright (C) 2009, Stefan Hacker <dd0t@users.sourceforge.net> Copyright (C) 2005-2009, Thorvald Natvig <thorvald@natvig.com> 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 Mumble Developers 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 FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "CustomElements.h" #include "ClientUser.h" /*! \fn int ChatbarLineEdit::completeAtCursor() The bar will try to complete the username, if the nickname is already complete it will try to find a longer match. If there is none it will cycle the nicknames alphabetically. Nothing is done on mismatch. */ void ChatbarLineEdit::focusInEvent(QFocusEvent *qfe) { QLineEdit::focusInEvent(qfe); if (bDefaultVisible) { QFont f = font(); f.setItalic(false); setFont(f); setAlignment(Qt::AlignLeft); setText(QString()); bDefaultVisible = false; } } void ChatbarLineEdit::focusOutEvent(QFocusEvent *qfe) { QLineEdit::focusOutEvent(qfe); if (text().trimmed().isEmpty()) { QFont f = font(); f.setItalic(true); setFont(f); setAlignment(Qt::AlignCenter); setText(qsDefaultText); bDefaultVisible = true; } else { bDefaultVisible = false; } } ChatbarLineEdit::ChatbarLineEdit(QWidget *p) : QLineEdit(p) { bDefaultVisible = true; setDefaultText(tr("Type chat message here")); } void ChatbarLineEdit::setDefaultText(const QString &new_default) { qsDefaultText = new_default; if (!hasFocus()) { QFont f = font(); f.setItalic(true); setFont(f); setAlignment(Qt::AlignCenter); setText(qsDefaultText); bDefaultVisible = true; } } bool ChatbarLineEdit::event(QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent *kev = static_cast<QKeyEvent*>(event); if (kev->key() == Qt::Key_Tab) { emit tabPressed(); return true; } else if (kev->key() == Qt::Key_Space && kev->modifiers() == Qt::ControlModifier) { emit ctrlSpacePressed(); return true; } } return QLineEdit::event(event); } unsigned int ChatbarLineEdit::completeAtCursor() { // Get an alphabetically sorted list of usernames unsigned int id = 0; QList<QString> qlsUsernames; if (ClientUser::c_qmUsers.empty()) return id; foreach (ClientUser *usr, ClientUser::c_qmUsers) { qlsUsernames.append(usr->qsName); } qSort(qlsUsernames); QString newtext; newtext = text(); QString target = QString(); if (newtext.isEmpty()) { target = qlsUsernames.first(); newtext = target; } else { // Get the word before the cursor bool bBaseIsName = false; int iend = cursorPosition(); int istart = newtext.lastIndexOf(QLatin1Char(' '), iend - 1) + 1; QString base = newtext.mid(istart, iend - istart); if (qlsUsernames.last() == base) { bBaseIsName = true; target = qlsUsernames.first(); } else { if (qlsUsernames.contains(base)) { // Prevent to complete to what's already there while (qlsUsernames.takeFirst() != base) {} bBaseIsName = true; } foreach (QString name, qlsUsernames) { if (name.startsWith(base, Qt::CaseInsensitive)) { target = name; break; } } } if (bBaseIsName && target.isEmpty() && !qlsUsernames.empty()) { // If autocomplete failed and base was a name get the next one target = qlsUsernames.first(); } if (!target.isEmpty()) { newtext.replace(istart, base.length(), target); } } if (!target.isEmpty()) { foreach (ClientUser *usr, ClientUser::c_qmUsers) { if (usr->qsName == target) { id = usr->uiSession; break; } } setText(newtext); } return id; } DockTitleBar::DockTitleBar() { qtTick = new QTimer(this); qtTick->setSingleShot(true); connect(qtTick, SIGNAL(timeout()), this, SLOT(tick())); size = newsize = 0; } QSize DockTitleBar::sizeHint() const { return minimumSizeHint(); } QSize DockTitleBar::minimumSizeHint() const { return QSize(size,size); } bool DockTitleBar::eventFilter(QObject *, QEvent *evt) { QDockWidget *qdw = qobject_cast<QDockWidget*>(parentWidget()); switch (evt->type()) { case QEvent::Leave: case QEvent::Enter: case QEvent::MouseMove: case QEvent::MouseButtonRelease: { newsize = 0; QPoint p = qdw->mapFromGlobal(QCursor::pos()); if ((p.x() >= iroundf(static_cast<float>(qdw->width()) * 0.1f)) && (p.x() < iroundf(static_cast<float>(qdw->width()) * 0.9f)) && (p.y() >= 0) && (p.y() < 15)) newsize = 15; if (newsize > 0 && !qtTick->isActive()) qtTick->start(500); else if ((newsize == size) && qtTick->isActive()) qtTick->stop(); else if (newsize == 0) tick(); } default: break; } return false; } void DockTitleBar::tick() { QDockWidget *qdw = qobject_cast<QDockWidget*>(parentWidget()); if (newsize == size) return; size = newsize; qdw->setTitleBarWidget(this); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) Qxt Foundation. Some rights reserved. ** ** This file is part of the QxtWeb module of the Qxt library. ** ** This library is free software; you can redistribute it and/or modify it ** under the terms of the Common Public License, version 1.0, as published ** by IBM, and/or under the terms of the GNU Lesser General Public License, ** version 2.1, as published by the Free Software Foundation. ** ** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY ** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY ** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR ** FITNESS FOR A PARTICULAR PURPOSE. ** ** You should have received a copy of the CPL and the LGPL along with this ** file. See the LICENSE file and the cpl1.0.txt/lgpl-2.1.txt files ** included with the source distribution for more information. ** If you did not receive a copy of the licenses, contact the Qxt Foundation. ** ** <http://libqxt.org> <foundation@libqxt.org> ** ****************************************************************************/ /*! \class QxtXmlRpcCall \inmodule QxtNetwork \brief The QxtXmlRpcCall class represents a Call to an XMLRPC Service. */ /*! \fn QxtXmlRpcCall::downloadProgress ( qint64 bytesReceived, qint64 bytesTotal ) This signal is emitted to indicate the progress of retreiving the response from the remote service \sa QNetworkReply::downloadProgress() */ /*! \fn QxtXmlRpcCall::error(QNetworkReply::NetworkError code) Signals a network error \sa QNetworkReply::error() */ /*! \fn QxtXmlRpcCall::finished() emitted once the result is fully available \sa QNetworkReply::finished() */ /*! \fn QxtXmlRpcCall::sslErrors ( const QList<QSslError> & errors ); \sa QNetworkReply::sslErrors() */ /*! \fn QxtXmlRpcCall:: uploadProgress() This signal is emitted to indicate the progress of sending the request to the remote service \sa QNetworkReply::uploadProgress() */ #include "qxtxmlrpccall.h" #include "qxtxmlrpc_p.h" #include <QXmlStreamReader> #include <QNetworkReply> class QxtXmlRpcCallPrivate { public: bool isFault; QNetworkReply * reply; QVariant result; void d_finished(); QxtXmlRpcCall * pub; }; /*! returns true if the remote service sent a fault message */ bool QxtXmlRpcCall::isFault() const { return d->isFault; } /*! returns the result or fault message or a null QVariant() if the call isnt finished yet \sa QxtXmlRpcClient#type-conversion */ QVariant QxtXmlRpcCall::result() const { return d->result; } /*! returns an associated network error. */ QNetworkReply::NetworkError QxtXmlRpcCall::error() const { return d->reply->error(); } QxtXmlRpcCall::QxtXmlRpcCall(QNetworkReply * reply) : d(new QxtXmlRpcCallPrivate()) { d->isFault = false; d->reply = reply; d->pub = this; connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SIGNAL(downloadProgress(qint64, qint64))); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SIGNAL(error(QNetworkReply::NetworkError))); connect(reply, SIGNAL(sslErrors(const QList<QSslError> &)), this, SIGNAL(sslErrors(const QList<QSslError> &))); connect(reply, SIGNAL(uploadProgress(qint64, qint64)), this, SIGNAL(uploadProgress(qint64, qint64))); connect(reply, SIGNAL(finished()), this, SLOT(d_finished())); } void QxtXmlRpcCallPrivate::d_finished() { if (!reply->error()) { int s = 0; QXmlStreamReader xml(reply->readAll()); while (!xml.atEnd()) { xml.readNext(); if (xml.isStartElement()) { if (s == 0) { if (xml.name().toString() == "methodResponse") { s = 1; } else { xml.raiseError("expected <methodResponse>, got:<" + xml.name().toString() + ">"); } } else if (s == 1) { if (xml.name().toString() == "params") { s = 2; } else if (xml.name().toString() == "fault") { isFault = true; s = 3; } else { xml.raiseError("expected <params> or <fault>, got:<" + xml.name().toString() + ">"); } } else if (s == 2) { if (xml.name().toString() == "param") { s = 3; } else { xml.raiseError("expected <param>, got:<" + xml.name().toString() + ">"); } } else if (s == 3) { if (xml.name().toString() == "value") { result = QxtXmlRpc::deserialize(xml); s = 4; } else { xml.raiseError("expected <value>, got:<" + xml.name().toString() + ">"); } } } } if (xml.hasError()) { qWarning(QString("QxtXmlRpcCall: " + xml.errorString() + " at line " + QString::number(xml.lineNumber()) + " column " + QString::number(xml.columnNumber())).toLocal8Bit().data()); } } emit pub->finished(); } #include "moc_qxtxmlrpccall.cpp" <commit_msg>- fix format string problem (gcc 4.4.1 did not accept to compile in previous state)<commit_after>/**************************************************************************** ** ** Copyright (C) Qxt Foundation. Some rights reserved. ** ** This file is part of the QxtWeb module of the Qxt library. ** ** This library is free software; you can redistribute it and/or modify it ** under the terms of the Common Public License, version 1.0, as published ** by IBM, and/or under the terms of the GNU Lesser General Public License, ** version 2.1, as published by the Free Software Foundation. ** ** This file is provided "AS IS", without WARRANTIES OR CONDITIONS OF ANY ** KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY ** WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR ** FITNESS FOR A PARTICULAR PURPOSE. ** ** You should have received a copy of the CPL and the LGPL along with this ** file. See the LICENSE file and the cpl1.0.txt/lgpl-2.1.txt files ** included with the source distribution for more information. ** If you did not receive a copy of the licenses, contact the Qxt Foundation. ** ** <http://libqxt.org> <foundation@libqxt.org> ** ****************************************************************************/ /*! \class QxtXmlRpcCall \inmodule QxtNetwork \brief The QxtXmlRpcCall class represents a Call to an XMLRPC Service. */ /*! \fn QxtXmlRpcCall::downloadProgress ( qint64 bytesReceived, qint64 bytesTotal ) This signal is emitted to indicate the progress of retreiving the response from the remote service \sa QNetworkReply::downloadProgress() */ /*! \fn QxtXmlRpcCall::error(QNetworkReply::NetworkError code) Signals a network error \sa QNetworkReply::error() */ /*! \fn QxtXmlRpcCall::finished() emitted once the result is fully available \sa QNetworkReply::finished() */ /*! \fn QxtXmlRpcCall::sslErrors ( const QList<QSslError> & errors ); \sa QNetworkReply::sslErrors() */ /*! \fn QxtXmlRpcCall:: uploadProgress() This signal is emitted to indicate the progress of sending the request to the remote service \sa QNetworkReply::uploadProgress() */ #include "qxtxmlrpccall.h" #include "qxtxmlrpc_p.h" #include <QXmlStreamReader> #include <QNetworkReply> class QxtXmlRpcCallPrivate { public: bool isFault; QNetworkReply * reply; QVariant result; void d_finished(); QxtXmlRpcCall * pub; }; /*! returns true if the remote service sent a fault message */ bool QxtXmlRpcCall::isFault() const { return d->isFault; } /*! returns the result or fault message or a null QVariant() if the call isnt finished yet \sa QxtXmlRpcClient#type-conversion */ QVariant QxtXmlRpcCall::result() const { return d->result; } /*! returns an associated network error. */ QNetworkReply::NetworkError QxtXmlRpcCall::error() const { return d->reply->error(); } QxtXmlRpcCall::QxtXmlRpcCall(QNetworkReply * reply) : d(new QxtXmlRpcCallPrivate()) { d->isFault = false; d->reply = reply; d->pub = this; connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SIGNAL(downloadProgress(qint64, qint64))); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SIGNAL(error(QNetworkReply::NetworkError))); connect(reply, SIGNAL(sslErrors(const QList<QSslError> &)), this, SIGNAL(sslErrors(const QList<QSslError> &))); connect(reply, SIGNAL(uploadProgress(qint64, qint64)), this, SIGNAL(uploadProgress(qint64, qint64))); connect(reply, SIGNAL(finished()), this, SLOT(d_finished())); } void QxtXmlRpcCallPrivate::d_finished() { if (!reply->error()) { int s = 0; QXmlStreamReader xml(reply->readAll()); while (!xml.atEnd()) { xml.readNext(); if (xml.isStartElement()) { if (s == 0) { if (xml.name().toString() == "methodResponse") { s = 1; } else { xml.raiseError("expected <methodResponse>, got:<" + xml.name().toString() + ">"); } } else if (s == 1) { if (xml.name().toString() == "params") { s = 2; } else if (xml.name().toString() == "fault") { isFault = true; s = 3; } else { xml.raiseError("expected <params> or <fault>, got:<" + xml.name().toString() + ">"); } } else if (s == 2) { if (xml.name().toString() == "param") { s = 3; } else { xml.raiseError("expected <param>, got:<" + xml.name().toString() + ">"); } } else if (s == 3) { if (xml.name().toString() == "value") { result = QxtXmlRpc::deserialize(xml); s = 4; } else { xml.raiseError("expected <value>, got:<" + xml.name().toString() + ">"); } } } } if (xml.hasError()) { qWarning("QxtXmlRpcCall: %s at line %d column %d", xml.errorString().toLocal8Bit().data(), QString::number(xml.lineNumber()), QString::number(xml.columnNumber())); } } emit pub->finished(); } #include "moc_qxtxmlrpccall.cpp" <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osg/GLBeginEndAdapter> #include <osg/State> #include <osg/Notify> #include <osg/io_utils> using namespace osg; GLBeginEndAdapter::GLBeginEndAdapter(State* state): _state(state), _mode(APPLY_LOCAL_MATRICES_TO_VERTICES), _normalAssigned(false), _normal(0.0f,0.0f,1.0f), _colorAssigned(false), _color(1.0f,1.0f,1.0f,1.0f) { } void GLBeginEndAdapter::PushMatrix() { if (_matrixStack.empty()) { if (_mode==APPLY_LOCAL_MATRICES_TO_VERTICES) _matrixStack.push_back(Matrixd()); else _matrixStack.push_back(_state->getModelViewMatrix()); } else _matrixStack.push_back(_matrixStack.back()); } void GLBeginEndAdapter::PopMatrix() { if (!_matrixStack.empty()) _matrixStack.pop_back(); } void GLBeginEndAdapter::LoadIdentity() { if (_matrixStack.empty()) _matrixStack.push_back(Matrixd::identity()); else _matrixStack.back().makeIdentity(); } void GLBeginEndAdapter::LoadMatrixd(const GLdouble* m) { if (_matrixStack.empty()) _matrixStack.push_back(Matrixd(m)); else _matrixStack.back().set(m); } void GLBeginEndAdapter::MultMatrixd(const GLdouble* m) { if (_matrixStack.empty()) { if (_mode==APPLY_LOCAL_MATRICES_TO_VERTICES) _matrixStack.push_back(Matrixd()); else _matrixStack.push_back(_state->getModelViewMatrix()); } _matrixStack.back().preMult(Matrixd(m)); } void GLBeginEndAdapter::Translated(GLdouble x, GLdouble y, GLdouble z) { if (_matrixStack.empty()) { if (_mode==APPLY_LOCAL_MATRICES_TO_VERTICES) _matrixStack.push_back(Matrixd()); else _matrixStack.push_back(_state->getModelViewMatrix()); } _matrixStack.back().preMultTranslate(Vec3d(x,y,z)); } void GLBeginEndAdapter::Scaled(GLdouble x, GLdouble y, GLdouble z) { if (_matrixStack.empty()) { if (_mode==APPLY_LOCAL_MATRICES_TO_VERTICES) _matrixStack.push_back(Matrixd()); else _matrixStack.push_back(_state->getModelViewMatrix()); } _matrixStack.back().preMultScale(Vec3d(x,y,z)); } void GLBeginEndAdapter::Rotated(GLdouble angle, GLdouble x, GLdouble y, GLdouble z) { if (_matrixStack.empty()) { if (_mode==APPLY_LOCAL_MATRICES_TO_VERTICES) _matrixStack.push_back(Matrixd()); else _matrixStack.push_back(_state->getModelViewMatrix()); } _matrixStack.back().preMultRotate(Quat(DegreesToRadians(angle), Vec3d(x,y,z))); } void GLBeginEndAdapter::MultiTexCoord4f(GLenum target, GLfloat x, GLfloat y, GLfloat z, GLfloat w) { unsigned int unit = static_cast<unsigned int>(target-GL_TEXTURE0); if (unit>=_texCoordAssignedList.size()) _texCoordAssignedList.resize(unit+1, false); if (unit>=_texCoordList.size()) _texCoordList.resize(unit+1, osg::Vec4(0.0f,0.0f,0.0f,0.0f)); _texCoordAssignedList[unit] = true; _texCoordList[unit].set(x,y,z,w); } void GLBeginEndAdapter::VertexAttrib4f(GLuint unit, GLfloat x, GLfloat y, GLfloat z, GLfloat w) { if (unit>=_vertexAttribAssignedList.size()) _vertexAttribAssignedList.resize(unit+1, false); if (unit>=_vertexAttribList.size()) _vertexAttribList.resize(unit+1, osg::Vec4(0.0f,0.0f,0.0f,0.0f)); _vertexAttribAssignedList[unit] = true; _vertexAttribList[unit].set(x,y,z,w); } void GLBeginEndAdapter::Vertex3f(GLfloat x, GLfloat y, GLfloat z) { osg::Vec3 vertex(x,y,z); if (!_vertices) _vertices = new osg::Vec3Array; if (_normalAssigned) { if (!_normals) _normals = new osg::Vec3Array; if (_normals->size()<_vertices->size()) _normals->resize(_vertices->size(), _overallNormal); _normals->push_back(_normal); } if (_colorAssigned) { if (!_colors) _colors = new osg::Vec4Array; if (_colors->size()<_vertices->size()) _colors->resize(_vertices->size(), _overallColor); _colors->push_back(_color); } if (!_texCoordAssignedList.empty()) { for(unsigned int unit=0; unit<_texCoordAssignedList.size(); ++unit) { if (_texCoordAssignedList[unit]) { if (unit>=_texCoordsList.size()) _texCoordsList.resize(unit+1); if (!_texCoordsList[unit]) _texCoordsList[unit] = new osg::Vec4Array; if (_texCoordsList[unit]->size()<_vertices->size()) _texCoordsList[unit]->resize(_vertices->size(), osg::Vec4(0.0,0.0f,0.0f,0.0f)); _texCoordsList[unit]->push_back(_texCoordList[unit]); } } } if (!_vertexAttribAssignedList.empty()) { for(unsigned int unit=0; unit<_vertexAttribAssignedList.size(); ++unit) { if (_vertexAttribAssignedList[unit]) { if (unit>=_vertexAttribsList.size()) _vertexAttribsList.resize(unit+1); if (!_vertexAttribsList[unit]) _vertexAttribsList[unit] = new osg::Vec4Array; if (_vertexAttribsList[unit]->size()<_vertices->size()) _vertexAttribsList[unit]->resize(_vertices->size(), osg::Vec4(0.0,0.0f,0.0f,0.0f)); _vertexAttribsList[unit]->push_back(_vertexAttribList[unit]); } } } _vertices->push_back(vertex); } void GLBeginEndAdapter::Begin(GLenum mode) { _overallNormal = _normal; _overallColor = _color; // reset geometry _primitiveMode = mode; if (_vertices.valid()) _vertices->clear(); _normalAssigned = false; if (_normals.valid()) _normals->clear(); _colorAssigned = false; if (_colors.valid()) _colors->clear(); _texCoordAssignedList.clear(); _texCoordList.clear(); for(VertexArrayList::iterator itr = _texCoordsList.begin(); itr != _texCoordsList.end(); ++itr) { if (itr->valid()) (*itr)->clear(); } _vertexAttribAssignedList.clear(); _vertexAttribList.clear(); } void GLBeginEndAdapter::End() { if (!_vertices || _vertices->empty()) return; if (!_matrixStack.empty()) { const osg::Matrixd& matrix = _matrixStack.back(); if (_mode==APPLY_LOCAL_MATRICES_TO_VERTICES) { osg::Matrix inverse; inverse.invert(matrix); for(Vec3Array::iterator itr = _vertices->begin(); itr != _vertices->end(); ++itr) { *itr = *itr * matrix; } if (_normalAssigned && _normals.valid()) { for(Vec3Array::iterator itr = _normals->begin(); itr != _normals->end(); ++itr) { *itr = osg::Matrixd::transform3x3(inverse, *itr); (*itr).normalize(); } } else { _overallNormal = osg::Matrixd::transform3x3(inverse, _overallNormal); _overallNormal.normalize(); } } else { _state->applyModelViewMatrix(new RefMatrix(matrix)); } } _state->lazyDisablingOfVertexAttributes(); if (_colorAssigned) { _state->setColorPointer(_colors.get()); } else { _state->Color(_overallColor.r(), _overallColor.g(), _overallColor.b(), _overallColor.a()); } if (_normalAssigned) { _state->setNormalPointer(_normals.get()); } else { _state->Normal(_overallNormal.x(), _overallNormal.y(), _overallNormal.z()); } for(unsigned int unit=0; unit<_texCoordAssignedList.size(); ++unit) { if (_texCoordAssignedList[unit] && _texCoordsList[unit].valid()) { _state->setTexCoordPointer(unit, _texCoordsList[unit].get()); } } for(unsigned int unit=0; unit<_vertexAttribAssignedList.size(); ++unit) { if (_vertexAttribAssignedList[unit] && _vertexAttribsList[unit].valid()) { _state->setVertexAttribPointer(unit, _vertexAttribsList[unit].get(), false); } } _state->setVertexPointer(_vertices.get()); _state->applyDisablingOfVertexAttributes(); if (_primitiveMode==GL_QUADS) { _state->drawQuads(0, _vertices->size()); } else if (_primitiveMode==GL_QUAD_STRIP) { // will the winding be wrong? Do we need to swap it? glDrawArrays(GL_TRIANGLE_STRIP, 0, _vertices->size()); } else if (_primitiveMode==GL_POLYGON) glDrawArrays(GL_TRIANGLE_FAN, 0, _vertices->size()); else glDrawArrays(_primitiveMode, 0, _vertices->size()); } <commit_msg>Fixed Coverity issue.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osg/GLBeginEndAdapter> #include <osg/State> #include <osg/Notify> #include <osg/io_utils> using namespace osg; GLBeginEndAdapter::GLBeginEndAdapter(State* state): _state(state), _mode(APPLY_LOCAL_MATRICES_TO_VERTICES), _normalAssigned(false), _normal(0.0f,0.0f,1.0f), _colorAssigned(false), _color(1.0f,1.0f,1.0f,1.0f), _primitiveMode(0) { } void GLBeginEndAdapter::PushMatrix() { if (_matrixStack.empty()) { if (_mode==APPLY_LOCAL_MATRICES_TO_VERTICES) _matrixStack.push_back(Matrixd()); else _matrixStack.push_back(_state->getModelViewMatrix()); } else _matrixStack.push_back(_matrixStack.back()); } void GLBeginEndAdapter::PopMatrix() { if (!_matrixStack.empty()) _matrixStack.pop_back(); } void GLBeginEndAdapter::LoadIdentity() { if (_matrixStack.empty()) _matrixStack.push_back(Matrixd::identity()); else _matrixStack.back().makeIdentity(); } void GLBeginEndAdapter::LoadMatrixd(const GLdouble* m) { if (_matrixStack.empty()) _matrixStack.push_back(Matrixd(m)); else _matrixStack.back().set(m); } void GLBeginEndAdapter::MultMatrixd(const GLdouble* m) { if (_matrixStack.empty()) { if (_mode==APPLY_LOCAL_MATRICES_TO_VERTICES) _matrixStack.push_back(Matrixd()); else _matrixStack.push_back(_state->getModelViewMatrix()); } _matrixStack.back().preMult(Matrixd(m)); } void GLBeginEndAdapter::Translated(GLdouble x, GLdouble y, GLdouble z) { if (_matrixStack.empty()) { if (_mode==APPLY_LOCAL_MATRICES_TO_VERTICES) _matrixStack.push_back(Matrixd()); else _matrixStack.push_back(_state->getModelViewMatrix()); } _matrixStack.back().preMultTranslate(Vec3d(x,y,z)); } void GLBeginEndAdapter::Scaled(GLdouble x, GLdouble y, GLdouble z) { if (_matrixStack.empty()) { if (_mode==APPLY_LOCAL_MATRICES_TO_VERTICES) _matrixStack.push_back(Matrixd()); else _matrixStack.push_back(_state->getModelViewMatrix()); } _matrixStack.back().preMultScale(Vec3d(x,y,z)); } void GLBeginEndAdapter::Rotated(GLdouble angle, GLdouble x, GLdouble y, GLdouble z) { if (_matrixStack.empty()) { if (_mode==APPLY_LOCAL_MATRICES_TO_VERTICES) _matrixStack.push_back(Matrixd()); else _matrixStack.push_back(_state->getModelViewMatrix()); } _matrixStack.back().preMultRotate(Quat(DegreesToRadians(angle), Vec3d(x,y,z))); } void GLBeginEndAdapter::MultiTexCoord4f(GLenum target, GLfloat x, GLfloat y, GLfloat z, GLfloat w) { unsigned int unit = static_cast<unsigned int>(target-GL_TEXTURE0); if (unit>=_texCoordAssignedList.size()) _texCoordAssignedList.resize(unit+1, false); if (unit>=_texCoordList.size()) _texCoordList.resize(unit+1, osg::Vec4(0.0f,0.0f,0.0f,0.0f)); _texCoordAssignedList[unit] = true; _texCoordList[unit].set(x,y,z,w); } void GLBeginEndAdapter::VertexAttrib4f(GLuint unit, GLfloat x, GLfloat y, GLfloat z, GLfloat w) { if (unit>=_vertexAttribAssignedList.size()) _vertexAttribAssignedList.resize(unit+1, false); if (unit>=_vertexAttribList.size()) _vertexAttribList.resize(unit+1, osg::Vec4(0.0f,0.0f,0.0f,0.0f)); _vertexAttribAssignedList[unit] = true; _vertexAttribList[unit].set(x,y,z,w); } void GLBeginEndAdapter::Vertex3f(GLfloat x, GLfloat y, GLfloat z) { osg::Vec3 vertex(x,y,z); if (!_vertices) _vertices = new osg::Vec3Array; if (_normalAssigned) { if (!_normals) _normals = new osg::Vec3Array; if (_normals->size()<_vertices->size()) _normals->resize(_vertices->size(), _overallNormal); _normals->push_back(_normal); } if (_colorAssigned) { if (!_colors) _colors = new osg::Vec4Array; if (_colors->size()<_vertices->size()) _colors->resize(_vertices->size(), _overallColor); _colors->push_back(_color); } if (!_texCoordAssignedList.empty()) { for(unsigned int unit=0; unit<_texCoordAssignedList.size(); ++unit) { if (_texCoordAssignedList[unit]) { if (unit>=_texCoordsList.size()) _texCoordsList.resize(unit+1); if (!_texCoordsList[unit]) _texCoordsList[unit] = new osg::Vec4Array; if (_texCoordsList[unit]->size()<_vertices->size()) _texCoordsList[unit]->resize(_vertices->size(), osg::Vec4(0.0,0.0f,0.0f,0.0f)); _texCoordsList[unit]->push_back(_texCoordList[unit]); } } } if (!_vertexAttribAssignedList.empty()) { for(unsigned int unit=0; unit<_vertexAttribAssignedList.size(); ++unit) { if (_vertexAttribAssignedList[unit]) { if (unit>=_vertexAttribsList.size()) _vertexAttribsList.resize(unit+1); if (!_vertexAttribsList[unit]) _vertexAttribsList[unit] = new osg::Vec4Array; if (_vertexAttribsList[unit]->size()<_vertices->size()) _vertexAttribsList[unit]->resize(_vertices->size(), osg::Vec4(0.0,0.0f,0.0f,0.0f)); _vertexAttribsList[unit]->push_back(_vertexAttribList[unit]); } } } _vertices->push_back(vertex); } void GLBeginEndAdapter::Begin(GLenum mode) { _overallNormal = _normal; _overallColor = _color; // reset geometry _primitiveMode = mode; if (_vertices.valid()) _vertices->clear(); _normalAssigned = false; if (_normals.valid()) _normals->clear(); _colorAssigned = false; if (_colors.valid()) _colors->clear(); _texCoordAssignedList.clear(); _texCoordList.clear(); for(VertexArrayList::iterator itr = _texCoordsList.begin(); itr != _texCoordsList.end(); ++itr) { if (itr->valid()) (*itr)->clear(); } _vertexAttribAssignedList.clear(); _vertexAttribList.clear(); } void GLBeginEndAdapter::End() { if (!_vertices || _vertices->empty()) return; if (!_matrixStack.empty()) { const osg::Matrixd& matrix = _matrixStack.back(); if (_mode==APPLY_LOCAL_MATRICES_TO_VERTICES) { osg::Matrix inverse; inverse.invert(matrix); for(Vec3Array::iterator itr = _vertices->begin(); itr != _vertices->end(); ++itr) { *itr = *itr * matrix; } if (_normalAssigned && _normals.valid()) { for(Vec3Array::iterator itr = _normals->begin(); itr != _normals->end(); ++itr) { *itr = osg::Matrixd::transform3x3(inverse, *itr); (*itr).normalize(); } } else { _overallNormal = osg::Matrixd::transform3x3(inverse, _overallNormal); _overallNormal.normalize(); } } else { _state->applyModelViewMatrix(new RefMatrix(matrix)); } } _state->lazyDisablingOfVertexAttributes(); if (_colorAssigned) { _state->setColorPointer(_colors.get()); } else { _state->Color(_overallColor.r(), _overallColor.g(), _overallColor.b(), _overallColor.a()); } if (_normalAssigned) { _state->setNormalPointer(_normals.get()); } else { _state->Normal(_overallNormal.x(), _overallNormal.y(), _overallNormal.z()); } for(unsigned int unit=0; unit<_texCoordAssignedList.size(); ++unit) { if (_texCoordAssignedList[unit] && _texCoordsList[unit].valid()) { _state->setTexCoordPointer(unit, _texCoordsList[unit].get()); } } for(unsigned int unit=0; unit<_vertexAttribAssignedList.size(); ++unit) { if (_vertexAttribAssignedList[unit] && _vertexAttribsList[unit].valid()) { _state->setVertexAttribPointer(unit, _vertexAttribsList[unit].get(), false); } } _state->setVertexPointer(_vertices.get()); _state->applyDisablingOfVertexAttributes(); if (_primitiveMode==GL_QUADS) { _state->drawQuads(0, _vertices->size()); } else if (_primitiveMode==GL_QUAD_STRIP) { // will the winding be wrong? Do we need to swap it? glDrawArrays(GL_TRIANGLE_STRIP, 0, _vertices->size()); } else if (_primitiveMode==GL_POLYGON) glDrawArrays(GL_TRIANGLE_FAN, 0, _vertices->size()); else glDrawArrays(_primitiveMode, 0, _vertices->size()); } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osg/UserDataContainer> namespace osg { /////////////////////////////////////////////////////////////////////////////////////////////////// // // UserDataContainer // UserDataContainer::UserDataContainer(): Object(true) { } UserDataContainer::UserDataContainer(const UserDataContainer& udc, const osg::CopyOp& copyop): Object(udc, copyop) { } Object* UserDataContainer::getUserObject(const std::string& name, unsigned int startPos) { return getUserObject(getUserObjectIndex(name, startPos)); } const Object* UserDataContainer::getUserObject(const std::string& name, unsigned int startPos) const { return getUserObject(getUserObjectIndex(name, startPos)); } ////////////////////////////////////////////////////////////////////////////////////////////////// // // DefaultUserDataContainer // DefaultUserDataContainer::DefaultUserDataContainer() { } DefaultUserDataContainer::DefaultUserDataContainer(const DefaultUserDataContainer& udc, const osg::CopyOp& copyop): UserDataContainer(udc, copyop) { _userData = udc._userData; _descriptionList = udc._descriptionList; } void DefaultUserDataContainer::setThreadSafeRefUnref(bool threadSafe) { Object::setThreadSafeRefUnref(threadSafe); if (_userData.valid()) _userData->setThreadSafeRefUnref(threadSafe); for(ObjectList::iterator itr = _objectList.begin(); itr != _objectList.end(); ++itr) { (*itr)->setThreadSafeRefUnref(threadSafe); } } void DefaultUserDataContainer::setUserData(Referenced* obj) { _userData = obj; } Referenced* DefaultUserDataContainer::getUserData() { return _userData.get(); } const Referenced* DefaultUserDataContainer::getUserData() const { return _userData.get(); } unsigned int DefaultUserDataContainer::addUserObject(Object* obj) { // make sure that the object isn't already in the container unsigned int i = getUserObjectIndex(obj); if (i<_objectList.size()) { // object already in container so just return. return i; } unsigned int pos = _objectList.size(); // object not already on user data container so add it in. _objectList.push_back(obj); return pos; } void DefaultUserDataContainer::removeUserObject(unsigned int i) { if (i<_objectList.size()) { _objectList.erase(_objectList.begin()+i); } } void DefaultUserDataContainer::setUserObject(unsigned int i, Object* obj) { if (i<_objectList.size()) { _objectList[i] = obj; } } Object* DefaultUserDataContainer::getUserObject(unsigned int i) { if (i<_objectList.size()) { return _objectList[i].get(); } return 0; } const Object* DefaultUserDataContainer::getUserObject(unsigned int i) const { if (i<_objectList.size()) { return _objectList[i].get(); } return 0; } unsigned int DefaultUserDataContainer::getNumUserObjects() const { return _objectList.size(); } unsigned int DefaultUserDataContainer::getUserObjectIndex(const osg::Object* obj, unsigned int startPos) const { for(unsigned int i = startPos; i < _objectList.size(); ++i) { if (_objectList[i]==obj) return i; } return _objectList.size(); } unsigned int DefaultUserDataContainer::getUserObjectIndex(const std::string& name, unsigned int startPos) const { for(unsigned int i = startPos; i < _objectList.size(); ++i) { Object* obj = _objectList[i].get(); if (obj && obj->getName()==name) return i; } return _objectList.size(); } void DefaultUserDataContainer::setDescriptions(const DescriptionList& descriptions) { _descriptionList = descriptions; } UserDataContainer::DescriptionList& DefaultUserDataContainer::getDescriptions() { return _descriptionList; } const UserDataContainer::DescriptionList& DefaultUserDataContainer::getDescriptions() const { return _descriptionList; } unsigned int DefaultUserDataContainer::getNumDescriptions() const { return _descriptionList.size(); } void DefaultUserDataContainer::addDescription(const std::string& desc) { _descriptionList.push_back(desc); } } // end of namespace osg <commit_msg>From Rudolf Wiedemann, "the file attached fixes the incomplete implementation of "osg::DefaultUserDataContainer"'s copy constructor. Copying user objects was missing."<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osg/UserDataContainer> namespace osg { /////////////////////////////////////////////////////////////////////////////////////////////////// // // UserDataContainer // UserDataContainer::UserDataContainer(): Object(true) { } UserDataContainer::UserDataContainer(const UserDataContainer& udc, const osg::CopyOp& copyop): Object(udc, copyop) { } Object* UserDataContainer::getUserObject(const std::string& name, unsigned int startPos) { return getUserObject(getUserObjectIndex(name, startPos)); } const Object* UserDataContainer::getUserObject(const std::string& name, unsigned int startPos) const { return getUserObject(getUserObjectIndex(name, startPos)); } ////////////////////////////////////////////////////////////////////////////////////////////////// // // DefaultUserDataContainer // DefaultUserDataContainer::DefaultUserDataContainer() { } DefaultUserDataContainer::DefaultUserDataContainer(const DefaultUserDataContainer& udc, const osg::CopyOp& copyop): UserDataContainer(udc, copyop) { _userData = udc._userData; _descriptionList = udc._descriptionList; for(ObjectList::const_iterator itr = udc._objectList.begin(); itr != udc._objectList.end(); ++itr) { _objectList.push_back(copyop(*itr)); } } void DefaultUserDataContainer::setThreadSafeRefUnref(bool threadSafe) { Object::setThreadSafeRefUnref(threadSafe); if (_userData.valid()) _userData->setThreadSafeRefUnref(threadSafe); for(ObjectList::iterator itr = _objectList.begin(); itr != _objectList.end(); ++itr) { (*itr)->setThreadSafeRefUnref(threadSafe); } } void DefaultUserDataContainer::setUserData(Referenced* obj) { _userData = obj; } Referenced* DefaultUserDataContainer::getUserData() { return _userData.get(); } const Referenced* DefaultUserDataContainer::getUserData() const { return _userData.get(); } unsigned int DefaultUserDataContainer::addUserObject(Object* obj) { // make sure that the object isn't already in the container unsigned int i = getUserObjectIndex(obj); if (i<_objectList.size()) { // object already in container so just return. return i; } unsigned int pos = _objectList.size(); // object not already on user data container so add it in. _objectList.push_back(obj); return pos; } void DefaultUserDataContainer::removeUserObject(unsigned int i) { if (i<_objectList.size()) { _objectList.erase(_objectList.begin()+i); } } void DefaultUserDataContainer::setUserObject(unsigned int i, Object* obj) { if (i<_objectList.size()) { _objectList[i] = obj; } } Object* DefaultUserDataContainer::getUserObject(unsigned int i) { if (i<_objectList.size()) { return _objectList[i].get(); } return 0; } const Object* DefaultUserDataContainer::getUserObject(unsigned int i) const { if (i<_objectList.size()) { return _objectList[i].get(); } return 0; } unsigned int DefaultUserDataContainer::getNumUserObjects() const { return _objectList.size(); } unsigned int DefaultUserDataContainer::getUserObjectIndex(const osg::Object* obj, unsigned int startPos) const { for(unsigned int i = startPos; i < _objectList.size(); ++i) { if (_objectList[i]==obj) return i; } return _objectList.size(); } unsigned int DefaultUserDataContainer::getUserObjectIndex(const std::string& name, unsigned int startPos) const { for(unsigned int i = startPos; i < _objectList.size(); ++i) { Object* obj = _objectList[i].get(); if (obj && obj->getName()==name) return i; } return _objectList.size(); } void DefaultUserDataContainer::setDescriptions(const DescriptionList& descriptions) { _descriptionList = descriptions; } UserDataContainer::DescriptionList& DefaultUserDataContainer::getDescriptions() { return _descriptionList; } const UserDataContainer::DescriptionList& DefaultUserDataContainer::getDescriptions() const { return _descriptionList; } unsigned int DefaultUserDataContainer::getNumDescriptions() const { return _descriptionList.size(); } void DefaultUserDataContainer::addDescription(const std::string& desc) { _descriptionList.push_back(desc); } } // end of namespace osg <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osgGA/GUIEventAdapter> using namespace osgGA; GUIEventAdapter::GUIEventAdapter(): _eventType(NONE), _time(0.0), _key(0), _button(0), _Xmin(0.0), _Xmax(1.0), _Ymin(0.0), _Ymax(1.0), _mx(0.5), _my(0.5), _pressure(0.0), _buttonMask(0), _modKeyMask(0), _scrollingMotion(SCROLL_NONE), _scrollingDeltaX(0), _scrollingDeltaY(0), _mouseYOrientation(Y_INCREASING_DOWNWARDS), _tabletPointerType(UNKNOWN) {} GUIEventAdapter::GUIEventAdapter(const GUIEventAdapter& rhs): Referenced(), _eventType(rhs._eventType), _time(rhs._time), _key(rhs._key), _button(rhs._button), _Xmin(rhs._Xmin), _Xmax(rhs._Xmax), _Ymin(rhs._Ymin), _Ymax(rhs._Ymax), _mx(rhs._mx), _my(rhs._my), _pressure(rhs._pressure), _buttonMask(rhs._buttonMask), _modKeyMask(rhs._modKeyMask), _scrollingMotion(rhs._scrollingMotion), _scrollingDeltaX(rhs._scrollingDeltaX), _scrollingDeltaY(rhs._scrollingDeltaY), _mouseYOrientation(rhs._mouseYOrientation), _tabletPointerType(rhs._tabletPointerType) {} GUIEventAdapter::~GUIEventAdapter() { } void GUIEventAdapter::setWindowSize(float Xmin, float Ymin, float Xmax, float Ymax) { _Xmin = Xmin; _Ymin = Ymin; _Xmax = Xmax; _Ymax = Ymax; } <commit_msg>Added osg:: to Referenced() to fix IRIX build.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osgGA/GUIEventAdapter> using namespace osgGA; GUIEventAdapter::GUIEventAdapter(): _eventType(NONE), _time(0.0), _key(0), _button(0), _Xmin(0.0), _Xmax(1.0), _Ymin(0.0), _Ymax(1.0), _mx(0.5), _my(0.5), _pressure(0.0), _buttonMask(0), _modKeyMask(0), _scrollingMotion(SCROLL_NONE), _scrollingDeltaX(0), _scrollingDeltaY(0), _mouseYOrientation(Y_INCREASING_DOWNWARDS), _tabletPointerType(UNKNOWN) {} GUIEventAdapter::GUIEventAdapter(const GUIEventAdapter& rhs): osg::Referenced(), _eventType(rhs._eventType), _time(rhs._time), _key(rhs._key), _button(rhs._button), _Xmin(rhs._Xmin), _Xmax(rhs._Xmax), _Ymin(rhs._Ymin), _Ymax(rhs._Ymax), _mx(rhs._mx), _my(rhs._my), _pressure(rhs._pressure), _buttonMask(rhs._buttonMask), _modKeyMask(rhs._modKeyMask), _scrollingMotion(rhs._scrollingMotion), _scrollingDeltaX(rhs._scrollingDeltaX), _scrollingDeltaY(rhs._scrollingDeltaY), _mouseYOrientation(rhs._mouseYOrientation), _tabletPointerType(rhs._tabletPointerType) {} GUIEventAdapter::~GUIEventAdapter() { } void GUIEventAdapter::setWindowSize(float Xmin, float Ymin, float Xmax, float Ymax) { _Xmin = Xmin; _Ymin = Ymin; _Xmax = Xmax; _Ymax = Ymax; } <|endoftext|>
<commit_before>// Copyright 2012-2013 Samplecount S.L. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef METHCLA_MEMORY_HPP_INCLUDED #define METHCLA_MEMORY_HPP_INCLUDED #include "Methcla/Utility/Macros.h" #include <algorithm> #include <cassert> #include <cstddef> #include <cstdint> #if !defined(METHCLA_USE_BOOST_SHARED_PTR) # if defined(__native_client__) # define METHCLA_USE_BOOST_SHARED_PTR 1 # else # define METHCLA_USE_BOOST_SHARED_PTR 0 # endif #endif #if METHCLA_USE_BOOST_SHARED_PTR METHCLA_WITHOUT_WARNINGS_BEGIN # include <boost/shared_ptr.hpp> # include <boost/make_shared.hpp> METHCLA_WITHOUT_WARNINGS_END #else # include <memory> #endif namespace Methcla { namespace Memory { class Alignment { public: Alignment(size_t alignment) : m_alignment(std::max(alignment, sizeof(void*))) { assert( (m_alignment & (m_alignment - 1)) == 0 /* Alignment must be a power of two */ ); } Alignment(const Alignment&) = default; operator size_t () const { return m_alignment; } template <typename T> bool isAligned(T size) const { return isAligned(m_alignment, size); } template <typename T> T align(T size) const { return align(m_alignment, size); } template <typename T> size_t padding(T size) const { return padding(m_alignment, size); } // Aligning pointers template <typename T> bool isAligned(T* ptr) const { return isAligned(reinterpret_cast<uintptr_t>(ptr)); } template <typename T> T* align(T* ptr) const { return reinterpret_cast<T*>(align(reinterpret_cast<uintptr_t>(ptr))); } template <typename T> size_t padding(T* ptr) const { return padding(reinterpret_cast<uintptr_t>(ptr)); } // Static alignment functions template <typename T> static bool isAligned(size_t alignment, T n) { return (n & ~(alignment-1)) == n; } template <typename T> static T align(size_t alignment, T n) { return (n + alignment) & ~(alignment-1); } template <typename T> static size_t padding(size_t alignment, T n) { return align(alignment, n) - n; } private: size_t m_alignment; }; //* Alignment needed for data accessed by SIMD instructions. static const Alignment kSIMDAlignment(16); //* Allocate memory of `size` bytes. // // @throw std::invalid_argument // @throw std::bad_alloc void* alloc(size_t size); //* Allocate aligned memory of `size` bytes. // // @throw std::invalid_argument // @throw std::bad_alloc void* allocAligned(Alignment align, size_t size); //* Free memory allocated by this allocator. void free(void* ptr) noexcept; //* Allocate memory for `n` elements of type `T`. // // @throw std::invalid_argument // @throw std::bad_alloc template <typename T> T* allocOf(size_t n=1) { return static_cast<T*>(alloc(n * sizeof(T))); } //* Allocate aligned memory for `n` elements of type `T`. // // @throw std::invalid_argument // @throw std::bad_alloc template <typename T> T* allocAlignedOf(Alignment align, size_t n=1) { return static_cast<T*>(allocAligned(align, n * sizeof(T))); } #if METHCLA_USE_BOOST_SHARED_PTR using boost::shared_ptr; using boost::make_shared; using boost::allocate_shared; #else using std::shared_ptr; using std::make_shared; using std::allocate_shared; #endif } } #endif // METHCLA_MEMORY_HPP_INCLUDED <commit_msg>Throw std::invalid_argument instead of using assert<commit_after>// Copyright 2012-2013 Samplecount S.L. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef METHCLA_MEMORY_HPP_INCLUDED #define METHCLA_MEMORY_HPP_INCLUDED #include "Methcla/Utility/Macros.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <stdexcept> #if !defined(METHCLA_USE_BOOST_SHARED_PTR) # if defined(__native_client__) # define METHCLA_USE_BOOST_SHARED_PTR 1 # else # define METHCLA_USE_BOOST_SHARED_PTR 0 # endif #endif #if METHCLA_USE_BOOST_SHARED_PTR METHCLA_WITHOUT_WARNINGS_BEGIN # include <boost/shared_ptr.hpp> # include <boost/make_shared.hpp> METHCLA_WITHOUT_WARNINGS_END #else # include <memory> #endif namespace Methcla { namespace Memory { class Alignment { public: Alignment(size_t alignment) : m_alignment(std::max(alignment, sizeof(void*))) { if ((m_alignment & (m_alignment - 1)) != 0) // Alignment must be a power of two throw std::invalid_argument("Alignment must be a power of two"); } Alignment(const Alignment&) = default; operator size_t () const { return m_alignment; } template <typename T> bool isAligned(T size) const { return isAligned(m_alignment, size); } template <typename T> T align(T size) const { return align(m_alignment, size); } template <typename T> size_t padding(T size) const { return padding(m_alignment, size); } // Aligning pointers template <typename T> bool isAligned(T* ptr) const { return isAligned(reinterpret_cast<uintptr_t>(ptr)); } template <typename T> T* align(T* ptr) const { return reinterpret_cast<T*>(align(reinterpret_cast<uintptr_t>(ptr))); } template <typename T> size_t padding(T* ptr) const { return padding(reinterpret_cast<uintptr_t>(ptr)); } // Static alignment functions template <typename T> static bool isAligned(size_t alignment, T n) { return (n & ~(alignment-1)) == n; } template <typename T> static T align(size_t alignment, T n) { return (n + alignment) & ~(alignment-1); } template <typename T> static size_t padding(size_t alignment, T n) { return align(alignment, n) - n; } private: size_t m_alignment; }; //* Alignment needed for data accessed by SIMD instructions. static const Alignment kSIMDAlignment(16); //* Allocate memory of `size` bytes. // // @throw std::invalid_argument // @throw std::bad_alloc void* alloc(size_t size); //* Allocate aligned memory of `size` bytes. // // @throw std::invalid_argument // @throw std::bad_alloc void* allocAligned(Alignment align, size_t size); //* Free memory allocated by this allocator. void free(void* ptr) noexcept; //* Allocate memory for `n` elements of type `T`. // // @throw std::invalid_argument // @throw std::bad_alloc template <typename T> T* allocOf(size_t n=1) { return static_cast<T*>(alloc(n * sizeof(T))); } //* Allocate aligned memory for `n` elements of type `T`. // // @throw std::invalid_argument // @throw std::bad_alloc template <typename T> T* allocAlignedOf(Alignment align, size_t n=1) { return static_cast<T*>(allocAligned(align, n * sizeof(T))); } #if METHCLA_USE_BOOST_SHARED_PTR using boost::shared_ptr; using boost::make_shared; using boost::allocate_shared; #else using std::shared_ptr; using std::make_shared; using std::allocate_shared; #endif } } #endif // METHCLA_MEMORY_HPP_INCLUDED <|endoftext|>
<commit_before> #include "ComputeProcessor.h" #include <cassert> #include <string> #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> std::string GetExecutableFullPath() { char buffer[512]; GetModuleFileName(NULL, buffer, sizeof(buffer) - 1); return buffer; } #endif // List of all registered transform descriptions static std::vector<TransformDescBase*> g_TransformDescs; Arguments::Arguments(int argc, const char* argv[]) { // Copy from the command-line into local storage m_Arguments.resize(argc); for (size_t i = 0; i < m_Arguments.size(); i++) m_Arguments[i] = argv[i]; // Override first argument with complete path to executable m_Arguments[0] = GetExecutableFullPath(); } size_t Arguments::GetIndexOf(const std::string& arg, int occurrence) const { // Linear search for a matching argument int found = 0; for (size_t i = 0; i < m_Arguments.size(); i++) { if (m_Arguments[i] == arg) { if (found++ == occurrence) return i; } } return -1; } bool Arguments::Have(const std::string& arg) const { // Does the specific argument exist? return GetIndexOf(arg) != -1; } std::string Arguments::GetProperty(const std::string& arg, int occurrence) const { // Does the arg exist and does it have a value size_t index = GetIndexOf(arg, occurrence); if (index == -1 || index + 1 >= m_Arguments.size()) return ""; return m_Arguments[index + 1]; } size_t Arguments::Count() const { return m_Arguments.size(); } const std::string& Arguments::operator [] (int index) const { return m_Arguments[index]; } TokenList::TokenList() : first(0) , last(0) , error(cmpError_CreateOK()) { } TokenList::TokenList(cmpToken* first_token, cmpToken* last_token) : first(first_token) , last(last_token) , error(cmpError_CreateOK()) { } cmpToken* TokenList::Add(cmpToken *token) { cmpToken_AddToList(&first, &last, token); return token; } cmpToken* TokenList::Add(enum cmpTokenType type, const char* start, cmpU32 length, cmpU32 line) { cmpToken* token; error = cmpToken_Create(&token, type, start, length, line); if (!cmpError_OK(&error)) throw error; return Add(token); } cmpToken* TokenList::Add(enum cmpTokenType type, cmpU32 line) { // Ensure this is a single character token assert(type != cmpToken_None); assert(type < cmpToken_InvalidSeparator); // Construnct a single character string out of its character code const char* text; switch (type) { case cmpToken_LBrace: text = "{"; break; case cmpToken_RBrace: text = "}"; break; case cmpToken_Comma: text = ","; break; case cmpToken_LBracket: text = "("; break; case cmpToken_RBracket: text = ")"; break; case cmpToken_LSqBracket: text = "["; break; case cmpToken_RSqBracket: text = "]"; break; case cmpToken_Colon: text = ":"; break; case cmpToken_SemiColon: text = ";"; break; case cmpToken_Period: text = "."; break; case cmpToken_Question: text = "?"; break; case cmpToken_Tilde: text = "~"; break; case cmpToken_LAngle: text = "<"; break; case cmpToken_RAngle: text = ">"; break; case cmpToken_Plus: text = "+"; break; case cmpToken_Minus: text = "-"; break; case cmpToken_Asterisk: text = "*"; break; case cmpToken_Divide: text = "/"; break; case cmpToken_Modulo: text = "%%"; break; case cmpToken_Equals: text = "="; break; case cmpToken_And: text = "&"; break; case cmpToken_Or: text = "|"; break; case cmpToken_Xor: text = "^"; break; case cmpToken_Not: text = "!"; break; case cmpToken_Hash: text = "#"; break; default: assert(false); } return Add(type, text, 1, line); } cmpToken* TokenList::Add(const HashString& string, cmpU32 line) { // Create a symbol token using globally persistent HashString text cmpToken* token = Add(cmpToken_Symbol, string.text, string.length, line); token->hash = string.hash; return token; } cmpToken* TokenList::Add(const String& string, cmpU32 line) { cmpToken* token = Add(cmpToken_String, string.text, string.length, line); token->hash = cmpHash(string.text, string.length); return token; } void TokenList::DeleteAll() { // Move one beyond last for while comparison delete to be inclusive if (last != 0) last = last->next; while (first != last) { cmpToken* next = first->next; cmpToken_Destroy(first); first = next; } first = 0; last = 0; } ComputeProcessor::ComputeProcessor(const ::Arguments& arguments) : m_Arguments(arguments) , m_InputFilename(arguments[1]) , m_MemoryFile(0) , m_LexerCursor(0) , m_ParserCursor(0) , m_RootNode(0) { // Parse the executable path looking for its directory m_ExecutableDirectory = m_Arguments[0]; size_t sep = m_ExecutableDirectory.rfind('\\'); if (sep == -1) sep = m_ExecutableDirectory.rfind('/'); if (sep != -1) m_ExecutableDirectory = m_ExecutableDirectory.substr(0, sep); } ComputeProcessor::~ComputeProcessor() { // Destroy all transforms, assuming transform description list and allocate transforms lists are in sync for (size_t i = 0; i < m_Transforms.size(); i++) { const TransformDescBase* desc = g_TransformDescs[i]; assert(desc != 0); assert(desc->delete_func != 0); desc->delete_func(m_Transforms[i]); } // Destroy all tokens m_Tokens.DeleteAll(); // Destroy all nodes if (m_RootNode != 0) cmpNode_Destroy(m_RootNode); // Destroy all parser objects if (m_ParserCursor != 0) cmpParserCursor_Destroy(m_ParserCursor); if (m_LexerCursor != 0) cmpLexerCursor_Destroy(m_LexerCursor); if (m_MemoryFile != 0) cmpMemoryFile_Destroy(m_MemoryFile); } bool ComputeProcessor::ParseFile() { const char* filename = m_InputFilename.c_str(); bool verbose = m_Arguments.Have("-verbose"); // Open the input file if (cmpError error = cmpMemoryFile_Create(&m_MemoryFile, filename)) { printf("Error opening input file: %s\n\n", cmpError_Text(&error)); return false; } // Build a list of tokens if (cmpError error = cmpLexerCursor_Create(&m_LexerCursor, cmpMemoryFile_Data(m_MemoryFile), cmpMemoryFile_Size(m_MemoryFile), verbose)) { printf("Error creating lexer cursor: %s\n\n", cmpError_Text(&error)); return false; } while (cmpToken* token = cmpLexer_ConsumeToken(m_LexerCursor)) { m_Tokens.Add(token); if (verbose) printf("[0x%2x] %s %d\n", token->type, cmpTokenType_Name(token->type), token->length); } // Print any lexer errors if (cmpError error = cmpLexerCursor_Error(m_LexerCursor)) { printf("%s(%d): %s\n", filename, cmpLexerCursor_Line(m_LexerCursor), cmpError_Text(&error)); return false; } cmpError error = cmpNode_CreateEmpty(&m_RootNode); if (!cmpError_OK(&error)) { printf("Error: %s\n", error.text); return false; } // Build a list of parser nodes if (cmpError error = cmpParserCursor_Create(&m_ParserCursor, m_Tokens.first, verbose)) { printf("Error creating parser cursor: %s\n\n", cmpError_Text(&error)); return false; } while (cmpNode* node = cmpParser_ConsumeNode(m_ParserCursor)) cmpNode_AddChild(m_RootNode, node); if (verbose) cmpParser_LogNodes(m_RootNode, 0); // Print any parser errors if (cmpError error = cmpParserCursor_Error(m_ParserCursor)) { printf("%s(%d): %s\n",filename, cmpParserCursor_Line(m_ParserCursor), cmpError_Text(&error)); return false; } return true; } namespace { bool VisitNode(const ComputeProcessor& processor, cmpNode* node, INodeVisitor* visitor) { assert(visitor != 0); assert(node != 0); if (!visitor->Visit(processor, *node)) return false; for (cmpNode* child = node->first_child; child != 0; child = child->next_sibling) { if (!VisitNode(processor, child, visitor)) return false; } return true; } } bool ComputeProcessor::VisitNodes(INodeVisitor* visitor) { assert(visitor != 0); return VisitNode(*this, m_RootNode, visitor); } cmpError ComputeProcessor::ApplyTransforms() { if (m_Transforms.empty()) { // Create all transforms for the processor the first time this function is called for (size_t i = 0; i < g_TransformDescs.size(); i++) { const TransformDescBase* desc = g_TransformDescs[i]; assert(desc != 0); assert(desc->new_func != 0); ITransform* transform = desc->new_func(); assert(transform != 0); m_Transforms.push_back(transform); } } // Apply all transforms in the (indeterminate) order they are registered for (size_t i = 0; i < m_Transforms.size(); i++) { ITransform* transform = m_Transforms[i]; assert(transform != 0); cmpError error = transform->Apply(*this); if (!cmpError_OK(&error)) return error; } return cmpError_CreateOK(); } TokenIterator::TokenIterator(cmpNode& node) : first_token(node.first_token) , last_token(node.last_token ? node.last_token->next : 0) , token(first_token) { } cmpToken* TokenIterator::SkipWhitespace() { // Skip all whitespace/EOL tokens while ( token != last_token && (token->type == cmpToken_Whitespace || token->type == cmpToken_EOL)) token = token->next; // Return NULL if skipped over all tokens return token == last_token ? token : 0; } TokenIterator::operator bool () const { return token != last_token; } TokenIterator& TokenIterator::operator ++ () { if (token != last_token) token = token->next; else token = 0; return *this; } String::String() : text(0) , length(0) { } String::String(const char *source, size_t src_length) : text(0) , length(0) { Set(source, src_length); } String::String(const std::string& source) : text(0) , length(0) { Set(source.c_str(), source.length()); } String::String(const String& rhs) : text(rhs.text) , length(rhs.length) { // Take ownership rhs.text = 0; } String::~String() { if (text != 0) delete [] text; } void String::Set(const char *source, size_t src_length) { // Copy and null terminate assert(text == 0); length = src_length; text = new char[length + 1]; memcpy(text, source, length); text[length] = 0; } String& String::operator = (const String& rhs) { // Take ownership assert(text == 0); text = rhs.text; length = rhs.length; rhs.text = 0; return *this; } TransformDescBase::TransformDescBase(NewFunc new_func, DeleteFunc delete_func) : new_func(new_func) , delete_func(delete_func) { // Register transform description g_TransformDescs.push_back(this); } <commit_msg>ComputeBridge: Add cmpToken_Whitespace and cmpToken_EOL as single character emitters for TokenList.<commit_after> #include "ComputeProcessor.h" #include <cassert> #include <string> #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> std::string GetExecutableFullPath() { char buffer[512]; GetModuleFileName(NULL, buffer, sizeof(buffer) - 1); return buffer; } #endif // List of all registered transform descriptions static std::vector<TransformDescBase*> g_TransformDescs; Arguments::Arguments(int argc, const char* argv[]) { // Copy from the command-line into local storage m_Arguments.resize(argc); for (size_t i = 0; i < m_Arguments.size(); i++) m_Arguments[i] = argv[i]; // Override first argument with complete path to executable m_Arguments[0] = GetExecutableFullPath(); } size_t Arguments::GetIndexOf(const std::string& arg, int occurrence) const { // Linear search for a matching argument int found = 0; for (size_t i = 0; i < m_Arguments.size(); i++) { if (m_Arguments[i] == arg) { if (found++ == occurrence) return i; } } return -1; } bool Arguments::Have(const std::string& arg) const { // Does the specific argument exist? return GetIndexOf(arg) != -1; } std::string Arguments::GetProperty(const std::string& arg, int occurrence) const { // Does the arg exist and does it have a value size_t index = GetIndexOf(arg, occurrence); if (index == -1 || index + 1 >= m_Arguments.size()) return ""; return m_Arguments[index + 1]; } size_t Arguments::Count() const { return m_Arguments.size(); } const std::string& Arguments::operator [] (int index) const { return m_Arguments[index]; } TokenList::TokenList() : first(0) , last(0) , error(cmpError_CreateOK()) { } TokenList::TokenList(cmpToken* first_token, cmpToken* last_token) : first(first_token) , last(last_token) , error(cmpError_CreateOK()) { } cmpToken* TokenList::Add(cmpToken *token) { cmpToken_AddToList(&first, &last, token); return token; } cmpToken* TokenList::Add(enum cmpTokenType type, const char* start, cmpU32 length, cmpU32 line) { cmpToken* token; error = cmpToken_Create(&token, type, start, length, line); if (!cmpError_OK(&error)) throw error; return Add(token); } cmpToken* TokenList::Add(enum cmpTokenType type, cmpU32 line) { // Ensure this is a single character token assert(type != cmpToken_None); assert(type == cmpToken_Whitespace || type == cmpToken_EOL || type < cmpToken_InvalidSeparator); // Construnct a single character string out of its character code const char* text; switch (type) { case cmpToken_LBrace: text = "{"; break; case cmpToken_RBrace: text = "}"; break; case cmpToken_Comma: text = ","; break; case cmpToken_LBracket: text = "("; break; case cmpToken_RBracket: text = ")"; break; case cmpToken_LSqBracket: text = "["; break; case cmpToken_RSqBracket: text = "]"; break; case cmpToken_Colon: text = ":"; break; case cmpToken_SemiColon: text = ";"; break; case cmpToken_Period: text = "."; break; case cmpToken_Question: text = "?"; break; case cmpToken_Tilde: text = "~"; break; case cmpToken_LAngle: text = "<"; break; case cmpToken_RAngle: text = ">"; break; case cmpToken_Plus: text = "+"; break; case cmpToken_Minus: text = "-"; break; case cmpToken_Asterisk: text = "*"; break; case cmpToken_Divide: text = "/"; break; case cmpToken_Modulo: text = "%%"; break; case cmpToken_Equals: text = "="; break; case cmpToken_And: text = "&"; break; case cmpToken_Or: text = "|"; break; case cmpToken_Xor: text = "^"; break; case cmpToken_Not: text = "!"; break; case cmpToken_Hash: text = "#"; break; // Single character tokens for writing to file but not necessarily as input case cmpToken_Whitespace: text = " "; break; case cmpToken_EOL: text = "\n"; break; default: assert(false); } return Add(type, text, 1, line); } cmpToken* TokenList::Add(const HashString& string, cmpU32 line) { // Create a symbol token using globally persistent HashString text cmpToken* token = Add(cmpToken_Symbol, string.text, string.length, line); token->hash = string.hash; return token; } cmpToken* TokenList::Add(const String& string, cmpU32 line) { cmpToken* token = Add(cmpToken_String, string.text, string.length, line); token->hash = cmpHash(string.text, string.length); return token; } void TokenList::DeleteAll() { // Move one beyond last for while comparison delete to be inclusive if (last != 0) last = last->next; while (first != last) { cmpToken* next = first->next; cmpToken_Destroy(first); first = next; } first = 0; last = 0; } ComputeProcessor::ComputeProcessor(const ::Arguments& arguments) : m_Arguments(arguments) , m_InputFilename(arguments[1]) , m_MemoryFile(0) , m_LexerCursor(0) , m_ParserCursor(0) , m_RootNode(0) { // Parse the executable path looking for its directory m_ExecutableDirectory = m_Arguments[0]; size_t sep = m_ExecutableDirectory.rfind('\\'); if (sep == -1) sep = m_ExecutableDirectory.rfind('/'); if (sep != -1) m_ExecutableDirectory = m_ExecutableDirectory.substr(0, sep); } ComputeProcessor::~ComputeProcessor() { // Destroy all transforms, assuming transform description list and allocate transforms lists are in sync for (size_t i = 0; i < m_Transforms.size(); i++) { const TransformDescBase* desc = g_TransformDescs[i]; assert(desc != 0); assert(desc->delete_func != 0); desc->delete_func(m_Transforms[i]); } // Destroy all tokens m_Tokens.DeleteAll(); // Destroy all nodes if (m_RootNode != 0) cmpNode_Destroy(m_RootNode); // Destroy all parser objects if (m_ParserCursor != 0) cmpParserCursor_Destroy(m_ParserCursor); if (m_LexerCursor != 0) cmpLexerCursor_Destroy(m_LexerCursor); if (m_MemoryFile != 0) cmpMemoryFile_Destroy(m_MemoryFile); } bool ComputeProcessor::ParseFile() { const char* filename = m_InputFilename.c_str(); bool verbose = m_Arguments.Have("-verbose"); // Open the input file if (cmpError error = cmpMemoryFile_Create(&m_MemoryFile, filename)) { printf("Error opening input file: %s\n\n", cmpError_Text(&error)); return false; } // Build a list of tokens if (cmpError error = cmpLexerCursor_Create(&m_LexerCursor, cmpMemoryFile_Data(m_MemoryFile), cmpMemoryFile_Size(m_MemoryFile), verbose)) { printf("Error creating lexer cursor: %s\n\n", cmpError_Text(&error)); return false; } while (cmpToken* token = cmpLexer_ConsumeToken(m_LexerCursor)) { m_Tokens.Add(token); if (verbose) printf("[0x%2x] %s %d\n", token->type, cmpTokenType_Name(token->type), token->length); } // Print any lexer errors if (cmpError error = cmpLexerCursor_Error(m_LexerCursor)) { printf("%s(%d): %s\n", filename, cmpLexerCursor_Line(m_LexerCursor), cmpError_Text(&error)); return false; } cmpError error = cmpNode_CreateEmpty(&m_RootNode); if (!cmpError_OK(&error)) { printf("Error: %s\n", error.text); return false; } // Build a list of parser nodes if (cmpError error = cmpParserCursor_Create(&m_ParserCursor, m_Tokens.first, verbose)) { printf("Error creating parser cursor: %s\n\n", cmpError_Text(&error)); return false; } while (cmpNode* node = cmpParser_ConsumeNode(m_ParserCursor)) cmpNode_AddChild(m_RootNode, node); if (verbose) cmpParser_LogNodes(m_RootNode, 0); // Print any parser errors if (cmpError error = cmpParserCursor_Error(m_ParserCursor)) { printf("%s(%d): %s\n",filename, cmpParserCursor_Line(m_ParserCursor), cmpError_Text(&error)); return false; } return true; } namespace { bool VisitNode(const ComputeProcessor& processor, cmpNode* node, INodeVisitor* visitor) { assert(visitor != 0); assert(node != 0); if (!visitor->Visit(processor, *node)) return false; for (cmpNode* child = node->first_child; child != 0; child = child->next_sibling) { if (!VisitNode(processor, child, visitor)) return false; } return true; } } bool ComputeProcessor::VisitNodes(INodeVisitor* visitor) { assert(visitor != 0); return VisitNode(*this, m_RootNode, visitor); } cmpError ComputeProcessor::ApplyTransforms() { if (m_Transforms.empty()) { // Create all transforms for the processor the first time this function is called for (size_t i = 0; i < g_TransformDescs.size(); i++) { const TransformDescBase* desc = g_TransformDescs[i]; assert(desc != 0); assert(desc->new_func != 0); ITransform* transform = desc->new_func(); assert(transform != 0); m_Transforms.push_back(transform); } } // Apply all transforms in the (indeterminate) order they are registered for (size_t i = 0; i < m_Transforms.size(); i++) { ITransform* transform = m_Transforms[i]; assert(transform != 0); cmpError error = transform->Apply(*this); if (!cmpError_OK(&error)) return error; } return cmpError_CreateOK(); } TokenIterator::TokenIterator(cmpNode& node) : first_token(node.first_token) , last_token(node.last_token ? node.last_token->next : 0) , token(first_token) { } cmpToken* TokenIterator::SkipWhitespace() { // Skip all whitespace/EOL tokens while ( token != last_token && (token->type == cmpToken_Whitespace || token->type == cmpToken_EOL)) token = token->next; // Return NULL if skipped over all tokens return token == last_token ? token : 0; } TokenIterator::operator bool () const { return token != last_token; } TokenIterator& TokenIterator::operator ++ () { if (token != last_token) token = token->next; else token = 0; return *this; } String::String() : text(0) , length(0) { } String::String(const char *source, size_t src_length) : text(0) , length(0) { Set(source, src_length); } String::String(const std::string& source) : text(0) , length(0) { Set(source.c_str(), source.length()); } String::String(const String& rhs) : text(rhs.text) , length(rhs.length) { // Take ownership rhs.text = 0; } String::~String() { if (text != 0) delete [] text; } void String::Set(const char *source, size_t src_length) { // Copy and null terminate assert(text == 0); length = src_length; text = new char[length + 1]; memcpy(text, source, length); text[length] = 0; } String& String::operator = (const String& rhs) { // Take ownership assert(text == 0); text = rhs.text; length = rhs.length; rhs.text = 0; return *this; } TransformDescBase::TransformDescBase(NewFunc new_func, DeleteFunc delete_func) : new_func(new_func) , delete_func(delete_func) { // Register transform description g_TransformDescs.push_back(this); } <|endoftext|>
<commit_before>#include "is_valid_char.hxx" #include "../../Positive_Matrix_With_Prefactor_State.hxx" #include <algorithm> #include <iterator> #include <string> using namespace std::literals; inline void check_iterator(const char character, const std::vector<char>::const_iterator &begin, const std::vector<char>::const_iterator &iterator, const std::vector<char>::const_iterator &end) { if(iterator == end) { throw std::runtime_error("Invalid polynomial string after '"s + character + "': " + std::string(begin,end)); } } std::vector<char>::const_iterator parse_polynomial(const std::vector<char>::const_iterator &begin, const std::vector<char>::const_iterator &end, Polynomial &polynomial) { const std::vector<char> delimiters({',', '}'}); const auto delimiter( std::find_first_of(begin, end, delimiters.begin(), delimiters.end())); if(delimiter == end) { throw std::runtime_error("Missing '}' at end of array of polynomials"); } std::string mantissa; for(auto c(begin); c < delimiter; ++c) { if(*c == '`') { do { ++c; } while(c != delimiter && (std::isdigit(*c) || *c == '.' || !is_valid_char(*c) || *c == '`')); } if(*c == '*') { do { ++c; check_iterator('*',begin, c, delimiter); } while(!is_valid_char(*c)); std::string exponent; if(*c == '^') { exponent = "E"; ++c; check_iterator('^', begin, c, delimiter); while(c!=delimiter && (exponent.size() == 1 && (*c == '-' || *c == '+')) || std::isdigit(*c) || !is_valid_char(*c)) { if(is_valid_char(*c)) { exponent.push_back(*c); } ++c; } while(c != delimiter && (!is_valid_char(*c) || *c == '*')) { ++c; } } size_t degree(0); // Hard code the polynomial to be in 'x' since that is what // SDPB.m uses. if(*c == 'x') { ++c; while(!is_valid_char(*c)) { ++c; check_iterator('x', begin, c, delimiter); } if(*c != '^') { degree = 1; } else { ++c; std::string degree_string; while((degree_string.empty() && (*c == '-' || *c == '+')) || std::isdigit(*c) || !is_valid_char(*c)) { if(is_valid_char(*c) && *c != '+') { degree_string.push_back(*c); } ++c; } degree = std::stoull(degree_string); } } if(polynomial.coefficients.size() < degree + 1) { polynomial.coefficients.resize(degree + 1); } polynomial.coefficients.at(degree) = El::BigFloat(mantissa + exponent); mantissa.clear(); } else if(!mantissa.empty() && (*c == '-' || *c == '+' || c == delimiter)) { if(polynomial.coefficients.size() < 1) { polynomial.coefficients.resize(1); } polynomial.coefficients.at(0) = El::BigFloat(mantissa); mantissa.clear(); } if(is_valid_char(*c) && *c != '+') { mantissa.push_back(*c); } } return delimiter; } <commit_msg>Fix logic when parsing exponents<commit_after>#include "is_valid_char.hxx" #include "../../Positive_Matrix_With_Prefactor_State.hxx" #include <algorithm> #include <iterator> #include <string> using namespace std::literals; inline void check_iterator(const char character, const std::vector<char>::const_iterator &begin, const std::vector<char>::const_iterator &iterator, const std::vector<char>::const_iterator &end) { if(iterator == end) { throw std::runtime_error("Invalid polynomial string after '"s + character + "': " + std::string(begin,end)); } } std::vector<char>::const_iterator parse_polynomial(const std::vector<char>::const_iterator &begin, const std::vector<char>::const_iterator &end, Polynomial &polynomial) { const std::vector<char> delimiters({',', '}'}); const auto delimiter( std::find_first_of(begin, end, delimiters.begin(), delimiters.end())); if(delimiter == end) { throw std::runtime_error("Missing '}' at end of array of polynomials"); } std::string mantissa; for(auto c(begin); c < delimiter; ++c) { if(*c == '`') { do { ++c; } while(c != delimiter && (std::isdigit(*c) || *c == '.' || !is_valid_char(*c) || *c == '`')); } if(*c == '*') { do { ++c; check_iterator('*',begin, c, delimiter); } while(!is_valid_char(*c)); std::string exponent; if(*c == '^') { exponent = "E"; ++c; check_iterator('^', begin, c, delimiter); while(c != delimiter && ((exponent.size() == 1 && (*c == '-' || *c == '+')) || std::isdigit(*c) || !is_valid_char(*c))) { if(is_valid_char(*c)) { exponent.push_back(*c); } ++c; } while(c != delimiter && (!is_valid_char(*c) || *c == '*')) { ++c; } } size_t degree(0); // Hard code the polynomial to be in 'x' since that is what // SDPB.m uses. if(*c == 'x') { ++c; while(!is_valid_char(*c)) { ++c; check_iterator('x', begin, c, delimiter); } if(*c != '^') { degree = 1; } else { ++c; std::string degree_string; while((degree_string.empty() && (*c == '-' || *c == '+')) || std::isdigit(*c) || !is_valid_char(*c)) { if(is_valid_char(*c) && *c != '+') { degree_string.push_back(*c); } ++c; } degree = std::stoull(degree_string); } } if(polynomial.coefficients.size() < degree + 1) { polynomial.coefficients.resize(degree + 1); } polynomial.coefficients.at(degree) = El::BigFloat(mantissa + exponent); mantissa.clear(); } else if(!mantissa.empty() && (*c == '-' || *c == '+' || c == delimiter)) { if(polynomial.coefficients.size() < 1) { polynomial.coefficients.resize(1); } polynomial.coefficients.at(0) = El::BigFloat(mantissa); mantissa.clear(); } if(is_valid_char(*c) && *c != '+') { mantissa.push_back(*c); } } return delimiter; } <|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/test/nacl/nacl_test.h" #include "base/file_util.h" #include "base/path_service.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "native_client/src/trusted/platform_qualify/nacl_os_qualify.h" #include "net/base/escape.h" #include "net/base/net_util.h" namespace { const char kTestCompleteCookie[] = "status"; const char kTestCompleteSuccess[] = "OK"; const FilePath::CharType kBaseUrl[] = FILE_PATH_LITERAL("http://localhost:5103/tests/prebuilt"); const FilePath::CharType kSrpcHwHtmlFileName[] = FILE_PATH_LITERAL("srpc_hw.html"); const FilePath::CharType kSrpcBasicHtmlFileName[] = FILE_PATH_LITERAL("srpc_basic.html"); const FilePath::CharType kSrpcSockAddrHtmlFileName[] = FILE_PATH_LITERAL("srpc_sockaddr.html"); const FilePath::CharType kSrpcShmHtmlFileName[] = FILE_PATH_LITERAL("srpc_shm.html"); const FilePath::CharType kSrpcPluginHtmlFileName[] = FILE_PATH_LITERAL("srpc_plugin.html"); const FilePath::CharType kSrpcNrdXferHtmlFileName[] = FILE_PATH_LITERAL("srpc_nrd_xfer.html"); const FilePath::CharType kServerHtmlFileName[] = FILE_PATH_LITERAL("server_test.html"); const FilePath::CharType kNpapiHwHtmlFileName[] = FILE_PATH_LITERAL("npapi_hw.html"); } // anonymous namespace NaClTest::NaClTest() : UITest(), use_x64_nexes_(false) { launch_arguments_.AppendSwitch(switches::kEnableNaCl); // Currently we disable some of the sandboxes. See: // Make NaCl work in Chromium's Linux seccomp sandbox and the Mac sandbox // http://code.google.com/p/nativeclient/issues/detail?id=344 #if defined(OS_LINUX) && defined(USE_SECCOMP_SANDBOX) launch_arguments_.AppendSwitch(switches::kDisableSeccompSandbox); #endif launch_arguments_.AppendSwitchWithValue(switches::kLoggingLevel, "0"); } NaClTest::~NaClTest() {} FilePath NaClTest::GetTestRootDir() { FilePath path; PathService::Get(base::DIR_SOURCE_ROOT, &path); path = path.AppendASCII("native_client"); return path; } GURL NaClTest::GetTestUrl(const FilePath& filename) { FilePath path(kBaseUrl); if (use_x64_nexes_) path = path.AppendASCII("x64"); else path = path.AppendASCII("x86"); path = path.Append(filename); return GURL(path.value()); } void NaClTest::WaitForFinish(const FilePath& filename, int wait_time) { GURL url = GetTestUrl(filename); scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); bool test_result = WaitUntilCookieValue(tab.get(), url, kTestCompleteCookie, wait_time, kTestCompleteSuccess); EXPECT_TRUE(test_result); } void NaClTest::RunTest(const FilePath& filename, int timeout) { GURL url = GetTestUrl(filename); NavigateToURL(url); WaitForFinish(filename, timeout); } void NaClTest::SetUp() { FilePath nacl_test_dir = GetTestRootDir(); #if defined(OS_WIN) if (NaClOsIs64BitWindows()) use_x64_nexes_ = true; #elif defined(OS_LINUX) && defined(__LP64__) use_x64_nexes_ = true; #endif UITest::SetUp(); StartHttpServerWithPort(nacl_test_dir, L"5103"); } void NaClTest::TearDown() { StopHttpServer(); UITest::TearDown(); } TEST_F(NaClTest, ServerTest) { FilePath test_file(kServerHtmlFileName); RunTest(test_file, action_max_timeout_ms()); } TEST_F(NaClTest, SrpcHelloWorld) { FilePath test_file(kSrpcHwHtmlFileName); RunTest(test_file, action_max_timeout_ms()); } TEST_F(NaClTest, SrpcBasicTest) { FilePath test_file(kSrpcBasicHtmlFileName); RunTest(test_file, action_max_timeout_ms()); } TEST_F(NaClTest, SrpcSockAddrTest) { FilePath test_file(kSrpcSockAddrHtmlFileName); RunTest(test_file, action_max_timeout_ms()); } TEST_F(NaClTest, SrpcShmTest) { FilePath test_file(kSrpcShmHtmlFileName); RunTest(test_file, action_max_timeout_ms()); } TEST_F(NaClTest, SrpcPluginTest) { FilePath test_file(kSrpcPluginHtmlFileName); RunTest(test_file, action_max_timeout_ms()); } TEST_F(NaClTest, SrpcNrdXferTest) { FilePath test_file(kSrpcNrdXferHtmlFileName); RunTest(test_file, action_max_timeout_ms()); } TEST_F(NaClTest, NpapiHwTest) { FilePath test_file(kNpapiHwHtmlFileName); RunTest(test_file, action_max_timeout_ms()); } <commit_msg>Mark SrpcPluginTest as flaky.<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/test/nacl/nacl_test.h" #include "base/file_util.h" #include "base/path_service.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "native_client/src/trusted/platform_qualify/nacl_os_qualify.h" #include "net/base/escape.h" #include "net/base/net_util.h" namespace { const char kTestCompleteCookie[] = "status"; const char kTestCompleteSuccess[] = "OK"; const FilePath::CharType kBaseUrl[] = FILE_PATH_LITERAL("http://localhost:5103/tests/prebuilt"); const FilePath::CharType kSrpcHwHtmlFileName[] = FILE_PATH_LITERAL("srpc_hw.html"); const FilePath::CharType kSrpcBasicHtmlFileName[] = FILE_PATH_LITERAL("srpc_basic.html"); const FilePath::CharType kSrpcSockAddrHtmlFileName[] = FILE_PATH_LITERAL("srpc_sockaddr.html"); const FilePath::CharType kSrpcShmHtmlFileName[] = FILE_PATH_LITERAL("srpc_shm.html"); const FilePath::CharType kSrpcPluginHtmlFileName[] = FILE_PATH_LITERAL("srpc_plugin.html"); const FilePath::CharType kSrpcNrdXferHtmlFileName[] = FILE_PATH_LITERAL("srpc_nrd_xfer.html"); const FilePath::CharType kServerHtmlFileName[] = FILE_PATH_LITERAL("server_test.html"); const FilePath::CharType kNpapiHwHtmlFileName[] = FILE_PATH_LITERAL("npapi_hw.html"); } // anonymous namespace NaClTest::NaClTest() : UITest(), use_x64_nexes_(false) { launch_arguments_.AppendSwitch(switches::kEnableNaCl); // Currently we disable some of the sandboxes. See: // Make NaCl work in Chromium's Linux seccomp sandbox and the Mac sandbox // http://code.google.com/p/nativeclient/issues/detail?id=344 #if defined(OS_LINUX) && defined(USE_SECCOMP_SANDBOX) launch_arguments_.AppendSwitch(switches::kDisableSeccompSandbox); #endif launch_arguments_.AppendSwitchWithValue(switches::kLoggingLevel, "0"); } NaClTest::~NaClTest() {} FilePath NaClTest::GetTestRootDir() { FilePath path; PathService::Get(base::DIR_SOURCE_ROOT, &path); path = path.AppendASCII("native_client"); return path; } GURL NaClTest::GetTestUrl(const FilePath& filename) { FilePath path(kBaseUrl); if (use_x64_nexes_) path = path.AppendASCII("x64"); else path = path.AppendASCII("x86"); path = path.Append(filename); return GURL(path.value()); } void NaClTest::WaitForFinish(const FilePath& filename, int wait_time) { GURL url = GetTestUrl(filename); scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); bool test_result = WaitUntilCookieValue(tab.get(), url, kTestCompleteCookie, wait_time, kTestCompleteSuccess); EXPECT_TRUE(test_result); } void NaClTest::RunTest(const FilePath& filename, int timeout) { GURL url = GetTestUrl(filename); NavigateToURL(url); WaitForFinish(filename, timeout); } void NaClTest::SetUp() { FilePath nacl_test_dir = GetTestRootDir(); #if defined(OS_WIN) if (NaClOsIs64BitWindows()) use_x64_nexes_ = true; #elif defined(OS_LINUX) && defined(__LP64__) use_x64_nexes_ = true; #endif UITest::SetUp(); StartHttpServerWithPort(nacl_test_dir, L"5103"); } void NaClTest::TearDown() { StopHttpServer(); UITest::TearDown(); } TEST_F(NaClTest, ServerTest) { FilePath test_file(kServerHtmlFileName); RunTest(test_file, action_max_timeout_ms()); } TEST_F(NaClTest, SrpcHelloWorld) { FilePath test_file(kSrpcHwHtmlFileName); RunTest(test_file, action_max_timeout_ms()); } TEST_F(NaClTest, SrpcBasicTest) { FilePath test_file(kSrpcBasicHtmlFileName); RunTest(test_file, action_max_timeout_ms()); } TEST_F(NaClTest, SrpcSockAddrTest) { FilePath test_file(kSrpcSockAddrHtmlFileName); RunTest(test_file, action_max_timeout_ms()); } TEST_F(NaClTest, SrpcShmTest) { FilePath test_file(kSrpcShmHtmlFileName); RunTest(test_file, action_max_timeout_ms()); } TEST_F(NaClTest, FLAKY_SrpcPluginTest) { FilePath test_file(kSrpcPluginHtmlFileName); RunTest(test_file, action_max_timeout_ms()); } TEST_F(NaClTest, SrpcNrdXferTest) { FilePath test_file(kSrpcNrdXferHtmlFileName); RunTest(test_file, action_max_timeout_ms()); } TEST_F(NaClTest, NpapiHwTest) { FilePath test_file(kNpapiHwHtmlFileName); RunTest(test_file, action_max_timeout_ms()); } <|endoftext|>
<commit_before>//============================================================================ // Name : sandpile1.cpp // Author : Aldo Guzmán-Sáenz // Version : // Copyright : // Description : This program simulates an abelian sandpile's evolution. //============================================================================ #include <iostream> #include <stack> #include <vector> #include <stdlib.h> #include <fstream> using namespace std; #define CRITICAL 4 // Value at which points become unstable stack< pair<int,int> > unstable1, unstable2; // Stacks used to store the current unstable cells in the grid vector< pair<int,int> > initialunstable; // Vector used to store the initial unstable cells in the grid int n; // Size of a size of the grid vector<int> grid; // Our sandpile, stored as an integer grid, the size is specified in main() pair<int,int> operator+( // Function to add pairs using the operator + const pair<int, int>& x, const pair<int, int>& y) { return make_pair(x.first+y.first, x.second+y.second); } int ih(pair<int,int> index) // Index Helper function to convert from pairs of indices to a single index { return index.first*n + index.second; } pair<int,int> ih(int index) // Overload of ih to convert from an index to a pair of indices { return make_pair(index/n,index%n); } vector< pair<int,int> > adjacent(const pair<int,int>& current) // Returns the positions of the 4 adjacent cells in our grid { vector< pair<int,int> > result; result.push_back(current+make_pair(-1,0)); result.push_back(current+make_pair(0,1)); result.push_back(current+make_pair(1,0)); result.push_back(current+make_pair(0,-1)); return result; } bool issink(const pair<int, int>& index) // Determines if the cell at index is a sink (not affected by toppling) { // In our case, only cells at the boundary are sinks return (index.first>=n || index.first<0 || index.second>=n || index.second<0); } void relax() // Main relaxation function (uses two stacks to keep track of unstable cells in our grid) { vector< pair<int,int> > neighbors(CRITICAL); unsigned int i; pair<int,int> current; while(!unstable1.empty() || !unstable2.empty()) { while(!unstable1.empty()) { current=unstable1.top(); while (grid[ih(current)] >= CRITICAL) { grid[ih(current)] -= CRITICAL; neighbors = adjacent(current); for(i=0;i<neighbors.size();++i) if (issink(neighbors[i])==false) { grid[ih(neighbors[i])]+=1; if (grid[ih(neighbors[i])] >= CRITICAL) unstable2.push(neighbors[i]); } } unstable1.pop(); } while(!unstable2.empty()) { current=unstable2.top(); while (grid[ih(current)] >= CRITICAL) { grid[ih(current)] -= CRITICAL; neighbors = adjacent(current); for(i=0;i<neighbors.size();++i) if (issink(neighbors[i])==false) { grid[ih(neighbors[i])]+=1; if (grid[ih(neighbors[i])] >= CRITICAL) unstable1.push(neighbors[i]); } } unstable2.pop(); } } } //============================================================================ // TODO: Implement parameter parsing // Parameters: // --size N size of the grid // --numberofgrains number of initial unstable cells (at random positions) //============================================================================ int main(int argc, char **argv) { string path("./grid.dat"); ofstream output(path.c_str(), ios::out | ofstream::binary); n=100; // Default grid size //n=atoi(argv[1]); // Read grid size from command line if available int nunstable=150; grid.resize(n*n,3); // Fill our grid with 3's srand(2); initialunstable.resize(nunstable); for(unsigned int i=0; i< initialunstable.size();++i) { initialunstable[i].first=rand()%n; initialunstable[i].second=rand()%n; } for(unsigned int i=0; i< initialunstable.size();++i) { grid[ih(initialunstable[i])]=4; unstable1.push(initialunstable[i]); } relax(); output.write(reinterpret_cast<const char *>(&n), sizeof(n)); output.write(reinterpret_cast<const char *>(&nunstable), sizeof(nunstable)); for (unsigned int i=0;i<grid.size();++i) { output.write(reinterpret_cast<const char *>(&grid[i]),sizeof(grid[i])); } for (unsigned int i=0;i<initialunstable.size();++i) { output.write(reinterpret_cast<const char *>(&initialunstable[i].first),sizeof(initialunstable[i].first)); output.write(reinterpret_cast<const char *>(&initialunstable[i].second),sizeof(initialunstable[i].second)); } return 0; } <commit_msg>Delete sandpile1.cpp<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: saltimer.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2003-05-28 12:35: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): _______________________________________ * * ************************************************************************/ #ifndef _SVWIN_H #include <tools/svwin.h> #endif #define _SV_SALTIMER_CXX #ifndef _SV_SALDATA_HXX #include <saldata.hxx> #endif #ifndef _SV_SALTIMER_HXX #include <saltimer.hxx> #endif // ======================================================================= // Maximale Periode #define MAX_SYSPERIOD 65533 // ======================================================================= void ImplSalStartTimer( ULONG nMS, BOOL bMutex ) { SalData* pSalData = GetSalData(); // Remenber the time of the timer pSalData->mnTimerMS = nMS; if ( !bMutex ) pSalData->mnTimerOrgMS = nMS; // Periode darf nicht zu gross sein, da Windows mit USHORT arbeitet if ( nMS > MAX_SYSPERIOD ) nMS = MAX_SYSPERIOD; // Gibt es einen Timer, dann zerstoren if ( pSalData->mnTimerId ) KillTimer( 0, pSalData->mnTimerId ); // Make a new timer with new period pSalData->mnTimerId = SetTimer( 0, 0, (UINT)nMS, SalTimerProc ); } // ----------------------------------------------------------------------- void SalTimer::Stop() { SalData* pSalData = GetSalData(); // If we have a timer, than if ( pSalData->mnTimerId ) { KillTimer( 0, pSalData->mnTimerId ); pSalData->mnTimerId = 0; } } // ----------------------------------------------------------------------- void SalTimer::SetCallback( SALTIMERPROC pProc ) { SalData* pSalData = GetSalData(); pSalData->mpTimerProc = pProc; } // ----------------------------------------------------------------------- void CALLBACK SalTimerProc( HWND, UINT, UINT, DWORD ) { SalData* pSalData = GetSalData(); // Test for MouseLeave SalTestMouseLeave(); if ( pSalData->mpTimerProc ) { // Try to aquire the mutex. If we don't get the mutex then we // try this a short time later again. if ( ImplSalYieldMutexTryToAcquire() ) { pSalData->mbInTimerProc = TRUE; pSalData->mpTimerProc(); pSalData->mbInTimerProc = FALSE; ImplSalYieldMutexRelease(); // Run the timer in the correct time, if we start this // with a small timeout, because we don't get the mutex if ( pSalData->mnTimerId && (pSalData->mnTimerMS != pSalData->mnTimerOrgMS) ) ImplSalStartTimer( pSalData->mnTimerOrgMS, FALSE ); } else ImplSalStartTimer( 10, TRUE ); } } <commit_msg>INTEGRATION: CWS vclplug (1.2.134); FILE MERGED 2003/10/29 18:29:28 pl 1.2.134.2: #i21232# timer must run in main thread 2003/10/24 13:35:12 pl 1.2.134.1: #21232# win port of virtualiing sal part<commit_after>/************************************************************************* * * $RCSfile: saltimer.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2003-11-18 14:51:01 $ * * 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 _SVWIN_H #include <tools/svwin.h> #endif #define _SV_SALTIMER_CXX #ifndef _SV_SALDATA_HXX #include <saldata.hxx> #endif #ifndef _SV_SALTIMER_H #include <saltimer.h> #endif #ifndef _SV_SALINST_H #include <salinst.h> #endif // ======================================================================= // Maximale Periode #define MAX_SYSPERIOD 65533 // ======================================================================= void ImplSalStartTimer( ULONG nMS, BOOL bMutex ) { SalData* pSalData = GetSalData(); // Remenber the time of the timer pSalData->mnTimerMS = nMS; if ( !bMutex ) pSalData->mnTimerOrgMS = nMS; // Periode darf nicht zu gross sein, da Windows mit USHORT arbeitet if ( nMS > MAX_SYSPERIOD ) nMS = MAX_SYSPERIOD; // Gibt es einen Timer, dann zerstoren if ( pSalData->mnTimerId ) KillTimer( 0, pSalData->mnTimerId ); // Make a new timer with new period pSalData->mnTimerId = SetTimer( 0, 0, (UINT)nMS, SalTimerProc ); } // ----------------------------------------------------------------------- WinSalTimer::~WinSalTimer() { } void WinSalTimer::Start( ULONG nMS ) { // switch to main thread SalData* pSalData = GetSalData(); if ( pSalData->mpFirstInstance ) { if ( pSalData->mnAppThreadId != GetCurrentThreadId() ) ImplPostMessage( pSalData->mpFirstInstance->mhComWnd, SAL_MSG_STARTTIMER, 0, (LPARAM)nMS ); else ImplSendMessage( pSalData->mpFirstInstance->mhComWnd, SAL_MSG_STARTTIMER, 0, (LPARAM)nMS ); } else ImplSalStartTimer( nMS, FALSE ); } void WinSalTimer::Stop() { SalData* pSalData = GetSalData(); // If we have a timer, than if ( pSalData->mnTimerId ) { KillTimer( 0, pSalData->mnTimerId ); pSalData->mnTimerId = 0; } } // ----------------------------------------------------------------------- void CALLBACK SalTimerProc( HWND, UINT, UINT, DWORD ) { SalData* pSalData = GetSalData(); ImplSVData* pSVData = ImplGetSVData(); // Test for MouseLeave SalTestMouseLeave(); if ( pSVData->mpSalTimer ) { // Try to aquire the mutex. If we don't get the mutex then we // try this a short time later again. if ( ImplSalYieldMutexTryToAcquire() ) { pSalData->mbInTimerProc = TRUE; pSVData->mpSalTimer->CallCallback(); pSalData->mbInTimerProc = FALSE; ImplSalYieldMutexRelease(); // Run the timer in the correct time, if we start this // with a small timeout, because we don't get the mutex if ( pSalData->mnTimerId && (pSalData->mnTimerMS != pSalData->mnTimerOrgMS) ) ImplSalStartTimer( pSalData->mnTimerOrgMS, FALSE ); } else ImplSalStartTimer( 10, TRUE ); } } <|endoftext|>
<commit_before>// // scan.cpp // See the file "LICENSE.md" for the full license governing this code. // #include "compile.h" #if COMPILE_DMZ #include "scan.h" #include "expiry_categorize.h" #include "expiry_seg.h" #define SCAN_FOREVER 0 // useful for performance profiling #define EXTRA_TIME_FOR_EXPIRY_IN_MICROSECONDS 1000 // once the card number has been successfully identified, allow a bit more time to figure out the expiry #define kDecayFactor 0.8f #define kMinStability 0.7f void scanner_initialize(ScannerState *state) { scanner_reset(state); } void scanner_reset(ScannerState *state) { state->count15 = 0; state->count16 = 0; state->aggregated15 = NumberScores::Zero(); state->aggregated16 = NumberScores::Zero(); scan_analytics_init(&state->session_analytics); state->timeOfCardNumberCompletionInMilliseconds = 0; state->collect_expiry = false; state->expiry_month = 0; state->expiry_year = 0; state->expiry_groups.clear(); state->name_groups.clear(); } void scanner_add_frame(ScannerState *state, IplImage *y, bool collect_expiry, FrameScanResult *result) { bool still_need_to_collect_card_number = (state->timeOfCardNumberCompletionInMilliseconds == 0); bool still_need_to_collect_expiry = collect_expiry && (state->expiry_month == 0 || state->expiry_year == 0); // Don't bother with a bunch of assertions about y here, // since the frame reader will make them anyway. scan_card_image(y, still_need_to_collect_card_number, still_need_to_collect_expiry, result); if (result->upside_down) { return; } scan_analytics_record_frame(&state->session_analytics, result); // TODO: Scene change detection? if (!result->usable) { return; } if (still_need_to_collect_expiry) { state->collect_expiry = true; expiry_extract(y, state->expiry_groups, result->expiry_groups, &state->expiry_month, &state->expiry_year); state->name_groups = result->name_groups; // for now, for the debugging display } if (still_need_to_collect_card_number) { if(result->hseg.n_offsets == 15) { state->aggregated15 *= kDecayFactor; state->aggregated15 += result->scores * (1 - kDecayFactor); state->count15++; } else if(result->hseg.n_offsets == 16) { state->aggregated16 *= kDecayFactor; state->aggregated16 += result->scores * (1 - kDecayFactor); state->count16++; } else { assert(false); } } } void scanner_result(ScannerState *state, ScannerResult *result) { result->complete = false; // until we change our minds otherwise...avoids having to set this at all the possible early exits #if SCAN_FOREVER return; #endif if (state->timeOfCardNumberCompletionInMilliseconds > 0) { *result = state->successfulCardNumberResult; } else { uint16_t max_count = MAX(state->count15, state->count16); uint16_t min_count = MIN(state->count15, state->count16); // We want a three frame lead at a bare minimum. // Also guarantees we have at least three frames, period. :) if(max_count - min_count < 3) { return; } // Want a significant opinion about whether visa or amex if(min_count * 2 > max_count) { return; } // TODO: Sanity check the scores distributions // TODO: Do something else sophisticated here -- look at confidences, distributions, stability, hysteresis, etc. NumberScores aggregated; if(state->count15 > state->count16) { result->n_numbers = 15; aggregated = state->aggregated15; } else { result->n_numbers = 16; aggregated = state->aggregated16; } // Calculate result predictions // At the same time, put it in a convenient format for the basic consistency checks uint8_t number_as_u8s[16]; dmz_debug_print("Stability: "); for(uint8_t i = 0; i < result->n_numbers; i++) { NumberScores::Index r, c; float max_score = aggregated.row(i).maxCoeff(&r, &c); float sum = aggregated.row(i).sum(); result->predictions(i, 0) = c; number_as_u8s[i] = (uint8_t)c; float stability = max_score / sum; dmz_debug_print("%d ", (int) ceilf(stability * 100)); // Bail early if low stability if (stability < kMinStability) { dmz_debug_print("\n"); return; } } dmz_debug_print("\n"); // Don't return a number that fails basic prefix sanity checks CardType card_type = dmz_card_info_for_prefix_and_length(number_as_u8s, result->n_numbers, false).card_type; if(card_type != CardTypeAmbiguous && card_type != CardTypeUnrecognized && dmz_passes_luhn_checksum(number_as_u8s, result->n_numbers)) { dmz_debug_print("CARD NUMBER SCANNED SUCCESSFULLY.\n"); struct timeval time; gettimeofday(&time, NULL); state->timeOfCardNumberCompletionInMilliseconds = (long)((time.tv_sec * 1000) + (time.tv_usec / 1000)); state->successfulCardNumberResult = *result; } } // Once the card number has been successfully scanned, then wait a bit longer for successful expiry scan (if collecting expiry) if (state->timeOfCardNumberCompletionInMilliseconds > 0) { #if SCAN_EXPIRY if (state->collect_expiry) { #else if (false) { #endif struct timeval time; gettimeofday(&time, NULL); long now = (long)((time.tv_sec * 1000) + (time.tv_usec / 1000)); if ((state->expiry_month > 0 && state->expiry_year > 0) || now - state->timeOfCardNumberCompletionInMilliseconds > EXTRA_TIME_FOR_EXPIRY_IN_MICROSECONDS) { result->expiry_month = state->expiry_month; result->expiry_year = state->expiry_year; #if DMZ_DEBUG result->expiry_groups = state->expiry_groups; result->name_groups = state->name_groups; #endif result->complete = true; dmz_debug_print("Extra time for expiry scan: %6.3f seconds\n", ((float)(now - state->timeOfCardNumberCompletionInMilliseconds)) / 1000.0f); } } else { result->complete = true; } } } void scanner_destroy(ScannerState *state) { // currently a no-op } #endif // COMPILE_DMZ <commit_msg>Expiry: add another `#if SCAN_EXPIRY`<commit_after>// // scan.cpp // See the file "LICENSE.md" for the full license governing this code. // #include "compile.h" #if COMPILE_DMZ #include "scan.h" #include "expiry_categorize.h" #include "expiry_seg.h" #define SCAN_FOREVER 0 // useful for performance profiling #define EXTRA_TIME_FOR_EXPIRY_IN_MICROSECONDS 1000 // once the card number has been successfully identified, allow a bit more time to figure out the expiry #define kDecayFactor 0.8f #define kMinStability 0.7f void scanner_initialize(ScannerState *state) { scanner_reset(state); } void scanner_reset(ScannerState *state) { state->count15 = 0; state->count16 = 0; state->aggregated15 = NumberScores::Zero(); state->aggregated16 = NumberScores::Zero(); scan_analytics_init(&state->session_analytics); state->timeOfCardNumberCompletionInMilliseconds = 0; state->collect_expiry = false; state->expiry_month = 0; state->expiry_year = 0; state->expiry_groups.clear(); state->name_groups.clear(); } void scanner_add_frame(ScannerState *state, IplImage *y, bool collect_expiry, FrameScanResult *result) { bool still_need_to_collect_card_number = (state->timeOfCardNumberCompletionInMilliseconds == 0); bool still_need_to_collect_expiry = collect_expiry && (state->expiry_month == 0 || state->expiry_year == 0); // Don't bother with a bunch of assertions about y here, // since the frame reader will make them anyway. scan_card_image(y, still_need_to_collect_card_number, still_need_to_collect_expiry, result); if (result->upside_down) { return; } scan_analytics_record_frame(&state->session_analytics, result); // TODO: Scene change detection? if (!result->usable) { return; } #if SCAN_EXPIRY if (still_need_to_collect_expiry) { state->collect_expiry = true; expiry_extract(y, state->expiry_groups, result->expiry_groups, &state->expiry_month, &state->expiry_year); state->name_groups = result->name_groups; // for now, for the debugging display } #endif if (still_need_to_collect_card_number) { if(result->hseg.n_offsets == 15) { state->aggregated15 *= kDecayFactor; state->aggregated15 += result->scores * (1 - kDecayFactor); state->count15++; } else if(result->hseg.n_offsets == 16) { state->aggregated16 *= kDecayFactor; state->aggregated16 += result->scores * (1 - kDecayFactor); state->count16++; } else { assert(false); } } } void scanner_result(ScannerState *state, ScannerResult *result) { result->complete = false; // until we change our minds otherwise...avoids having to set this at all the possible early exits #if SCAN_FOREVER return; #endif if (state->timeOfCardNumberCompletionInMilliseconds > 0) { *result = state->successfulCardNumberResult; } else { uint16_t max_count = MAX(state->count15, state->count16); uint16_t min_count = MIN(state->count15, state->count16); // We want a three frame lead at a bare minimum. // Also guarantees we have at least three frames, period. :) if(max_count - min_count < 3) { return; } // Want a significant opinion about whether visa or amex if(min_count * 2 > max_count) { return; } // TODO: Sanity check the scores distributions // TODO: Do something else sophisticated here -- look at confidences, distributions, stability, hysteresis, etc. NumberScores aggregated; if(state->count15 > state->count16) { result->n_numbers = 15; aggregated = state->aggregated15; } else { result->n_numbers = 16; aggregated = state->aggregated16; } // Calculate result predictions // At the same time, put it in a convenient format for the basic consistency checks uint8_t number_as_u8s[16]; dmz_debug_print("Stability: "); for(uint8_t i = 0; i < result->n_numbers; i++) { NumberScores::Index r, c; float max_score = aggregated.row(i).maxCoeff(&r, &c); float sum = aggregated.row(i).sum(); result->predictions(i, 0) = c; number_as_u8s[i] = (uint8_t)c; float stability = max_score / sum; dmz_debug_print("%d ", (int) ceilf(stability * 100)); // Bail early if low stability if (stability < kMinStability) { dmz_debug_print("\n"); return; } } dmz_debug_print("\n"); // Don't return a number that fails basic prefix sanity checks CardType card_type = dmz_card_info_for_prefix_and_length(number_as_u8s, result->n_numbers, false).card_type; if(card_type != CardTypeAmbiguous && card_type != CardTypeUnrecognized && dmz_passes_luhn_checksum(number_as_u8s, result->n_numbers)) { dmz_debug_print("CARD NUMBER SCANNED SUCCESSFULLY.\n"); struct timeval time; gettimeofday(&time, NULL); state->timeOfCardNumberCompletionInMilliseconds = (long)((time.tv_sec * 1000) + (time.tv_usec / 1000)); state->successfulCardNumberResult = *result; } } // Once the card number has been successfully scanned, then wait a bit longer for successful expiry scan (if collecting expiry) if (state->timeOfCardNumberCompletionInMilliseconds > 0) { #if SCAN_EXPIRY if (state->collect_expiry) { #else if (false) { #endif struct timeval time; gettimeofday(&time, NULL); long now = (long)((time.tv_sec * 1000) + (time.tv_usec / 1000)); if ((state->expiry_month > 0 && state->expiry_year > 0) || now - state->timeOfCardNumberCompletionInMilliseconds > EXTRA_TIME_FOR_EXPIRY_IN_MICROSECONDS) { result->expiry_month = state->expiry_month; result->expiry_year = state->expiry_year; #if DMZ_DEBUG result->expiry_groups = state->expiry_groups; result->name_groups = state->name_groups; #endif result->complete = true; dmz_debug_print("Extra time for expiry scan: %6.3f seconds\n", ((float)(now - state->timeOfCardNumberCompletionInMilliseconds)) / 1000.0f); } } else { result->complete = true; } } } void scanner_destroy(ScannerState *state) { // currently a no-op } #endif // COMPILE_DMZ <|endoftext|>
<commit_before>// Virvo - Virtual Reality Volume Rendering // Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University // Contact: Jurgen P. Schulze, jschulze@ucsd.edu // // This file is part of Virvo. // // Virvo is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library (see license.txt); if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "vvdebugmsg.h" #include "vvrendercontext.h" #include <iostream> #include "vvx11.h" using namespace std; struct ContextArchData { #ifdef HAVE_X11 GLXContext glxContext; Display* display; Drawable drawable; #endif }; vvRenderContext::vvRenderContext(const char* displayName) { _archData = new ContextArchData; _initialized = false; init(displayName); } vvRenderContext::~vvRenderContext() { vvDebugMsg::msg(1, "vvRenderContext::~vvRenderContext"); if (_initialized) { #ifdef HAVE_X11 glXDestroyContext(_archData->display, _archData->glxContext); XCloseDisplay(_archData->display); #endif } delete _archData; } bool vvRenderContext::makeCurrent() const { if (_initialized) { #ifdef HAVE_X11 return glXMakeCurrent(_archData->display, _archData->drawable, _archData->glxContext); #endif } return false; } void vvRenderContext::init(const char* displayName) { #ifdef HAVE_X11 _archData->display = XOpenDisplay(displayName); if (_archData->display != NULL) { const Drawable parent = RootWindow(_archData->display, DefaultScreen(_archData->display)); int attrList[] = { GLX_RGBA, GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_ALPHA_SIZE, 8, GLX_DEPTH_SIZE, 24, None}; XVisualInfo* vi = glXChooseVisual(_archData->display, DefaultScreen(_archData->display), attrList); XSetWindowAttributes wa = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; wa.colormap = XCreateColormap(_archData->display, parent, vi->visual, AllocNone); wa.background_pixmap = None; wa.border_pixel = 0; if (vvDebugMsg::getDebugLevel() == 0) { wa.override_redirect = true; } else { wa.override_redirect = false; } _archData->glxContext = glXCreateContext(_archData->display, vi, NULL, True); if (_archData->glxContext != 0) { int windowWidth = 1; int windowHeight = 1; if (vvDebugMsg::getDebugLevel() > 0) { windowWidth = 512; windowHeight = 512; } _archData->drawable = XCreateWindow(_archData->display, parent, 0, 0, windowWidth, windowHeight, 0, vi->depth, InputOutput, vi->visual, CWBackPixmap|CWBorderPixel|CWColormap|CWOverrideRedirect, &wa); XMapWindow(_archData->display, _archData->drawable); XFlush(_archData->display); _initialized = true; } else { cerr << "Couldn't create OpenGL context" << endl; _initialized = false; } delete vi; } else { cerr << "Couldn't open X display" << endl; _initialized = false; } #else (void)displayName; #endif } // vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0 <commit_msg>remove using namespace std<commit_after>// Virvo - Virtual Reality Volume Rendering // Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University // Contact: Jurgen P. Schulze, jschulze@ucsd.edu // // This file is part of Virvo. // // Virvo is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library (see license.txt); if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "vvdebugmsg.h" #include "vvrendercontext.h" #include <iostream> #include "vvx11.h" struct ContextArchData { #ifdef HAVE_X11 GLXContext glxContext; Display* display; Drawable drawable; #endif }; vvRenderContext::vvRenderContext(const char* displayName) { _archData = new ContextArchData; _initialized = false; init(displayName); } vvRenderContext::~vvRenderContext() { vvDebugMsg::msg(1, "vvRenderContext::~vvRenderContext"); if (_initialized) { #ifdef HAVE_X11 glXDestroyContext(_archData->display, _archData->glxContext); XCloseDisplay(_archData->display); #endif } delete _archData; } bool vvRenderContext::makeCurrent() const { if (_initialized) { #ifdef HAVE_X11 return glXMakeCurrent(_archData->display, _archData->drawable, _archData->glxContext); #endif } return false; } void vvRenderContext::init(const char* displayName) { #ifdef HAVE_X11 _archData->display = XOpenDisplay(displayName); if (_archData->display != NULL) { const Drawable parent = RootWindow(_archData->display, DefaultScreen(_archData->display)); int attrList[] = { GLX_RGBA, GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8, GLX_ALPHA_SIZE, 8, GLX_DEPTH_SIZE, 24, None}; XVisualInfo* vi = glXChooseVisual(_archData->display, DefaultScreen(_archData->display), attrList); XSetWindowAttributes wa = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; wa.colormap = XCreateColormap(_archData->display, parent, vi->visual, AllocNone); wa.background_pixmap = None; wa.border_pixel = 0; if (vvDebugMsg::getDebugLevel() == 0) { wa.override_redirect = true; } else { wa.override_redirect = false; } _archData->glxContext = glXCreateContext(_archData->display, vi, NULL, True); if (_archData->glxContext != 0) { int windowWidth = 1; int windowHeight = 1; if (vvDebugMsg::getDebugLevel() > 0) { windowWidth = 512; windowHeight = 512; } _archData->drawable = XCreateWindow(_archData->display, parent, 0, 0, windowWidth, windowHeight, 0, vi->depth, InputOutput, vi->visual, CWBackPixmap|CWBorderPixel|CWColormap|CWOverrideRedirect, &wa); XMapWindow(_archData->display, _archData->drawable); XFlush(_archData->display); _initialized = true; } else { std::cerr << "Couldn't create OpenGL context" << std::endl; _initialized = false; } delete vi; } else { std::cerr << "Couldn't open X display" << std::endl; _initialized = false; } #else (void)displayName; #endif } // vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0 <|endoftext|>
<commit_before>/* pvsops.c: pvs and other spectral-based opcodes Copyright (C) 2017 Victor Lazzarini This file is part of Csound. The Csound Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. Csound 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 Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <plugin.h> #include <algorithm> struct PVTrace : csnd::FPlugin<1, 2> { csnd::AuxMem<float> amps; static constexpr char const *otypes = "f"; static constexpr char const *itypes = "fk"; int init() { if (inargs.fsig_data(0).isSliding()) return csound->init_error(Str("sliding not supported")); if (inargs.fsig_data(0).fsig_format() != csnd::fsig_format::pvs && inargs.fsig_data(0).fsig_format() != csnd::fsig_format::polar) return csound->init_error(Str("fsig format not supported")); amps.allocate(csound, inargs.fsig_data(0).nbins()); csnd::Fsig &fout = outargs.fsig_data(0); fout.init(csound, inargs.fsig_data(0)); framecount = 0; return OK; } int kperf() { csnd::pv_frame &fin = inargs.fsig_data(0); csnd::pv_frame &fout = outargs.fsig_data(0); if (framecount < fin.count()) { int n = fin.len() - (int) inargs[1]; float thrsh; std::transform(fin.begin(), fin.end(), amps.begin(), [](csnd::pv_bin f){ return f.amp(); }); std::nth_element(amps.begin(), amps.begin()+n, amps.end()); thrsh = amps[n]; std::transform(fin.begin(), fin.end(), fout.begin(), [thrsh](csnd::pv_bin f){ return f.amp() >= thrsh ? f : csnd::pv_bin(); }); framecount = fout.count(fin.count()); } return OK; } }; struct TVConv : csnd::Plugin<1,4> { static constexpr char const *otypes = "a"; static constexpr char const *itypes = "aaii"; csnd::AuxMem<MYFLT> ir; csnd::AuxMem<MYFLT> in; csnd::AuxMem<MYFLT> out; csnd::AuxMem<MYFLT> saved; uint32_t n; uint32_t fils; uint32_t pars; uint32_t ffts; uint32_t nparts; uint32_t pp; csnd::fftp fwd,inv; typedef std::complex<MYFLT> cmplx; uint32_t rpow2(uint32_t n) { uint32_t v = 2; while (v <= n) v <<= 1; if((n - (v >> 1)) < (v - n)) return v >> 1; else return v; } cmplx *to_cmplx(MYFLT *f) { return reinterpret_cast<cmplx*>(f); } cmplx real_prod(cmplx &a, cmplx &b) { return cmplx(a.real()*b.real(), a.imag()*b.imag()); } int init() { pars = inargs[2]; fils = inargs[3]; if(pars > fils) std::swap(pars,fils); if(pars > 1) { pars = rpow2(pars); fils = rpow2(fils); ffts = pars*2; fwd = csound->fft_setup(ffts,FFT_FWD); inv = csound->fft_setup(ffts,FFT_INV); out.allocate(csound, 2*pars); saved.allocate(csound, pars); ir.allocate(csound, 2*fils); in.allocate(csound, 2*fils); nparts = fils/pars; fils *= 2; } else { ir.allocate(csound, fils); in.allocate(csound, fils); } n = 0; pp = 0; return OK; } int pconv(csnd::AudioSig &outsig, csnd::AudioSig &insig, csnd::AudioSig &irsig){ auto irp = irsig.begin(); auto inp = insig.begin(); for(auto &s: outsig) { ir[n+pp] = *irp++; in[n+pp] = *inp++; in[n+pp+pars] = ir[n+pp+pars] = 0.; s = out[n] + saved[n]; saved[n] = out[n + pars]; if(++n == pars) { cmplx *ins,*irs, *ous = to_cmplx(out.data()); std::fill(out.begin(), out.end(), 0.); // FFT csound->rfft(fwd, ir.data() + pp); csound->rfft(fwd, in.data() + pp); pp += ffts; if(pp == fils) pp = 0; // spectral delay line for(uint32_t k = 0, kp = pp; k < nparts; k++, kp+=ffts) { if(kp == fils) kp = 0; ins = to_cmplx(in.data() + kp); irs = to_cmplx(ir.data() + (nparts - k - 1)*ffts); // spectral product for(uint i=1; i < pars; i++) ous[i] += ins[i] * irs[i]; ous[0] += real_prod(ins[0],irs[0]); } // IFFT csound->rfft(inv, out.data()); n = 0; } } return OK; } int dconv(csnd::AudioSig &outsig, csnd::AudioSig &insig, csnd::AudioSig &irsig) { auto irp = irsig.begin(); auto inp = insig.begin(); MYFLT sum = 0.0; for(auto &s: outsig) { ir[pp] = *irp++; in[pp] = *inp++; pp = pp != fils - 1 ? pp + 1 : 0; for(uint32_t k = 0, kp = pp; k < fils; k++, kp++) { if(kp == fils) kp = 0; sum += in[kp] * ir[fils - k - 1]; } s = sum; sum = 0; } return OK; } int aperf() { csnd::AudioSig ins(this, inargs(0)); csnd::AudioSig irs(this, inargs(1)); csnd::AudioSig outs(this, outargs(0)); if(pars > 1) return pconv(outs, ins, irs); else return dconv(outs, ins, irs); } }; #include <modload.h> void csnd::on_load(Csound *csound) { csnd::plugin<PVTrace>(csound, "pvstrace", csnd::thread::ik); csnd::plugin<TVConv>(csound, "tvconv", csnd::thread::ia); } <commit_msg>tvconv with freeze params<commit_after>/* pvsops.c: pvs and other spectral-based opcodes Copyright (C) 2017 Victor Lazzarini This file is part of Csound. The Csound Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. Csound 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 Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <plugin.h> #include <algorithm> struct PVTrace : csnd::FPlugin<1, 2> { csnd::AuxMem<float> amps; static constexpr char const *otypes = "f"; static constexpr char const *itypes = "fk"; int init() { if (inargs.fsig_data(0).isSliding()) return csound->init_error(Str("sliding not supported")); if (inargs.fsig_data(0).fsig_format() != csnd::fsig_format::pvs && inargs.fsig_data(0).fsig_format() != csnd::fsig_format::polar) return csound->init_error(Str("fsig format not supported")); amps.allocate(csound, inargs.fsig_data(0).nbins()); csnd::Fsig &fout = outargs.fsig_data(0); fout.init(csound, inargs.fsig_data(0)); framecount = 0; return OK; } int kperf() { csnd::pv_frame &fin = inargs.fsig_data(0); csnd::pv_frame &fout = outargs.fsig_data(0); if (framecount < fin.count()) { int n = fin.len() - (int) inargs[1]; float thrsh; std::transform(fin.begin(), fin.end(), amps.begin(), [](csnd::pv_bin f){ return f.amp(); }); std::nth_element(amps.begin(), amps.begin()+n, amps.end()); thrsh = amps[n]; std::transform(fin.begin(), fin.end(), fout.begin(), [thrsh](csnd::pv_bin f){ return f.amp() >= thrsh ? f : csnd::pv_bin(); }); framecount = fout.count(fin.count()); } return OK; } }; struct TVConv : csnd::Plugin<1,6> { csnd::AuxMem<MYFLT> ir; csnd::AuxMem<MYFLT> in; csnd::AuxMem<MYFLT> insp; csnd::AuxMem<MYFLT> irsp; csnd::AuxMem<MYFLT> out; csnd::AuxMem<MYFLT> saved; uint32_t n; uint32_t fils; uint32_t pars; uint32_t ffts; uint32_t nparts; uint32_t pp; csnd::fftp fwd,inv; typedef std::complex<MYFLT> cmplx; uint32_t rpow2(uint32_t n) { uint32_t v = 2; while (v <= n) v <<= 1; if((n - (v >> 1)) < (v - n)) return v >> 1; else return v; } cmplx *to_cmplx(MYFLT *f) { return reinterpret_cast<cmplx*>(f); } cmplx real_prod(cmplx &a, cmplx &b) { return cmplx(a.real()*b.real(), a.imag()*b.imag()); } int init() { pars = inargs[4]; fils = inargs[5]; if(pars > fils) std::swap(pars,fils); if(pars > 1) { pars = rpow2(pars); fils = rpow2(fils); ffts = pars*2; fwd = csound->fft_setup(ffts,FFT_FWD); inv = csound->fft_setup(ffts,FFT_INV); out.allocate(csound, 2*pars); insp.allocate(csound, 2*fils); irsp.allocate(csound, 2*fils); saved.allocate(csound, pars); ir.allocate(csound, 2*fils); in.allocate(csound, 2*fils); nparts = fils/pars; fils *= 2; } else { ir.allocate(csound, fils); in.allocate(csound, fils); } n = 0; pp = 0; return OK; } int pconv(csnd::AudioSig &outsig, csnd::AudioSig &insig, csnd::AudioSig &irsig){ auto irp = irsig.begin(); auto inp = insig.begin(); MYFLT *frz1 = inargs(2); MYFLT *frz2 = inargs(3); bool inc1 = csound->is_asig(inargs(2)); bool inc2 = csound->is_asig(inargs(3)); for(auto &s: outsig) { *frz1 > 0 ? (in[n+pp] = *inp++) : *inp++; *frz2 > 0 ? (ir[n+pp] = *irp++) : *irp++; frz1 += inc1; frz2 += inc2; s = out[n] + saved[n]; saved[n] = out[n + pars]; if(++n == pars) { cmplx *ins,*irs, *ous = to_cmplx(out.data()); std::copy(in.begin() + pp, in.begin() + pp + ffts, insp.begin() + pp); std::copy(ir.begin() + pp, ir.begin() + pp + ffts, irsp.begin() + pp); std::fill(out.begin(), out.end(), 0.); // FFT csound->rfft(fwd, insp.data() + pp); csound->rfft(fwd, irsp.data() + pp); pp += ffts; if(pp == fils) pp = 0; // spectral delay line for(uint32_t k = 0, kp = pp; k < nparts; k++, kp+=ffts) { if(kp == fils) kp = 0; ins = to_cmplx(insp.data() + kp); irs = to_cmplx(irsp.data() + (nparts - k - 1)*ffts); // spectral product for(uint i=1; i < pars; i++) ous[i] += ins[i] * irs[i]; ous[0] += real_prod(ins[0],irs[0]); } // IFFT csound->rfft(inv, out.data()); n = 0; } } return OK; } int dconv(csnd::AudioSig &outsig, csnd::AudioSig &insig, csnd::AudioSig &irsig) { auto irp = irsig.begin(); auto inp = insig.begin(); MYFLT *frz1 = inargs(2); MYFLT *frz2 = inargs(3); bool inc1 = csound->is_asig(inargs(2)); bool inc2 = csound->is_asig(inargs(3)); MYFLT sum = 0.0; for(auto &s: outsig) { *frz1 > 0 ? (in[pp] = *inp++) : *inp++; *frz2 > 0 ? (ir[pp] = *irp++) : *irp++; pp = pp != fils - 1 ? pp + 1 : 0; for(uint32_t k = 0, kp = pp; k < fils; k++, kp++) { if(kp == fils) kp = 0; sum += in[kp] * ir[fils - k - 1]; } s = sum; sum = 0; frz1 += inc1; frz2 += inc2; } return OK; } int aperf() { csnd::AudioSig ins(this, inargs(0)); csnd::AudioSig irs(this, inargs(1)); csnd::AudioSig outs(this, outargs(0)); if(pars > 1) return pconv(outs, ins, irs); else return dconv(outs, ins, irs); } }; #include <modload.h> void csnd::on_load(Csound *csound) { csnd::plugin<PVTrace>(csound, "pvstrace", csnd::thread::ik); csnd::plugin<TVConv>(csound, "tvconv", "a", "aakkii", csnd::thread::ia); csnd::plugin<TVConv>(csound, "tvconv", "a", "aaakii", csnd::thread::ia); csnd::plugin<TVConv>(csound, "tvconv", "a", "aakaii", csnd::thread::ia); csnd::plugin<TVConv>(csound, "tvconv", "a", "aaaaii", csnd::thread::ia); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: unmovss.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2008-03-12 11:41:25 $ * * 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_sd.hxx" #include "unmovss.hxx" #include "DrawDocShell.hxx" #include "drawdoc.hxx" #include "stlsheet.hxx" #include "stlpool.hxx" SdMoveStyleSheetsUndoAction::SdMoveStyleSheetsUndoAction( SdDrawDocument* pTheDoc, SdStyleSheetVector& rTheStyles, bool bInserted) : SdUndoAction(pTheDoc) , mbMySheets( !bInserted ) { maStyles.swap( rTheStyles ); maListOfChildLists.resize( maStyles.size() ); // Liste mit den Listen der StyleSheet-Kinder erstellen std::size_t i = 0; for(SdStyleSheetVector::iterator iter = maStyles.begin(); iter != maStyles.end(); iter++ ) { maListOfChildLists[i++] = SdStyleSheetPool::CreateChildList( (*iter).get() ); } } /************************************************************************* |* |* Undo() |* \************************************************************************/ void SdMoveStyleSheetsUndoAction::Undo() { SfxStyleSheetBasePool* pPool = mpDoc->GetStyleSheetPool(); if (mbMySheets) { // the styles have to be inserted in the pool // first insert all styles to the pool for(SdStyleSheetVector::iterator iter = maStyles.begin(); iter != maStyles.end(); iter++ ) { pPool->Insert((*iter).get()); } // now assign the childs again std::vector< SdStyleSheetVector >::iterator childlistiter( maListOfChildLists.begin() ); for(SdStyleSheetVector::iterator iter = maStyles.begin(); iter != maStyles.end(); iter++, childlistiter++ ) { String aParent((*iter)->GetName()); for( SdStyleSheetVector::iterator childiter = (*childlistiter).begin(); childiter != (*childlistiter).end(); childiter++ ) { (*childiter)->SetParent(aParent); } } } else { // remove the styles again from the pool for(SdStyleSheetVector::iterator iter = maStyles.begin(); iter != maStyles.end(); iter++ ) { pPool->Remove((*iter).get()); } } mbMySheets = !mbMySheets; } void SdMoveStyleSheetsUndoAction::Redo() { Undo(); } SdMoveStyleSheetsUndoAction::~SdMoveStyleSheetsUndoAction() { } String SdMoveStyleSheetsUndoAction::GetComment() const { return String(); } <commit_msg>INTEGRATION: CWS changefileheader (1.7.16); FILE MERGED 2008/03/31 13:58:07 rt 1.7.16.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: unmovss.cxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include "unmovss.hxx" #include "DrawDocShell.hxx" #include "drawdoc.hxx" #include "stlsheet.hxx" #include "stlpool.hxx" SdMoveStyleSheetsUndoAction::SdMoveStyleSheetsUndoAction( SdDrawDocument* pTheDoc, SdStyleSheetVector& rTheStyles, bool bInserted) : SdUndoAction(pTheDoc) , mbMySheets( !bInserted ) { maStyles.swap( rTheStyles ); maListOfChildLists.resize( maStyles.size() ); // Liste mit den Listen der StyleSheet-Kinder erstellen std::size_t i = 0; for(SdStyleSheetVector::iterator iter = maStyles.begin(); iter != maStyles.end(); iter++ ) { maListOfChildLists[i++] = SdStyleSheetPool::CreateChildList( (*iter).get() ); } } /************************************************************************* |* |* Undo() |* \************************************************************************/ void SdMoveStyleSheetsUndoAction::Undo() { SfxStyleSheetBasePool* pPool = mpDoc->GetStyleSheetPool(); if (mbMySheets) { // the styles have to be inserted in the pool // first insert all styles to the pool for(SdStyleSheetVector::iterator iter = maStyles.begin(); iter != maStyles.end(); iter++ ) { pPool->Insert((*iter).get()); } // now assign the childs again std::vector< SdStyleSheetVector >::iterator childlistiter( maListOfChildLists.begin() ); for(SdStyleSheetVector::iterator iter = maStyles.begin(); iter != maStyles.end(); iter++, childlistiter++ ) { String aParent((*iter)->GetName()); for( SdStyleSheetVector::iterator childiter = (*childlistiter).begin(); childiter != (*childlistiter).end(); childiter++ ) { (*childiter)->SetParent(aParent); } } } else { // remove the styles again from the pool for(SdStyleSheetVector::iterator iter = maStyles.begin(); iter != maStyles.end(); iter++ ) { pPool->Remove((*iter).get()); } } mbMySheets = !mbMySheets; } void SdMoveStyleSheetsUndoAction::Redo() { Undo(); } SdMoveStyleSheetsUndoAction::~SdMoveStyleSheetsUndoAction() { } String SdMoveStyleSheetsUndoAction::GetComment() const { return String(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: fuconbez.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: aw $ $Date: 2002-02-15 17:02:42 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER 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 _SD_FUCONBEZ_HXX #define _SD_FUCONBEZ_HXX #ifndef _SD_FUCONSTR_HXX #include "fuconstr.hxx" #endif class SdDrawViewShell; class SdWindow; class SdDrawView; class SdDrawDocument; /************************************************************************* |* |* Basisklasse fuer alle Funktionen |* \************************************************************************/ class FuConstBezPoly : public FuConstruct { protected: USHORT nEditMode; public: TYPEINFO(); FuConstBezPoly(SdViewShell* pViewSh, SdWindow* pWin, SdView* pView, SdDrawDocument* pDoc, SfxRequest& rReq); virtual ~FuConstBezPoly(); // Mouse- & Key-Events virtual BOOL KeyInput(const KeyEvent& rKEvt); virtual BOOL MouseMove(const MouseEvent& rMEvt); virtual BOOL MouseButtonUp(const MouseEvent& rMEvt); virtual BOOL MouseButtonDown(const MouseEvent& rMEvt); virtual void Activate(); // Function aktivieren virtual void Deactivate(); // Function deaktivieren virtual void SelectionHasChanged(); void SetEditMode(USHORT nMode); USHORT GetEditMode() { return nEditMode; } // #97016# virtual SdrObject* CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle); }; #endif // _FUCONBEZ_HXX <commit_msg>INTEGRATION: CWS impress1 (1.2.226); FILE MERGED 2003/09/16 13:35:50 af 1.2.226.1: #111996# Introduction of namespace sd. Use of sub-shells.<commit_after>/************************************************************************* * * $RCSfile: fuconbez.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2004-01-20 11:56:47 $ * * 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 SD_FU_CONSTRUCT_BEZIER_HXX #define SD_FU_CONSTRUCT_BEZIER_HXX #ifndef SD_FU_CONSTRUCT_HXX #include "fuconstr.hxx" #endif class SdDrawDocument; namespace sd { class DrawView; class DrawViewShell; class Window; class FuConstructBezierPolygon : public FuConstruct { public: TYPEINFO(); FuConstructBezierPolygon ( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq); virtual ~FuConstructBezierPolygon (void); // Mouse- & Key-Events virtual BOOL KeyInput(const KeyEvent& rKEvt); virtual BOOL MouseMove(const MouseEvent& rMEvt); virtual BOOL MouseButtonUp(const MouseEvent& rMEvt); virtual BOOL MouseButtonDown(const MouseEvent& rMEvt); virtual void Activate(); // Function aktivieren virtual void Deactivate(); // Function deaktivieren virtual void SelectionHasChanged(); void SetEditMode(USHORT nMode); USHORT GetEditMode() { return nEditMode; } // #97016# virtual SdrObject* CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle); protected: USHORT nEditMode; }; } // end of namespace sd #endif <|endoftext|>
<commit_before>#include "selfdrive/ui/qt/onroad.h" #include <iostream> #include "selfdrive/common/swaglog.h" #include "selfdrive/common/timing.h" #include "selfdrive/ui/paint.h" #include "selfdrive/ui/qt/util.h" #ifdef ENABLE_MAPS #include "selfdrive/ui/qt/maps/map.h" #endif OnroadWindow::OnroadWindow(QWidget *parent) : QWidget(parent) { main_layout = new QStackedLayout(this); main_layout->setStackingMode(QStackedLayout::StackAll); // old UI on bottom nvg = new NvgWindow(this); QObject::connect(this, &OnroadWindow::update, nvg, &NvgWindow::update); QWidget * split_wrapper = new QWidget; split = new QHBoxLayout(split_wrapper); split->setContentsMargins(0, 0, 0, 0); split->setSpacing(0); split->addWidget(nvg); main_layout->addWidget(split_wrapper); alerts = new OnroadAlerts(this); alerts->setAttribute(Qt::WA_TransparentForMouseEvents, true); QObject::connect(this, &OnroadWindow::update, alerts, &OnroadAlerts::updateState); QObject::connect(this, &OnroadWindow::offroadTransitionSignal, alerts, &OnroadAlerts::offroadTransition); QObject::connect(this, &OnroadWindow::offroadTransitionSignal, this, &OnroadWindow::offroadTransition); main_layout->addWidget(alerts); // setup stacking order alerts->raise(); setAttribute(Qt::WA_OpaquePaintEvent); } void OnroadWindow::offroadTransition(bool offroad) { #ifdef ENABLE_MAPS if (!offroad) { QString token = QString::fromStdString(Params().get("MapboxToken")); if (map == nullptr && !token.isEmpty()) { QMapboxGLSettings settings; if (!Hardware::PC()) { settings.setCacheDatabasePath("/data/mbgl-cache.db"); } settings.setCacheDatabaseMaximumSize(20 * 1024 * 1024); settings.setAccessToken(token.trimmed()); MapWindow * m = new MapWindow(settings); QObject::connect(this, &OnroadWindow::offroadTransitionSignal, m, &MapWindow::offroadTransition); split->addWidget(m); map = m; } } #endif } // ***** onroad widgets ***** OnroadAlerts::OnroadAlerts(QWidget *parent) : QWidget(parent) { for (auto &kv : sound_map) { auto path = QUrl::fromLocalFile(kv.second.first); sounds[kv.first].setSource(path); } } void OnroadAlerts::updateState(const UIState &s) { SubMaster &sm = *(s.sm); if (sm.updated("carState")) { // scale volume with speed volume = util::map_val(sm["carState"].getCarState().getVEgo(), 0.f, 20.f, Hardware::MIN_VOLUME, Hardware::MAX_VOLUME); } if (sm["deviceState"].getDeviceState().getStarted()) { if (sm.updated("controlsState")) { const cereal::ControlsState::Reader &cs = sm["controlsState"].getControlsState(); updateAlert(QString::fromStdString(cs.getAlertText1()), QString::fromStdString(cs.getAlertText2()), cs.getAlertBlinkingRate(), cs.getAlertType(), cs.getAlertSize(), cs.getAlertSound()); } else if ((sm.frame - s.scene.started_frame) > 10 * UI_FREQ) { // Handle controls timeout if (sm.rcv_frame("controlsState") < s.scene.started_frame) { // car is started, but controlsState hasn't been seen at all updateAlert("openpilot Unavailable", "Waiting for controls to start", 0, "controlsWaiting", cereal::ControlsState::AlertSize::MID, AudibleAlert::NONE); } else if ((sm.frame - sm.rcv_frame("controlsState")) > 5 * UI_FREQ) { // car is started, but controls is lagging or died updateAlert("TAKE CONTROL IMMEDIATELY", "Controls Unresponsive", 0, "controlsUnresponsive", cereal::ControlsState::AlertSize::FULL, AudibleAlert::CHIME_WARNING_REPEAT); // TODO: clean this up once Qt handles the border QUIState::ui_state.status = STATUS_ALERT; } } } // TODO: add blinking back if performant //float alpha = 0.375 * cos((millis_since_boot() / 1000) * 2 * M_PI * blinking_rate) + 0.625; bg = bg_colors[s.status]; } void OnroadAlerts::offroadTransition(bool offroad) { updateAlert("", "", 0, "", cereal::ControlsState::AlertSize::NONE, AudibleAlert::NONE); } void OnroadAlerts::updateAlert(const QString &t1, const QString &t2, float blink_rate, const std::string &type, cereal::ControlsState::AlertSize size, AudibleAlert sound) { if (alert_type.compare(type) == 0 && text1.compare(t1) == 0 && text2.compare(t2) == 0) { return; } stopSounds(); if (sound != AudibleAlert::NONE) { playSound(sound); } text1 = t1; text2 = t2; alert_type = type; alert_size = size; blinking_rate = blink_rate; update(); } void OnroadAlerts::playSound(AudibleAlert alert) { int loops = sound_map[alert].second ? QSoundEffect::Infinite : 0; sounds[alert].setLoopCount(loops); sounds[alert].setVolume(volume); sounds[alert].play(); } void OnroadAlerts::stopSounds() { for (auto &kv : sounds) { // Only stop repeating sounds if (kv.second.loopsRemaining() == QSoundEffect::Infinite) { kv.second.stop(); } } } void OnroadAlerts::paintEvent(QPaintEvent *event) { QPainter p(this); if (alert_size == cereal::ControlsState::AlertSize::NONE) { return; } static std::map<cereal::ControlsState::AlertSize, const int> alert_sizes = { {cereal::ControlsState::AlertSize::SMALL, 271}, {cereal::ControlsState::AlertSize::MID, 420}, {cereal::ControlsState::AlertSize::FULL, height()}, }; int h = alert_sizes[alert_size]; QRect r = QRect(0, height() - h, width(), h); // draw background + gradient p.setPen(Qt::NoPen); p.setCompositionMode(QPainter::CompositionMode_SourceOver); p.setBrush(QBrush(bg)); p.drawRect(r); QLinearGradient g(0, r.y(), 0, r.bottom()); g.setColorAt(0, QColor::fromRgbF(0, 0, 0, 0.05)); g.setColorAt(1, QColor::fromRgbF(0, 0, 0, 0.35)); p.setCompositionMode(QPainter::CompositionMode_DestinationOver); p.setBrush(QBrush(g)); p.fillRect(r, g); p.setCompositionMode(QPainter::CompositionMode_SourceOver); // remove bottom border r = QRect(0, height() - h, width(), h - 30); // text const QPoint c = r.center(); p.setPen(QColor(0xff, 0xff, 0xff)); p.setRenderHint(QPainter::TextAntialiasing); if (alert_size == cereal::ControlsState::AlertSize::SMALL) { configFont(p, "Open Sans", 74, "SemiBold"); p.drawText(r, Qt::AlignCenter, text1); } else if (alert_size == cereal::ControlsState::AlertSize::MID) { configFont(p, "Open Sans", 88, "Bold"); p.drawText(QRect(0, c.y() - 125, width(), 150), Qt::AlignHCenter | Qt::AlignTop, text1); configFont(p, "Open Sans", 66, "Regular"); p.drawText(QRect(0, c.y() + 21, width(), 90), Qt::AlignHCenter, text2); } else if (alert_size == cereal::ControlsState::AlertSize::FULL) { bool l = text1.length() > 15; configFont(p, "Open Sans", l ? 132 : 177, "Bold"); p.drawText(QRect(0, r.y() + (l ? 240 : 270), width(), 600), Qt::AlignHCenter | Qt::TextWordWrap, text1); configFont(p, "Open Sans", 88, "Regular"); p.drawText(QRect(0, r.height() - (l ? 361 : 420), width(), 300), Qt::AlignHCenter | Qt::TextWordWrap, text2); } } NvgWindow::NvgWindow(QWidget *parent) : QOpenGLWidget(parent) { setAttribute(Qt::WA_OpaquePaintEvent); } NvgWindow::~NvgWindow() { makeCurrent(); doneCurrent(); } void NvgWindow::initializeGL() { initializeOpenGLFunctions(); std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl; std::cout << "OpenGL vendor: " << glGetString(GL_VENDOR) << std::endl; std::cout << "OpenGL renderer: " << glGetString(GL_RENDERER) << std::endl; std::cout << "OpenGL language version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; ui_nvg_init(&QUIState::ui_state); prev_draw_t = millis_since_boot(); } void NvgWindow::update(const UIState &s) { // Connecting to visionIPC requires opengl to be current if (s.vipc_client->connected) { makeCurrent(); } repaint(); } void NvgWindow::resizeGL(int w, int h) { ui_resize(&QUIState::ui_state, w, h); } void NvgWindow::paintGL() { ui_draw(&QUIState::ui_state, width(), height()); double cur_draw_t = millis_since_boot(); double dt = cur_draw_t - prev_draw_t; if (dt > 66) { // warn on sub 15fps LOGW("slow frame time: %.2f", dt); } prev_draw_t = cur_draw_t; } <commit_msg>OnroadAlerts: construct QPainter only when needed (#21260)<commit_after>#include "selfdrive/ui/qt/onroad.h" #include <iostream> #include "selfdrive/common/swaglog.h" #include "selfdrive/common/timing.h" #include "selfdrive/ui/paint.h" #include "selfdrive/ui/qt/util.h" #ifdef ENABLE_MAPS #include "selfdrive/ui/qt/maps/map.h" #endif OnroadWindow::OnroadWindow(QWidget *parent) : QWidget(parent) { main_layout = new QStackedLayout(this); main_layout->setStackingMode(QStackedLayout::StackAll); // old UI on bottom nvg = new NvgWindow(this); QObject::connect(this, &OnroadWindow::update, nvg, &NvgWindow::update); QWidget * split_wrapper = new QWidget; split = new QHBoxLayout(split_wrapper); split->setContentsMargins(0, 0, 0, 0); split->setSpacing(0); split->addWidget(nvg); main_layout->addWidget(split_wrapper); alerts = new OnroadAlerts(this); alerts->setAttribute(Qt::WA_TransparentForMouseEvents, true); QObject::connect(this, &OnroadWindow::update, alerts, &OnroadAlerts::updateState); QObject::connect(this, &OnroadWindow::offroadTransitionSignal, alerts, &OnroadAlerts::offroadTransition); QObject::connect(this, &OnroadWindow::offroadTransitionSignal, this, &OnroadWindow::offroadTransition); main_layout->addWidget(alerts); // setup stacking order alerts->raise(); setAttribute(Qt::WA_OpaquePaintEvent); } void OnroadWindow::offroadTransition(bool offroad) { #ifdef ENABLE_MAPS if (!offroad) { QString token = QString::fromStdString(Params().get("MapboxToken")); if (map == nullptr && !token.isEmpty()) { QMapboxGLSettings settings; if (!Hardware::PC()) { settings.setCacheDatabasePath("/data/mbgl-cache.db"); } settings.setCacheDatabaseMaximumSize(20 * 1024 * 1024); settings.setAccessToken(token.trimmed()); MapWindow * m = new MapWindow(settings); QObject::connect(this, &OnroadWindow::offroadTransitionSignal, m, &MapWindow::offroadTransition); split->addWidget(m); map = m; } } #endif } // ***** onroad widgets ***** OnroadAlerts::OnroadAlerts(QWidget *parent) : QWidget(parent) { for (auto &kv : sound_map) { auto path = QUrl::fromLocalFile(kv.second.first); sounds[kv.first].setSource(path); } } void OnroadAlerts::updateState(const UIState &s) { SubMaster &sm = *(s.sm); if (sm.updated("carState")) { // scale volume with speed volume = util::map_val(sm["carState"].getCarState().getVEgo(), 0.f, 20.f, Hardware::MIN_VOLUME, Hardware::MAX_VOLUME); } if (sm["deviceState"].getDeviceState().getStarted()) { if (sm.updated("controlsState")) { const cereal::ControlsState::Reader &cs = sm["controlsState"].getControlsState(); updateAlert(QString::fromStdString(cs.getAlertText1()), QString::fromStdString(cs.getAlertText2()), cs.getAlertBlinkingRate(), cs.getAlertType(), cs.getAlertSize(), cs.getAlertSound()); } else if ((sm.frame - s.scene.started_frame) > 10 * UI_FREQ) { // Handle controls timeout if (sm.rcv_frame("controlsState") < s.scene.started_frame) { // car is started, but controlsState hasn't been seen at all updateAlert("openpilot Unavailable", "Waiting for controls to start", 0, "controlsWaiting", cereal::ControlsState::AlertSize::MID, AudibleAlert::NONE); } else if ((sm.frame - sm.rcv_frame("controlsState")) > 5 * UI_FREQ) { // car is started, but controls is lagging or died updateAlert("TAKE CONTROL IMMEDIATELY", "Controls Unresponsive", 0, "controlsUnresponsive", cereal::ControlsState::AlertSize::FULL, AudibleAlert::CHIME_WARNING_REPEAT); // TODO: clean this up once Qt handles the border QUIState::ui_state.status = STATUS_ALERT; } } } // TODO: add blinking back if performant //float alpha = 0.375 * cos((millis_since_boot() / 1000) * 2 * M_PI * blinking_rate) + 0.625; bg = bg_colors[s.status]; } void OnroadAlerts::offroadTransition(bool offroad) { updateAlert("", "", 0, "", cereal::ControlsState::AlertSize::NONE, AudibleAlert::NONE); } void OnroadAlerts::updateAlert(const QString &t1, const QString &t2, float blink_rate, const std::string &type, cereal::ControlsState::AlertSize size, AudibleAlert sound) { if (alert_type.compare(type) == 0 && text1.compare(t1) == 0 && text2.compare(t2) == 0) { return; } stopSounds(); if (sound != AudibleAlert::NONE) { playSound(sound); } text1 = t1; text2 = t2; alert_type = type; alert_size = size; blinking_rate = blink_rate; update(); } void OnroadAlerts::playSound(AudibleAlert alert) { int loops = sound_map[alert].second ? QSoundEffect::Infinite : 0; sounds[alert].setLoopCount(loops); sounds[alert].setVolume(volume); sounds[alert].play(); } void OnroadAlerts::stopSounds() { for (auto &kv : sounds) { // Only stop repeating sounds if (kv.second.loopsRemaining() == QSoundEffect::Infinite) { kv.second.stop(); } } } void OnroadAlerts::paintEvent(QPaintEvent *event) { if (alert_size == cereal::ControlsState::AlertSize::NONE) { return; } static std::map<cereal::ControlsState::AlertSize, const int> alert_sizes = { {cereal::ControlsState::AlertSize::SMALL, 271}, {cereal::ControlsState::AlertSize::MID, 420}, {cereal::ControlsState::AlertSize::FULL, height()}, }; int h = alert_sizes[alert_size]; QRect r = QRect(0, height() - h, width(), h); QPainter p(this); // draw background + gradient p.setPen(Qt::NoPen); p.setCompositionMode(QPainter::CompositionMode_SourceOver); p.setBrush(QBrush(bg)); p.drawRect(r); QLinearGradient g(0, r.y(), 0, r.bottom()); g.setColorAt(0, QColor::fromRgbF(0, 0, 0, 0.05)); g.setColorAt(1, QColor::fromRgbF(0, 0, 0, 0.35)); p.setCompositionMode(QPainter::CompositionMode_DestinationOver); p.setBrush(QBrush(g)); p.fillRect(r, g); p.setCompositionMode(QPainter::CompositionMode_SourceOver); // remove bottom border r = QRect(0, height() - h, width(), h - 30); // text const QPoint c = r.center(); p.setPen(QColor(0xff, 0xff, 0xff)); p.setRenderHint(QPainter::TextAntialiasing); if (alert_size == cereal::ControlsState::AlertSize::SMALL) { configFont(p, "Open Sans", 74, "SemiBold"); p.drawText(r, Qt::AlignCenter, text1); } else if (alert_size == cereal::ControlsState::AlertSize::MID) { configFont(p, "Open Sans", 88, "Bold"); p.drawText(QRect(0, c.y() - 125, width(), 150), Qt::AlignHCenter | Qt::AlignTop, text1); configFont(p, "Open Sans", 66, "Regular"); p.drawText(QRect(0, c.y() + 21, width(), 90), Qt::AlignHCenter, text2); } else if (alert_size == cereal::ControlsState::AlertSize::FULL) { bool l = text1.length() > 15; configFont(p, "Open Sans", l ? 132 : 177, "Bold"); p.drawText(QRect(0, r.y() + (l ? 240 : 270), width(), 600), Qt::AlignHCenter | Qt::TextWordWrap, text1); configFont(p, "Open Sans", 88, "Regular"); p.drawText(QRect(0, r.height() - (l ? 361 : 420), width(), 300), Qt::AlignHCenter | Qt::TextWordWrap, text2); } } NvgWindow::NvgWindow(QWidget *parent) : QOpenGLWidget(parent) { setAttribute(Qt::WA_OpaquePaintEvent); } NvgWindow::~NvgWindow() { makeCurrent(); doneCurrent(); } void NvgWindow::initializeGL() { initializeOpenGLFunctions(); std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl; std::cout << "OpenGL vendor: " << glGetString(GL_VENDOR) << std::endl; std::cout << "OpenGL renderer: " << glGetString(GL_RENDERER) << std::endl; std::cout << "OpenGL language version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl; ui_nvg_init(&QUIState::ui_state); prev_draw_t = millis_since_boot(); } void NvgWindow::update(const UIState &s) { // Connecting to visionIPC requires opengl to be current if (s.vipc_client->connected) { makeCurrent(); } repaint(); } void NvgWindow::resizeGL(int w, int h) { ui_resize(&QUIState::ui_state, w, h); } void NvgWindow::paintGL() { ui_draw(&QUIState::ui_state, width(), height()); double cur_draw_t = millis_since_boot(); double dt = cur_draw_t - prev_draw_t; if (dt > 66) { // warn on sub 15fps LOGW("slow frame time: %.2f", dt); } prev_draw_t = cur_draw_t; } <|endoftext|>
<commit_before>#include <hdmarker/subpattern.hpp> #include <ucalib/ucalib.hpp> #include <cliini/cliini.hpp> #include <opencv2/highgui.hpp> #include <metamat/mat.hpp> #include <ucalib/proxy.hpp> #include <iostream> using namespace cv; using namespace cliini; using namespace hdmarker; cliini_opt opts[] = { { "help", 0, //argcount 0, //argcount CLIINI_NONE, //type 0, //flags 'h' }, { "imgs", 1, //argcount min CLIINI_ARGCOUNT_ANY, //argcount max CLIINI_STRING, //type 0, //flags 'i', NULL, "read imgs and detect calibration points with HDMarkers", "[file1] [file2] ..." }, { "store", 1, //argcount min 1, //argcount max CLIINI_STRING, //type 0, //flags 's', NULL, "store detected calibration points", "<file>" }, { "load", 1, //argcount min 1, //argcount max CLIINI_STRING, //type 0, //flags 'l', NULL, "load stored calibration points and execute calibration", "<file>" } }; cliini_optgroup group = { opts, NULL, sizeof(opts)/sizeof(*opts), 0, 0 }; int main(int argc, const char *argv[]) { Marker::init(); cliargs args(argc, argv, &group); std::vector<Corner> corners_rough; std::vector<Corner> corners; double unit_size = 39.94; //marker size in mm MetaMat::Mat_<float> proxy({2, 33, 25, args["imgs"].count()}); MetaMat::Mat_<float> jacobian({2, 2, 33, 25, args["imgs"].count()}); std::string img_f = args["imgs"].str(0); Mat ex_img = imread(img_f, CV_LOAD_IMAGE_GRAYSCALE); for(int i=0;i<args["imgs"].count();i++) { img_f = args["imgs"].str(i); std::vector<Point2f> ipoints_v; std::vector<Point3f> wpoints_v; if (boost::filesystem::exists(img_f+".pointcache.yaml")) { FileStorage fs(img_f+".pointcache.yaml", FileStorage::READ); fs["img_points"] >> ipoints_v; fs["world_points"] >> wpoints_v; printf("%d points\n", ipoints_v.size()); } else { std::cout << img_f+".pointcache.yaml" << "does not exist!\n"; Mat img = imread(img_f, CV_LOAD_IMAGE_GRAYSCALE); printf("detect img %s\n", args["imgs"].str(i).c_str()); corners_rough.resize(0); Marker::detect(img, corners_rough, false, 0, 100, 3); Mat debug; corners.resize(0); double unit_size_res = unit_size; hdmarker_detect_subpattern(img, corners_rough, corners, 3, &unit_size_res, &debug, NULL, 0); imwrite((img_f+".detect.png").c_str(), debug); ipoints_v.resize(corners.size()); wpoints_v.resize(corners.size()); for(int ci=0;ci<corners.size();ci++) { ipoints_v[ci] = corners[ci].p; Point2f w_2d = unit_size_res*Point2f(corners[ci].id.x, corners[ci].id.y); wpoints_v[ci] = Point3f(w_2d.x, w_2d.y, 0); } std::cout << "write " << img_f+".pointcache.yaml" << "\n"; FileStorage fs(img_f+".pointcache.yaml", FileStorage::WRITE); fs << "img_points" << ipoints_v; fs << "world_points" << wpoints_v; } if (boost::filesystem::exists(img_f+".proxycache.yaml")) { cv::Mat sub_proxy; cv::Mat sub_j; FileStorage fs(img_f+".proxycache.yaml", FileStorage::READ); fs["proxy"] >> sub_proxy; fs["jacobian"] >> sub_j; sub_proxy.copyTo(cvMat(proxy.bind(3, i))); sub_j.copyTo(cvMat(jacobian.bind(4, i))); } else { MetaMat::Mat_<float> sub_proxy = proxy.bind(3, i); MetaMat::Mat_<float> sub_j = jacobian.bind(4, i); ucalib::proxy_backwards_pers_poly_generate<0,0>(sub_proxy, ipoints_v, wpoints_v, ex_img.size(), 0, 0, &sub_j); FileStorage fs(img_f+".proxycache.yaml", FileStorage::WRITE); fs << "proxy" << cvMat(sub_proxy); fs << "jacobian" << cvMat(sub_j); } } ucalib::calibrate_rays(proxy, jacobian, ex_img.size(), MetaMat::DimSpec(-1), ucalib::LIVE | ucalib::SHOW_TARGET); //TODO calibration... return EXIT_SUCCESS; } <commit_msg>implement undistortion example<commit_after>#include <hdmarker/subpattern.hpp> #include <ucalib/ucalib.hpp> #include <cliini/cliini.hpp> #include <opencv2/highgui.hpp> #include <metamat/mat.hpp> #include <ucalib/proxy.hpp> #include <iostream> using namespace cv; using namespace cliini; using namespace hdmarker; cliini_opt opts[] = { { "help", 0, //argcount 0, //argcount CLIINI_NONE, //type 0, //flags 'h' }, { "imgs", 1, //argcount min CLIINI_ARGCOUNT_ANY, //argcount max CLIINI_STRING, //type 0, //flags 'i', NULL, "read imgs and detect calibration points with HDMarkers", "[file1] [file2] ..." }, { "store", 1, //argcount min 1, //argcount max CLIINI_STRING, //type 0, //flags 's', NULL, "store calibration", "<file>" }, { "load", 1, //argcount min 1, //argcount max CLIINI_STRING, //type 0, //flags 'l', NULL, "load calibration", "<file>" }, { "undistort", 1, //argcount min CLIINI_ARGCOUNT_ANY, //argcount max CLIINI_STRING, //type 0, //flags 'u', NULL, "undistort image with calibration model", "[file1] [file2] ..." }, { "z", 1, //argcount min 1, //argcount max CLIINI_DOUBLE, //type 0, //flags 'z', NULL, "z distance for undistortion", "<depth>" } }; cliini_optgroup group = { opts, NULL, sizeof(opts)/sizeof(*opts), 0, 0 }; std::string replace_all(std::string str, const std::string& search, const std::string& replace) { size_t pos = 0; while ((pos = str.find(search, pos)) != std::string::npos) { str.replace(pos, search.length(), replace); pos += replace.length(); } return str; } void save_mat(boost::filesystem::path path, MetaMat::Mat m, FileStorage &fs) { fs << replace_all(path.generic_string(),"/","_S_") << cvMat(m); } void save_str(boost::filesystem::path path, const char* str, FileStorage &fs) { fs << replace_all(path.generic_string(),"/","_S_") << str; } MetaMat::Mat load_mat(boost::filesystem::path path, FileStorage &fs) { cv::Mat m; fs[replace_all(path.generic_string(),"/","_S_")] >> m; return MetaMat::Mat(m); } const char *load_str(boost::filesystem::path path, FileStorage &fs) { std::string str; fs[replace_all(path.generic_string(),"/","_S_")] >> str; return strdup(str.c_str()); } int main(int argc, const char *argv[]) { Marker::init(); cliargs args(argc, argv, &group); std::vector<Corner> corners_rough; std::vector<Corner> corners; double unit_size = 39.94; //marker size in mm ucalib::Calib *calib = NULL; if (args["imgs"].valid()) { MetaMat::Mat_<float> proxy({2, 33, 25, args["imgs"].count()}); MetaMat::Mat_<float> jacobian({2, 2, 33, 25, args["imgs"].count()}); std::string img_f = args["imgs"].str(0); Mat ex_img = imread(img_f, CV_LOAD_IMAGE_GRAYSCALE); for(int i=0;i<args["imgs"].count();i++) { img_f = args["imgs"].str(i); std::vector<Point2f> ipoints_v; std::vector<Point3f> wpoints_v; if (boost::filesystem::exists(img_f+".pointcache.yaml")) { FileStorage fs(img_f+".pointcache.yaml", FileStorage::READ); fs["img_points"] >> ipoints_v; fs["world_points"] >> wpoints_v; printf("%d points\n", ipoints_v.size()); } else { std::cout << img_f+".pointcache.yaml" << "does not exist!\n"; Mat img = imread(img_f, CV_LOAD_IMAGE_GRAYSCALE); printf("detect img %s\n", args["imgs"].str(i).c_str()); corners_rough.resize(0); Marker::detect(img, corners_rough, false, 0, 100, 3); Mat debug; corners.resize(0); double unit_size_res = unit_size; hdmarker_detect_subpattern(img, corners_rough, corners, 3, &unit_size_res, &debug, NULL, 0); imwrite((img_f+".detect.png").c_str(), debug); ipoints_v.resize(corners.size()); wpoints_v.resize(corners.size()); for(int ci=0;ci<corners.size();ci++) { ipoints_v[ci] = corners[ci].p; Point2f w_2d = unit_size_res*Point2f(corners[ci].id.x, corners[ci].id.y); wpoints_v[ci] = Point3f(w_2d.x, w_2d.y, 0); } std::cout << "write " << img_f+".pointcache.yaml" << "\n"; FileStorage fs(img_f+".pointcache.yaml", FileStorage::WRITE); fs << "img_points" << ipoints_v; fs << "world_points" << wpoints_v; } if (boost::filesystem::exists(img_f+".proxycache.yaml")) { cv::Mat sub_proxy; cv::Mat sub_j; FileStorage fs(img_f+".proxycache.yaml", FileStorage::READ); fs["proxy"] >> sub_proxy; fs["jacobian"] >> sub_j; sub_proxy.copyTo(cvMat(proxy.bind(3, i))); sub_j.copyTo(cvMat(jacobian.bind(4, i))); } else { MetaMat::Mat_<float> sub_proxy = proxy.bind(3, i); MetaMat::Mat_<float> sub_j = jacobian.bind(4, i); ucalib::proxy_backwards_pers_poly_generate<0,0>(sub_proxy, ipoints_v, wpoints_v, ex_img.size(), 0, 0, &sub_j); FileStorage fs(img_f+".proxycache.yaml", FileStorage::WRITE); fs << "proxy" << cvMat(sub_proxy); fs << "jacobian" << cvMat(sub_j); } } calib = ucalib::calibrate_rays(proxy, jacobian, ex_img.size(), MetaMat::DimSpec(-1), ucalib::LIVE | ucalib::SHOW_TARGET); } if (args["load"]) { FileStorage fs(args["load"].str(), FileStorage::READ); std::function<ucalib::Mat(ucalib::cpath)> _l_m = std::bind(load_mat,std::placeholders::_1, fs); std::function<const char*(ucalib::cpath)> _l_y = std::bind(load_str,std::placeholders::_1, fs); calib = ucalib::load(_l_m, _l_y); } if (args["store"]) { FileStorage fs(args["store"].str(), FileStorage::WRITE); std::function<void(ucalib::cpath,ucalib::Mat)> _s_m = std::bind(save_mat,std::placeholders::_1, std::placeholders::_2, fs); std::function<void(ucalib::cpath,const char*)> _s_y = std::bind(save_str,std::placeholders::_1, std::placeholders::_2, fs); calib->save(_s_m, _s_y); } if (calib && args["undistort"]) { double z = 1000; if (args["z"]) z = args["z"]; printf("z depth : %f\n", z); //FIXME should also work with empty idx! calib->set_ref_cam(calib->cam({0,0})); for(int i=0;i<args["undistort"].count();i++) { std::string img_f = args["undistort"].str(i); cv::Mat img = imread(img_f, CV_LOAD_IMAGE_GRAYSCALE); cv::Mat undist = imread(img_f, CV_LOAD_IMAGE_GRAYSCALE); calib->rectify(MetaMat::Mat(img), MetaMat::Mat(undist), {0}, z); imwrite(img_f+".undist.png", undist); } } return EXIT_SUCCESS; } <|endoftext|>